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 vectorizes 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 iteration 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/Transforms/Scalar.h"
83 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
84 #include "llvm/Transforms/Utils/Local.h"
90 static cl::opt<unsigned>
91 VectorizationFactor("force-vector-width", cl::init(0), cl::Hidden,
92 cl::desc("Sets the SIMD width. Zero is autoselect."));
94 static cl::opt<unsigned>
95 VectorizationUnroll("force-vector-unroll", cl::init(0), cl::Hidden,
96 cl::desc("Sets the vectorization unroll count. "
97 "Zero is autoselect."));
100 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
101 cl::desc("Enable if-conversion during vectorization."));
103 /// We don't vectorize loops with a known constant trip count below this number.
104 static cl::opt<unsigned>
105 TinyTripCountVectorThreshold("vectorizer-min-trip-count", cl::init(16), cl::Hidden,
106 cl::desc("The minimum trip count in the loops to vectorize."));
108 /// We don't unroll loops with a known constant trip count below this number.
109 static const unsigned TinyTripCountUnrollThreshold = 128;
111 /// When performing a runtime memory check, do not check more than this
112 /// number of pointers. Notice that the check is quadratic!
113 static const unsigned RuntimeMemoryCheckThreshold = 4;
117 // Forward declarations.
118 class LoopVectorizationLegality;
119 class LoopVectorizationCostModel;
121 /// InnerLoopVectorizer vectorizes loops which contain only one basic
122 /// block to a specified vectorization factor (VF).
123 /// This class performs the widening of scalars into vectors, or multiple
124 /// scalars. This class also implements the following features:
125 /// * It inserts an epilogue loop for handling loops that don't have iteration
126 /// counts that are known to be a multiple of the vectorization factor.
127 /// * It handles the code generation for reduction variables.
128 /// * Scalarization (implementation using scalars) of un-vectorizable
130 /// InnerLoopVectorizer does not perform any vectorization-legality
131 /// checks, and relies on the caller to check for the different legality
132 /// aspects. The InnerLoopVectorizer relies on the
133 /// LoopVectorizationLegality class to provide information about the induction
134 /// and reduction variables that were found to a given vectorization factor.
135 class InnerLoopVectorizer {
137 InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
138 DominatorTree *DT, DataLayout *DL, unsigned VecWidth,
139 unsigned UnrollFactor)
140 : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), DL(DL), VF(VecWidth),
141 UF(UnrollFactor), Builder(SE->getContext()), Induction(0),
142 OldInduction(0), WidenMap(UnrollFactor) {}
144 // Perform the actual loop widening (vectorization).
145 void vectorize(LoopVectorizationLegality *Legal) {
146 // Create a new empty loop. Unlink the old loop and connect the new one.
147 createEmptyLoop(Legal);
148 // Widen each instruction in the old loop to a new one in the new loop.
149 // Use the Legality module to find the induction and reduction variables.
150 vectorizeLoop(Legal);
151 // Register the new loop and update the analysis passes.
156 /// A small list of PHINodes.
157 typedef SmallVector<PHINode*, 4> PhiVector;
158 /// When we unroll loops we have multiple vector values for each scalar.
159 /// This data structure holds the unrolled and vectorized values that
160 /// originated from one scalar instruction.
161 typedef SmallVector<Value*, 2> VectorParts;
163 /// Add code that checks at runtime if the accessed arrays overlap.
164 /// Returns the comparator value or NULL if no check is needed.
165 Instruction *addRuntimeCheck(LoopVectorizationLegality *Legal,
167 /// Create an empty loop, based on the loop ranges of the old loop.
168 void createEmptyLoop(LoopVectorizationLegality *Legal);
169 /// Copy and widen the instructions from the old loop.
170 void vectorizeLoop(LoopVectorizationLegality *Legal);
172 /// A helper function that computes the predicate of the block BB, assuming
173 /// that the header block of the loop is set to True. It returns the *entry*
174 /// mask for the block BB.
175 VectorParts createBlockInMask(BasicBlock *BB);
176 /// A helper function that computes the predicate of the edge between SRC
178 VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
180 /// A helper function to vectorize a single BB within the innermost loop.
181 void vectorizeBlockInLoop(LoopVectorizationLegality *Legal, BasicBlock *BB,
184 /// Insert the new loop to the loop hierarchy and pass manager
185 /// and update the analysis passes.
186 void updateAnalysis();
188 /// This instruction is un-vectorizable. Implement it as a sequence
190 void scalarizeInstruction(Instruction *Instr);
192 /// Vectorize Load and Store instructions,
193 void vectorizeMemoryInstruction(Instruction *Instr,
194 LoopVectorizationLegality *Legal);
196 /// Create a broadcast instruction. This method generates a broadcast
197 /// instruction (shuffle) for loop invariant values and for the induction
198 /// value. If this is the induction variable then we extend it to N, N+1, ...
199 /// this is needed because each iteration in the loop corresponds to a SIMD
201 Value *getBroadcastInstrs(Value *V);
203 /// This function adds 0, 1, 2 ... to each vector element, starting at zero.
204 /// If Negate is set then negative numbers are added e.g. (0, -1, -2, ...).
205 /// The sequence starts at StartIndex.
206 Value *getConsecutiveVector(Value* Val, unsigned StartIdx, bool Negate);
208 /// When we go over instructions in the basic block we rely on previous
209 /// values within the current basic block or on loop invariant values.
210 /// When we widen (vectorize) values we place them in the map. If the values
211 /// are not within the map, they have to be loop invariant, so we simply
212 /// broadcast them into a vector.
213 VectorParts &getVectorValue(Value *V);
215 /// Generate a shuffle sequence that will reverse the vector Vec.
216 Value *reverseVector(Value *Vec);
218 /// This is a helper class that holds the vectorizer state. It maps scalar
219 /// instructions to vector instructions. When the code is 'unrolled' then
220 /// then a single scalar value is mapped to multiple vector parts. The parts
221 /// are stored in the VectorPart type.
223 /// C'tor. UnrollFactor controls the number of vectors ('parts') that
225 ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
227 /// \return True if 'Key' is saved in the Value Map.
228 bool has(Value *Key) const { return MapStorage.count(Key); }
230 /// Initializes a new entry in the map. Sets all of the vector parts to the
231 /// save value in 'Val'.
232 /// \return A reference to a vector with splat values.
233 VectorParts &splat(Value *Key, Value *Val) {
234 VectorParts &Entry = MapStorage[Key];
235 Entry.assign(UF, Val);
239 ///\return A reference to the value that is stored at 'Key'.
240 VectorParts &get(Value *Key) {
241 VectorParts &Entry = MapStorage[Key];
244 assert(Entry.size() == UF);
249 /// The unroll factor. Each entry in the map stores this number of vector
253 /// Map storage. We use std::map and not DenseMap because insertions to a
254 /// dense map invalidates its iterators.
255 std::map<Value *, VectorParts> MapStorage;
258 /// The original loop.
260 /// Scev analysis to use.
268 /// The vectorization SIMD factor to use. Each vector will have this many
271 /// The vectorization unroll factor to use. Each scalar is vectorized to this
272 /// many different vector instructions.
275 /// The builder that we use
278 // --- Vectorization state ---
280 /// The vector-loop preheader.
281 BasicBlock *LoopVectorPreHeader;
282 /// The scalar-loop preheader.
283 BasicBlock *LoopScalarPreHeader;
284 /// Middle Block between the vector and the scalar.
285 BasicBlock *LoopMiddleBlock;
286 ///The ExitBlock of the scalar loop.
287 BasicBlock *LoopExitBlock;
288 ///The vector loop body.
289 BasicBlock *LoopVectorBody;
290 ///The scalar loop body.
291 BasicBlock *LoopScalarBody;
292 /// A list of all bypass blocks. The first block is the entry of the loop.
293 SmallVector<BasicBlock *, 4> LoopBypassBlocks;
295 /// The new Induction variable which was added to the new block.
297 /// The induction variable of the old basic block.
298 PHINode *OldInduction;
299 /// Maps scalars to widened vectors.
303 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
304 /// to what vectorization factor.
305 /// This class does not look at the profitability of vectorization, only the
306 /// legality. This class has two main kinds of checks:
307 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
308 /// will change the order of memory accesses in a way that will change the
309 /// correctness of the program.
310 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
311 /// checks for a number of different conditions, such as the availability of a
312 /// single induction variable, that all types are supported and vectorize-able,
313 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
314 /// This class is also used by InnerLoopVectorizer for identifying
315 /// induction variable and the different reduction variables.
316 class LoopVectorizationLegality {
318 LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, DataLayout *DL,
320 : TheLoop(L), SE(SE), DL(DL), DT(DT), Induction(0) {}
322 /// This enum represents the kinds of reductions that we support.
324 RK_NoReduction, ///< Not a reduction.
325 RK_IntegerAdd, ///< Sum of integers.
326 RK_IntegerMult, ///< Product of integers.
327 RK_IntegerOr, ///< Bitwise or logical OR of numbers.
328 RK_IntegerAnd, ///< Bitwise or logical AND of numbers.
329 RK_IntegerXor, ///< Bitwise or logical XOR of numbers.
330 RK_FloatAdd, ///< Sum of floats.
331 RK_FloatMult ///< Product of floats.
334 /// This enum represents the kinds of inductions that we support.
336 IK_NoInduction, ///< Not an induction variable.
337 IK_IntInduction, ///< Integer induction variable. Step = 1.
338 IK_ReverseIntInduction, ///< Reverse int induction variable. Step = -1.
339 IK_PtrInduction, ///< Pointer induction var. Step = sizeof(elem).
340 IK_ReversePtrInduction ///< Reverse ptr indvar. Step = - sizeof(elem).
343 /// This POD struct holds information about reduction variables.
344 struct ReductionDescriptor {
345 ReductionDescriptor() : StartValue(0), LoopExitInstr(0),
346 Kind(RK_NoReduction) {}
348 ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K)
349 : StartValue(Start), LoopExitInstr(Exit), Kind(K) {}
351 // The starting value of the reduction.
352 // It does not have to be zero!
354 // The instruction who's value is used outside the loop.
355 Instruction *LoopExitInstr;
356 // The kind of the reduction.
360 // This POD struct holds information about the memory runtime legality
361 // check that a group of pointers do not overlap.
362 struct RuntimePointerCheck {
363 RuntimePointerCheck() : Need(false) {}
365 /// Reset the state of the pointer runtime information.
373 /// Insert a pointer and calculate the start and end SCEVs.
374 void insert(ScalarEvolution *SE, Loop *Lp, Value *Ptr);
376 /// This flag indicates if we need to add the runtime check.
378 /// Holds the pointers that we need to check.
379 SmallVector<Value*, 2> Pointers;
380 /// Holds the pointer value at the beginning of the loop.
381 SmallVector<const SCEV*, 2> Starts;
382 /// Holds the pointer value at the end of the loop.
383 SmallVector<const SCEV*, 2> Ends;
386 /// A POD for saving information about induction variables.
387 struct InductionInfo {
388 InductionInfo(Value *Start, InductionKind K) : StartValue(Start), IK(K) {}
389 InductionInfo() : StartValue(0), IK(IK_NoInduction) {}
396 /// ReductionList contains the reduction descriptors for all
397 /// of the reductions that were found in the loop.
398 typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
400 /// InductionList saves induction variables and maps them to the
401 /// induction descriptor.
402 typedef MapVector<PHINode*, InductionInfo> InductionList;
404 /// Returns true if it is legal to vectorize this loop.
405 /// This does not mean that it is profitable to vectorize this
406 /// loop, only that it is legal to do so.
409 /// Returns the Induction variable.
410 PHINode *getInduction() { return Induction; }
412 /// Returns the reduction variables found in the loop.
413 ReductionList *getReductionVars() { return &Reductions; }
415 /// Returns the induction variables found in the loop.
416 InductionList *getInductionVars() { return &Inductions; }
418 /// Returns True if V is an induction variable in this loop.
419 bool isInductionVariable(const Value *V);
421 /// Return true if the block BB needs to be predicated in order for the loop
422 /// to be vectorized.
423 bool blockNeedsPredication(BasicBlock *BB);
425 /// Check if this pointer is consecutive when vectorizing. This happens
426 /// when the last index of the GEP is the induction variable, or that the
427 /// pointer itself is an induction variable.
428 /// This check allows us to vectorize A[idx] into a wide load/store.
430 /// 0 - Stride is unknown or non consecutive.
431 /// 1 - Address is consecutive.
432 /// -1 - Address is consecutive, and decreasing.
433 int isConsecutivePtr(Value *Ptr);
435 /// Returns true if the value V is uniform within the loop.
436 bool isUniform(Value *V);
438 /// Returns true if this instruction will remain scalar after vectorization.
439 bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
441 /// Returns the information that we collected about runtime memory check.
442 RuntimePointerCheck *getRuntimePointerCheck() { return &PtrRtCheck; }
444 /// Check if a single basic block loop is vectorizable.
445 /// At this point we know that this is a loop with a constant trip count
446 /// and we only need to check individual instructions.
447 bool canVectorizeInstrs();
449 /// When we vectorize loops we may change the order in which
450 /// we read and write from memory. This method checks if it is
451 /// legal to vectorize the code, considering only memory constrains.
452 /// Returns true if the loop is vectorizable
453 bool canVectorizeMemory();
455 /// Return true if we can vectorize this loop using the IF-conversion
457 bool canVectorizeWithIfConvert();
459 /// Collect the variables that need to stay uniform after vectorization.
460 void collectLoopUniforms();
462 /// Return true if all of the instructions in the block can be speculatively
464 bool blockCanBePredicated(BasicBlock *BB);
466 /// Returns True, if 'Phi' is the kind of reduction variable for type
467 /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
468 bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
469 /// Returns true if the instruction I can be a reduction variable of type
471 bool isReductionInstr(Instruction *I, ReductionKind Kind);
472 /// Returns the induction kind of Phi. This function may return NoInduction
473 /// if the PHI is not an induction variable.
474 InductionKind isInductionVariable(PHINode *Phi);
475 /// Return true if can compute the address bounds of Ptr within the loop.
476 bool hasComputableBounds(Value *Ptr);
478 /// The loop that we evaluate.
482 /// DataLayout analysis.
487 // --- vectorization state --- //
489 /// Holds the integer induction variable. This is the counter of the
492 /// Holds the reduction variables.
493 ReductionList Reductions;
494 /// Holds all of the induction variables that we found in the loop.
495 /// Notice that inductions don't need to start at zero and that induction
496 /// variables can be pointers.
497 InductionList Inductions;
499 /// Allowed outside users. This holds the reduction
500 /// vars which can be accessed from outside the loop.
501 SmallPtrSet<Value*, 4> AllowedExit;
502 /// This set holds the variables which are known to be uniform after
504 SmallPtrSet<Instruction*, 4> Uniforms;
505 /// We need to check that all of the pointers in this list are disjoint
507 RuntimePointerCheck PtrRtCheck;
510 /// LoopVectorizationCostModel - estimates the expected speedups due to
512 /// In many cases vectorization is not profitable. This can happen because of
513 /// a number of reasons. In this class we mainly attempt to predict the
514 /// expected speedup/slowdowns due to the supported instruction set. We use the
515 /// TargetTransformInfo to query the different backends for the cost of
516 /// different operations.
517 class LoopVectorizationCostModel {
519 LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
520 LoopVectorizationLegality *Legal,
521 const TargetTransformInfo &TTI,
523 : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI), DL(DL) {}
525 /// Information about vectorization costs
526 struct VectorizationFactor {
527 unsigned Width; // Vector width with best cost
528 unsigned Cost; // Cost of the loop with that width
530 /// \return The most profitable vectorization factor and the cost of that VF.
531 /// This method checks every power of two up to VF. If UserVF is not ZERO
532 /// then this vectorization factor will be selected if vectorization is
534 VectorizationFactor selectVectorizationFactor(bool OptForSize, unsigned UserVF);
536 /// \return The size (in bits) of the widest type in the code that
537 /// needs to be vectorized. We ignore values that remain scalar such as
538 /// 64 bit loop indices.
539 unsigned getWidestType();
541 /// \return The most profitable unroll factor.
542 /// If UserUF is non-zero then this method finds the best unroll-factor
543 /// based on register pressure and other parameters.
544 /// VF and LoopCost are the selected vectorization factor and the cost of the
546 unsigned selectUnrollFactor(bool OptForSize, unsigned UserUF, unsigned VF,
549 /// \brief A struct that represents some properties of the register usage
551 struct RegisterUsage {
552 /// Holds the number of loop invariant values that are used in the loop.
553 unsigned LoopInvariantRegs;
554 /// Holds the maximum number of concurrent live intervals in the loop.
555 unsigned MaxLocalUsers;
556 /// Holds the number of instructions in the loop.
557 unsigned NumInstructions;
560 /// \return information about the register usage of the loop.
561 RegisterUsage calculateRegisterUsage();
563 /// A helper function for converting Scalar types to vector types.
564 /// If the incoming type is void, we return void. If the VF is 1, we return
566 static Type* ToVectorTy(Type *Scalar, unsigned VF);
569 /// Returns the expected execution cost. The unit of the cost does
570 /// not matter because we use the 'cost' units to compare different
571 /// vector widths. The cost that is returned is *not* normalized by
572 /// the factor width.
573 unsigned expectedCost(unsigned VF);
575 /// Returns the execution time cost of an instruction for a given vector
576 /// width. Vector width of one means scalar.
577 unsigned getInstructionCost(Instruction *I, unsigned VF);
579 /// Returns whether the instruction is a load or store and will be a emitted
580 /// as a vector operation.
581 bool isConsecutiveLoadOrStore(Instruction *I);
583 /// The loop that we evaluate.
587 /// Loop Info analysis.
589 /// Vectorization legality.
590 LoopVectorizationLegality *Legal;
591 /// Vector target information.
592 const TargetTransformInfo &TTI;
593 /// Target data layout information.
597 /// A helper class to compute the cost of a memory operation (load or store).
598 class MemoryCostComputation {
600 /// \brief This function computes the cost of a memory instruction, either of
601 /// a load or of a store.
602 /// \param Inst a pointer to a LoadInst or a StoreInst.
603 /// \param VF the vector factor to use.
604 /// \param TTI the target transform information used to obtain costs.
605 /// \param Legality the legality class used by this function to obtain the
606 /// access strid of the memory operation.
607 /// \returns the estimated cost of the memory instruction.
608 static unsigned computeCost(Value *Inst, unsigned VF,
609 const TargetTransformInfo &TTI,
610 LoopVectorizationLegality *Legality) {
611 if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
612 return StoreCost(Store, VF, TTI, Legality).cost();
614 return LoadCost(cast<LoadInst>(Inst), VF, TTI, Legality).cost();
618 /// An helper class to compute the cost of vectorize memory instruction. It is
619 /// subclassed by load and store cost computation classes who fill the fields
620 /// with values that require knowing about the concrete Load/StoreInst class.
623 /// \return the cost of vectorizing the memory access instruction.
625 if (VectorFactor == 1)
626 return TTI.getMemoryOpCost(Opcode, VectorTy, Alignment, AddressSpace);
628 if ((Stride = Legality->isConsecutivePtr(PointerOperand)))
629 return costOfWideMemInst();
631 return costOfScalarizedMemInst();
635 /// The pointer operand of the memory instruction.
636 Value *PointerOperand;
637 /// The scalar type of the memory access.
639 /// The vector type of the memory access.
641 /// The vector factor by which we vectorize.
642 unsigned VectorFactor;
643 /// The stride of the memory access.
645 /// The alignment of the memory operation.
647 /// The address space of the memory operation.
648 unsigned AddressSpace;
649 /// The opcode of the memory instruction.
651 /// Are we looking at a load or store instruction.
653 const TargetTransformInfo &TTI;
654 LoopVectorizationLegality *Legality;
656 /// Constructs a helper class to compute the cost of a memory instruction.
657 /// \param VF the vector factor (the length of the vector).
658 /// \param TI the target transform information used by this class to obtain
660 /// \param L the legality class used by this class to obtain the access
661 /// stride of the memory operation.
662 MemoryOpCost(unsigned VF, const TargetTransformInfo &TI,
663 LoopVectorizationLegality *L) :
664 VectorFactor(VF), TTI(TI), Legality(L) {
668 /// \return the cost if the memory instruction is scalarized.
669 unsigned costOfScalarizedMemInst() {
671 Cost += costOfExtractFromPointerVector();
672 Cost += costOfExtractFromValueVector();
673 Cost += VectorFactor * TTI.getMemoryOpCost(Opcode, ScalarTy, Alignment,
675 Cost += costOfInsertIntoValueVector();
679 /// \return the cost of extracting the pointers out of the pointer vector.
680 unsigned costOfExtractFromPointerVector() {
681 Type *PtrTy = getVectorizedPointerOperandType();
682 return costOfVectorInstForAllElems(Instruction::ExtractElement, PtrTy);
685 /// \return the cost for extracting values out of the value vector if the
686 /// memory instruction is a store and zero otherwise.
687 unsigned costOfExtractFromValueVector() {
691 return costOfVectorInstForAllElems(Instruction::ExtractElement, VectorTy);
694 /// \return the cost of insert values into the value vector if the memory
695 /// instruction was a load and zero otherwise.
696 unsigned costOfInsertIntoValueVector() {
700 return costOfVectorInstForAllElems(Instruction::InsertElement, VectorTy);
703 /// \return the cost of a vector memory instruction.
704 unsigned costOfWideMemInst() {
705 unsigned Cost = TTI.getMemoryOpCost(Opcode, VectorTy, Alignment,
709 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy,
714 /// Helper function to compute the cost of one insert- or extractelement
715 /// instruction per vector element.
716 /// \param VecOpcode the vector instruction opcode (Can be either
717 /// InsertElement or an ExtractElement).
718 /// \param Ty the vector type the vector instruction operates on.
719 /// \return the cost of an vector instruction applied to each vector
721 unsigned costOfVectorInstForAllElems(unsigned VecOpcode, Type *Ty) {
723 for (unsigned i = 0; i < VectorFactor; ++i)
724 Cost += TTI.getVectorInstrCost(VecOpcode, Ty, i);
728 /// \return a vectorized type for the pointer operand.
729 Type * getVectorizedPointerOperandType() {
730 Type *PointerOpTy = PointerOperand->getType();
731 return LoopVectorizationCostModel::ToVectorTy(PointerOpTy, VectorFactor);
735 /// Implementation of the abstract memory cost base class. Sets field of base
736 /// class whose value depends on the LoadInst.
737 class LoadCost : public MemoryOpCost {
739 LoadCost(LoadInst *Load, unsigned VF, const TargetTransformInfo &TI,
740 LoopVectorizationLegality *L) : MemoryOpCost(VF, TI, L) {
741 PointerOperand = Load->getPointerOperand();
742 ScalarTy = Load->getType();
743 VectorTy = LoopVectorizationCostModel::ToVectorTy(ScalarTy, VF);
744 Alignment = Load->getAlignment();
745 AddressSpace = Load->getPointerAddressSpace();
746 Opcode = Load->getOpcode();
751 /// Implementation of the abstract memory cost base class. Sets field of base
752 /// class whose value depends on the StoreInst.
753 class StoreCost : public MemoryOpCost {
755 StoreCost(StoreInst *Store, unsigned VF, const TargetTransformInfo &TI,
756 LoopVectorizationLegality *L) : MemoryOpCost(VF, TI, L) {
757 PointerOperand = Store->getPointerOperand();
758 ScalarTy = Store->getValueOperand()->getType();
759 VectorTy = LoopVectorizationCostModel::ToVectorTy(ScalarTy, VF);
760 Alignment = Store->getAlignment();
761 AddressSpace = Store->getPointerAddressSpace();
762 Opcode = Store->getOpcode();
768 /// The LoopVectorize Pass.
769 struct LoopVectorize : public LoopPass {
770 /// Pass identification, replacement for typeid
773 explicit LoopVectorize() : LoopPass(ID) {
774 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
780 TargetTransformInfo *TTI;
783 virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
784 // We only vectorize innermost loops.
788 SE = &getAnalysis<ScalarEvolution>();
789 DL = getAnalysisIfAvailable<DataLayout>();
790 LI = &getAnalysis<LoopInfo>();
791 TTI = &getAnalysis<TargetTransformInfo>();
792 DT = &getAnalysis<DominatorTree>();
794 DEBUG(dbgs() << "LV: Checking a loop in \"" <<
795 L->getHeader()->getParent()->getName() << "\"\n");
797 // Check if it is legal to vectorize the loop.
798 LoopVectorizationLegality LVL(L, SE, DL, DT);
799 if (!LVL.canVectorize()) {
800 DEBUG(dbgs() << "LV: Not vectorizing.\n");
804 // Use the cost model.
805 LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI, DL);
807 // Check the function attribues to find out if this function should be
808 // optimized for size.
809 Function *F = L->getHeader()->getParent();
810 Attribute::AttrKind SzAttr = Attribute::OptimizeForSize;
811 Attribute::AttrKind FlAttr = Attribute::NoImplicitFloat;
812 unsigned FnIndex = AttributeSet::FunctionIndex;
813 bool OptForSize = F->getAttributes().hasAttribute(FnIndex, SzAttr);
814 bool NoFloat = F->getAttributes().hasAttribute(FnIndex, FlAttr);
817 DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
818 "attribute is used.\n");
822 // Select the optimal vectorization factor.
823 LoopVectorizationCostModel::VectorizationFactor VF;
824 VF = CM.selectVectorizationFactor(OptForSize, VectorizationFactor);
825 // Select the unroll factor.
826 unsigned UF = CM.selectUnrollFactor(OptForSize, VectorizationUnroll,
830 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
834 DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< VF.Width << ") in "<<
835 F->getParent()->getModuleIdentifier()<<"\n");
836 DEBUG(dbgs() << "LV: Unroll Factor is " << UF << "\n");
838 // If we decided that it is *legal* to vectorizer the loop then do it.
839 InnerLoopVectorizer LB(L, SE, LI, DT, DL, VF.Width, UF);
842 DEBUG(verifyFunction(*L->getHeader()->getParent()));
846 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
847 LoopPass::getAnalysisUsage(AU);
848 AU.addRequiredID(LoopSimplifyID);
849 AU.addRequiredID(LCSSAID);
850 AU.addRequired<DominatorTree>();
851 AU.addRequired<LoopInfo>();
852 AU.addRequired<ScalarEvolution>();
853 AU.addRequired<TargetTransformInfo>();
854 AU.addPreserved<LoopInfo>();
855 AU.addPreserved<DominatorTree>();
860 } // end anonymous namespace
862 //===----------------------------------------------------------------------===//
863 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
864 // LoopVectorizationCostModel.
865 //===----------------------------------------------------------------------===//
868 LoopVectorizationLegality::RuntimePointerCheck::insert(ScalarEvolution *SE,
869 Loop *Lp, Value *Ptr) {
870 const SCEV *Sc = SE->getSCEV(Ptr);
871 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
872 assert(AR && "Invalid addrec expression");
873 const SCEV *Ex = SE->getExitCount(Lp, Lp->getLoopLatch());
874 const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
875 Pointers.push_back(Ptr);
876 Starts.push_back(AR->getStart());
877 Ends.push_back(ScEnd);
880 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
881 // Save the current insertion location.
882 Instruction *Loc = Builder.GetInsertPoint();
884 // We need to place the broadcast of invariant variables outside the loop.
885 Instruction *Instr = dyn_cast<Instruction>(V);
886 bool NewInstr = (Instr && Instr->getParent() == LoopVectorBody);
887 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
889 // Place the code for broadcasting invariant variables in the new preheader.
891 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
893 // Broadcast the scalar into all locations in the vector.
894 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
896 // Restore the builder insertion point.
898 Builder.SetInsertPoint(Loc);
903 Value *InnerLoopVectorizer::getConsecutiveVector(Value* Val, unsigned StartIdx,
905 assert(Val->getType()->isVectorTy() && "Must be a vector");
906 assert(Val->getType()->getScalarType()->isIntegerTy() &&
907 "Elem must be an integer");
909 Type *ITy = Val->getType()->getScalarType();
910 VectorType *Ty = cast<VectorType>(Val->getType());
911 int VLen = Ty->getNumElements();
912 SmallVector<Constant*, 8> Indices;
914 // Create a vector of consecutive numbers from zero to VF.
915 for (int i = 0; i < VLen; ++i) {
916 int Idx = Negate ? (-i): i;
917 Indices.push_back(ConstantInt::get(ITy, StartIdx + Idx));
920 // Add the consecutive indices to the vector value.
921 Constant *Cv = ConstantVector::get(Indices);
922 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
923 return Builder.CreateAdd(Val, Cv, "induction");
926 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
927 assert(Ptr->getType()->isPointerTy() && "Unexpected non ptr");
928 // Make sure that the pointer does not point to structs.
929 if (cast<PointerType>(Ptr->getType())->getElementType()->isAggregateType())
932 // If this value is a pointer induction variable we know it is consecutive.
933 PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
934 if (Phi && Inductions.count(Phi)) {
935 InductionInfo II = Inductions[Phi];
936 if (IK_PtrInduction == II.IK)
938 else if (IK_ReversePtrInduction == II.IK)
942 GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
946 unsigned NumOperands = Gep->getNumOperands();
947 Value *LastIndex = Gep->getOperand(NumOperands - 1);
949 Value *GpPtr = Gep->getPointerOperand();
950 // If this GEP value is a consecutive pointer induction variable and all of
951 // the indices are constant then we know it is consecutive. We can
952 Phi = dyn_cast<PHINode>(GpPtr);
953 if (Phi && Inductions.count(Phi)) {
955 // Make sure that the pointer does not point to structs.
956 PointerType *GepPtrType = cast<PointerType>(GpPtr->getType());
957 if (GepPtrType->getElementType()->isAggregateType())
960 // Make sure that all of the index operands are loop invariant.
961 for (unsigned i = 1; i < NumOperands; ++i)
962 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
965 InductionInfo II = Inductions[Phi];
966 if (IK_PtrInduction == II.IK)
968 else if (IK_ReversePtrInduction == II.IK)
972 // Check that all of the gep indices are uniform except for the last.
973 for (unsigned i = 0; i < NumOperands - 1; ++i)
974 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
977 // We can emit wide load/stores only if the last index is the induction
979 const SCEV *Last = SE->getSCEV(LastIndex);
980 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
981 const SCEV *Step = AR->getStepRecurrence(*SE);
983 // The memory is consecutive because the last index is consecutive
984 // and all other indices are loop invariant.
987 if (Step->isAllOnesValue())
994 bool LoopVectorizationLegality::isUniform(Value *V) {
995 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
998 InnerLoopVectorizer::VectorParts&
999 InnerLoopVectorizer::getVectorValue(Value *V) {
1000 assert(V != Induction && "The new induction variable should not be used.");
1001 assert(!V->getType()->isVectorTy() && "Can't widen a vector");
1003 // If we have this scalar in the map, return it.
1004 if (WidenMap.has(V))
1005 return WidenMap.get(V);
1007 // If this scalar is unknown, assume that it is a constant or that it is
1008 // loop invariant. Broadcast V and save the value for future uses.
1009 Value *B = getBroadcastInstrs(V);
1010 return WidenMap.splat(V, B);
1013 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
1014 assert(Vec->getType()->isVectorTy() && "Invalid type");
1015 SmallVector<Constant*, 8> ShuffleMask;
1016 for (unsigned i = 0; i < VF; ++i)
1017 ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
1019 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
1020 ConstantVector::get(ShuffleMask),
1025 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr,
1026 LoopVectorizationLegality *Legal) {
1027 // Attempt to issue a wide load.
1028 LoadInst *LI = dyn_cast<LoadInst>(Instr);
1029 StoreInst *SI = dyn_cast<StoreInst>(Instr);
1031 assert((LI || SI) && "Invalid Load/Store instruction");
1033 Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType();
1034 Type *DataTy = VectorType::get(ScalarDataTy, VF);
1035 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
1036 unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment();
1038 // If the pointer is loop invariant or if it is non consecutive,
1039 // scalarize the load.
1040 int Stride = Legal->isConsecutivePtr(Ptr);
1041 bool Reverse = Stride < 0;
1042 bool UniformLoad = LI && Legal->isUniform(Ptr);
1043 if (Stride == 0 || UniformLoad)
1044 return scalarizeInstruction(Instr);
1046 Constant *Zero = Builder.getInt32(0);
1047 VectorParts &Entry = WidenMap.get(Instr);
1049 // Handle consecutive loads/stores.
1050 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1051 if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) {
1052 Value *PtrOperand = Gep->getPointerOperand();
1053 Value *FirstBasePtr = getVectorValue(PtrOperand)[0];
1054 FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero);
1056 // Create the new GEP with the new induction variable.
1057 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1058 Gep2->setOperand(0, FirstBasePtr);
1059 Gep2->setName("gep.indvar.base");
1060 Ptr = Builder.Insert(Gep2);
1062 assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()),
1063 OrigLoop) && "Base ptr must be invariant");
1065 // The last index does not have to be the induction. It can be
1066 // consecutive and be a function of the index. For example A[I+1];
1067 unsigned NumOperands = Gep->getNumOperands();
1069 Value *LastGepOperand = Gep->getOperand(NumOperands - 1);
1070 VectorParts &GEPParts = getVectorValue(LastGepOperand);
1071 Value *LastIndex = GEPParts[0];
1072 LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
1074 // Create the new GEP with the new induction variable.
1075 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1076 Gep2->setOperand(NumOperands - 1, LastIndex);
1077 Gep2->setName("gep.indvar.idx");
1078 Ptr = Builder.Insert(Gep2);
1080 // Use the induction element ptr.
1081 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1082 VectorParts &PtrVal = getVectorValue(Ptr);
1083 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
1088 assert(!Legal->isUniform(SI->getPointerOperand()) &&
1089 "We do not allow storing to uniform addresses");
1091 VectorParts &StoredVal = getVectorValue(SI->getValueOperand());
1092 for (unsigned Part = 0; Part < UF; ++Part) {
1093 // Calculate the pointer for the specific unroll-part.
1094 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1097 // If we store to reverse consecutive memory locations then we need
1098 // to reverse the order of elements in the stored value.
1099 StoredVal[Part] = reverseVector(StoredVal[Part]);
1100 // If the address is consecutive but reversed, then the
1101 // wide store needs to start at the last vector element.
1102 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1103 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1106 Value *VecPtr = Builder.CreateBitCast(PartPtr, DataTy->getPointerTo());
1107 Builder.CreateStore(StoredVal[Part], VecPtr)->setAlignment(Alignment);
1111 for (unsigned Part = 0; Part < UF; ++Part) {
1112 // Calculate the pointer for the specific unroll-part.
1113 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1116 // If the address is consecutive but reversed, then the
1117 // wide store needs to start at the last vector element.
1118 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1119 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1122 Value *VecPtr = Builder.CreateBitCast(PartPtr, DataTy->getPointerTo());
1123 Value *LI = Builder.CreateLoad(VecPtr, "wide.load");
1124 cast<LoadInst>(LI)->setAlignment(Alignment);
1125 Entry[Part] = Reverse ? reverseVector(LI) : LI;
1129 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr) {
1130 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
1131 // Holds vector parameters or scalars, in case of uniform vals.
1132 SmallVector<VectorParts, 4> Params;
1134 // Find all of the vectorized parameters.
1135 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1136 Value *SrcOp = Instr->getOperand(op);
1138 // If we are accessing the old induction variable, use the new one.
1139 if (SrcOp == OldInduction) {
1140 Params.push_back(getVectorValue(SrcOp));
1144 // Try using previously calculated values.
1145 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
1147 // If the src is an instruction that appeared earlier in the basic block
1148 // then it should already be vectorized.
1149 if (SrcInst && OrigLoop->contains(SrcInst)) {
1150 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
1151 // The parameter is a vector value from earlier.
1152 Params.push_back(WidenMap.get(SrcInst));
1154 // The parameter is a scalar from outside the loop. Maybe even a constant.
1155 VectorParts Scalars;
1156 Scalars.append(UF, SrcOp);
1157 Params.push_back(Scalars);
1161 assert(Params.size() == Instr->getNumOperands() &&
1162 "Invalid number of operands");
1164 // Does this instruction return a value ?
1165 bool IsVoidRetTy = Instr->getType()->isVoidTy();
1167 Value *UndefVec = IsVoidRetTy ? 0 :
1168 UndefValue::get(VectorType::get(Instr->getType(), VF));
1169 // Create a new entry in the WidenMap and initialize it to Undef or Null.
1170 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
1172 // For each scalar that we create:
1173 for (unsigned Width = 0; Width < VF; ++Width) {
1174 // For each vector unroll 'part':
1175 for (unsigned Part = 0; Part < UF; ++Part) {
1176 Instruction *Cloned = Instr->clone();
1178 Cloned->setName(Instr->getName() + ".cloned");
1179 // Replace the operands of the cloned instrucions with extracted scalars.
1180 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1181 Value *Op = Params[op][Part];
1182 // Param is a vector. Need to extract the right lane.
1183 if (Op->getType()->isVectorTy())
1184 Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
1185 Cloned->setOperand(op, Op);
1188 // Place the cloned scalar in the new loop.
1189 Builder.Insert(Cloned);
1191 // If the original scalar returns a value we need to place it in a vector
1192 // so that future users will be able to use it.
1194 VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
1195 Builder.getInt32(Width));
1201 InnerLoopVectorizer::addRuntimeCheck(LoopVectorizationLegality *Legal,
1203 LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck =
1204 Legal->getRuntimePointerCheck();
1206 if (!PtrRtCheck->Need)
1209 Instruction *MemoryRuntimeCheck = 0;
1210 unsigned NumPointers = PtrRtCheck->Pointers.size();
1211 SmallVector<Value* , 2> Starts;
1212 SmallVector<Value* , 2> Ends;
1214 SCEVExpander Exp(*SE, "induction");
1216 // Use this type for pointer arithmetic.
1217 Type* PtrArithTy = Type::getInt8PtrTy(Loc->getContext(), 0);
1219 for (unsigned i = 0; i < NumPointers; ++i) {
1220 Value *Ptr = PtrRtCheck->Pointers[i];
1221 const SCEV *Sc = SE->getSCEV(Ptr);
1223 if (SE->isLoopInvariant(Sc, OrigLoop)) {
1224 DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" <<
1226 Starts.push_back(Ptr);
1227 Ends.push_back(Ptr);
1229 DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr <<"\n");
1231 Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc);
1232 Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
1233 Starts.push_back(Start);
1234 Ends.push_back(End);
1238 IRBuilder<> ChkBuilder(Loc);
1240 for (unsigned i = 0; i < NumPointers; ++i) {
1241 for (unsigned j = i+1; j < NumPointers; ++j) {
1242 Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy, "bc");
1243 Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy, "bc");
1244 Value *End0 = ChkBuilder.CreateBitCast(Ends[i], PtrArithTy, "bc");
1245 Value *End1 = ChkBuilder.CreateBitCast(Ends[j], PtrArithTy, "bc");
1247 Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
1248 Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
1249 Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1250 if (MemoryRuntimeCheck)
1251 IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict,
1254 MemoryRuntimeCheck = cast<Instruction>(IsConflict);
1258 return MemoryRuntimeCheck;
1262 InnerLoopVectorizer::createEmptyLoop(LoopVectorizationLegality *Legal) {
1264 In this function we generate a new loop. The new loop will contain
1265 the vectorized instructions while the old loop will continue to run the
1268 [ ] <-- vector loop bypass (may consist of multiple blocks).
1271 | [ ] <-- vector pre header.
1275 | [ ]_| <-- vector loop.
1278 >[ ] <--- middle-block.
1281 | [ ] <--- new preheader.
1285 | [ ]_| <-- old scalar loop to handle remainder.
1288 >[ ] <-- exit block.
1292 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
1293 BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
1294 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
1295 assert(ExitBlock && "Must have an exit block");
1297 // Some loops have a single integer induction variable, while other loops
1298 // don't. One example is c++ iterators that often have multiple pointer
1299 // induction variables. In the code below we also support a case where we
1300 // don't have a single induction variable.
1301 OldInduction = Legal->getInduction();
1302 Type *IdxTy = OldInduction ? OldInduction->getType() :
1303 DL->getIntPtrType(SE->getContext());
1305 // Find the loop boundaries.
1306 const SCEV *ExitCount = SE->getExitCount(OrigLoop, OrigLoop->getLoopLatch());
1307 assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
1309 // Get the total trip count from the count by adding 1.
1310 ExitCount = SE->getAddExpr(ExitCount,
1311 SE->getConstant(ExitCount->getType(), 1));
1313 // Expand the trip count and place the new instructions in the preheader.
1314 // Notice that the pre-header does not change, only the loop body.
1315 SCEVExpander Exp(*SE, "induction");
1317 // Count holds the overall loop count (N).
1318 Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
1319 BypassBlock->getTerminator());
1321 // The loop index does not have to start at Zero. Find the original start
1322 // value from the induction PHI node. If we don't have an induction variable
1323 // then we know that it starts at zero.
1324 Value *StartIdx = OldInduction ?
1325 OldInduction->getIncomingValueForBlock(BypassBlock):
1326 ConstantInt::get(IdxTy, 0);
1328 assert(BypassBlock && "Invalid loop structure");
1329 LoopBypassBlocks.push_back(BypassBlock);
1331 // Split the single block loop into the two loop structure described above.
1332 BasicBlock *VectorPH =
1333 BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
1334 BasicBlock *VecBody =
1335 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
1336 BasicBlock *MiddleBlock =
1337 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
1338 BasicBlock *ScalarPH =
1339 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
1341 // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
1343 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
1345 // Generate the induction variable.
1346 Induction = Builder.CreatePHI(IdxTy, 2, "index");
1347 // The loop step is equal to the vectorization factor (num of SIMD elements)
1348 // times the unroll factor (num of SIMD instructions).
1349 Constant *Step = ConstantInt::get(IdxTy, VF * UF);
1351 // This is the IR builder that we use to add all of the logic for bypassing
1352 // the new vector loop.
1353 IRBuilder<> BypassBuilder(BypassBlock->getTerminator());
1355 // We may need to extend the index in case there is a type mismatch.
1356 // We know that the count starts at zero and does not overflow.
1357 if (Count->getType() != IdxTy) {
1358 // The exit count can be of pointer type. Convert it to the correct
1360 if (ExitCount->getType()->isPointerTy())
1361 Count = BypassBuilder.CreatePointerCast(Count, IdxTy, "ptrcnt.to.int");
1363 Count = BypassBuilder.CreateZExtOrTrunc(Count, IdxTy, "cnt.cast");
1366 // Add the start index to the loop count to get the new end index.
1367 Value *IdxEnd = BypassBuilder.CreateAdd(Count, StartIdx, "end.idx");
1369 // Now we need to generate the expression for N - (N % VF), which is
1370 // the part that the vectorized body will execute.
1371 Value *R = BypassBuilder.CreateURem(Count, Step, "n.mod.vf");
1372 Value *CountRoundDown = BypassBuilder.CreateSub(Count, R, "n.vec");
1373 Value *IdxEndRoundDown = BypassBuilder.CreateAdd(CountRoundDown, StartIdx,
1374 "end.idx.rnd.down");
1376 // Now, compare the new count to zero. If it is zero skip the vector loop and
1377 // jump to the scalar loop.
1378 Value *Cmp = BypassBuilder.CreateICmpEQ(IdxEndRoundDown, StartIdx,
1381 BasicBlock *LastBypassBlock = BypassBlock;
1383 // Generate the code that checks in runtime if arrays overlap. We put the
1384 // checks into a separate block to make the more common case of few elements
1386 Instruction *MemRuntimeCheck = addRuntimeCheck(Legal,
1387 BypassBlock->getTerminator());
1388 if (MemRuntimeCheck) {
1389 // Create a new block containing the memory check.
1390 BasicBlock *CheckBlock = BypassBlock->splitBasicBlock(MemRuntimeCheck,
1392 LoopBypassBlocks.push_back(CheckBlock);
1394 // Replace the branch into the memory check block with a conditional branch
1395 // for the "few elements case".
1396 Instruction *OldTerm = BypassBlock->getTerminator();
1397 BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
1398 OldTerm->eraseFromParent();
1400 Cmp = MemRuntimeCheck;
1401 LastBypassBlock = CheckBlock;
1404 LastBypassBlock->getTerminator()->eraseFromParent();
1405 BranchInst::Create(MiddleBlock, VectorPH, Cmp,
1408 // We are going to resume the execution of the scalar loop.
1409 // Go over all of the induction variables that we found and fix the
1410 // PHIs that are left in the scalar version of the loop.
1411 // The starting values of PHI nodes depend on the counter of the last
1412 // iteration in the vectorized loop.
1413 // If we come from a bypass edge then we need to start from the original
1416 // This variable saves the new starting index for the scalar loop.
1417 PHINode *ResumeIndex = 0;
1418 LoopVectorizationLegality::InductionList::iterator I, E;
1419 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
1420 for (I = List->begin(), E = List->end(); I != E; ++I) {
1421 PHINode *OrigPhi = I->first;
1422 LoopVectorizationLegality::InductionInfo II = I->second;
1423 PHINode *ResumeVal = PHINode::Create(OrigPhi->getType(), 2, "resume.val",
1424 MiddleBlock->getTerminator());
1425 Value *EndValue = 0;
1427 case LoopVectorizationLegality::IK_NoInduction:
1428 llvm_unreachable("Unknown induction");
1429 case LoopVectorizationLegality::IK_IntInduction: {
1430 // Handle the integer induction counter:
1431 assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
1432 assert(OrigPhi == OldInduction && "Unknown integer PHI");
1433 // We know what the end value is.
1434 EndValue = IdxEndRoundDown;
1435 // We also know which PHI node holds it.
1436 ResumeIndex = ResumeVal;
1439 case LoopVectorizationLegality::IK_ReverseIntInduction: {
1440 // Convert the CountRoundDown variable to the PHI size.
1441 unsigned CRDSize = CountRoundDown->getType()->getScalarSizeInBits();
1442 unsigned IISize = II.StartValue->getType()->getScalarSizeInBits();
1443 Value *CRD = CountRoundDown;
1444 if (CRDSize > IISize)
1445 CRD = CastInst::Create(Instruction::Trunc, CountRoundDown,
1446 II.StartValue->getType(), "tr.crd",
1447 LoopBypassBlocks.back()->getTerminator());
1448 else if (CRDSize < IISize)
1449 CRD = CastInst::Create(Instruction::SExt, CountRoundDown,
1450 II.StartValue->getType(),
1452 LoopBypassBlocks.back()->getTerminator());
1453 // Handle reverse integer induction counter:
1455 BinaryOperator::CreateSub(II.StartValue, CRD, "rev.ind.end",
1456 LoopBypassBlocks.back()->getTerminator());
1459 case LoopVectorizationLegality::IK_PtrInduction: {
1460 // For pointer induction variables, calculate the offset using
1463 GetElementPtrInst::Create(II.StartValue, CountRoundDown, "ptr.ind.end",
1464 LoopBypassBlocks.back()->getTerminator());
1467 case LoopVectorizationLegality::IK_ReversePtrInduction: {
1468 // The value at the end of the loop for the reverse pointer is calculated
1469 // by creating a GEP with a negative index starting from the start value.
1470 Value *Zero = ConstantInt::get(CountRoundDown->getType(), 0);
1471 Value *NegIdx = BinaryOperator::CreateSub(Zero, CountRoundDown,
1473 LoopBypassBlocks.back()->getTerminator());
1474 EndValue = GetElementPtrInst::Create(II.StartValue, NegIdx,
1476 LoopBypassBlocks.back()->getTerminator());
1481 // The new PHI merges the original incoming value, in case of a bypass,
1482 // or the value at the end of the vectorized loop.
1483 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
1484 ResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
1485 ResumeVal->addIncoming(EndValue, VecBody);
1487 // Fix the scalar body counter (PHI node).
1488 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
1489 OrigPhi->setIncomingValue(BlockIdx, ResumeVal);
1492 // If we are generating a new induction variable then we also need to
1493 // generate the code that calculates the exit value. This value is not
1494 // simply the end of the counter because we may skip the vectorized body
1495 // in case of a runtime check.
1497 assert(!ResumeIndex && "Unexpected resume value found");
1498 ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
1499 MiddleBlock->getTerminator());
1500 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
1501 ResumeIndex->addIncoming(StartIdx, LoopBypassBlocks[I]);
1502 ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
1505 // Make sure that we found the index where scalar loop needs to continue.
1506 assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
1507 "Invalid resume Index");
1509 // Add a check in the middle block to see if we have completed
1510 // all of the iterations in the first vector loop.
1511 // If (N - N%VF) == N, then we *don't* need to run the remainder.
1512 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
1513 ResumeIndex, "cmp.n",
1514 MiddleBlock->getTerminator());
1516 BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
1517 // Remove the old terminator.
1518 MiddleBlock->getTerminator()->eraseFromParent();
1520 // Create i+1 and fill the PHINode.
1521 Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
1522 Induction->addIncoming(StartIdx, VectorPH);
1523 Induction->addIncoming(NextIdx, VecBody);
1524 // Create the compare.
1525 Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
1526 Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
1528 // Now we have two terminators. Remove the old one from the block.
1529 VecBody->getTerminator()->eraseFromParent();
1531 // Get ready to start creating new instructions into the vectorized body.
1532 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
1534 // Create and register the new vector loop.
1535 Loop* Lp = new Loop();
1536 Loop *ParentLoop = OrigLoop->getParentLoop();
1538 // Insert the new loop into the loop nest and register the new basic blocks.
1540 ParentLoop->addChildLoop(Lp);
1541 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
1542 ParentLoop->addBasicBlockToLoop(LoopBypassBlocks[I], LI->getBase());
1543 ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
1544 ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
1545 ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
1547 LI->addTopLevelLoop(Lp);
1550 Lp->addBasicBlockToLoop(VecBody, LI->getBase());
1553 LoopVectorPreHeader = VectorPH;
1554 LoopScalarPreHeader = ScalarPH;
1555 LoopMiddleBlock = MiddleBlock;
1556 LoopExitBlock = ExitBlock;
1557 LoopVectorBody = VecBody;
1558 LoopScalarBody = OldBasicBlock;
1561 /// This function returns the identity element (or neutral element) for
1562 /// the operation K.
1564 getReductionIdentity(LoopVectorizationLegality::ReductionKind K, Type *Tp) {
1566 case LoopVectorizationLegality:: RK_IntegerXor:
1567 case LoopVectorizationLegality:: RK_IntegerAdd:
1568 case LoopVectorizationLegality:: RK_IntegerOr:
1569 // Adding, Xoring, Oring zero to a number does not change it.
1570 return ConstantInt::get(Tp, 0);
1571 case LoopVectorizationLegality:: RK_IntegerMult:
1572 // Multiplying a number by 1 does not change it.
1573 return ConstantInt::get(Tp, 1);
1574 case LoopVectorizationLegality:: RK_IntegerAnd:
1575 // AND-ing a number with an all-1 value does not change it.
1576 return ConstantInt::get(Tp, -1, true);
1577 case LoopVectorizationLegality:: RK_FloatMult:
1578 // Multiplying a number by 1 does not change it.
1579 return ConstantFP::get(Tp, 1.0L);
1580 case LoopVectorizationLegality:: RK_FloatAdd:
1581 // Adding zero to a number does not change it.
1582 return ConstantFP::get(Tp, 0.0L);
1584 llvm_unreachable("Unknown reduction kind");
1589 isTriviallyVectorizableIntrinsic(Instruction *Inst) {
1590 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst);
1593 switch (II->getIntrinsicID()) {
1594 case Intrinsic::sqrt:
1595 case Intrinsic::sin:
1596 case Intrinsic::cos:
1597 case Intrinsic::exp:
1598 case Intrinsic::exp2:
1599 case Intrinsic::log:
1600 case Intrinsic::log10:
1601 case Intrinsic::log2:
1602 case Intrinsic::fabs:
1603 case Intrinsic::floor:
1604 case Intrinsic::ceil:
1605 case Intrinsic::trunc:
1606 case Intrinsic::rint:
1607 case Intrinsic::nearbyint:
1608 case Intrinsic::pow:
1609 case Intrinsic::fma:
1610 case Intrinsic::fmuladd:
1618 /// This function translates the reduction kind to an LLVM binary operator.
1619 static Instruction::BinaryOps
1620 getReductionBinOp(LoopVectorizationLegality::ReductionKind Kind) {
1622 case LoopVectorizationLegality::RK_IntegerAdd:
1623 return Instruction::Add;
1624 case LoopVectorizationLegality::RK_IntegerMult:
1625 return Instruction::Mul;
1626 case LoopVectorizationLegality::RK_IntegerOr:
1627 return Instruction::Or;
1628 case LoopVectorizationLegality::RK_IntegerAnd:
1629 return Instruction::And;
1630 case LoopVectorizationLegality::RK_IntegerXor:
1631 return Instruction::Xor;
1632 case LoopVectorizationLegality::RK_FloatMult:
1633 return Instruction::FMul;
1634 case LoopVectorizationLegality::RK_FloatAdd:
1635 return Instruction::FAdd;
1637 llvm_unreachable("Unknown reduction operation");
1642 InnerLoopVectorizer::vectorizeLoop(LoopVectorizationLegality *Legal) {
1643 //===------------------------------------------------===//
1645 // Notice: any optimization or new instruction that go
1646 // into the code below should be also be implemented in
1649 //===------------------------------------------------===//
1650 Constant *Zero = Builder.getInt32(0);
1652 // In order to support reduction variables we need to be able to vectorize
1653 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
1654 // stages. First, we create a new vector PHI node with no incoming edges.
1655 // We use this value when we vectorize all of the instructions that use the
1656 // PHI. Next, after all of the instructions in the block are complete we
1657 // add the new incoming edges to the PHI. At this point all of the
1658 // instructions in the basic block are vectorized, so we can use them to
1659 // construct the PHI.
1660 PhiVector RdxPHIsToFix;
1662 // Scan the loop in a topological order to ensure that defs are vectorized
1664 LoopBlocksDFS DFS(OrigLoop);
1667 // Vectorize all of the blocks in the original loop.
1668 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
1669 be = DFS.endRPO(); bb != be; ++bb)
1670 vectorizeBlockInLoop(Legal, *bb, &RdxPHIsToFix);
1672 // At this point every instruction in the original loop is widened to
1673 // a vector form. We are almost done. Now, we need to fix the PHI nodes
1674 // that we vectorized. The PHI nodes are currently empty because we did
1675 // not want to introduce cycles. Notice that the remaining PHI nodes
1676 // that we need to fix are reduction variables.
1678 // Create the 'reduced' values for each of the induction vars.
1679 // The reduced values are the vector values that we scalarize and combine
1680 // after the loop is finished.
1681 for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
1683 PHINode *RdxPhi = *it;
1684 assert(RdxPhi && "Unable to recover vectorized PHI");
1686 // Find the reduction variable descriptor.
1687 assert(Legal->getReductionVars()->count(RdxPhi) &&
1688 "Unable to find the reduction variable");
1689 LoopVectorizationLegality::ReductionDescriptor RdxDesc =
1690 (*Legal->getReductionVars())[RdxPhi];
1692 // We need to generate a reduction vector from the incoming scalar.
1693 // To do so, we need to generate the 'identity' vector and overide
1694 // one of the elements with the incoming scalar reduction. We need
1695 // to do it in the vector-loop preheader.
1696 Builder.SetInsertPoint(LoopBypassBlocks.back()->getTerminator());
1698 // This is the vector-clone of the value that leaves the loop.
1699 VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
1700 Type *VecTy = VectorExit[0]->getType();
1702 // Find the reduction identity variable. Zero for addition, or, xor,
1703 // one for multiplication, -1 for And.
1704 Constant *Iden = getReductionIdentity(RdxDesc.Kind, VecTy->getScalarType());
1705 Constant *Identity = ConstantVector::getSplat(VF, Iden);
1707 // This vector is the Identity vector where the first element is the
1708 // incoming scalar reduction.
1709 Value *VectorStart = Builder.CreateInsertElement(Identity,
1710 RdxDesc.StartValue, Zero);
1712 // Fix the vector-loop phi.
1713 // We created the induction variable so we know that the
1714 // preheader is the first entry.
1715 BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
1717 // Reductions do not have to start at zero. They can start with
1718 // any loop invariant values.
1719 VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
1720 BasicBlock *Latch = OrigLoop->getLoopLatch();
1721 Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
1722 VectorParts &Val = getVectorValue(LoopVal);
1723 for (unsigned part = 0; part < UF; ++part) {
1724 // Make sure to add the reduction stat value only to the
1725 // first unroll part.
1726 Value *StartVal = (part == 0) ? VectorStart : Identity;
1727 cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal, VecPreheader);
1728 cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part], LoopVectorBody);
1731 // Before each round, move the insertion point right between
1732 // the PHIs and the values we are going to write.
1733 // This allows us to write both PHINodes and the extractelement
1735 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
1737 VectorParts RdxParts;
1738 for (unsigned part = 0; part < UF; ++part) {
1739 // This PHINode contains the vectorized reduction variable, or
1740 // the initial value vector, if we bypass the vector loop.
1741 VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr);
1742 PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
1743 Value *StartVal = (part == 0) ? VectorStart : Identity;
1744 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
1745 NewPhi->addIncoming(StartVal, LoopBypassBlocks[I]);
1746 NewPhi->addIncoming(RdxExitVal[part], LoopVectorBody);
1747 RdxParts.push_back(NewPhi);
1750 // Reduce all of the unrolled parts into a single vector.
1751 Value *ReducedPartRdx = RdxParts[0];
1752 for (unsigned part = 1; part < UF; ++part) {
1753 Instruction::BinaryOps Op = getReductionBinOp(RdxDesc.Kind);
1754 ReducedPartRdx = Builder.CreateBinOp(Op, RdxParts[part], ReducedPartRdx,
1758 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
1759 // and vector ops, reducing the set of values being computed by half each
1761 assert(isPowerOf2_32(VF) &&
1762 "Reduction emission only supported for pow2 vectors!");
1763 Value *TmpVec = ReducedPartRdx;
1764 SmallVector<Constant*, 32> ShuffleMask(VF, 0);
1765 for (unsigned i = VF; i != 1; i >>= 1) {
1766 // Move the upper half of the vector to the lower half.
1767 for (unsigned j = 0; j != i/2; ++j)
1768 ShuffleMask[j] = Builder.getInt32(i/2 + j);
1770 // Fill the rest of the mask with undef.
1771 std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
1772 UndefValue::get(Builder.getInt32Ty()));
1775 Builder.CreateShuffleVector(TmpVec,
1776 UndefValue::get(TmpVec->getType()),
1777 ConstantVector::get(ShuffleMask),
1780 Instruction::BinaryOps Op = getReductionBinOp(RdxDesc.Kind);
1781 TmpVec = Builder.CreateBinOp(Op, TmpVec, Shuf, "bin.rdx");
1784 // The result is in the first element of the vector.
1785 Value *Scalar0 = Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
1787 // Now, we need to fix the users of the reduction variable
1788 // inside and outside of the scalar remainder loop.
1789 // We know that the loop is in LCSSA form. We need to update the
1790 // PHI nodes in the exit blocks.
1791 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
1792 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
1793 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
1794 if (!LCSSAPhi) continue;
1796 // All PHINodes need to have a single entry edge, or two if
1797 // we already fixed them.
1798 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
1800 // We found our reduction value exit-PHI. Update it with the
1801 // incoming bypass edge.
1802 if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
1803 // Add an edge coming from the bypass.
1804 LCSSAPhi->addIncoming(Scalar0, LoopMiddleBlock);
1807 }// end of the LCSSA phi scan.
1809 // Fix the scalar loop reduction variable with the incoming reduction sum
1810 // from the vector body and from the backedge value.
1811 int IncomingEdgeBlockIdx =
1812 (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
1813 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
1814 // Pick the other block.
1815 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
1816 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, Scalar0);
1817 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
1818 }// end of for each redux variable.
1820 // The Loop exit block may have single value PHI nodes where the incoming
1821 // value is 'undef'. While vectorizing we only handled real values that
1822 // were defined inside the loop. Here we handle the 'undef case'.
1824 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
1825 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
1826 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
1827 if (!LCSSAPhi) continue;
1828 if (LCSSAPhi->getNumIncomingValues() == 1)
1829 LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
1834 InnerLoopVectorizer::VectorParts
1835 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
1836 assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
1839 VectorParts SrcMask = createBlockInMask(Src);
1841 // The terminator has to be a branch inst!
1842 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
1843 assert(BI && "Unexpected terminator found");
1845 if (BI->isConditional()) {
1846 VectorParts EdgeMask = getVectorValue(BI->getCondition());
1848 if (BI->getSuccessor(0) != Dst)
1849 for (unsigned part = 0; part < UF; ++part)
1850 EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
1852 for (unsigned part = 0; part < UF; ++part)
1853 EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
1860 InnerLoopVectorizer::VectorParts
1861 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
1862 assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
1864 // Loop incoming mask is all-one.
1865 if (OrigLoop->getHeader() == BB) {
1866 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
1867 return getVectorValue(C);
1870 // This is the block mask. We OR all incoming edges, and with zero.
1871 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
1872 VectorParts BlockMask = getVectorValue(Zero);
1875 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
1876 VectorParts EM = createEdgeMask(*it, BB);
1877 for (unsigned part = 0; part < UF; ++part)
1878 BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
1885 InnerLoopVectorizer::vectorizeBlockInLoop(LoopVectorizationLegality *Legal,
1886 BasicBlock *BB, PhiVector *PV) {
1887 // For each instruction in the old loop.
1888 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1889 VectorParts &Entry = WidenMap.get(it);
1890 switch (it->getOpcode()) {
1891 case Instruction::Br:
1892 // Nothing to do for PHIs and BR, since we already took care of the
1893 // loop control flow instructions.
1895 case Instruction::PHI:{
1896 PHINode* P = cast<PHINode>(it);
1897 // Handle reduction variables:
1898 if (Legal->getReductionVars()->count(P)) {
1899 for (unsigned part = 0; part < UF; ++part) {
1900 // This is phase one of vectorizing PHIs.
1901 Type *VecTy = VectorType::get(it->getType(), VF);
1902 Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
1903 LoopVectorBody-> getFirstInsertionPt());
1909 // Check for PHI nodes that are lowered to vector selects.
1910 if (P->getParent() != OrigLoop->getHeader()) {
1911 // We know that all PHIs in non header blocks are converted into
1912 // selects, so we don't have to worry about the insertion order and we
1913 // can just use the builder.
1915 // At this point we generate the predication tree. There may be
1916 // duplications since this is a simple recursive scan, but future
1917 // optimizations will clean it up.
1918 VectorParts Cond = createEdgeMask(P->getIncomingBlock(0),
1921 for (unsigned part = 0; part < UF; ++part) {
1922 VectorParts &In0 = getVectorValue(P->getIncomingValue(0));
1923 VectorParts &In1 = getVectorValue(P->getIncomingValue(1));
1924 Entry[part] = Builder.CreateSelect(Cond[part], In0[part], In1[part],
1930 // This PHINode must be an induction variable.
1931 // Make sure that we know about it.
1932 assert(Legal->getInductionVars()->count(P) &&
1933 "Not an induction variable");
1935 LoopVectorizationLegality::InductionInfo II =
1936 Legal->getInductionVars()->lookup(P);
1939 case LoopVectorizationLegality::IK_NoInduction:
1940 llvm_unreachable("Unknown induction");
1941 case LoopVectorizationLegality::IK_IntInduction: {
1942 assert(P == OldInduction && "Unexpected PHI");
1943 Value *Broadcasted = getBroadcastInstrs(Induction);
1944 // After broadcasting the induction variable we need to make the
1945 // vector consecutive by adding 0, 1, 2 ...
1946 for (unsigned part = 0; part < UF; ++part)
1947 Entry[part] = getConsecutiveVector(Broadcasted, VF * part, false);
1950 case LoopVectorizationLegality::IK_ReverseIntInduction:
1951 case LoopVectorizationLegality::IK_PtrInduction:
1952 case LoopVectorizationLegality::IK_ReversePtrInduction:
1953 // Handle reverse integer and pointer inductions.
1954 Value *StartIdx = 0;
1955 // If we have a single integer induction variable then use it.
1956 // Otherwise, start counting at zero.
1958 LoopVectorizationLegality::InductionInfo OldII =
1959 Legal->getInductionVars()->lookup(OldInduction);
1960 StartIdx = OldII.StartValue;
1962 StartIdx = ConstantInt::get(Induction->getType(), 0);
1964 // This is the normalized GEP that starts counting at zero.
1965 Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
1968 // Handle the reverse integer induction variable case.
1969 if (LoopVectorizationLegality::IK_ReverseIntInduction == II.IK) {
1970 IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType());
1971 Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy,
1973 Value *ReverseInd = Builder.CreateSub(II.StartValue, CNI,
1976 // This is a new value so do not hoist it out.
1977 Value *Broadcasted = getBroadcastInstrs(ReverseInd);
1978 // After broadcasting the induction variable we need to make the
1979 // vector consecutive by adding ... -3, -2, -1, 0.
1980 for (unsigned part = 0; part < UF; ++part)
1981 Entry[part] = getConsecutiveVector(Broadcasted, -VF * part, true);
1985 // Handle the pointer induction variable case.
1986 assert(P->getType()->isPointerTy() && "Unexpected type.");
1988 // Is this a reverse induction ptr or a consecutive induction ptr.
1989 bool Reverse = (LoopVectorizationLegality::IK_ReversePtrInduction ==
1992 // This is the vector of results. Notice that we don't generate
1993 // vector geps because scalar geps result in better code.
1994 for (unsigned part = 0; part < UF; ++part) {
1995 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
1996 for (unsigned int i = 0; i < VF; ++i) {
1997 int EltIndex = (i + part * VF) * (Reverse ? -1 : 1);
1998 Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
2001 GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
2003 GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx");
2005 Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
2007 VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
2008 Builder.getInt32(i),
2011 Entry[part] = VecVal;
2018 case Instruction::Add:
2019 case Instruction::FAdd:
2020 case Instruction::Sub:
2021 case Instruction::FSub:
2022 case Instruction::Mul:
2023 case Instruction::FMul:
2024 case Instruction::UDiv:
2025 case Instruction::SDiv:
2026 case Instruction::FDiv:
2027 case Instruction::URem:
2028 case Instruction::SRem:
2029 case Instruction::FRem:
2030 case Instruction::Shl:
2031 case Instruction::LShr:
2032 case Instruction::AShr:
2033 case Instruction::And:
2034 case Instruction::Or:
2035 case Instruction::Xor: {
2036 // Just widen binops.
2037 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
2038 VectorParts &A = getVectorValue(it->getOperand(0));
2039 VectorParts &B = getVectorValue(it->getOperand(1));
2041 // Use this vector value for all users of the original instruction.
2042 for (unsigned Part = 0; Part < UF; ++Part) {
2043 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
2045 // Update the NSW, NUW and Exact flags. Notice: V can be an Undef.
2046 BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V);
2047 if (VecOp && isa<OverflowingBinaryOperator>(BinOp)) {
2048 VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap());
2049 VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap());
2051 if (VecOp && isa<PossiblyExactOperator>(VecOp))
2052 VecOp->setIsExact(BinOp->isExact());
2058 case Instruction::Select: {
2060 // If the selector is loop invariant we can create a select
2061 // instruction with a scalar condition. Otherwise, use vector-select.
2062 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
2065 // The condition can be loop invariant but still defined inside the
2066 // loop. This means that we can't just use the original 'cond' value.
2067 // We have to take the 'vectorized' value and pick the first lane.
2068 // Instcombine will make this a no-op.
2069 VectorParts &Cond = getVectorValue(it->getOperand(0));
2070 VectorParts &Op0 = getVectorValue(it->getOperand(1));
2071 VectorParts &Op1 = getVectorValue(it->getOperand(2));
2072 Value *ScalarCond = Builder.CreateExtractElement(Cond[0],
2073 Builder.getInt32(0));
2074 for (unsigned Part = 0; Part < UF; ++Part) {
2075 Entry[Part] = Builder.CreateSelect(
2076 InvariantCond ? ScalarCond : Cond[Part],
2083 case Instruction::ICmp:
2084 case Instruction::FCmp: {
2085 // Widen compares. Generate vector compares.
2086 bool FCmp = (it->getOpcode() == Instruction::FCmp);
2087 CmpInst *Cmp = dyn_cast<CmpInst>(it);
2088 VectorParts &A = getVectorValue(it->getOperand(0));
2089 VectorParts &B = getVectorValue(it->getOperand(1));
2090 for (unsigned Part = 0; Part < UF; ++Part) {
2093 C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
2095 C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
2101 case Instruction::Store:
2102 case Instruction::Load:
2103 vectorizeMemoryInstruction(it, Legal);
2105 case Instruction::ZExt:
2106 case Instruction::SExt:
2107 case Instruction::FPToUI:
2108 case Instruction::FPToSI:
2109 case Instruction::FPExt:
2110 case Instruction::PtrToInt:
2111 case Instruction::IntToPtr:
2112 case Instruction::SIToFP:
2113 case Instruction::UIToFP:
2114 case Instruction::Trunc:
2115 case Instruction::FPTrunc:
2116 case Instruction::BitCast: {
2117 CastInst *CI = dyn_cast<CastInst>(it);
2118 /// Optimize the special case where the source is the induction
2119 /// variable. Notice that we can only optimize the 'trunc' case
2120 /// because: a. FP conversions lose precision, b. sext/zext may wrap,
2121 /// c. other casts depend on pointer size.
2122 if (CI->getOperand(0) == OldInduction &&
2123 it->getOpcode() == Instruction::Trunc) {
2124 Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
2126 Value *Broadcasted = getBroadcastInstrs(ScalarCast);
2127 for (unsigned Part = 0; Part < UF; ++Part)
2128 Entry[Part] = getConsecutiveVector(Broadcasted, VF * Part, false);
2131 /// Vectorize casts.
2132 Type *DestTy = VectorType::get(CI->getType()->getScalarType(), VF);
2134 VectorParts &A = getVectorValue(it->getOperand(0));
2135 for (unsigned Part = 0; Part < UF; ++Part)
2136 Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
2140 case Instruction::Call: {
2141 assert(isTriviallyVectorizableIntrinsic(it));
2142 Module *M = BB->getParent()->getParent();
2143 IntrinsicInst *II = cast<IntrinsicInst>(it);
2144 Intrinsic::ID ID = II->getIntrinsicID();
2145 for (unsigned Part = 0; Part < UF; ++Part) {
2146 SmallVector<Value*, 4> Args;
2147 for (unsigned i = 0, ie = II->getNumArgOperands(); i != ie; ++i) {
2148 VectorParts &Arg = getVectorValue(II->getArgOperand(i));
2149 Args.push_back(Arg[Part]);
2151 Type *Tys[] = { VectorType::get(II->getType()->getScalarType(), VF) };
2152 Function *F = Intrinsic::getDeclaration(M, ID, Tys);
2153 Entry[Part] = Builder.CreateCall(F, Args);
2159 // All other instructions are unsupported. Scalarize them.
2160 scalarizeInstruction(it);
2163 }// end of for_each instr.
2166 void InnerLoopVectorizer::updateAnalysis() {
2167 // Forget the original basic block.
2168 SE->forgetLoop(OrigLoop);
2170 // Update the dominator tree information.
2171 assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
2172 "Entry does not dominate exit.");
2174 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2175 DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]);
2176 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back());
2177 DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader);
2178 DT->addNewBlock(LoopMiddleBlock, LoopBypassBlocks.front());
2179 DT->addNewBlock(LoopScalarPreHeader, LoopMiddleBlock);
2180 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
2181 DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
2183 DEBUG(DT->verifyAnalysis());
2186 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
2187 if (!EnableIfConversion)
2190 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
2191 std::vector<BasicBlock*> &LoopBlocks = TheLoop->getBlocksVector();
2193 // Collect the blocks that need predication.
2194 for (unsigned i = 0, e = LoopBlocks.size(); i < e; ++i) {
2195 BasicBlock *BB = LoopBlocks[i];
2197 // We don't support switch statements inside loops.
2198 if (!isa<BranchInst>(BB->getTerminator()))
2201 // We must have at most two predecessors because we need to convert
2202 // all PHIs to selects.
2203 unsigned Preds = std::distance(pred_begin(BB), pred_end(BB));
2207 // We must be able to predicate all blocks that need to be predicated.
2208 if (blockNeedsPredication(BB) && !blockCanBePredicated(BB))
2212 // We can if-convert this loop.
2216 bool LoopVectorizationLegality::canVectorize() {
2217 assert(TheLoop->getLoopPreheader() && "No preheader!!");
2219 // We can only vectorize innermost loops.
2220 if (TheLoop->getSubLoopsVector().size())
2223 // We must have a single backedge.
2224 if (TheLoop->getNumBackEdges() != 1)
2227 // We must have a single exiting block.
2228 if (!TheLoop->getExitingBlock())
2231 unsigned NumBlocks = TheLoop->getNumBlocks();
2233 // Check if we can if-convert non single-bb loops.
2234 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
2235 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
2239 // We need to have a loop header.
2240 BasicBlock *Latch = TheLoop->getLoopLatch();
2241 DEBUG(dbgs() << "LV: Found a loop: " <<
2242 TheLoop->getHeader()->getName() << "\n");
2244 // ScalarEvolution needs to be able to find the exit count.
2245 const SCEV *ExitCount = SE->getExitCount(TheLoop, Latch);
2246 if (ExitCount == SE->getCouldNotCompute()) {
2247 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
2251 // Do not loop-vectorize loops with a tiny trip count.
2252 unsigned TC = SE->getSmallConstantTripCount(TheLoop, Latch);
2253 if (TC > 0u && TC < TinyTripCountVectorThreshold) {
2254 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " <<
2255 "This loop is not worth vectorizing.\n");
2259 // Check if we can vectorize the instructions and CFG in this loop.
2260 if (!canVectorizeInstrs()) {
2261 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
2265 // Go over each instruction and look at memory deps.
2266 if (!canVectorizeMemory()) {
2267 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
2271 // Collect all of the variables that remain uniform after vectorization.
2272 collectLoopUniforms();
2274 DEBUG(dbgs() << "LV: We can vectorize this loop" <<
2275 (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
2278 // Okay! We can vectorize. At this point we don't have any other mem analysis
2279 // which may limit our maximum vectorization factor, so just return true with
2284 bool LoopVectorizationLegality::canVectorizeInstrs() {
2285 BasicBlock *PreHeader = TheLoop->getLoopPreheader();
2286 BasicBlock *Header = TheLoop->getHeader();
2288 // For each block in the loop.
2289 for (Loop::block_iterator bb = TheLoop->block_begin(),
2290 be = TheLoop->block_end(); bb != be; ++bb) {
2292 // Scan the instructions in the block and look for hazards.
2293 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
2296 if (PHINode *Phi = dyn_cast<PHINode>(it)) {
2297 // This should not happen because the loop should be normalized.
2298 if (Phi->getNumIncomingValues() != 2) {
2299 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
2303 // Check that this PHI type is allowed.
2304 if (!Phi->getType()->isIntegerTy() &&
2305 !Phi->getType()->isFloatingPointTy() &&
2306 !Phi->getType()->isPointerTy()) {
2307 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
2311 // If this PHINode is not in the header block, then we know that we
2312 // can convert it to select during if-conversion. No need to check if
2313 // the PHIs in this block are induction or reduction variables.
2317 // This is the value coming from the preheader.
2318 Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
2319 // Check if this is an induction variable.
2320 InductionKind IK = isInductionVariable(Phi);
2322 if (IK_NoInduction != IK) {
2323 // Int inductions are special because we only allow one IV.
2324 if (IK == IK_IntInduction) {
2326 DEBUG(dbgs() << "LV: Found too many inductions."<< *Phi <<"\n");
2332 DEBUG(dbgs() << "LV: Found an induction variable.\n");
2333 Inductions[Phi] = InductionInfo(StartValue, IK);
2337 if (AddReductionVar(Phi, RK_IntegerAdd)) {
2338 DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
2341 if (AddReductionVar(Phi, RK_IntegerMult)) {
2342 DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
2345 if (AddReductionVar(Phi, RK_IntegerOr)) {
2346 DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
2349 if (AddReductionVar(Phi, RK_IntegerAnd)) {
2350 DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
2353 if (AddReductionVar(Phi, RK_IntegerXor)) {
2354 DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
2357 if (AddReductionVar(Phi, RK_FloatMult)) {
2358 DEBUG(dbgs() << "LV: Found an FMult reduction PHI."<< *Phi <<"\n");
2361 if (AddReductionVar(Phi, RK_FloatAdd)) {
2362 DEBUG(dbgs() << "LV: Found an FAdd reduction PHI."<< *Phi <<"\n");
2366 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
2368 }// end of PHI handling
2370 // We still don't handle functions.
2371 CallInst *CI = dyn_cast<CallInst>(it);
2372 if (CI && !isTriviallyVectorizableIntrinsic(it)) {
2373 DEBUG(dbgs() << "LV: Found a call site.\n");
2377 // Check that the instruction return type is vectorizable.
2378 if (!VectorType::isValidElementType(it->getType()) &&
2379 !it->getType()->isVoidTy()) {
2380 DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n");
2384 // Check that the stored type is vectorizable.
2385 if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
2386 Type *T = ST->getValueOperand()->getType();
2387 if (!VectorType::isValidElementType(T))
2391 // Reduction instructions are allowed to have exit users.
2392 // All other instructions must not have external users.
2393 if (!AllowedExit.count(it))
2394 //Check that all of the users of the loop are inside the BB.
2395 for (Value::use_iterator I = it->use_begin(), E = it->use_end();
2397 Instruction *U = cast<Instruction>(*I);
2398 // This user may be a reduction exit value.
2399 if (!TheLoop->contains(U)) {
2400 DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n");
2409 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
2410 assert(getInductionVars()->size() && "No induction variables");
2416 void LoopVectorizationLegality::collectLoopUniforms() {
2417 // We now know that the loop is vectorizable!
2418 // Collect variables that will remain uniform after vectorization.
2419 std::vector<Value*> Worklist;
2420 BasicBlock *Latch = TheLoop->getLoopLatch();
2422 // Start with the conditional branch and walk up the block.
2423 Worklist.push_back(Latch->getTerminator()->getOperand(0));
2425 while (Worklist.size()) {
2426 Instruction *I = dyn_cast<Instruction>(Worklist.back());
2427 Worklist.pop_back();
2429 // Look at instructions inside this loop.
2430 // Stop when reaching PHI nodes.
2431 // TODO: we need to follow values all over the loop, not only in this block.
2432 if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
2435 // This is a known uniform.
2438 // Insert all operands.
2439 for (int i = 0, Op = I->getNumOperands(); i < Op; ++i) {
2440 Worklist.push_back(I->getOperand(i));
2445 bool LoopVectorizationLegality::canVectorizeMemory() {
2446 typedef SmallVector<Value*, 16> ValueVector;
2447 typedef SmallPtrSet<Value*, 16> ValueSet;
2448 // Holds the Load and Store *instructions*.
2451 PtrRtCheck.Pointers.clear();
2452 PtrRtCheck.Need = false;
2455 for (Loop::block_iterator bb = TheLoop->block_begin(),
2456 be = TheLoop->block_end(); bb != be; ++bb) {
2458 // Scan the BB and collect legal loads and stores.
2459 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
2462 // If this is a load, save it. If this instruction can read from memory
2463 // but is not a load, then we quit. Notice that we don't handle function
2464 // calls that read or write.
2465 if (it->mayReadFromMemory()) {
2466 LoadInst *Ld = dyn_cast<LoadInst>(it);
2467 if (!Ld) return false;
2468 if (!Ld->isSimple()) {
2469 DEBUG(dbgs() << "LV: Found a non-simple load.\n");
2472 Loads.push_back(Ld);
2476 // Save 'store' instructions. Abort if other instructions write to memory.
2477 if (it->mayWriteToMemory()) {
2478 StoreInst *St = dyn_cast<StoreInst>(it);
2479 if (!St) return false;
2480 if (!St->isSimple()) {
2481 DEBUG(dbgs() << "LV: Found a non-simple store.\n");
2484 Stores.push_back(St);
2489 // Now we have two lists that hold the loads and the stores.
2490 // Next, we find the pointers that they use.
2492 // Check if we see any stores. If there are no stores, then we don't
2493 // care if the pointers are *restrict*.
2494 if (!Stores.size()) {
2495 DEBUG(dbgs() << "LV: Found a read-only loop!\n");
2499 // Holds the read and read-write *pointers* that we find.
2501 ValueVector ReadWrites;
2503 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
2504 // multiple times on the same object. If the ptr is accessed twice, once
2505 // for read and once for write, it will only appear once (on the write
2506 // list). This is okay, since we are going to check for conflicts between
2507 // writes and between reads and writes, but not between reads and reads.
2510 ValueVector::iterator I, IE;
2511 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
2512 StoreInst *ST = cast<StoreInst>(*I);
2513 Value* Ptr = ST->getPointerOperand();
2515 if (isUniform(Ptr)) {
2516 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
2520 // If we did *not* see this pointer before, insert it to
2521 // the read-write list. At this phase it is only a 'write' list.
2522 if (Seen.insert(Ptr))
2523 ReadWrites.push_back(Ptr);
2526 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
2527 LoadInst *LD = cast<LoadInst>(*I);
2528 Value* Ptr = LD->getPointerOperand();
2529 // If we did *not* see this pointer before, insert it to the
2530 // read list. If we *did* see it before, then it is already in
2531 // the read-write list. This allows us to vectorize expressions
2532 // such as A[i] += x; Because the address of A[i] is a read-write
2533 // pointer. This only works if the index of A[i] is consecutive.
2534 // If the address of i is unknown (for example A[B[i]]) then we may
2535 // read a few words, modify, and write a few words, and some of the
2536 // words may be written to the same address.
2537 if (Seen.insert(Ptr) || 0 == isConsecutivePtr(Ptr))
2538 Reads.push_back(Ptr);
2541 // If we write (or read-write) to a single destination and there are no
2542 // other reads in this loop then is it safe to vectorize.
2543 if (ReadWrites.size() == 1 && Reads.size() == 0) {
2544 DEBUG(dbgs() << "LV: Found a write-only loop!\n");
2548 // Find pointers with computable bounds. We are going to use this information
2549 // to place a runtime bound check.
2550 bool CanDoRT = true;
2551 for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I)
2552 if (hasComputableBounds(*I)) {
2553 PtrRtCheck.insert(SE, TheLoop, *I);
2554 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n");
2559 for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I)
2560 if (hasComputableBounds(*I)) {
2561 PtrRtCheck.insert(SE, TheLoop, *I);
2562 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n");
2568 // Check that we did not collect too many pointers or found a
2569 // unsizeable pointer.
2570 if (!CanDoRT || PtrRtCheck.Pointers.size() > RuntimeMemoryCheckThreshold) {
2576 DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
2579 bool NeedRTCheck = false;
2581 // Now that the pointers are in two lists (Reads and ReadWrites), we
2582 // can check that there are no conflicts between each of the writes and
2583 // between the writes to the reads.
2584 ValueSet WriteObjects;
2585 ValueVector TempObjects;
2587 // Check that the read-writes do not conflict with other read-write
2589 bool AllWritesIdentified = true;
2590 for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I) {
2591 GetUnderlyingObjects(*I, TempObjects, DL);
2592 for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
2594 if (!isIdentifiedObject(*it)) {
2595 DEBUG(dbgs() << "LV: Found an unidentified write ptr:"<< **it <<"\n");
2597 AllWritesIdentified = false;
2599 if (!WriteObjects.insert(*it)) {
2600 DEBUG(dbgs() << "LV: Found a possible write-write reorder:"
2605 TempObjects.clear();
2608 /// Check that the reads don't conflict with the read-writes.
2609 for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I) {
2610 GetUnderlyingObjects(*I, TempObjects, DL);
2611 for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
2613 // If all of the writes are identified then we don't care if the read
2614 // pointer is identified or not.
2615 if (!AllWritesIdentified && !isIdentifiedObject(*it)) {
2616 DEBUG(dbgs() << "LV: Found an unidentified read ptr:"<< **it <<"\n");
2619 if (WriteObjects.count(*it)) {
2620 DEBUG(dbgs() << "LV: Found a possible read/write reorder:"
2625 TempObjects.clear();
2628 PtrRtCheck.Need = NeedRTCheck;
2629 if (NeedRTCheck && !CanDoRT) {
2630 DEBUG(dbgs() << "LV: We can't vectorize because we can't find " <<
2631 "the array bounds.\n");
2636 DEBUG(dbgs() << "LV: We "<< (NeedRTCheck ? "" : "don't") <<
2637 " need a runtime memory check.\n");
2641 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
2642 ReductionKind Kind) {
2643 if (Phi->getNumIncomingValues() != 2)
2646 // Reduction variables are only found in the loop header block.
2647 if (Phi->getParent() != TheLoop->getHeader())
2650 // Obtain the reduction start value from the value that comes from the loop
2652 Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
2654 // ExitInstruction is the single value which is used outside the loop.
2655 // We only allow for a single reduction value to be used outside the loop.
2656 // This includes users of the reduction, variables (which form a cycle
2657 // which ends in the phi node).
2658 Instruction *ExitInstruction = 0;
2659 // Indicates that we found a binary operation in our scan.
2660 bool FoundBinOp = false;
2662 // Iter is our iterator. We start with the PHI node and scan for all of the
2663 // users of this instruction. All users must be instructions that can be
2664 // used as reduction variables (such as ADD). We may have a single
2665 // out-of-block user. The cycle must end with the original PHI.
2666 Instruction *Iter = Phi;
2668 // If the instruction has no users then this is a broken
2669 // chain and can't be a reduction variable.
2670 if (Iter->use_empty())
2673 // Did we find a user inside this loop already ?
2674 bool FoundInBlockUser = false;
2675 // Did we reach the initial PHI node already ?
2676 bool FoundStartPHI = false;
2678 // Is this a bin op ?
2679 FoundBinOp |= !isa<PHINode>(Iter);
2681 // For each of the *users* of iter.
2682 for (Value::use_iterator it = Iter->use_begin(), e = Iter->use_end();
2684 Instruction *U = cast<Instruction>(*it);
2685 // We already know that the PHI is a user.
2687 FoundStartPHI = true;
2691 // Check if we found the exit user.
2692 BasicBlock *Parent = U->getParent();
2693 if (!TheLoop->contains(Parent)) {
2694 // Exit if you find multiple outside users.
2695 if (ExitInstruction != 0)
2697 ExitInstruction = Iter;
2700 // We allow in-loop PHINodes which are not the original reduction PHI
2701 // node. If this PHI is the only user of Iter (happens in IF w/ no ELSE
2702 // structure) then don't skip this PHI.
2703 if (isa<PHINode>(Iter) && isa<PHINode>(U) &&
2704 U->getParent() != TheLoop->getHeader() &&
2705 TheLoop->contains(U) &&
2706 Iter->getNumUses() > 1)
2709 // We can't have multiple inside users.
2710 if (FoundInBlockUser)
2712 FoundInBlockUser = true;
2714 // Any reduction instr must be of one of the allowed kinds.
2715 if (!isReductionInstr(U, Kind))
2718 // Reductions of instructions such as Div, and Sub is only
2719 // possible if the LHS is the reduction variable.
2720 if (!U->isCommutative() && !isa<PHINode>(U) && U->getOperand(0) != Iter)
2726 // We found a reduction var if we have reached the original
2727 // phi node and we only have a single instruction with out-of-loop
2729 if (FoundStartPHI) {
2730 // This instruction is allowed to have out-of-loop users.
2731 AllowedExit.insert(ExitInstruction);
2733 // Save the description of this reduction variable.
2734 ReductionDescriptor RD(RdxStart, ExitInstruction, Kind);
2735 Reductions[Phi] = RD;
2736 // We've ended the cycle. This is a reduction variable if we have an
2737 // outside user and it has a binary op.
2738 return FoundBinOp && ExitInstruction;
2744 LoopVectorizationLegality::isReductionInstr(Instruction *I,
2745 ReductionKind Kind) {
2746 bool FP = I->getType()->isFloatingPointTy();
2747 bool FastMath = (FP && I->isCommutative() && I->isAssociative());
2749 switch (I->getOpcode()) {
2752 case Instruction::PHI:
2753 if (FP && (Kind != RK_FloatMult && Kind != RK_FloatAdd))
2757 case Instruction::Sub:
2758 case Instruction::Add:
2759 return Kind == RK_IntegerAdd;
2760 case Instruction::SDiv:
2761 case Instruction::UDiv:
2762 case Instruction::Mul:
2763 return Kind == RK_IntegerMult;
2764 case Instruction::And:
2765 return Kind == RK_IntegerAnd;
2766 case Instruction::Or:
2767 return Kind == RK_IntegerOr;
2768 case Instruction::Xor:
2769 return Kind == RK_IntegerXor;
2770 case Instruction::FMul:
2771 return Kind == RK_FloatMult && FastMath;
2772 case Instruction::FAdd:
2773 return Kind == RK_FloatAdd && FastMath;
2777 LoopVectorizationLegality::InductionKind
2778 LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
2779 Type *PhiTy = Phi->getType();
2780 // We only handle integer and pointer inductions variables.
2781 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
2782 return IK_NoInduction;
2784 // Check that the PHI is consecutive.
2785 const SCEV *PhiScev = SE->getSCEV(Phi);
2786 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
2788 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
2789 return IK_NoInduction;
2791 const SCEV *Step = AR->getStepRecurrence(*SE);
2793 // Integer inductions need to have a stride of one.
2794 if (PhiTy->isIntegerTy()) {
2796 return IK_IntInduction;
2797 if (Step->isAllOnesValue())
2798 return IK_ReverseIntInduction;
2799 return IK_NoInduction;
2802 // Calculate the pointer stride and check if it is consecutive.
2803 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
2805 return IK_NoInduction;
2807 assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
2808 uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType());
2809 if (C->getValue()->equalsInt(Size))
2810 return IK_PtrInduction;
2811 else if (C->getValue()->equalsInt(0 - Size))
2812 return IK_ReversePtrInduction;
2814 return IK_NoInduction;
2817 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
2818 Value *In0 = const_cast<Value*>(V);
2819 PHINode *PN = dyn_cast_or_null<PHINode>(In0);
2823 return Inductions.count(PN);
2826 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
2827 assert(TheLoop->contains(BB) && "Unknown block used");
2829 // Blocks that do not dominate the latch need predication.
2830 BasicBlock* Latch = TheLoop->getLoopLatch();
2831 return !DT->dominates(BB, Latch);
2834 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB) {
2835 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2836 // We don't predicate loads/stores at the moment.
2837 if (it->mayReadFromMemory() || it->mayWriteToMemory() || it->mayThrow())
2840 // The instructions below can trap.
2841 switch (it->getOpcode()) {
2843 case Instruction::UDiv:
2844 case Instruction::SDiv:
2845 case Instruction::URem:
2846 case Instruction::SRem:
2854 bool LoopVectorizationLegality::hasComputableBounds(Value *Ptr) {
2855 const SCEV *PhiScev = SE->getSCEV(Ptr);
2856 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
2860 return AR->isAffine();
2863 LoopVectorizationCostModel::VectorizationFactor
2864 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize,
2866 // Width 1 means no vectorize
2867 VectorizationFactor Factor = { 1U, 0U };
2868 if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
2869 DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
2873 // Find the trip count.
2874 unsigned TC = SE->getSmallConstantTripCount(TheLoop, TheLoop->getLoopLatch());
2875 DEBUG(dbgs() << "LV: Found trip count:"<<TC<<"\n");
2877 unsigned WidestType = getWidestType();
2878 unsigned WidestRegister = TTI.getRegisterBitWidth(true);
2879 unsigned MaxVectorSize = WidestRegister / WidestType;
2880 DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n");
2881 DEBUG(dbgs() << "LV: The Widest register is:" << WidestRegister << "bits.\n");
2883 if (MaxVectorSize == 0) {
2884 DEBUG(dbgs() << "LV: The target has no vector registers.\n");
2888 assert(MaxVectorSize <= 32 && "Did not expect to pack so many elements"
2889 " into one vector!");
2891 unsigned VF = MaxVectorSize;
2893 // If we optimize the program for size, avoid creating the tail loop.
2895 // If we are unable to calculate the trip count then don't try to vectorize.
2897 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
2901 // Find the maximum SIMD width that can fit within the trip count.
2902 VF = TC % MaxVectorSize;
2907 // If the trip count that we found modulo the vectorization factor is not
2908 // zero then we require a tail.
2910 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
2916 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
2917 DEBUG(dbgs() << "LV: Using user VF "<<UserVF<<".\n");
2919 Factor.Width = UserVF;
2923 float Cost = expectedCost(1);
2925 DEBUG(dbgs() << "LV: Scalar loop costs: "<< (int)Cost << ".\n");
2926 for (unsigned i=2; i <= VF; i*=2) {
2927 // Notice that the vector loop needs to be executed less times, so
2928 // we need to divide the cost of the vector loops by the width of
2929 // the vector elements.
2930 float VectorCost = expectedCost(i) / (float)i;
2931 DEBUG(dbgs() << "LV: Vector loop of width "<< i << " costs: " <<
2932 (int)VectorCost << ".\n");
2933 if (VectorCost < Cost) {
2939 DEBUG(dbgs() << "LV: Selecting VF = : "<< Width << ".\n");
2940 Factor.Width = Width;
2941 Factor.Cost = Width * Cost;
2945 unsigned LoopVectorizationCostModel::getWidestType() {
2946 unsigned MaxWidth = 8;
2949 for (Loop::block_iterator bb = TheLoop->block_begin(),
2950 be = TheLoop->block_end(); bb != be; ++bb) {
2951 BasicBlock *BB = *bb;
2953 // For each instruction in the loop.
2954 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2955 Type *T = it->getType();
2957 // Only examine Loads, Stores and PHINodes.
2958 if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
2961 // Examine PHI nodes that are reduction variables.
2962 if (PHINode *PN = dyn_cast<PHINode>(it))
2963 if (!Legal->getReductionVars()->count(PN))
2966 // Examine the stored values.
2968 if ((ST = dyn_cast<StoreInst>(it)))
2969 T = ST->getValueOperand()->getType();
2971 // Ignore loaded pointer types and stored pointer types that are not
2972 // consecutive. However, we do want to take consecutive stores/loads of
2973 // pointer vectors into account.
2974 if (T->isPointerTy() && isConsecutiveLoadOrStore(it))
2975 MaxWidth = std::max(MaxWidth, DL->getPointerSizeInBits());
2977 MaxWidth = std::max(MaxWidth, T->getScalarSizeInBits());
2985 LoopVectorizationCostModel::selectUnrollFactor(bool OptForSize,
2988 unsigned LoopCost) {
2990 // -- The unroll heuristics --
2991 // We unroll the loop in order to expose ILP and reduce the loop overhead.
2992 // There are many micro-architectural considerations that we can't predict
2993 // at this level. For example frontend pressure (on decode or fetch) due to
2994 // code size, or the number and capabilities of the execution ports.
2996 // We use the following heuristics to select the unroll factor:
2997 // 1. If the code has reductions the we unroll in order to break the cross
2998 // iteration dependency.
2999 // 2. If the loop is really small then we unroll in order to reduce the loop
3001 // 3. We don't unroll if we think that we will spill registers to memory due
3002 // to the increased register pressure.
3004 // Use the user preference, unless 'auto' is selected.
3008 // When we optimize for size we don't unroll.
3012 // Do not unroll loops with a relatively small trip count.
3013 unsigned TC = SE->getSmallConstantTripCount(TheLoop,
3014 TheLoop->getLoopLatch());
3015 if (TC > 1 && TC < TinyTripCountUnrollThreshold)
3018 unsigned TargetVectorRegisters = TTI.getNumberOfRegisters(true);
3019 DEBUG(dbgs() << "LV: The target has " << TargetVectorRegisters <<
3020 " vector registers\n");
3022 LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
3023 // We divide by these constants so assume that we have at least one
3024 // instruction that uses at least one register.
3025 R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
3026 R.NumInstructions = std::max(R.NumInstructions, 1U);
3028 // We calculate the unroll factor using the following formula.
3029 // Subtract the number of loop invariants from the number of available
3030 // registers. These registers are used by all of the unrolled instances.
3031 // Next, divide the remaining registers by the number of registers that is
3032 // required by the loop, in order to estimate how many parallel instances
3033 // fit without causing spills.
3034 unsigned UF = (TargetVectorRegisters - R.LoopInvariantRegs) / R.MaxLocalUsers;
3036 // Clamp the unroll factor ranges to reasonable factors.
3037 unsigned MaxUnrollSize = TTI.getMaximumUnrollFactor();
3039 // If we did not calculate the cost for VF (because the user selected the VF)
3040 // then we calculate the cost of VF here.
3042 LoopCost = expectedCost(VF);
3044 // Clamp the calculated UF to be between the 1 and the max unroll factor
3045 // that the target allows.
3046 if (UF > MaxUnrollSize)
3051 if (Legal->getReductionVars()->size()) {
3052 DEBUG(dbgs() << "LV: Unrolling because of reductions. \n");
3056 // We want to unroll tiny loops in order to reduce the loop overhead.
3057 // We assume that the cost overhead is 1 and we use the cost model
3058 // to estimate the cost of the loop and unroll until the cost of the
3059 // loop overhead is about 5% of the cost of the loop.
3060 DEBUG(dbgs() << "LV: Loop cost is "<< LoopCost <<" \n");
3061 if (LoopCost < 20) {
3062 DEBUG(dbgs() << "LV: Unrolling to reduce branch cost. \n");
3063 unsigned NewUF = 20/LoopCost + 1;
3064 return std::min(NewUF, UF);
3067 DEBUG(dbgs() << "LV: Not Unrolling. \n");
3071 LoopVectorizationCostModel::RegisterUsage
3072 LoopVectorizationCostModel::calculateRegisterUsage() {
3073 // This function calculates the register usage by measuring the highest number
3074 // of values that are alive at a single location. Obviously, this is a very
3075 // rough estimation. We scan the loop in a topological order in order and
3076 // assign a number to each instruction. We use RPO to ensure that defs are
3077 // met before their users. We assume that each instruction that has in-loop
3078 // users starts an interval. We record every time that an in-loop value is
3079 // used, so we have a list of the first and last occurrences of each
3080 // instruction. Next, we transpose this data structure into a multi map that
3081 // holds the list of intervals that *end* at a specific location. This multi
3082 // map allows us to perform a linear search. We scan the instructions linearly
3083 // and record each time that a new interval starts, by placing it in a set.
3084 // If we find this value in the multi-map then we remove it from the set.
3085 // The max register usage is the maximum size of the set.
3086 // We also search for instructions that are defined outside the loop, but are
3087 // used inside the loop. We need this number separately from the max-interval
3088 // usage number because when we unroll, loop-invariant values do not take
3090 LoopBlocksDFS DFS(TheLoop);
3094 R.NumInstructions = 0;
3096 // Each 'key' in the map opens a new interval. The values
3097 // of the map are the index of the 'last seen' usage of the
3098 // instruction that is the key.
3099 typedef DenseMap<Instruction*, unsigned> IntervalMap;
3100 // Maps instruction to its index.
3101 DenseMap<unsigned, Instruction*> IdxToInstr;
3102 // Marks the end of each interval.
3103 IntervalMap EndPoint;
3104 // Saves the list of instruction indices that are used in the loop.
3105 SmallSet<Instruction*, 8> Ends;
3106 // Saves the list of values that are used in the loop but are
3107 // defined outside the loop, such as arguments and constants.
3108 SmallPtrSet<Value*, 8> LoopInvariants;
3111 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
3112 be = DFS.endRPO(); bb != be; ++bb) {
3113 R.NumInstructions += (*bb)->size();
3114 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
3116 Instruction *I = it;
3117 IdxToInstr[Index++] = I;
3119 // Save the end location of each USE.
3120 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
3121 Value *U = I->getOperand(i);
3122 Instruction *Instr = dyn_cast<Instruction>(U);
3124 // Ignore non-instruction values such as arguments, constants, etc.
3125 if (!Instr) continue;
3127 // If this instruction is outside the loop then record it and continue.
3128 if (!TheLoop->contains(Instr)) {
3129 LoopInvariants.insert(Instr);
3133 // Overwrite previous end points.
3134 EndPoint[Instr] = Index;
3140 // Saves the list of intervals that end with the index in 'key'.
3141 typedef SmallVector<Instruction*, 2> InstrList;
3142 DenseMap<unsigned, InstrList> TransposeEnds;
3144 // Transpose the EndPoints to a list of values that end at each index.
3145 for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
3147 TransposeEnds[it->second].push_back(it->first);
3149 SmallSet<Instruction*, 8> OpenIntervals;
3150 unsigned MaxUsage = 0;
3153 DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
3154 for (unsigned int i = 0; i < Index; ++i) {
3155 Instruction *I = IdxToInstr[i];
3156 // Ignore instructions that are never used within the loop.
3157 if (!Ends.count(I)) continue;
3159 // Remove all of the instructions that end at this location.
3160 InstrList &List = TransposeEnds[i];
3161 for (unsigned int j=0, e = List.size(); j < e; ++j)
3162 OpenIntervals.erase(List[j]);
3164 // Count the number of live interals.
3165 MaxUsage = std::max(MaxUsage, OpenIntervals.size());
3167 DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
3168 OpenIntervals.size() <<"\n");
3170 // Add the current instruction to the list of open intervals.
3171 OpenIntervals.insert(I);
3174 unsigned Invariant = LoopInvariants.size();
3175 DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << " \n");
3176 DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << " \n");
3177 DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << " \n");
3179 R.LoopInvariantRegs = Invariant;
3180 R.MaxLocalUsers = MaxUsage;
3184 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
3188 for (Loop::block_iterator bb = TheLoop->block_begin(),
3189 be = TheLoop->block_end(); bb != be; ++bb) {
3190 unsigned BlockCost = 0;
3191 BasicBlock *BB = *bb;
3193 // For each instruction in the old loop.
3194 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
3195 unsigned C = getInstructionCost(it, VF);
3197 DEBUG(dbgs() << "LV: Found an estimated cost of "<< C <<" for VF " <<
3198 VF << " For instruction: "<< *it << "\n");
3201 // We assume that if-converted blocks have a 50% chance of being executed.
3202 // When the code is scalar then some of the blocks are avoided due to CF.
3203 // When the code is vectorized we execute all code paths.
3204 if (Legal->blockNeedsPredication(*bb) && VF == 1)
3214 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
3215 // If we know that this instruction will remain uniform, check the cost of
3216 // the scalar version.
3217 if (Legal->isUniformAfterVectorization(I))
3220 Type *RetTy = I->getType();
3221 Type *VectorTy = ToVectorTy(RetTy, VF);
3223 // TODO: We need to estimate the cost of intrinsic calls.
3224 switch (I->getOpcode()) {
3225 case Instruction::GetElementPtr:
3226 // We mark this instruction as zero-cost because scalar GEPs are usually
3227 // lowered to the intruction addressing mode. At the moment we don't
3228 // generate vector geps.
3230 case Instruction::Br: {
3231 return TTI.getCFInstrCost(I->getOpcode());
3233 case Instruction::PHI:
3234 //TODO: IF-converted IFs become selects.
3236 case Instruction::Add:
3237 case Instruction::FAdd:
3238 case Instruction::Sub:
3239 case Instruction::FSub:
3240 case Instruction::Mul:
3241 case Instruction::FMul:
3242 case Instruction::UDiv:
3243 case Instruction::SDiv:
3244 case Instruction::FDiv:
3245 case Instruction::URem:
3246 case Instruction::SRem:
3247 case Instruction::FRem:
3248 case Instruction::Shl:
3249 case Instruction::LShr:
3250 case Instruction::AShr:
3251 case Instruction::And:
3252 case Instruction::Or:
3253 case Instruction::Xor:
3254 return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy);
3255 case Instruction::Select: {
3256 SelectInst *SI = cast<SelectInst>(I);
3257 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
3258 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
3259 Type *CondTy = SI->getCondition()->getType();
3261 CondTy = VectorType::get(CondTy, VF);
3263 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
3265 case Instruction::ICmp:
3266 case Instruction::FCmp: {
3267 Type *ValTy = I->getOperand(0)->getType();
3268 VectorTy = ToVectorTy(ValTy, VF);
3269 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
3271 case Instruction::Load:
3272 case Instruction::Store: {
3273 return MemoryCostComputation::computeCost(I, VF, TTI, Legal);
3276 case Instruction::ZExt:
3277 case Instruction::SExt:
3278 case Instruction::FPToUI:
3279 case Instruction::FPToSI:
3280 case Instruction::FPExt:
3281 case Instruction::PtrToInt:
3282 case Instruction::IntToPtr:
3283 case Instruction::SIToFP:
3284 case Instruction::UIToFP:
3285 case Instruction::Trunc:
3286 case Instruction::FPTrunc:
3287 case Instruction::BitCast: {
3288 // We optimize the truncation of induction variable.
3289 // The cost of these is the same as the scalar operation.
3290 if (I->getOpcode() == Instruction::Trunc &&
3291 Legal->isInductionVariable(I->getOperand(0)))
3292 return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
3293 I->getOperand(0)->getType());
3295 Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
3296 return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
3298 case Instruction::Call: {
3299 assert(isTriviallyVectorizableIntrinsic(I));
3300 IntrinsicInst *II = cast<IntrinsicInst>(I);
3301 Type *RetTy = ToVectorTy(II->getType(), VF);
3302 SmallVector<Type*, 4> Tys;
3303 for (unsigned i = 0, ie = II->getNumArgOperands(); i != ie; ++i)
3304 Tys.push_back(ToVectorTy(II->getArgOperand(i)->getType(), VF));
3305 return TTI.getIntrinsicInstrCost(II->getIntrinsicID(), RetTy, Tys);
3308 // We are scalarizing the instruction. Return the cost of the scalar
3309 // instruction, plus the cost of insert and extract into vector
3310 // elements, times the vector width.
3313 if (!RetTy->isVoidTy() && VF != 1) {
3314 unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
3316 unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
3319 // The cost of inserting the results plus extracting each one of the
3321 Cost += VF * (InsCost + ExtCost * I->getNumOperands());
3324 // The cost of executing VF copies of the scalar instruction. This opcode
3325 // is unknown. Assume that it is the same as 'mul'.
3326 Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
3332 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
3333 if (Scalar->isVoidTy() || VF == 1)
3335 return VectorType::get(Scalar, VF);
3338 char LoopVectorize::ID = 0;
3339 static const char lv_name[] = "Loop Vectorization";
3340 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
3341 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3342 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
3343 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
3344 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
3345 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
3348 Pass *createLoopVectorizePass() {
3349 return new LoopVectorize();
3353 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
3354 // Check for a store.
3355 StoreInst *ST = dyn_cast<StoreInst>(Inst);
3357 return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0;
3359 // Check for a load.
3360 LoadInst *LI = dyn_cast<LoadInst>(Inst);
3362 return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0;