1 //===- LoopVectorize.cpp - A Loop Vectorizer ------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This is the LLVM loop vectorizer. This pass modifies 'vectorizable' loops
11 // and generates target-independent LLVM-IR. Legalization of the IR is done
12 // in the codegen. However, the vectorizer uses (will use) the codegen
13 // interfaces to generate IR that is likely to result in an optimal binary.
15 // The loop vectorizer combines consecutive loop iterations into a single
16 // 'wide' iteration. After this transformation the index is incremented
17 // by the SIMD vector width, and not by one.
19 // This pass has three parts:
20 // 1. The main loop pass that drives the different parts.
21 // 2. LoopVectorizationLegality - A unit that checks for the legality
22 // of the vectorization.
23 // 3. InnerLoopVectorizer - A unit that performs the actual
24 // widening of instructions.
25 // 4. LoopVectorizationCostModel - A unit that checks for the profitability
26 // of vectorization. It decides on the optimal vector width, which
27 // can be one, if vectorization is not profitable.
29 //===----------------------------------------------------------------------===//
31 // The reduction-variable vectorization is based on the paper:
32 // D. Nuzman and R. Henderson. Multi-platform Auto-vectorization.
34 // Variable uniformity checks are inspired by:
35 // Karrenberg, R. and Hack, S. Whole Function Vectorization.
37 // Other ideas/concepts are from:
38 // A. Zaks and D. Nuzman. Autovectorization in GCC-two years later.
40 // S. Maleki, Y. Gao, M. Garzaran, T. Wong and D. Padua. An Evaluation of
41 // Vectorizing Compilers.
43 //===----------------------------------------------------------------------===//
45 #define LV_NAME "loop-vectorize"
46 #define DEBUG_TYPE LV_NAME
48 #include "llvm/Transforms/Vectorize.h"
49 #include "llvm/ADT/DenseMap.h"
50 #include "llvm/ADT/MapVector.h"
51 #include "llvm/ADT/SmallPtrSet.h"
52 #include "llvm/ADT/SmallSet.h"
53 #include "llvm/ADT/SmallVector.h"
54 #include "llvm/ADT/StringExtras.h"
55 #include "llvm/Analysis/AliasAnalysis.h"
56 #include "llvm/Analysis/AliasSetTracker.h"
57 #include "llvm/Analysis/Dominators.h"
58 #include "llvm/Analysis/LoopInfo.h"
59 #include "llvm/Analysis/LoopIterator.h"
60 #include "llvm/Analysis/LoopPass.h"
61 #include "llvm/Analysis/ScalarEvolution.h"
62 #include "llvm/Analysis/ScalarEvolutionExpander.h"
63 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
64 #include "llvm/Analysis/TargetTransformInfo.h"
65 #include "llvm/Analysis/ValueTracking.h"
66 #include "llvm/Analysis/Verifier.h"
67 #include "llvm/IR/Constants.h"
68 #include "llvm/IR/DataLayout.h"
69 #include "llvm/IR/DerivedTypes.h"
70 #include "llvm/IR/Function.h"
71 #include "llvm/IR/IRBuilder.h"
72 #include "llvm/IR/Instructions.h"
73 #include "llvm/IR/IntrinsicInst.h"
74 #include "llvm/IR/LLVMContext.h"
75 #include "llvm/IR/Module.h"
76 #include "llvm/IR/Type.h"
77 #include "llvm/IR/Value.h"
78 #include "llvm/Pass.h"
79 #include "llvm/Support/CommandLine.h"
80 #include "llvm/Support/Debug.h"
81 #include "llvm/Support/raw_ostream.h"
82 #include "llvm/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),
107 cl::desc("Don't vectorize loops with a constant "
108 "trip count that is smaller than this "
111 /// We don't unroll loops with a known constant trip count below this number.
112 static const unsigned TinyTripCountUnrollThreshold = 128;
114 /// When performing a runtime memory check, do not check more than this
115 /// number of pointers. Notice that the check is quadratic!
116 static const unsigned RuntimeMemoryCheckThreshold = 4;
120 // Forward declarations.
121 class LoopVectorizationLegality;
122 class LoopVectorizationCostModel;
124 /// InnerLoopVectorizer vectorizes loops which contain only one basic
125 /// block to a specified vectorization factor (VF).
126 /// This class performs the widening of scalars into vectors, or multiple
127 /// scalars. This class also implements the following features:
128 /// * It inserts an epilogue loop for handling loops that don't have iteration
129 /// counts that are known to be a multiple of the vectorization factor.
130 /// * It handles the code generation for reduction variables.
131 /// * Scalarization (implementation using scalars) of un-vectorizable
133 /// InnerLoopVectorizer does not perform any vectorization-legality
134 /// checks, and relies on the caller to check for the different legality
135 /// aspects. The InnerLoopVectorizer relies on the
136 /// LoopVectorizationLegality class to provide information about the induction
137 /// and reduction variables that were found to a given vectorization factor.
138 class InnerLoopVectorizer {
140 InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
141 DominatorTree *DT, DataLayout *DL, unsigned VecWidth,
142 unsigned UnrollFactor)
143 : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), DL(DL), VF(VecWidth),
144 UF(UnrollFactor), Builder(SE->getContext()), Induction(0),
145 OldInduction(0), WidenMap(UnrollFactor) {}
147 // Perform the actual loop widening (vectorization).
148 void vectorize(LoopVectorizationLegality *Legal) {
149 // Create a new empty loop. Unlink the old loop and connect the new one.
150 createEmptyLoop(Legal);
151 // Widen each instruction in the old loop to a new one in the new loop.
152 // Use the Legality module to find the induction and reduction variables.
153 vectorizeLoop(Legal);
154 // Register the new loop and update the analysis passes.
159 /// A small list of PHINodes.
160 typedef SmallVector<PHINode*, 4> PhiVector;
161 /// When we unroll loops we have multiple vector values for each scalar.
162 /// This data structure holds the unrolled and vectorized values that
163 /// originated from one scalar instruction.
164 typedef SmallVector<Value*, 2> VectorParts;
166 /// Add code that checks at runtime if the accessed arrays overlap.
167 /// Returns the comparator value or NULL if no check is needed.
168 Instruction *addRuntimeCheck(LoopVectorizationLegality *Legal,
170 /// Create an empty loop, based on the loop ranges of the old loop.
171 void createEmptyLoop(LoopVectorizationLegality *Legal);
172 /// Copy and widen the instructions from the old loop.
173 void vectorizeLoop(LoopVectorizationLegality *Legal);
175 /// A helper function that computes the predicate of the block BB, assuming
176 /// that the header block of the loop is set to True. It returns the *entry*
177 /// mask for the block BB.
178 VectorParts createBlockInMask(BasicBlock *BB);
179 /// A helper function that computes the predicate of the edge between SRC
181 VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
183 /// A helper function to vectorize a single BB within the innermost loop.
184 void vectorizeBlockInLoop(LoopVectorizationLegality *Legal, BasicBlock *BB,
187 /// Insert the new loop to the loop hierarchy and pass manager
188 /// and update the analysis passes.
189 void updateAnalysis();
191 /// This instruction is un-vectorizable. Implement it as a sequence
193 void scalarizeInstruction(Instruction *Instr);
195 /// Vectorize Load and Store instructions,
196 void vectorizeMemoryInstruction(Instruction *Instr,
197 LoopVectorizationLegality *Legal);
199 /// Create a broadcast instruction. This method generates a broadcast
200 /// instruction (shuffle) for loop invariant values and for the induction
201 /// value. If this is the induction variable then we extend it to N, N+1, ...
202 /// this is needed because each iteration in the loop corresponds to a SIMD
204 Value *getBroadcastInstrs(Value *V);
206 /// This function adds 0, 1, 2 ... to each vector element, starting at zero.
207 /// If Negate is set then negative numbers are added e.g. (0, -1, -2, ...).
208 /// The sequence starts at StartIndex.
209 Value *getConsecutiveVector(Value* Val, unsigned StartIdx, bool Negate);
211 /// When we go over instructions in the basic block we rely on previous
212 /// values within the current basic block or on loop invariant values.
213 /// When we widen (vectorize) values we place them in the map. If the values
214 /// are not within the map, they have to be loop invariant, so we simply
215 /// broadcast them into a vector.
216 VectorParts &getVectorValue(Value *V);
218 /// Generate a shuffle sequence that will reverse the vector Vec.
219 Value *reverseVector(Value *Vec);
221 /// This is a helper class that holds the vectorizer state. It maps scalar
222 /// instructions to vector instructions. When the code is 'unrolled' then
223 /// then a single scalar value is mapped to multiple vector parts. The parts
224 /// are stored in the VectorPart type.
226 /// C'tor. UnrollFactor controls the number of vectors ('parts') that
228 ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
230 /// \return True if 'Key' is saved in the Value Map.
231 bool has(Value *Key) const { return MapStorage.count(Key); }
233 /// Initializes a new entry in the map. Sets all of the vector parts to the
234 /// save value in 'Val'.
235 /// \return A reference to a vector with splat values.
236 VectorParts &splat(Value *Key, Value *Val) {
237 VectorParts &Entry = MapStorage[Key];
238 Entry.assign(UF, Val);
242 ///\return A reference to the value that is stored at 'Key'.
243 VectorParts &get(Value *Key) {
244 VectorParts &Entry = MapStorage[Key];
247 assert(Entry.size() == UF);
252 /// The unroll factor. Each entry in the map stores this number of vector
256 /// Map storage. We use std::map and not DenseMap because insertions to a
257 /// dense map invalidates its iterators.
258 std::map<Value *, VectorParts> MapStorage;
261 /// The original loop.
263 /// Scev analysis to use.
271 /// The vectorization SIMD factor to use. Each vector will have this many
274 /// The vectorization unroll factor to use. Each scalar is vectorized to this
275 /// many different vector instructions.
278 /// The builder that we use
281 // --- Vectorization state ---
283 /// The vector-loop preheader.
284 BasicBlock *LoopVectorPreHeader;
285 /// The scalar-loop preheader.
286 BasicBlock *LoopScalarPreHeader;
287 /// Middle Block between the vector and the scalar.
288 BasicBlock *LoopMiddleBlock;
289 ///The ExitBlock of the scalar loop.
290 BasicBlock *LoopExitBlock;
291 ///The vector loop body.
292 BasicBlock *LoopVectorBody;
293 ///The scalar loop body.
294 BasicBlock *LoopScalarBody;
295 /// A list of all bypass blocks. The first block is the entry of the loop.
296 SmallVector<BasicBlock *, 4> LoopBypassBlocks;
298 /// The new Induction variable which was added to the new block.
300 /// The induction variable of the old basic block.
301 PHINode *OldInduction;
302 /// Maps scalars to widened vectors.
306 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
307 /// to what vectorization factor.
308 /// This class does not look at the profitability of vectorization, only the
309 /// legality. This class has two main kinds of checks:
310 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
311 /// will change the order of memory accesses in a way that will change the
312 /// correctness of the program.
313 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
314 /// checks for a number of different conditions, such as the availability of a
315 /// single induction variable, that all types are supported and vectorize-able,
316 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
317 /// This class is also used by InnerLoopVectorizer for identifying
318 /// induction variable and the different reduction variables.
319 class LoopVectorizationLegality {
321 LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, DataLayout *DL,
323 : TheLoop(L), SE(SE), DL(DL), DT(DT), Induction(0) {}
325 /// This enum represents the kinds of reductions that we support.
327 RK_NoReduction, ///< Not a reduction.
328 RK_IntegerAdd, ///< Sum of integers.
329 RK_IntegerMult, ///< Product of integers.
330 RK_IntegerOr, ///< Bitwise or logical OR of numbers.
331 RK_IntegerAnd, ///< Bitwise or logical AND of numbers.
332 RK_IntegerXor, ///< Bitwise or logical XOR of numbers.
333 RK_FloatAdd, ///< Sum of floats.
334 RK_FloatMult ///< Product of floats.
337 /// This enum represents the kinds of inductions that we support.
339 IK_NoInduction, ///< Not an induction variable.
340 IK_IntInduction, ///< Integer induction variable. Step = 1.
341 IK_ReverseIntInduction, ///< Reverse int induction variable. Step = -1.
342 IK_PtrInduction, ///< Pointer induction var. Step = sizeof(elem).
343 IK_ReversePtrInduction ///< Reverse ptr indvar. Step = - sizeof(elem).
346 /// This POD struct holds information about reduction variables.
347 struct ReductionDescriptor {
348 ReductionDescriptor() : StartValue(0), LoopExitInstr(0),
349 Kind(RK_NoReduction) {}
351 ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K)
352 : StartValue(Start), LoopExitInstr(Exit), Kind(K) {}
354 // The starting value of the reduction.
355 // It does not have to be zero!
357 // The instruction who's value is used outside the loop.
358 Instruction *LoopExitInstr;
359 // The kind of the reduction.
363 // This POD struct holds information about the memory runtime legality
364 // check that a group of pointers do not overlap.
365 struct RuntimePointerCheck {
366 RuntimePointerCheck() : Need(false) {}
368 /// Reset the state of the pointer runtime information.
376 /// Insert a pointer and calculate the start and end SCEVs.
377 void insert(ScalarEvolution *SE, Loop *Lp, Value *Ptr);
379 /// This flag indicates if we need to add the runtime check.
381 /// Holds the pointers that we need to check.
382 SmallVector<Value*, 2> Pointers;
383 /// Holds the pointer value at the beginning of the loop.
384 SmallVector<const SCEV*, 2> Starts;
385 /// Holds the pointer value at the end of the loop.
386 SmallVector<const SCEV*, 2> Ends;
389 /// A POD for saving information about induction variables.
390 struct InductionInfo {
391 InductionInfo(Value *Start, InductionKind K) : StartValue(Start), IK(K) {}
392 InductionInfo() : StartValue(0), IK(IK_NoInduction) {}
399 /// ReductionList contains the reduction descriptors for all
400 /// of the reductions that were found in the loop.
401 typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
403 /// InductionList saves induction variables and maps them to the
404 /// induction descriptor.
405 typedef MapVector<PHINode*, InductionInfo> InductionList;
407 /// Returns true if it is legal to vectorize this loop.
408 /// This does not mean that it is profitable to vectorize this
409 /// loop, only that it is legal to do so.
412 /// Returns the Induction variable.
413 PHINode *getInduction() { return Induction; }
415 /// Returns the reduction variables found in the loop.
416 ReductionList *getReductionVars() { return &Reductions; }
418 /// Returns the induction variables found in the loop.
419 InductionList *getInductionVars() { return &Inductions; }
421 /// Returns True if V is an induction variable in this loop.
422 bool isInductionVariable(const Value *V);
424 /// Return true if the block BB needs to be predicated in order for the loop
425 /// to be vectorized.
426 bool blockNeedsPredication(BasicBlock *BB);
428 /// Check if this pointer is consecutive when vectorizing. This happens
429 /// when the last index of the GEP is the induction variable, or that the
430 /// pointer itself is an induction variable.
431 /// This check allows us to vectorize A[idx] into a wide load/store.
433 /// 0 - Stride is unknown or non consecutive.
434 /// 1 - Address is consecutive.
435 /// -1 - Address is consecutive, and decreasing.
436 int isConsecutivePtr(Value *Ptr);
438 /// Returns true if the value V is uniform within the loop.
439 bool isUniform(Value *V);
441 /// Returns true if this instruction will remain scalar after vectorization.
442 bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
444 /// Returns the information that we collected about runtime memory check.
445 RuntimePointerCheck *getRuntimePointerCheck() { return &PtrRtCheck; }
447 /// Check if a single basic block loop is vectorizable.
448 /// At this point we know that this is a loop with a constant trip count
449 /// and we only need to check individual instructions.
450 bool canVectorizeInstrs();
452 /// When we vectorize loops we may change the order in which
453 /// we read and write from memory. This method checks if it is
454 /// legal to vectorize the code, considering only memory constrains.
455 /// Returns true if the loop is vectorizable
456 bool canVectorizeMemory();
458 /// Return true if we can vectorize this loop using the IF-conversion
460 bool canVectorizeWithIfConvert();
462 /// Collect the variables that need to stay uniform after vectorization.
463 void collectLoopUniforms();
465 /// Return true if all of the instructions in the block can be speculatively
467 bool blockCanBePredicated(BasicBlock *BB);
469 /// Returns True, if 'Phi' is the kind of reduction variable for type
470 /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
471 bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
472 /// Returns true if the instruction I can be a reduction variable of type
474 bool isReductionInstr(Instruction *I, ReductionKind Kind);
475 /// Returns the induction kind of Phi. This function may return NoInduction
476 /// if the PHI is not an induction variable.
477 InductionKind isInductionVariable(PHINode *Phi);
478 /// Return true if can compute the address bounds of Ptr within the loop.
479 bool hasComputableBounds(Value *Ptr);
481 /// The loop that we evaluate.
485 /// DataLayout analysis.
490 // --- vectorization state --- //
492 /// Holds the integer induction variable. This is the counter of the
495 /// Holds the reduction variables.
496 ReductionList Reductions;
497 /// Holds all of the induction variables that we found in the loop.
498 /// Notice that inductions don't need to start at zero and that induction
499 /// variables can be pointers.
500 InductionList Inductions;
502 /// Allowed outside users. This holds the reduction
503 /// vars which can be accessed from outside the loop.
504 SmallPtrSet<Value*, 4> AllowedExit;
505 /// This set holds the variables which are known to be uniform after
507 SmallPtrSet<Instruction*, 4> Uniforms;
508 /// We need to check that all of the pointers in this list are disjoint
510 RuntimePointerCheck PtrRtCheck;
513 /// LoopVectorizationCostModel - estimates the expected speedups due to
515 /// In many cases vectorization is not profitable. This can happen because of
516 /// a number of reasons. In this class we mainly attempt to predict the
517 /// expected speedup/slowdowns due to the supported instruction set. We use the
518 /// TargetTransformInfo to query the different backends for the cost of
519 /// different operations.
520 class LoopVectorizationCostModel {
522 LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
523 LoopVectorizationLegality *Legal,
524 const TargetTransformInfo &TTI,
526 : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI), DL(DL) {}
528 /// Information about vectorization costs
529 struct VectorizationFactor {
530 unsigned Width; // Vector width with best cost
531 unsigned Cost; // Cost of the loop with that width
533 /// \return The most profitable vectorization factor and the cost of that VF.
534 /// This method checks every power of two up to VF. If UserVF is not ZERO
535 /// then this vectorization factor will be selected if vectorization is
537 VectorizationFactor selectVectorizationFactor(bool OptForSize,
540 /// \return The size (in bits) of the widest type in the code that
541 /// needs to be vectorized. We ignore values that remain scalar such as
542 /// 64 bit loop indices.
543 unsigned getWidestType();
545 /// \return The most profitable unroll factor.
546 /// If UserUF is non-zero then this method finds the best unroll-factor
547 /// based on register pressure and other parameters.
548 /// VF and LoopCost are the selected vectorization factor and the cost of the
550 unsigned selectUnrollFactor(bool OptForSize, unsigned UserUF, unsigned VF,
553 /// \brief A struct that represents some properties of the register usage
555 struct RegisterUsage {
556 /// Holds the number of loop invariant values that are used in the loop.
557 unsigned LoopInvariantRegs;
558 /// Holds the maximum number of concurrent live intervals in the loop.
559 unsigned MaxLocalUsers;
560 /// Holds the number of instructions in the loop.
561 unsigned NumInstructions;
564 /// \return information about the register usage of the loop.
565 RegisterUsage calculateRegisterUsage();
568 /// Returns the expected execution cost. The unit of the cost does
569 /// not matter because we use the 'cost' units to compare different
570 /// vector widths. The cost that is returned is *not* normalized by
571 /// the factor width.
572 unsigned expectedCost(unsigned VF);
574 /// Returns the execution time cost of an instruction for a given vector
575 /// width. Vector width of one means scalar.
576 unsigned getInstructionCost(Instruction *I, unsigned VF);
578 /// A helper function for converting Scalar types to vector types.
579 /// If the incoming type is void, we return void. If the VF is 1, we return
581 static Type* ToVectorTy(Type *Scalar, unsigned VF);
583 /// Returns whether the instruction is a load or store and will be a emitted
584 /// as a vector operation.
585 bool isConsecutiveLoadOrStore(Instruction *I);
587 /// The loop that we evaluate.
591 /// Loop Info analysis.
593 /// Vectorization legality.
594 LoopVectorizationLegality *Legal;
595 /// Vector target information.
596 const TargetTransformInfo &TTI;
597 /// Target data layout information.
601 /// The LoopVectorize Pass.
602 struct LoopVectorize : public LoopPass {
603 /// Pass identification, replacement for typeid
606 explicit LoopVectorize() : LoopPass(ID) {
607 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
613 TargetTransformInfo *TTI;
616 virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
617 // We only vectorize innermost loops.
621 SE = &getAnalysis<ScalarEvolution>();
622 DL = getAnalysisIfAvailable<DataLayout>();
623 LI = &getAnalysis<LoopInfo>();
624 TTI = &getAnalysis<TargetTransformInfo>();
625 DT = &getAnalysis<DominatorTree>();
627 DEBUG(dbgs() << "LV: Checking a loop in \"" <<
628 L->getHeader()->getParent()->getName() << "\"\n");
630 // Check if it is legal to vectorize the loop.
631 LoopVectorizationLegality LVL(L, SE, DL, DT);
632 if (!LVL.canVectorize()) {
633 DEBUG(dbgs() << "LV: Not vectorizing.\n");
637 // Use the cost model.
638 LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI, DL);
640 // Check the function attributes to find out if this function should be
641 // optimized for size.
642 Function *F = L->getHeader()->getParent();
643 Attribute::AttrKind SzAttr = Attribute::OptimizeForSize;
644 Attribute::AttrKind FlAttr = Attribute::NoImplicitFloat;
645 unsigned FnIndex = AttributeSet::FunctionIndex;
646 bool OptForSize = F->getAttributes().hasAttribute(FnIndex, SzAttr);
647 bool NoFloat = F->getAttributes().hasAttribute(FnIndex, FlAttr);
650 DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
651 "attribute is used.\n");
655 // Select the optimal vectorization factor.
656 LoopVectorizationCostModel::VectorizationFactor VF;
657 VF = CM.selectVectorizationFactor(OptForSize, VectorizationFactor);
658 // Select the unroll factor.
659 unsigned UF = CM.selectUnrollFactor(OptForSize, VectorizationUnroll,
663 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
667 DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< VF.Width << ") in "<<
668 F->getParent()->getModuleIdentifier()<<"\n");
669 DEBUG(dbgs() << "LV: Unroll Factor is " << UF << "\n");
671 // If we decided that it is *legal* to vectorize the loop then do it.
672 InnerLoopVectorizer LB(L, SE, LI, DT, DL, VF.Width, UF);
675 DEBUG(verifyFunction(*L->getHeader()->getParent()));
679 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
680 LoopPass::getAnalysisUsage(AU);
681 AU.addRequiredID(LoopSimplifyID);
682 AU.addRequiredID(LCSSAID);
683 AU.addRequired<DominatorTree>();
684 AU.addRequired<LoopInfo>();
685 AU.addRequired<ScalarEvolution>();
686 AU.addRequired<TargetTransformInfo>();
687 AU.addPreserved<LoopInfo>();
688 AU.addPreserved<DominatorTree>();
693 } // end anonymous namespace
695 //===----------------------------------------------------------------------===//
696 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
697 // LoopVectorizationCostModel.
698 //===----------------------------------------------------------------------===//
701 LoopVectorizationLegality::RuntimePointerCheck::insert(ScalarEvolution *SE,
702 Loop *Lp, Value *Ptr) {
703 const SCEV *Sc = SE->getSCEV(Ptr);
704 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
705 assert(AR && "Invalid addrec expression");
706 const SCEV *Ex = SE->getExitCount(Lp, Lp->getLoopLatch());
707 const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
708 Pointers.push_back(Ptr);
709 Starts.push_back(AR->getStart());
710 Ends.push_back(ScEnd);
713 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
714 // Save the current insertion location.
715 Instruction *Loc = Builder.GetInsertPoint();
717 // We need to place the broadcast of invariant variables outside the loop.
718 Instruction *Instr = dyn_cast<Instruction>(V);
719 bool NewInstr = (Instr && Instr->getParent() == LoopVectorBody);
720 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
722 // Place the code for broadcasting invariant variables in the new preheader.
724 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
726 // Broadcast the scalar into all locations in the vector.
727 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
729 // Restore the builder insertion point.
731 Builder.SetInsertPoint(Loc);
736 Value *InnerLoopVectorizer::getConsecutiveVector(Value* Val, unsigned StartIdx,
738 assert(Val->getType()->isVectorTy() && "Must be a vector");
739 assert(Val->getType()->getScalarType()->isIntegerTy() &&
740 "Elem must be an integer");
742 Type *ITy = Val->getType()->getScalarType();
743 VectorType *Ty = cast<VectorType>(Val->getType());
744 int VLen = Ty->getNumElements();
745 SmallVector<Constant*, 8> Indices;
747 // Create a vector of consecutive numbers from zero to VF.
748 for (int i = 0; i < VLen; ++i) {
749 int Idx = Negate ? (-i): i;
750 Indices.push_back(ConstantInt::get(ITy, StartIdx + Idx));
753 // Add the consecutive indices to the vector value.
754 Constant *Cv = ConstantVector::get(Indices);
755 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
756 return Builder.CreateAdd(Val, Cv, "induction");
759 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
760 assert(Ptr->getType()->isPointerTy() && "Unexpected non ptr");
761 // Make sure that the pointer does not point to structs.
762 if (cast<PointerType>(Ptr->getType())->getElementType()->isAggregateType())
765 // If this value is a pointer induction variable we know it is consecutive.
766 PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
767 if (Phi && Inductions.count(Phi)) {
768 InductionInfo II = Inductions[Phi];
769 if (IK_PtrInduction == II.IK)
771 else if (IK_ReversePtrInduction == II.IK)
775 GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
779 unsigned NumOperands = Gep->getNumOperands();
780 Value *LastIndex = Gep->getOperand(NumOperands - 1);
782 Value *GpPtr = Gep->getPointerOperand();
783 // If this GEP value is a consecutive pointer induction variable and all of
784 // the indices are constant then we know it is consecutive. We can
785 Phi = dyn_cast<PHINode>(GpPtr);
786 if (Phi && Inductions.count(Phi)) {
788 // Make sure that the pointer does not point to structs.
789 PointerType *GepPtrType = cast<PointerType>(GpPtr->getType());
790 if (GepPtrType->getElementType()->isAggregateType())
793 // Make sure that all of the index operands are loop invariant.
794 for (unsigned i = 1; i < NumOperands; ++i)
795 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
798 InductionInfo II = Inductions[Phi];
799 if (IK_PtrInduction == II.IK)
801 else if (IK_ReversePtrInduction == II.IK)
805 // Check that all of the gep indices are uniform except for the last.
806 for (unsigned i = 0; i < NumOperands - 1; ++i)
807 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
810 // We can emit wide load/stores only if the last index is the induction
812 const SCEV *Last = SE->getSCEV(LastIndex);
813 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
814 const SCEV *Step = AR->getStepRecurrence(*SE);
816 // The memory is consecutive because the last index is consecutive
817 // and all other indices are loop invariant.
820 if (Step->isAllOnesValue())
827 bool LoopVectorizationLegality::isUniform(Value *V) {
828 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
831 InnerLoopVectorizer::VectorParts&
832 InnerLoopVectorizer::getVectorValue(Value *V) {
833 assert(V != Induction && "The new induction variable should not be used.");
834 assert(!V->getType()->isVectorTy() && "Can't widen a vector");
836 // If we have this scalar in the map, return it.
838 return WidenMap.get(V);
840 // If this scalar is unknown, assume that it is a constant or that it is
841 // loop invariant. Broadcast V and save the value for future uses.
842 Value *B = getBroadcastInstrs(V);
843 return WidenMap.splat(V, B);
846 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
847 assert(Vec->getType()->isVectorTy() && "Invalid type");
848 SmallVector<Constant*, 8> ShuffleMask;
849 for (unsigned i = 0; i < VF; ++i)
850 ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
852 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
853 ConstantVector::get(ShuffleMask),
858 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr,
859 LoopVectorizationLegality *Legal) {
860 // Attempt to issue a wide load.
861 LoadInst *LI = dyn_cast<LoadInst>(Instr);
862 StoreInst *SI = dyn_cast<StoreInst>(Instr);
864 assert((LI || SI) && "Invalid Load/Store instruction");
866 Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType();
867 Type *DataTy = VectorType::get(ScalarDataTy, VF);
868 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
869 unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment();
871 // If the pointer is loop invariant or if it is non consecutive,
872 // scalarize the load.
873 int Stride = Legal->isConsecutivePtr(Ptr);
874 bool Reverse = Stride < 0;
875 bool UniformLoad = LI && Legal->isUniform(Ptr);
876 if (Stride == 0 || UniformLoad)
877 return scalarizeInstruction(Instr);
879 Constant *Zero = Builder.getInt32(0);
880 VectorParts &Entry = WidenMap.get(Instr);
882 // Handle consecutive loads/stores.
883 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
884 if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) {
885 Value *PtrOperand = Gep->getPointerOperand();
886 Value *FirstBasePtr = getVectorValue(PtrOperand)[0];
887 FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero);
889 // Create the new GEP with the new induction variable.
890 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
891 Gep2->setOperand(0, FirstBasePtr);
892 Gep2->setName("gep.indvar.base");
893 Ptr = Builder.Insert(Gep2);
895 assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()),
896 OrigLoop) && "Base ptr must be invariant");
898 // The last index does not have to be the induction. It can be
899 // consecutive and be a function of the index. For example A[I+1];
900 unsigned NumOperands = Gep->getNumOperands();
902 Value *LastGepOperand = Gep->getOperand(NumOperands - 1);
903 VectorParts &GEPParts = getVectorValue(LastGepOperand);
904 Value *LastIndex = GEPParts[0];
905 LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
907 // Create the new GEP with the new induction variable.
908 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
909 Gep2->setOperand(NumOperands - 1, LastIndex);
910 Gep2->setName("gep.indvar.idx");
911 Ptr = Builder.Insert(Gep2);
913 // Use the induction element ptr.
914 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
915 VectorParts &PtrVal = getVectorValue(Ptr);
916 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
921 assert(!Legal->isUniform(SI->getPointerOperand()) &&
922 "We do not allow storing to uniform addresses");
924 VectorParts &StoredVal = getVectorValue(SI->getValueOperand());
925 for (unsigned Part = 0; Part < UF; ++Part) {
926 // Calculate the pointer for the specific unroll-part.
927 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
930 // If we store to reverse consecutive memory locations then we need
931 // to reverse the order of elements in the stored value.
932 StoredVal[Part] = reverseVector(StoredVal[Part]);
933 // If the address is consecutive but reversed, then the
934 // wide store needs to start at the last vector element.
935 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
936 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
939 Value *VecPtr = Builder.CreateBitCast(PartPtr, DataTy->getPointerTo());
940 Builder.CreateStore(StoredVal[Part], VecPtr)->setAlignment(Alignment);
944 for (unsigned Part = 0; Part < UF; ++Part) {
945 // Calculate the pointer for the specific unroll-part.
946 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
949 // If the address is consecutive but reversed, then the
950 // wide store needs to start at the last vector element.
951 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
952 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
955 Value *VecPtr = Builder.CreateBitCast(PartPtr, DataTy->getPointerTo());
956 Value *LI = Builder.CreateLoad(VecPtr, "wide.load");
957 cast<LoadInst>(LI)->setAlignment(Alignment);
958 Entry[Part] = Reverse ? reverseVector(LI) : LI;
962 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr) {
963 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
964 // Holds vector parameters or scalars, in case of uniform vals.
965 SmallVector<VectorParts, 4> Params;
967 // Find all of the vectorized parameters.
968 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
969 Value *SrcOp = Instr->getOperand(op);
971 // If we are accessing the old induction variable, use the new one.
972 if (SrcOp == OldInduction) {
973 Params.push_back(getVectorValue(SrcOp));
977 // Try using previously calculated values.
978 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
980 // If the src is an instruction that appeared earlier in the basic block
981 // then it should already be vectorized.
982 if (SrcInst && OrigLoop->contains(SrcInst)) {
983 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
984 // The parameter is a vector value from earlier.
985 Params.push_back(WidenMap.get(SrcInst));
987 // The parameter is a scalar from outside the loop. Maybe even a constant.
989 Scalars.append(UF, SrcOp);
990 Params.push_back(Scalars);
994 assert(Params.size() == Instr->getNumOperands() &&
995 "Invalid number of operands");
997 // Does this instruction return a value ?
998 bool IsVoidRetTy = Instr->getType()->isVoidTy();
1000 Value *UndefVec = IsVoidRetTy ? 0 :
1001 UndefValue::get(VectorType::get(Instr->getType(), VF));
1002 // Create a new entry in the WidenMap and initialize it to Undef or Null.
1003 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
1005 // For each scalar that we create:
1006 for (unsigned Width = 0; Width < VF; ++Width) {
1007 // For each vector unroll 'part':
1008 for (unsigned Part = 0; Part < UF; ++Part) {
1009 Instruction *Cloned = Instr->clone();
1011 Cloned->setName(Instr->getName() + ".cloned");
1012 // Replace the operands of the cloned instrucions with extracted scalars.
1013 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1014 Value *Op = Params[op][Part];
1015 // Param is a vector. Need to extract the right lane.
1016 if (Op->getType()->isVectorTy())
1017 Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
1018 Cloned->setOperand(op, Op);
1021 // Place the cloned scalar in the new loop.
1022 Builder.Insert(Cloned);
1024 // If the original scalar returns a value we need to place it in a vector
1025 // so that future users will be able to use it.
1027 VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
1028 Builder.getInt32(Width));
1034 InnerLoopVectorizer::addRuntimeCheck(LoopVectorizationLegality *Legal,
1036 LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck =
1037 Legal->getRuntimePointerCheck();
1039 if (!PtrRtCheck->Need)
1042 Instruction *MemoryRuntimeCheck = 0;
1043 unsigned NumPointers = PtrRtCheck->Pointers.size();
1044 SmallVector<Value* , 2> Starts;
1045 SmallVector<Value* , 2> Ends;
1047 SCEVExpander Exp(*SE, "induction");
1049 // Use this type for pointer arithmetic.
1050 Type* PtrArithTy = Type::getInt8PtrTy(Loc->getContext(), 0);
1052 for (unsigned i = 0; i < NumPointers; ++i) {
1053 Value *Ptr = PtrRtCheck->Pointers[i];
1054 const SCEV *Sc = SE->getSCEV(Ptr);
1056 if (SE->isLoopInvariant(Sc, OrigLoop)) {
1057 DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" <<
1059 Starts.push_back(Ptr);
1060 Ends.push_back(Ptr);
1062 DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr <<"\n");
1064 Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc);
1065 Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
1066 Starts.push_back(Start);
1067 Ends.push_back(End);
1071 IRBuilder<> ChkBuilder(Loc);
1073 for (unsigned i = 0; i < NumPointers; ++i) {
1074 for (unsigned j = i+1; j < NumPointers; ++j) {
1075 Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy, "bc");
1076 Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy, "bc");
1077 Value *End0 = ChkBuilder.CreateBitCast(Ends[i], PtrArithTy, "bc");
1078 Value *End1 = ChkBuilder.CreateBitCast(Ends[j], PtrArithTy, "bc");
1080 Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
1081 Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
1082 Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1083 if (MemoryRuntimeCheck)
1084 IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict,
1087 MemoryRuntimeCheck = cast<Instruction>(IsConflict);
1091 return MemoryRuntimeCheck;
1095 InnerLoopVectorizer::createEmptyLoop(LoopVectorizationLegality *Legal) {
1097 In this function we generate a new loop. The new loop will contain
1098 the vectorized instructions while the old loop will continue to run the
1101 [ ] <-- vector loop bypass (may consist of multiple blocks).
1104 | [ ] <-- vector pre header.
1108 | [ ]_| <-- vector loop.
1111 >[ ] <--- middle-block.
1114 | [ ] <--- new preheader.
1118 | [ ]_| <-- old scalar loop to handle remainder.
1121 >[ ] <-- exit block.
1125 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
1126 BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
1127 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
1128 assert(ExitBlock && "Must have an exit block");
1130 // Some loops have a single integer induction variable, while other loops
1131 // don't. One example is c++ iterators that often have multiple pointer
1132 // induction variables. In the code below we also support a case where we
1133 // don't have a single induction variable.
1134 OldInduction = Legal->getInduction();
1135 Type *IdxTy = OldInduction ? OldInduction->getType() :
1136 DL->getIntPtrType(SE->getContext());
1138 // Find the loop boundaries.
1139 const SCEV *ExitCount = SE->getExitCount(OrigLoop, OrigLoop->getLoopLatch());
1140 assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
1142 // Get the total trip count from the count by adding 1.
1143 ExitCount = SE->getAddExpr(ExitCount,
1144 SE->getConstant(ExitCount->getType(), 1));
1146 // Expand the trip count and place the new instructions in the preheader.
1147 // Notice that the pre-header does not change, only the loop body.
1148 SCEVExpander Exp(*SE, "induction");
1150 // Count holds the overall loop count (N).
1151 Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
1152 BypassBlock->getTerminator());
1154 // The loop index does not have to start at Zero. Find the original start
1155 // value from the induction PHI node. If we don't have an induction variable
1156 // then we know that it starts at zero.
1157 Value *StartIdx = OldInduction ?
1158 OldInduction->getIncomingValueForBlock(BypassBlock):
1159 ConstantInt::get(IdxTy, 0);
1161 assert(BypassBlock && "Invalid loop structure");
1162 LoopBypassBlocks.push_back(BypassBlock);
1164 // Split the single block loop into the two loop structure described above.
1165 BasicBlock *VectorPH =
1166 BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
1167 BasicBlock *VecBody =
1168 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
1169 BasicBlock *MiddleBlock =
1170 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
1171 BasicBlock *ScalarPH =
1172 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
1174 // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
1176 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
1178 // Generate the induction variable.
1179 Induction = Builder.CreatePHI(IdxTy, 2, "index");
1180 // The loop step is equal to the vectorization factor (num of SIMD elements)
1181 // times the unroll factor (num of SIMD instructions).
1182 Constant *Step = ConstantInt::get(IdxTy, VF * UF);
1184 // This is the IR builder that we use to add all of the logic for bypassing
1185 // the new vector loop.
1186 IRBuilder<> BypassBuilder(BypassBlock->getTerminator());
1188 // We may need to extend the index in case there is a type mismatch.
1189 // We know that the count starts at zero and does not overflow.
1190 if (Count->getType() != IdxTy) {
1191 // The exit count can be of pointer type. Convert it to the correct
1193 if (ExitCount->getType()->isPointerTy())
1194 Count = BypassBuilder.CreatePointerCast(Count, IdxTy, "ptrcnt.to.int");
1196 Count = BypassBuilder.CreateZExtOrTrunc(Count, IdxTy, "cnt.cast");
1199 // Add the start index to the loop count to get the new end index.
1200 Value *IdxEnd = BypassBuilder.CreateAdd(Count, StartIdx, "end.idx");
1202 // Now we need to generate the expression for N - (N % VF), which is
1203 // the part that the vectorized body will execute.
1204 Value *R = BypassBuilder.CreateURem(Count, Step, "n.mod.vf");
1205 Value *CountRoundDown = BypassBuilder.CreateSub(Count, R, "n.vec");
1206 Value *IdxEndRoundDown = BypassBuilder.CreateAdd(CountRoundDown, StartIdx,
1207 "end.idx.rnd.down");
1209 // Now, compare the new count to zero. If it is zero skip the vector loop and
1210 // jump to the scalar loop.
1211 Value *Cmp = BypassBuilder.CreateICmpEQ(IdxEndRoundDown, StartIdx,
1214 BasicBlock *LastBypassBlock = BypassBlock;
1216 // Generate the code that checks in runtime if arrays overlap. We put the
1217 // checks into a separate block to make the more common case of few elements
1219 Instruction *MemRuntimeCheck = addRuntimeCheck(Legal,
1220 BypassBlock->getTerminator());
1221 if (MemRuntimeCheck) {
1222 // Create a new block containing the memory check.
1223 BasicBlock *CheckBlock = BypassBlock->splitBasicBlock(MemRuntimeCheck,
1225 LoopBypassBlocks.push_back(CheckBlock);
1227 // Replace the branch into the memory check block with a conditional branch
1228 // for the "few elements case".
1229 Instruction *OldTerm = BypassBlock->getTerminator();
1230 BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
1231 OldTerm->eraseFromParent();
1233 Cmp = MemRuntimeCheck;
1234 LastBypassBlock = CheckBlock;
1237 LastBypassBlock->getTerminator()->eraseFromParent();
1238 BranchInst::Create(MiddleBlock, VectorPH, Cmp,
1241 // We are going to resume the execution of the scalar loop.
1242 // Go over all of the induction variables that we found and fix the
1243 // PHIs that are left in the scalar version of the loop.
1244 // The starting values of PHI nodes depend on the counter of the last
1245 // iteration in the vectorized loop.
1246 // If we come from a bypass edge then we need to start from the original
1249 // This variable saves the new starting index for the scalar loop.
1250 PHINode *ResumeIndex = 0;
1251 LoopVectorizationLegality::InductionList::iterator I, E;
1252 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
1253 for (I = List->begin(), E = List->end(); I != E; ++I) {
1254 PHINode *OrigPhi = I->first;
1255 LoopVectorizationLegality::InductionInfo II = I->second;
1256 PHINode *ResumeVal = PHINode::Create(OrigPhi->getType(), 2, "resume.val",
1257 MiddleBlock->getTerminator());
1258 Value *EndValue = 0;
1260 case LoopVectorizationLegality::IK_NoInduction:
1261 llvm_unreachable("Unknown induction");
1262 case LoopVectorizationLegality::IK_IntInduction: {
1263 // Handle the integer induction counter:
1264 assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
1265 assert(OrigPhi == OldInduction && "Unknown integer PHI");
1266 // We know what the end value is.
1267 EndValue = IdxEndRoundDown;
1268 // We also know which PHI node holds it.
1269 ResumeIndex = ResumeVal;
1272 case LoopVectorizationLegality::IK_ReverseIntInduction: {
1273 // Convert the CountRoundDown variable to the PHI size.
1274 unsigned CRDSize = CountRoundDown->getType()->getScalarSizeInBits();
1275 unsigned IISize = II.StartValue->getType()->getScalarSizeInBits();
1276 Value *CRD = CountRoundDown;
1277 if (CRDSize > IISize)
1278 CRD = CastInst::Create(Instruction::Trunc, CountRoundDown,
1279 II.StartValue->getType(), "tr.crd",
1280 LoopBypassBlocks.back()->getTerminator());
1281 else if (CRDSize < IISize)
1282 CRD = CastInst::Create(Instruction::SExt, CountRoundDown,
1283 II.StartValue->getType(),
1285 LoopBypassBlocks.back()->getTerminator());
1286 // Handle reverse integer induction counter:
1288 BinaryOperator::CreateSub(II.StartValue, CRD, "rev.ind.end",
1289 LoopBypassBlocks.back()->getTerminator());
1292 case LoopVectorizationLegality::IK_PtrInduction: {
1293 // For pointer induction variables, calculate the offset using
1296 GetElementPtrInst::Create(II.StartValue, CountRoundDown, "ptr.ind.end",
1297 LoopBypassBlocks.back()->getTerminator());
1300 case LoopVectorizationLegality::IK_ReversePtrInduction: {
1301 // The value at the end of the loop for the reverse pointer is calculated
1302 // by creating a GEP with a negative index starting from the start value.
1303 Value *Zero = ConstantInt::get(CountRoundDown->getType(), 0);
1304 Value *NegIdx = BinaryOperator::CreateSub(Zero, CountRoundDown,
1306 LoopBypassBlocks.back()->getTerminator());
1307 EndValue = GetElementPtrInst::Create(II.StartValue, NegIdx,
1309 LoopBypassBlocks.back()->getTerminator());
1314 // The new PHI merges the original incoming value, in case of a bypass,
1315 // or the value at the end of the vectorized loop.
1316 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
1317 ResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
1318 ResumeVal->addIncoming(EndValue, VecBody);
1320 // Fix the scalar body counter (PHI node).
1321 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
1322 OrigPhi->setIncomingValue(BlockIdx, ResumeVal);
1325 // If we are generating a new induction variable then we also need to
1326 // generate the code that calculates the exit value. This value is not
1327 // simply the end of the counter because we may skip the vectorized body
1328 // in case of a runtime check.
1330 assert(!ResumeIndex && "Unexpected resume value found");
1331 ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
1332 MiddleBlock->getTerminator());
1333 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
1334 ResumeIndex->addIncoming(StartIdx, LoopBypassBlocks[I]);
1335 ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
1338 // Make sure that we found the index where scalar loop needs to continue.
1339 assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
1340 "Invalid resume Index");
1342 // Add a check in the middle block to see if we have completed
1343 // all of the iterations in the first vector loop.
1344 // If (N - N%VF) == N, then we *don't* need to run the remainder.
1345 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
1346 ResumeIndex, "cmp.n",
1347 MiddleBlock->getTerminator());
1349 BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
1350 // Remove the old terminator.
1351 MiddleBlock->getTerminator()->eraseFromParent();
1353 // Create i+1 and fill the PHINode.
1354 Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
1355 Induction->addIncoming(StartIdx, VectorPH);
1356 Induction->addIncoming(NextIdx, VecBody);
1357 // Create the compare.
1358 Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
1359 Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
1361 // Now we have two terminators. Remove the old one from the block.
1362 VecBody->getTerminator()->eraseFromParent();
1364 // Get ready to start creating new instructions into the vectorized body.
1365 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
1367 // Create and register the new vector loop.
1368 Loop* Lp = new Loop();
1369 Loop *ParentLoop = OrigLoop->getParentLoop();
1371 // Insert the new loop into the loop nest and register the new basic blocks.
1373 ParentLoop->addChildLoop(Lp);
1374 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
1375 ParentLoop->addBasicBlockToLoop(LoopBypassBlocks[I], LI->getBase());
1376 ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
1377 ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
1378 ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
1380 LI->addTopLevelLoop(Lp);
1383 Lp->addBasicBlockToLoop(VecBody, LI->getBase());
1386 LoopVectorPreHeader = VectorPH;
1387 LoopScalarPreHeader = ScalarPH;
1388 LoopMiddleBlock = MiddleBlock;
1389 LoopExitBlock = ExitBlock;
1390 LoopVectorBody = VecBody;
1391 LoopScalarBody = OldBasicBlock;
1394 /// This function returns the identity element (or neutral element) for
1395 /// the operation K.
1397 getReductionIdentity(LoopVectorizationLegality::ReductionKind K, Type *Tp) {
1399 case LoopVectorizationLegality:: RK_IntegerXor:
1400 case LoopVectorizationLegality:: RK_IntegerAdd:
1401 case LoopVectorizationLegality:: RK_IntegerOr:
1402 // Adding, Xoring, Oring zero to a number does not change it.
1403 return ConstantInt::get(Tp, 0);
1404 case LoopVectorizationLegality:: RK_IntegerMult:
1405 // Multiplying a number by 1 does not change it.
1406 return ConstantInt::get(Tp, 1);
1407 case LoopVectorizationLegality:: RK_IntegerAnd:
1408 // AND-ing a number with an all-1 value does not change it.
1409 return ConstantInt::get(Tp, -1, true);
1410 case LoopVectorizationLegality:: RK_FloatMult:
1411 // Multiplying a number by 1 does not change it.
1412 return ConstantFP::get(Tp, 1.0L);
1413 case LoopVectorizationLegality:: RK_FloatAdd:
1414 // Adding zero to a number does not change it.
1415 return ConstantFP::get(Tp, 0.0L);
1417 llvm_unreachable("Unknown reduction kind");
1422 isTriviallyVectorizableIntrinsic(Instruction *Inst) {
1423 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst);
1426 switch (II->getIntrinsicID()) {
1427 case Intrinsic::sqrt:
1428 case Intrinsic::sin:
1429 case Intrinsic::cos:
1430 case Intrinsic::exp:
1431 case Intrinsic::exp2:
1432 case Intrinsic::log:
1433 case Intrinsic::log10:
1434 case Intrinsic::log2:
1435 case Intrinsic::fabs:
1436 case Intrinsic::floor:
1437 case Intrinsic::ceil:
1438 case Intrinsic::trunc:
1439 case Intrinsic::rint:
1440 case Intrinsic::nearbyint:
1441 case Intrinsic::pow:
1442 case Intrinsic::fma:
1443 case Intrinsic::fmuladd:
1451 /// This function translates the reduction kind to an LLVM binary operator.
1452 static Instruction::BinaryOps
1453 getReductionBinOp(LoopVectorizationLegality::ReductionKind Kind) {
1455 case LoopVectorizationLegality::RK_IntegerAdd:
1456 return Instruction::Add;
1457 case LoopVectorizationLegality::RK_IntegerMult:
1458 return Instruction::Mul;
1459 case LoopVectorizationLegality::RK_IntegerOr:
1460 return Instruction::Or;
1461 case LoopVectorizationLegality::RK_IntegerAnd:
1462 return Instruction::And;
1463 case LoopVectorizationLegality::RK_IntegerXor:
1464 return Instruction::Xor;
1465 case LoopVectorizationLegality::RK_FloatMult:
1466 return Instruction::FMul;
1467 case LoopVectorizationLegality::RK_FloatAdd:
1468 return Instruction::FAdd;
1470 llvm_unreachable("Unknown reduction operation");
1475 InnerLoopVectorizer::vectorizeLoop(LoopVectorizationLegality *Legal) {
1476 //===------------------------------------------------===//
1478 // Notice: any optimization or new instruction that go
1479 // into the code below should be also be implemented in
1482 //===------------------------------------------------===//
1483 Constant *Zero = Builder.getInt32(0);
1485 // In order to support reduction variables we need to be able to vectorize
1486 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
1487 // stages. First, we create a new vector PHI node with no incoming edges.
1488 // We use this value when we vectorize all of the instructions that use the
1489 // PHI. Next, after all of the instructions in the block are complete we
1490 // add the new incoming edges to the PHI. At this point all of the
1491 // instructions in the basic block are vectorized, so we can use them to
1492 // construct the PHI.
1493 PhiVector RdxPHIsToFix;
1495 // Scan the loop in a topological order to ensure that defs are vectorized
1497 LoopBlocksDFS DFS(OrigLoop);
1500 // Vectorize all of the blocks in the original loop.
1501 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
1502 be = DFS.endRPO(); bb != be; ++bb)
1503 vectorizeBlockInLoop(Legal, *bb, &RdxPHIsToFix);
1505 // At this point every instruction in the original loop is widened to
1506 // a vector form. We are almost done. Now, we need to fix the PHI nodes
1507 // that we vectorized. The PHI nodes are currently empty because we did
1508 // not want to introduce cycles. Notice that the remaining PHI nodes
1509 // that we need to fix are reduction variables.
1511 // Create the 'reduced' values for each of the induction vars.
1512 // The reduced values are the vector values that we scalarize and combine
1513 // after the loop is finished.
1514 for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
1516 PHINode *RdxPhi = *it;
1517 assert(RdxPhi && "Unable to recover vectorized PHI");
1519 // Find the reduction variable descriptor.
1520 assert(Legal->getReductionVars()->count(RdxPhi) &&
1521 "Unable to find the reduction variable");
1522 LoopVectorizationLegality::ReductionDescriptor RdxDesc =
1523 (*Legal->getReductionVars())[RdxPhi];
1525 // We need to generate a reduction vector from the incoming scalar.
1526 // To do so, we need to generate the 'identity' vector and overide
1527 // one of the elements with the incoming scalar reduction. We need
1528 // to do it in the vector-loop preheader.
1529 Builder.SetInsertPoint(LoopBypassBlocks.back()->getTerminator());
1531 // This is the vector-clone of the value that leaves the loop.
1532 VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
1533 Type *VecTy = VectorExit[0]->getType();
1535 // Find the reduction identity variable. Zero for addition, or, xor,
1536 // one for multiplication, -1 for And.
1537 Constant *Iden = getReductionIdentity(RdxDesc.Kind, VecTy->getScalarType());
1538 Constant *Identity = ConstantVector::getSplat(VF, Iden);
1540 // This vector is the Identity vector where the first element is the
1541 // incoming scalar reduction.
1542 Value *VectorStart = Builder.CreateInsertElement(Identity,
1543 RdxDesc.StartValue, Zero);
1545 // Fix the vector-loop phi.
1546 // We created the induction variable so we know that the
1547 // preheader is the first entry.
1548 BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
1550 // Reductions do not have to start at zero. They can start with
1551 // any loop invariant values.
1552 VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
1553 BasicBlock *Latch = OrigLoop->getLoopLatch();
1554 Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
1555 VectorParts &Val = getVectorValue(LoopVal);
1556 for (unsigned part = 0; part < UF; ++part) {
1557 // Make sure to add the reduction stat value only to the
1558 // first unroll part.
1559 Value *StartVal = (part == 0) ? VectorStart : Identity;
1560 cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal, VecPreheader);
1561 cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part], LoopVectorBody);
1564 // Before each round, move the insertion point right between
1565 // the PHIs and the values we are going to write.
1566 // This allows us to write both PHINodes and the extractelement
1568 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
1570 VectorParts RdxParts;
1571 for (unsigned part = 0; part < UF; ++part) {
1572 // This PHINode contains the vectorized reduction variable, or
1573 // the initial value vector, if we bypass the vector loop.
1574 VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr);
1575 PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
1576 Value *StartVal = (part == 0) ? VectorStart : Identity;
1577 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
1578 NewPhi->addIncoming(StartVal, LoopBypassBlocks[I]);
1579 NewPhi->addIncoming(RdxExitVal[part], LoopVectorBody);
1580 RdxParts.push_back(NewPhi);
1583 // Reduce all of the unrolled parts into a single vector.
1584 Value *ReducedPartRdx = RdxParts[0];
1585 for (unsigned part = 1; part < UF; ++part) {
1586 Instruction::BinaryOps Op = getReductionBinOp(RdxDesc.Kind);
1587 ReducedPartRdx = Builder.CreateBinOp(Op, RdxParts[part], ReducedPartRdx,
1591 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
1592 // and vector ops, reducing the set of values being computed by half each
1594 assert(isPowerOf2_32(VF) &&
1595 "Reduction emission only supported for pow2 vectors!");
1596 Value *TmpVec = ReducedPartRdx;
1597 SmallVector<Constant*, 32> ShuffleMask(VF, 0);
1598 for (unsigned i = VF; i != 1; i >>= 1) {
1599 // Move the upper half of the vector to the lower half.
1600 for (unsigned j = 0; j != i/2; ++j)
1601 ShuffleMask[j] = Builder.getInt32(i/2 + j);
1603 // Fill the rest of the mask with undef.
1604 std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
1605 UndefValue::get(Builder.getInt32Ty()));
1608 Builder.CreateShuffleVector(TmpVec,
1609 UndefValue::get(TmpVec->getType()),
1610 ConstantVector::get(ShuffleMask),
1613 Instruction::BinaryOps Op = getReductionBinOp(RdxDesc.Kind);
1614 TmpVec = Builder.CreateBinOp(Op, TmpVec, Shuf, "bin.rdx");
1617 // The result is in the first element of the vector.
1618 Value *Scalar0 = Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
1620 // Now, we need to fix the users of the reduction variable
1621 // inside and outside of the scalar remainder loop.
1622 // We know that the loop is in LCSSA form. We need to update the
1623 // PHI nodes in the exit blocks.
1624 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
1625 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
1626 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
1627 if (!LCSSAPhi) continue;
1629 // All PHINodes need to have a single entry edge, or two if
1630 // we already fixed them.
1631 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
1633 // We found our reduction value exit-PHI. Update it with the
1634 // incoming bypass edge.
1635 if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
1636 // Add an edge coming from the bypass.
1637 LCSSAPhi->addIncoming(Scalar0, LoopMiddleBlock);
1640 }// end of the LCSSA phi scan.
1642 // Fix the scalar loop reduction variable with the incoming reduction sum
1643 // from the vector body and from the backedge value.
1644 int IncomingEdgeBlockIdx =
1645 (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
1646 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
1647 // Pick the other block.
1648 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
1649 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, Scalar0);
1650 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
1651 }// end of for each redux variable.
1653 // The Loop exit block may have single value PHI nodes where the incoming
1654 // value is 'undef'. While vectorizing we only handled real values that
1655 // were defined inside the loop. Here we handle the 'undef case'.
1657 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
1658 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
1659 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
1660 if (!LCSSAPhi) continue;
1661 if (LCSSAPhi->getNumIncomingValues() == 1)
1662 LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
1667 InnerLoopVectorizer::VectorParts
1668 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
1669 assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
1672 VectorParts SrcMask = createBlockInMask(Src);
1674 // The terminator has to be a branch inst!
1675 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
1676 assert(BI && "Unexpected terminator found");
1678 if (BI->isConditional()) {
1679 VectorParts EdgeMask = getVectorValue(BI->getCondition());
1681 if (BI->getSuccessor(0) != Dst)
1682 for (unsigned part = 0; part < UF; ++part)
1683 EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
1685 for (unsigned part = 0; part < UF; ++part)
1686 EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
1693 InnerLoopVectorizer::VectorParts
1694 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
1695 assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
1697 // Loop incoming mask is all-one.
1698 if (OrigLoop->getHeader() == BB) {
1699 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
1700 return getVectorValue(C);
1703 // This is the block mask. We OR all incoming edges, and with zero.
1704 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
1705 VectorParts BlockMask = getVectorValue(Zero);
1708 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
1709 VectorParts EM = createEdgeMask(*it, BB);
1710 for (unsigned part = 0; part < UF; ++part)
1711 BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
1718 InnerLoopVectorizer::vectorizeBlockInLoop(LoopVectorizationLegality *Legal,
1719 BasicBlock *BB, PhiVector *PV) {
1720 // For each instruction in the old loop.
1721 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1722 VectorParts &Entry = WidenMap.get(it);
1723 switch (it->getOpcode()) {
1724 case Instruction::Br:
1725 // Nothing to do for PHIs and BR, since we already took care of the
1726 // loop control flow instructions.
1728 case Instruction::PHI:{
1729 PHINode* P = cast<PHINode>(it);
1730 // Handle reduction variables:
1731 if (Legal->getReductionVars()->count(P)) {
1732 for (unsigned part = 0; part < UF; ++part) {
1733 // This is phase one of vectorizing PHIs.
1734 Type *VecTy = VectorType::get(it->getType(), VF);
1735 Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
1736 LoopVectorBody-> getFirstInsertionPt());
1742 // Check for PHI nodes that are lowered to vector selects.
1743 if (P->getParent() != OrigLoop->getHeader()) {
1744 // We know that all PHIs in non header blocks are converted into
1745 // selects, so we don't have to worry about the insertion order and we
1746 // can just use the builder.
1748 // At this point we generate the predication tree. There may be
1749 // duplications since this is a simple recursive scan, but future
1750 // optimizations will clean it up.
1751 VectorParts Cond = createEdgeMask(P->getIncomingBlock(0),
1754 for (unsigned part = 0; part < UF; ++part) {
1755 VectorParts &In0 = getVectorValue(P->getIncomingValue(0));
1756 VectorParts &In1 = getVectorValue(P->getIncomingValue(1));
1757 Entry[part] = Builder.CreateSelect(Cond[part], In0[part], In1[part],
1763 // This PHINode must be an induction variable.
1764 // Make sure that we know about it.
1765 assert(Legal->getInductionVars()->count(P) &&
1766 "Not an induction variable");
1768 LoopVectorizationLegality::InductionInfo II =
1769 Legal->getInductionVars()->lookup(P);
1772 case LoopVectorizationLegality::IK_NoInduction:
1773 llvm_unreachable("Unknown induction");
1774 case LoopVectorizationLegality::IK_IntInduction: {
1775 assert(P == OldInduction && "Unexpected PHI");
1776 Value *Broadcasted = getBroadcastInstrs(Induction);
1777 // After broadcasting the induction variable we need to make the
1778 // vector consecutive by adding 0, 1, 2 ...
1779 for (unsigned part = 0; part < UF; ++part)
1780 Entry[part] = getConsecutiveVector(Broadcasted, VF * part, false);
1783 case LoopVectorizationLegality::IK_ReverseIntInduction:
1784 case LoopVectorizationLegality::IK_PtrInduction:
1785 case LoopVectorizationLegality::IK_ReversePtrInduction:
1786 // Handle reverse integer and pointer inductions.
1787 Value *StartIdx = 0;
1788 // If we have a single integer induction variable then use it.
1789 // Otherwise, start counting at zero.
1791 LoopVectorizationLegality::InductionInfo OldII =
1792 Legal->getInductionVars()->lookup(OldInduction);
1793 StartIdx = OldII.StartValue;
1795 StartIdx = ConstantInt::get(Induction->getType(), 0);
1797 // This is the normalized GEP that starts counting at zero.
1798 Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
1801 // Handle the reverse integer induction variable case.
1802 if (LoopVectorizationLegality::IK_ReverseIntInduction == II.IK) {
1803 IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType());
1804 Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy,
1806 Value *ReverseInd = Builder.CreateSub(II.StartValue, CNI,
1809 // This is a new value so do not hoist it out.
1810 Value *Broadcasted = getBroadcastInstrs(ReverseInd);
1811 // After broadcasting the induction variable we need to make the
1812 // vector consecutive by adding ... -3, -2, -1, 0.
1813 for (unsigned part = 0; part < UF; ++part)
1814 Entry[part] = getConsecutiveVector(Broadcasted, -VF * part, true);
1818 // Handle the pointer induction variable case.
1819 assert(P->getType()->isPointerTy() && "Unexpected type.");
1821 // Is this a reverse induction ptr or a consecutive induction ptr.
1822 bool Reverse = (LoopVectorizationLegality::IK_ReversePtrInduction ==
1825 // This is the vector of results. Notice that we don't generate
1826 // vector geps because scalar geps result in better code.
1827 for (unsigned part = 0; part < UF; ++part) {
1828 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
1829 for (unsigned int i = 0; i < VF; ++i) {
1830 int EltIndex = (i + part * VF) * (Reverse ? -1 : 1);
1831 Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
1834 GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
1836 GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx");
1838 Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
1840 VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
1841 Builder.getInt32(i),
1844 Entry[part] = VecVal;
1851 case Instruction::Add:
1852 case Instruction::FAdd:
1853 case Instruction::Sub:
1854 case Instruction::FSub:
1855 case Instruction::Mul:
1856 case Instruction::FMul:
1857 case Instruction::UDiv:
1858 case Instruction::SDiv:
1859 case Instruction::FDiv:
1860 case Instruction::URem:
1861 case Instruction::SRem:
1862 case Instruction::FRem:
1863 case Instruction::Shl:
1864 case Instruction::LShr:
1865 case Instruction::AShr:
1866 case Instruction::And:
1867 case Instruction::Or:
1868 case Instruction::Xor: {
1869 // Just widen binops.
1870 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
1871 VectorParts &A = getVectorValue(it->getOperand(0));
1872 VectorParts &B = getVectorValue(it->getOperand(1));
1874 // Use this vector value for all users of the original instruction.
1875 for (unsigned Part = 0; Part < UF; ++Part) {
1876 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
1878 // Update the NSW, NUW and Exact flags. Notice: V can be an Undef.
1879 BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V);
1880 if (VecOp && isa<OverflowingBinaryOperator>(BinOp)) {
1881 VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap());
1882 VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap());
1884 if (VecOp && isa<PossiblyExactOperator>(VecOp))
1885 VecOp->setIsExact(BinOp->isExact());
1891 case Instruction::Select: {
1893 // If the selector is loop invariant we can create a select
1894 // instruction with a scalar condition. Otherwise, use vector-select.
1895 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
1898 // The condition can be loop invariant but still defined inside the
1899 // loop. This means that we can't just use the original 'cond' value.
1900 // We have to take the 'vectorized' value and pick the first lane.
1901 // Instcombine will make this a no-op.
1902 VectorParts &Cond = getVectorValue(it->getOperand(0));
1903 VectorParts &Op0 = getVectorValue(it->getOperand(1));
1904 VectorParts &Op1 = getVectorValue(it->getOperand(2));
1905 Value *ScalarCond = Builder.CreateExtractElement(Cond[0],
1906 Builder.getInt32(0));
1907 for (unsigned Part = 0; Part < UF; ++Part) {
1908 Entry[Part] = Builder.CreateSelect(
1909 InvariantCond ? ScalarCond : Cond[Part],
1916 case Instruction::ICmp:
1917 case Instruction::FCmp: {
1918 // Widen compares. Generate vector compares.
1919 bool FCmp = (it->getOpcode() == Instruction::FCmp);
1920 CmpInst *Cmp = dyn_cast<CmpInst>(it);
1921 VectorParts &A = getVectorValue(it->getOperand(0));
1922 VectorParts &B = getVectorValue(it->getOperand(1));
1923 for (unsigned Part = 0; Part < UF; ++Part) {
1926 C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
1928 C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
1934 case Instruction::Store:
1935 case Instruction::Load:
1936 vectorizeMemoryInstruction(it, Legal);
1938 case Instruction::ZExt:
1939 case Instruction::SExt:
1940 case Instruction::FPToUI:
1941 case Instruction::FPToSI:
1942 case Instruction::FPExt:
1943 case Instruction::PtrToInt:
1944 case Instruction::IntToPtr:
1945 case Instruction::SIToFP:
1946 case Instruction::UIToFP:
1947 case Instruction::Trunc:
1948 case Instruction::FPTrunc:
1949 case Instruction::BitCast: {
1950 CastInst *CI = dyn_cast<CastInst>(it);
1951 /// Optimize the special case where the source is the induction
1952 /// variable. Notice that we can only optimize the 'trunc' case
1953 /// because: a. FP conversions lose precision, b. sext/zext may wrap,
1954 /// c. other casts depend on pointer size.
1955 if (CI->getOperand(0) == OldInduction &&
1956 it->getOpcode() == Instruction::Trunc) {
1957 Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
1959 Value *Broadcasted = getBroadcastInstrs(ScalarCast);
1960 for (unsigned Part = 0; Part < UF; ++Part)
1961 Entry[Part] = getConsecutiveVector(Broadcasted, VF * Part, false);
1964 /// Vectorize casts.
1965 Type *DestTy = VectorType::get(CI->getType()->getScalarType(), VF);
1967 VectorParts &A = getVectorValue(it->getOperand(0));
1968 for (unsigned Part = 0; Part < UF; ++Part)
1969 Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
1973 case Instruction::Call: {
1974 assert(isTriviallyVectorizableIntrinsic(it));
1975 Module *M = BB->getParent()->getParent();
1976 IntrinsicInst *II = cast<IntrinsicInst>(it);
1977 Intrinsic::ID ID = II->getIntrinsicID();
1978 for (unsigned Part = 0; Part < UF; ++Part) {
1979 SmallVector<Value*, 4> Args;
1980 for (unsigned i = 0, ie = II->getNumArgOperands(); i != ie; ++i) {
1981 VectorParts &Arg = getVectorValue(II->getArgOperand(i));
1982 Args.push_back(Arg[Part]);
1984 Type *Tys[] = { VectorType::get(II->getType()->getScalarType(), VF) };
1985 Function *F = Intrinsic::getDeclaration(M, ID, Tys);
1986 Entry[Part] = Builder.CreateCall(F, Args);
1992 // All other instructions are unsupported. Scalarize them.
1993 scalarizeInstruction(it);
1996 }// end of for_each instr.
1999 void InnerLoopVectorizer::updateAnalysis() {
2000 // Forget the original basic block.
2001 SE->forgetLoop(OrigLoop);
2003 // Update the dominator tree information.
2004 assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
2005 "Entry does not dominate exit.");
2007 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2008 DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]);
2009 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back());
2010 DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader);
2011 DT->addNewBlock(LoopMiddleBlock, LoopBypassBlocks.front());
2012 DT->addNewBlock(LoopScalarPreHeader, LoopMiddleBlock);
2013 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
2014 DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
2016 DEBUG(DT->verifyAnalysis());
2019 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
2020 if (!EnableIfConversion)
2023 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
2024 std::vector<BasicBlock*> &LoopBlocks = TheLoop->getBlocksVector();
2026 // Collect the blocks that need predication.
2027 for (unsigned i = 0, e = LoopBlocks.size(); i < e; ++i) {
2028 BasicBlock *BB = LoopBlocks[i];
2030 // We don't support switch statements inside loops.
2031 if (!isa<BranchInst>(BB->getTerminator()))
2034 // We must have at most two predecessors because we need to convert
2035 // all PHIs to selects.
2036 unsigned Preds = std::distance(pred_begin(BB), pred_end(BB));
2040 // We must be able to predicate all blocks that need to be predicated.
2041 if (blockNeedsPredication(BB) && !blockCanBePredicated(BB))
2045 // We can if-convert this loop.
2049 bool LoopVectorizationLegality::canVectorize() {
2050 assert(TheLoop->getLoopPreheader() && "No preheader!!");
2052 // We can only vectorize innermost loops.
2053 if (TheLoop->getSubLoopsVector().size())
2056 // We must have a single backedge.
2057 if (TheLoop->getNumBackEdges() != 1)
2060 // We must have a single exiting block.
2061 if (!TheLoop->getExitingBlock())
2064 unsigned NumBlocks = TheLoop->getNumBlocks();
2066 // Check if we can if-convert non single-bb loops.
2067 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
2068 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
2072 // We need to have a loop header.
2073 BasicBlock *Latch = TheLoop->getLoopLatch();
2074 DEBUG(dbgs() << "LV: Found a loop: " <<
2075 TheLoop->getHeader()->getName() << "\n");
2077 // ScalarEvolution needs to be able to find the exit count.
2078 const SCEV *ExitCount = SE->getExitCount(TheLoop, Latch);
2079 if (ExitCount == SE->getCouldNotCompute()) {
2080 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
2084 // Do not loop-vectorize loops with a tiny trip count.
2085 unsigned TC = SE->getSmallConstantTripCount(TheLoop, Latch);
2086 if (TC > 0u && TC < TinyTripCountVectorThreshold) {
2087 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " <<
2088 "This loop is not worth vectorizing.\n");
2092 // Check if we can vectorize the instructions and CFG in this loop.
2093 if (!canVectorizeInstrs()) {
2094 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
2098 // Go over each instruction and look at memory deps.
2099 if (!canVectorizeMemory()) {
2100 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
2104 // Collect all of the variables that remain uniform after vectorization.
2105 collectLoopUniforms();
2107 DEBUG(dbgs() << "LV: We can vectorize this loop" <<
2108 (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
2111 // Okay! We can vectorize. At this point we don't have any other mem analysis
2112 // which may limit our maximum vectorization factor, so just return true with
2117 bool LoopVectorizationLegality::canVectorizeInstrs() {
2118 BasicBlock *PreHeader = TheLoop->getLoopPreheader();
2119 BasicBlock *Header = TheLoop->getHeader();
2121 // For each block in the loop.
2122 for (Loop::block_iterator bb = TheLoop->block_begin(),
2123 be = TheLoop->block_end(); bb != be; ++bb) {
2125 // Scan the instructions in the block and look for hazards.
2126 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
2129 if (PHINode *Phi = dyn_cast<PHINode>(it)) {
2130 // This should not happen because the loop should be normalized.
2131 if (Phi->getNumIncomingValues() != 2) {
2132 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
2136 // Check that this PHI type is allowed.
2137 if (!Phi->getType()->isIntegerTy() &&
2138 !Phi->getType()->isFloatingPointTy() &&
2139 !Phi->getType()->isPointerTy()) {
2140 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
2144 // If this PHINode is not in the header block, then we know that we
2145 // can convert it to select during if-conversion. No need to check if
2146 // the PHIs in this block are induction or reduction variables.
2150 // This is the value coming from the preheader.
2151 Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
2152 // Check if this is an induction variable.
2153 InductionKind IK = isInductionVariable(Phi);
2155 if (IK_NoInduction != IK) {
2156 // Int inductions are special because we only allow one IV.
2157 if (IK == IK_IntInduction) {
2159 DEBUG(dbgs() << "LV: Found too many inductions."<< *Phi <<"\n");
2165 DEBUG(dbgs() << "LV: Found an induction variable.\n");
2166 Inductions[Phi] = InductionInfo(StartValue, IK);
2170 if (AddReductionVar(Phi, RK_IntegerAdd)) {
2171 DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
2174 if (AddReductionVar(Phi, RK_IntegerMult)) {
2175 DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
2178 if (AddReductionVar(Phi, RK_IntegerOr)) {
2179 DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
2182 if (AddReductionVar(Phi, RK_IntegerAnd)) {
2183 DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
2186 if (AddReductionVar(Phi, RK_IntegerXor)) {
2187 DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
2190 if (AddReductionVar(Phi, RK_FloatMult)) {
2191 DEBUG(dbgs() << "LV: Found an FMult reduction PHI."<< *Phi <<"\n");
2194 if (AddReductionVar(Phi, RK_FloatAdd)) {
2195 DEBUG(dbgs() << "LV: Found an FAdd reduction PHI."<< *Phi <<"\n");
2199 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
2201 }// end of PHI handling
2203 // We still don't handle functions.
2204 CallInst *CI = dyn_cast<CallInst>(it);
2205 if (CI && !isTriviallyVectorizableIntrinsic(it)) {
2206 DEBUG(dbgs() << "LV: Found a call site.\n");
2210 // Check that the instruction return type is vectorizable.
2211 if (!VectorType::isValidElementType(it->getType()) &&
2212 !it->getType()->isVoidTy()) {
2213 DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n");
2217 // Check that the stored type is vectorizable.
2218 if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
2219 Type *T = ST->getValueOperand()->getType();
2220 if (!VectorType::isValidElementType(T))
2224 // Reduction instructions are allowed to have exit users.
2225 // All other instructions must not have external users.
2226 if (!AllowedExit.count(it))
2227 //Check that all of the users of the loop are inside the BB.
2228 for (Value::use_iterator I = it->use_begin(), E = it->use_end();
2230 Instruction *U = cast<Instruction>(*I);
2231 // This user may be a reduction exit value.
2232 if (!TheLoop->contains(U)) {
2233 DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n");
2242 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
2243 assert(getInductionVars()->size() && "No induction variables");
2249 void LoopVectorizationLegality::collectLoopUniforms() {
2250 // We now know that the loop is vectorizable!
2251 // Collect variables that will remain uniform after vectorization.
2252 std::vector<Value*> Worklist;
2253 BasicBlock *Latch = TheLoop->getLoopLatch();
2255 // Start with the conditional branch and walk up the block.
2256 Worklist.push_back(Latch->getTerminator()->getOperand(0));
2258 while (Worklist.size()) {
2259 Instruction *I = dyn_cast<Instruction>(Worklist.back());
2260 Worklist.pop_back();
2262 // Look at instructions inside this loop.
2263 // Stop when reaching PHI nodes.
2264 // TODO: we need to follow values all over the loop, not only in this block.
2265 if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
2268 // This is a known uniform.
2271 // Insert all operands.
2272 for (int i = 0, Op = I->getNumOperands(); i < Op; ++i) {
2273 Worklist.push_back(I->getOperand(i));
2278 bool LoopVectorizationLegality::canVectorizeMemory() {
2279 typedef SmallVector<Value*, 16> ValueVector;
2280 typedef SmallPtrSet<Value*, 16> ValueSet;
2281 // Holds the Load and Store *instructions*.
2284 PtrRtCheck.Pointers.clear();
2285 PtrRtCheck.Need = false;
2288 for (Loop::block_iterator bb = TheLoop->block_begin(),
2289 be = TheLoop->block_end(); bb != be; ++bb) {
2291 // Scan the BB and collect legal loads and stores.
2292 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
2295 // If this is a load, save it. If this instruction can read from memory
2296 // but is not a load, then we quit. Notice that we don't handle function
2297 // calls that read or write.
2298 if (it->mayReadFromMemory()) {
2299 LoadInst *Ld = dyn_cast<LoadInst>(it);
2300 if (!Ld) return false;
2301 if (!Ld->isSimple()) {
2302 DEBUG(dbgs() << "LV: Found a non-simple load.\n");
2305 Loads.push_back(Ld);
2309 // Save 'store' instructions. Abort if other instructions write to memory.
2310 if (it->mayWriteToMemory()) {
2311 StoreInst *St = dyn_cast<StoreInst>(it);
2312 if (!St) return false;
2313 if (!St->isSimple()) {
2314 DEBUG(dbgs() << "LV: Found a non-simple store.\n");
2317 Stores.push_back(St);
2322 // Now we have two lists that hold the loads and the stores.
2323 // Next, we find the pointers that they use.
2325 // Check if we see any stores. If there are no stores, then we don't
2326 // care if the pointers are *restrict*.
2327 if (!Stores.size()) {
2328 DEBUG(dbgs() << "LV: Found a read-only loop!\n");
2332 // Holds the read and read-write *pointers* that we find.
2334 ValueVector ReadWrites;
2336 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
2337 // multiple times on the same object. If the ptr is accessed twice, once
2338 // for read and once for write, it will only appear once (on the write
2339 // list). This is okay, since we are going to check for conflicts between
2340 // writes and between reads and writes, but not between reads and reads.
2343 ValueVector::iterator I, IE;
2344 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
2345 StoreInst *ST = cast<StoreInst>(*I);
2346 Value* Ptr = ST->getPointerOperand();
2348 if (isUniform(Ptr)) {
2349 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
2353 // If we did *not* see this pointer before, insert it to
2354 // the read-write list. At this phase it is only a 'write' list.
2355 if (Seen.insert(Ptr))
2356 ReadWrites.push_back(Ptr);
2359 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
2360 LoadInst *LD = cast<LoadInst>(*I);
2361 Value* Ptr = LD->getPointerOperand();
2362 // If we did *not* see this pointer before, insert it to the
2363 // read list. If we *did* see it before, then it is already in
2364 // the read-write list. This allows us to vectorize expressions
2365 // such as A[i] += x; Because the address of A[i] is a read-write
2366 // pointer. This only works if the index of A[i] is consecutive.
2367 // If the address of i is unknown (for example A[B[i]]) then we may
2368 // read a few words, modify, and write a few words, and some of the
2369 // words may be written to the same address.
2370 if (Seen.insert(Ptr) || 0 == isConsecutivePtr(Ptr))
2371 Reads.push_back(Ptr);
2374 // If we write (or read-write) to a single destination and there are no
2375 // other reads in this loop then is it safe to vectorize.
2376 if (ReadWrites.size() == 1 && Reads.size() == 0) {
2377 DEBUG(dbgs() << "LV: Found a write-only loop!\n");
2381 // Find pointers with computable bounds. We are going to use this information
2382 // to place a runtime bound check.
2383 bool CanDoRT = true;
2384 for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I)
2385 if (hasComputableBounds(*I)) {
2386 PtrRtCheck.insert(SE, TheLoop, *I);
2387 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n");
2392 for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I)
2393 if (hasComputableBounds(*I)) {
2394 PtrRtCheck.insert(SE, TheLoop, *I);
2395 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n");
2401 // Check that we did not collect too many pointers or found a
2402 // unsizeable pointer.
2403 if (!CanDoRT || PtrRtCheck.Pointers.size() > RuntimeMemoryCheckThreshold) {
2409 DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
2412 bool NeedRTCheck = false;
2414 // Now that the pointers are in two lists (Reads and ReadWrites), we
2415 // can check that there are no conflicts between each of the writes and
2416 // between the writes to the reads.
2417 ValueSet WriteObjects;
2418 ValueVector TempObjects;
2420 // Check that the read-writes do not conflict with other read-write
2422 bool AllWritesIdentified = true;
2423 for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I) {
2424 GetUnderlyingObjects(*I, TempObjects, DL);
2425 for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
2427 if (!isIdentifiedObject(*it)) {
2428 DEBUG(dbgs() << "LV: Found an unidentified write ptr:"<< **it <<"\n");
2430 AllWritesIdentified = false;
2432 if (!WriteObjects.insert(*it)) {
2433 DEBUG(dbgs() << "LV: Found a possible write-write reorder:"
2438 TempObjects.clear();
2441 /// Check that the reads don't conflict with the read-writes.
2442 for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I) {
2443 GetUnderlyingObjects(*I, TempObjects, DL);
2444 for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
2446 // If all of the writes are identified then we don't care if the read
2447 // pointer is identified or not.
2448 if (!AllWritesIdentified && !isIdentifiedObject(*it)) {
2449 DEBUG(dbgs() << "LV: Found an unidentified read ptr:"<< **it <<"\n");
2452 if (WriteObjects.count(*it)) {
2453 DEBUG(dbgs() << "LV: Found a possible read/write reorder:"
2458 TempObjects.clear();
2461 PtrRtCheck.Need = NeedRTCheck;
2462 if (NeedRTCheck && !CanDoRT) {
2463 DEBUG(dbgs() << "LV: We can't vectorize because we can't find " <<
2464 "the array bounds.\n");
2469 DEBUG(dbgs() << "LV: We "<< (NeedRTCheck ? "" : "don't") <<
2470 " need a runtime memory check.\n");
2474 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
2475 ReductionKind Kind) {
2476 if (Phi->getNumIncomingValues() != 2)
2479 // Reduction variables are only found in the loop header block.
2480 if (Phi->getParent() != TheLoop->getHeader())
2483 // Obtain the reduction start value from the value that comes from the loop
2485 Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
2487 // ExitInstruction is the single value which is used outside the loop.
2488 // We only allow for a single reduction value to be used outside the loop.
2489 // This includes users of the reduction, variables (which form a cycle
2490 // which ends in the phi node).
2491 Instruction *ExitInstruction = 0;
2492 // Indicates that we found a binary operation in our scan.
2493 bool FoundBinOp = false;
2495 // Iter is our iterator. We start with the PHI node and scan for all of the
2496 // users of this instruction. All users must be instructions that can be
2497 // used as reduction variables (such as ADD). We may have a single
2498 // out-of-block user. The cycle must end with the original PHI.
2499 Instruction *Iter = Phi;
2501 // If the instruction has no users then this is a broken
2502 // chain and can't be a reduction variable.
2503 if (Iter->use_empty())
2506 // Did we find a user inside this loop already ?
2507 bool FoundInBlockUser = false;
2508 // Did we reach the initial PHI node already ?
2509 bool FoundStartPHI = false;
2511 // Is this a bin op ?
2512 FoundBinOp |= !isa<PHINode>(Iter);
2514 // For each of the *users* of iter.
2515 for (Value::use_iterator it = Iter->use_begin(), e = Iter->use_end();
2517 Instruction *U = cast<Instruction>(*it);
2518 // We already know that the PHI is a user.
2520 FoundStartPHI = true;
2524 // Check if we found the exit user.
2525 BasicBlock *Parent = U->getParent();
2526 if (!TheLoop->contains(Parent)) {
2527 // Exit if you find multiple outside users.
2528 if (ExitInstruction != 0)
2530 ExitInstruction = Iter;
2533 // We allow in-loop PHINodes which are not the original reduction PHI
2534 // node. If this PHI is the only user of Iter (happens in IF w/ no ELSE
2535 // structure) then don't skip this PHI.
2536 if (isa<PHINode>(Iter) && isa<PHINode>(U) &&
2537 U->getParent() != TheLoop->getHeader() &&
2538 TheLoop->contains(U) &&
2539 Iter->getNumUses() > 1)
2542 // We can't have multiple inside users.
2543 if (FoundInBlockUser)
2545 FoundInBlockUser = true;
2547 // Any reduction instr must be of one of the allowed kinds.
2548 if (!isReductionInstr(U, Kind))
2551 // Reductions of instructions such as Div, and Sub is only
2552 // possible if the LHS is the reduction variable.
2553 if (!U->isCommutative() && !isa<PHINode>(U) && U->getOperand(0) != Iter)
2559 // We found a reduction var if we have reached the original
2560 // phi node and we only have a single instruction with out-of-loop
2562 if (FoundStartPHI) {
2563 // This instruction is allowed to have out-of-loop users.
2564 AllowedExit.insert(ExitInstruction);
2566 // Save the description of this reduction variable.
2567 ReductionDescriptor RD(RdxStart, ExitInstruction, Kind);
2568 Reductions[Phi] = RD;
2569 // We've ended the cycle. This is a reduction variable if we have an
2570 // outside user and it has a binary op.
2571 return FoundBinOp && ExitInstruction;
2577 LoopVectorizationLegality::isReductionInstr(Instruction *I,
2578 ReductionKind Kind) {
2579 bool FP = I->getType()->isFloatingPointTy();
2580 bool FastMath = (FP && I->isCommutative() && I->isAssociative());
2582 switch (I->getOpcode()) {
2585 case Instruction::PHI:
2586 if (FP && (Kind != RK_FloatMult && Kind != RK_FloatAdd))
2590 case Instruction::Sub:
2591 case Instruction::Add:
2592 return Kind == RK_IntegerAdd;
2593 case Instruction::SDiv:
2594 case Instruction::UDiv:
2595 case Instruction::Mul:
2596 return Kind == RK_IntegerMult;
2597 case Instruction::And:
2598 return Kind == RK_IntegerAnd;
2599 case Instruction::Or:
2600 return Kind == RK_IntegerOr;
2601 case Instruction::Xor:
2602 return Kind == RK_IntegerXor;
2603 case Instruction::FMul:
2604 return Kind == RK_FloatMult && FastMath;
2605 case Instruction::FAdd:
2606 return Kind == RK_FloatAdd && FastMath;
2610 LoopVectorizationLegality::InductionKind
2611 LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
2612 Type *PhiTy = Phi->getType();
2613 // We only handle integer and pointer inductions variables.
2614 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
2615 return IK_NoInduction;
2617 // Check that the PHI is consecutive.
2618 const SCEV *PhiScev = SE->getSCEV(Phi);
2619 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
2621 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
2622 return IK_NoInduction;
2624 const SCEV *Step = AR->getStepRecurrence(*SE);
2626 // Integer inductions need to have a stride of one.
2627 if (PhiTy->isIntegerTy()) {
2629 return IK_IntInduction;
2630 if (Step->isAllOnesValue())
2631 return IK_ReverseIntInduction;
2632 return IK_NoInduction;
2635 // Calculate the pointer stride and check if it is consecutive.
2636 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
2638 return IK_NoInduction;
2640 assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
2641 uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType());
2642 if (C->getValue()->equalsInt(Size))
2643 return IK_PtrInduction;
2644 else if (C->getValue()->equalsInt(0 - Size))
2645 return IK_ReversePtrInduction;
2647 return IK_NoInduction;
2650 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
2651 Value *In0 = const_cast<Value*>(V);
2652 PHINode *PN = dyn_cast_or_null<PHINode>(In0);
2656 return Inductions.count(PN);
2659 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
2660 assert(TheLoop->contains(BB) && "Unknown block used");
2662 // Blocks that do not dominate the latch need predication.
2663 BasicBlock* Latch = TheLoop->getLoopLatch();
2664 return !DT->dominates(BB, Latch);
2667 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB) {
2668 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2669 // We don't predicate loads/stores at the moment.
2670 if (it->mayReadFromMemory() || it->mayWriteToMemory() || it->mayThrow())
2673 // The instructions below can trap.
2674 switch (it->getOpcode()) {
2676 case Instruction::UDiv:
2677 case Instruction::SDiv:
2678 case Instruction::URem:
2679 case Instruction::SRem:
2687 bool LoopVectorizationLegality::hasComputableBounds(Value *Ptr) {
2688 const SCEV *PhiScev = SE->getSCEV(Ptr);
2689 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
2693 return AR->isAffine();
2696 LoopVectorizationCostModel::VectorizationFactor
2697 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize,
2699 // Width 1 means no vectorize
2700 VectorizationFactor Factor = { 1U, 0U };
2701 if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
2702 DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
2706 // Find the trip count.
2707 unsigned TC = SE->getSmallConstantTripCount(TheLoop, TheLoop->getLoopLatch());
2708 DEBUG(dbgs() << "LV: Found trip count:"<<TC<<"\n");
2710 unsigned WidestType = getWidestType();
2711 unsigned WidestRegister = TTI.getRegisterBitWidth(true);
2712 unsigned MaxVectorSize = WidestRegister / WidestType;
2713 DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n");
2714 DEBUG(dbgs() << "LV: The Widest register is:" << WidestRegister << "bits.\n");
2716 if (MaxVectorSize == 0) {
2717 DEBUG(dbgs() << "LV: The target has no vector registers.\n");
2721 assert(MaxVectorSize <= 32 && "Did not expect to pack so many elements"
2722 " into one vector!");
2724 unsigned VF = MaxVectorSize;
2726 // If we optimize the program for size, avoid creating the tail loop.
2728 // If we are unable to calculate the trip count then don't try to vectorize.
2730 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
2734 // Find the maximum SIMD width that can fit within the trip count.
2735 VF = TC % MaxVectorSize;
2740 // If the trip count that we found modulo the vectorization factor is not
2741 // zero then we require a tail.
2743 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
2749 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
2750 DEBUG(dbgs() << "LV: Using user VF "<<UserVF<<".\n");
2752 Factor.Width = UserVF;
2756 float Cost = expectedCost(1);
2758 DEBUG(dbgs() << "LV: Scalar loop costs: "<< (int)Cost << ".\n");
2759 for (unsigned i=2; i <= VF; i*=2) {
2760 // Notice that the vector loop needs to be executed less times, so
2761 // we need to divide the cost of the vector loops by the width of
2762 // the vector elements.
2763 float VectorCost = expectedCost(i) / (float)i;
2764 DEBUG(dbgs() << "LV: Vector loop of width "<< i << " costs: " <<
2765 (int)VectorCost << ".\n");
2766 if (VectorCost < Cost) {
2772 DEBUG(dbgs() << "LV: Selecting VF = : "<< Width << ".\n");
2773 Factor.Width = Width;
2774 Factor.Cost = Width * Cost;
2778 unsigned LoopVectorizationCostModel::getWidestType() {
2779 unsigned MaxWidth = 8;
2782 for (Loop::block_iterator bb = TheLoop->block_begin(),
2783 be = TheLoop->block_end(); bb != be; ++bb) {
2784 BasicBlock *BB = *bb;
2786 // For each instruction in the loop.
2787 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2788 Type *T = it->getType();
2790 // Only examine Loads, Stores and PHINodes.
2791 if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
2794 // Examine PHI nodes that are reduction variables.
2795 if (PHINode *PN = dyn_cast<PHINode>(it))
2796 if (!Legal->getReductionVars()->count(PN))
2799 // Examine the stored values.
2801 if ((ST = dyn_cast<StoreInst>(it)))
2802 T = ST->getValueOperand()->getType();
2804 // Ignore loaded pointer types and stored pointer types that are not
2805 // consecutive. However, we do want to take consecutive stores/loads of
2806 // pointer vectors into account.
2807 if (T->isPointerTy() && isConsecutiveLoadOrStore(it))
2808 MaxWidth = std::max(MaxWidth, DL->getPointerSizeInBits());
2810 MaxWidth = std::max(MaxWidth, T->getScalarSizeInBits());
2818 LoopVectorizationCostModel::selectUnrollFactor(bool OptForSize,
2821 unsigned LoopCost) {
2823 // -- The unroll heuristics --
2824 // We unroll the loop in order to expose ILP and reduce the loop overhead.
2825 // There are many micro-architectural considerations that we can't predict
2826 // at this level. For example frontend pressure (on decode or fetch) due to
2827 // code size, or the number and capabilities of the execution ports.
2829 // We use the following heuristics to select the unroll factor:
2830 // 1. If the code has reductions the we unroll in order to break the cross
2831 // iteration dependency.
2832 // 2. If the loop is really small then we unroll in order to reduce the loop
2834 // 3. We don't unroll if we think that we will spill registers to memory due
2835 // to the increased register pressure.
2837 // Use the user preference, unless 'auto' is selected.
2841 // When we optimize for size we don't unroll.
2845 // Do not unroll loops with a relatively small trip count.
2846 unsigned TC = SE->getSmallConstantTripCount(TheLoop,
2847 TheLoop->getLoopLatch());
2848 if (TC > 1 && TC < TinyTripCountUnrollThreshold)
2851 unsigned TargetVectorRegisters = TTI.getNumberOfRegisters(true);
2852 DEBUG(dbgs() << "LV: The target has " << TargetVectorRegisters <<
2853 " vector registers\n");
2855 LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
2856 // We divide by these constants so assume that we have at least one
2857 // instruction that uses at least one register.
2858 R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
2859 R.NumInstructions = std::max(R.NumInstructions, 1U);
2861 // We calculate the unroll factor using the following formula.
2862 // Subtract the number of loop invariants from the number of available
2863 // registers. These registers are used by all of the unrolled instances.
2864 // Next, divide the remaining registers by the number of registers that is
2865 // required by the loop, in order to estimate how many parallel instances
2866 // fit without causing spills.
2867 unsigned UF = (TargetVectorRegisters - R.LoopInvariantRegs) / R.MaxLocalUsers;
2869 // Clamp the unroll factor ranges to reasonable factors.
2870 unsigned MaxUnrollSize = TTI.getMaximumUnrollFactor();
2872 // If we did not calculate the cost for VF (because the user selected the VF)
2873 // then we calculate the cost of VF here.
2875 LoopCost = expectedCost(VF);
2877 // Clamp the calculated UF to be between the 1 and the max unroll factor
2878 // that the target allows.
2879 if (UF > MaxUnrollSize)
2884 if (Legal->getReductionVars()->size()) {
2885 DEBUG(dbgs() << "LV: Unrolling because of reductions. \n");
2889 // We want to unroll tiny loops in order to reduce the loop overhead.
2890 // We assume that the cost overhead is 1 and we use the cost model
2891 // to estimate the cost of the loop and unroll until the cost of the
2892 // loop overhead is about 5% of the cost of the loop.
2893 DEBUG(dbgs() << "LV: Loop cost is "<< LoopCost <<" \n");
2894 if (LoopCost < 20) {
2895 DEBUG(dbgs() << "LV: Unrolling to reduce branch cost. \n");
2896 unsigned NewUF = 20/LoopCost + 1;
2897 return std::min(NewUF, UF);
2900 DEBUG(dbgs() << "LV: Not Unrolling. \n");
2904 LoopVectorizationCostModel::RegisterUsage
2905 LoopVectorizationCostModel::calculateRegisterUsage() {
2906 // This function calculates the register usage by measuring the highest number
2907 // of values that are alive at a single location. Obviously, this is a very
2908 // rough estimation. We scan the loop in a topological order in order and
2909 // assign a number to each instruction. We use RPO to ensure that defs are
2910 // met before their users. We assume that each instruction that has in-loop
2911 // users starts an interval. We record every time that an in-loop value is
2912 // used, so we have a list of the first and last occurrences of each
2913 // instruction. Next, we transpose this data structure into a multi map that
2914 // holds the list of intervals that *end* at a specific location. This multi
2915 // map allows us to perform a linear search. We scan the instructions linearly
2916 // and record each time that a new interval starts, by placing it in a set.
2917 // If we find this value in the multi-map then we remove it from the set.
2918 // The max register usage is the maximum size of the set.
2919 // We also search for instructions that are defined outside the loop, but are
2920 // used inside the loop. We need this number separately from the max-interval
2921 // usage number because when we unroll, loop-invariant values do not take
2923 LoopBlocksDFS DFS(TheLoop);
2927 R.NumInstructions = 0;
2929 // Each 'key' in the map opens a new interval. The values
2930 // of the map are the index of the 'last seen' usage of the
2931 // instruction that is the key.
2932 typedef DenseMap<Instruction*, unsigned> IntervalMap;
2933 // Maps instruction to its index.
2934 DenseMap<unsigned, Instruction*> IdxToInstr;
2935 // Marks the end of each interval.
2936 IntervalMap EndPoint;
2937 // Saves the list of instruction indices that are used in the loop.
2938 SmallSet<Instruction*, 8> Ends;
2939 // Saves the list of values that are used in the loop but are
2940 // defined outside the loop, such as arguments and constants.
2941 SmallPtrSet<Value*, 8> LoopInvariants;
2944 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
2945 be = DFS.endRPO(); bb != be; ++bb) {
2946 R.NumInstructions += (*bb)->size();
2947 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
2949 Instruction *I = it;
2950 IdxToInstr[Index++] = I;
2952 // Save the end location of each USE.
2953 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
2954 Value *U = I->getOperand(i);
2955 Instruction *Instr = dyn_cast<Instruction>(U);
2957 // Ignore non-instruction values such as arguments, constants, etc.
2958 if (!Instr) continue;
2960 // If this instruction is outside the loop then record it and continue.
2961 if (!TheLoop->contains(Instr)) {
2962 LoopInvariants.insert(Instr);
2966 // Overwrite previous end points.
2967 EndPoint[Instr] = Index;
2973 // Saves the list of intervals that end with the index in 'key'.
2974 typedef SmallVector<Instruction*, 2> InstrList;
2975 DenseMap<unsigned, InstrList> TransposeEnds;
2977 // Transpose the EndPoints to a list of values that end at each index.
2978 for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
2980 TransposeEnds[it->second].push_back(it->first);
2982 SmallSet<Instruction*, 8> OpenIntervals;
2983 unsigned MaxUsage = 0;
2986 DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
2987 for (unsigned int i = 0; i < Index; ++i) {
2988 Instruction *I = IdxToInstr[i];
2989 // Ignore instructions that are never used within the loop.
2990 if (!Ends.count(I)) continue;
2992 // Remove all of the instructions that end at this location.
2993 InstrList &List = TransposeEnds[i];
2994 for (unsigned int j=0, e = List.size(); j < e; ++j)
2995 OpenIntervals.erase(List[j]);
2997 // Count the number of live interals.
2998 MaxUsage = std::max(MaxUsage, OpenIntervals.size());
3000 DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
3001 OpenIntervals.size() <<"\n");
3003 // Add the current instruction to the list of open intervals.
3004 OpenIntervals.insert(I);
3007 unsigned Invariant = LoopInvariants.size();
3008 DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << " \n");
3009 DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << " \n");
3010 DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << " \n");
3012 R.LoopInvariantRegs = Invariant;
3013 R.MaxLocalUsers = MaxUsage;
3017 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
3021 for (Loop::block_iterator bb = TheLoop->block_begin(),
3022 be = TheLoop->block_end(); bb != be; ++bb) {
3023 unsigned BlockCost = 0;
3024 BasicBlock *BB = *bb;
3026 // For each instruction in the old loop.
3027 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
3028 unsigned C = getInstructionCost(it, VF);
3030 DEBUG(dbgs() << "LV: Found an estimated cost of "<< C <<" for VF " <<
3031 VF << " For instruction: "<< *it << "\n");
3034 // We assume that if-converted blocks have a 50% chance of being executed.
3035 // When the code is scalar then some of the blocks are avoided due to CF.
3036 // When the code is vectorized we execute all code paths.
3037 if (Legal->blockNeedsPredication(*bb) && VF == 1)
3047 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
3048 // If we know that this instruction will remain uniform, check the cost of
3049 // the scalar version.
3050 if (Legal->isUniformAfterVectorization(I))
3053 Type *RetTy = I->getType();
3054 Type *VectorTy = ToVectorTy(RetTy, VF);
3056 // TODO: We need to estimate the cost of intrinsic calls.
3057 switch (I->getOpcode()) {
3058 case Instruction::GetElementPtr:
3059 // We mark this instruction as zero-cost because the cost of GEPs in
3060 // vectorized code depends on whether the corresponding memory instruction
3061 // is scalarized or not. Therefore, we handle GEPs with the memory
3062 // instruction cost.
3064 case Instruction::Br: {
3065 return TTI.getCFInstrCost(I->getOpcode());
3067 case Instruction::PHI:
3068 //TODO: IF-converted IFs become selects.
3070 case Instruction::Add:
3071 case Instruction::FAdd:
3072 case Instruction::Sub:
3073 case Instruction::FSub:
3074 case Instruction::Mul:
3075 case Instruction::FMul:
3076 case Instruction::UDiv:
3077 case Instruction::SDiv:
3078 case Instruction::FDiv:
3079 case Instruction::URem:
3080 case Instruction::SRem:
3081 case Instruction::FRem:
3082 case Instruction::Shl:
3083 case Instruction::LShr:
3084 case Instruction::AShr:
3085 case Instruction::And:
3086 case Instruction::Or:
3087 case Instruction::Xor:
3088 return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy);
3089 case Instruction::Select: {
3090 SelectInst *SI = cast<SelectInst>(I);
3091 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
3092 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
3093 Type *CondTy = SI->getCondition()->getType();
3095 CondTy = VectorType::get(CondTy, VF);
3097 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
3099 case Instruction::ICmp:
3100 case Instruction::FCmp: {
3101 Type *ValTy = I->getOperand(0)->getType();
3102 VectorTy = ToVectorTy(ValTy, VF);
3103 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
3105 case Instruction::Store:
3106 case Instruction::Load: {
3107 StoreInst *SI = dyn_cast<StoreInst>(I);
3108 LoadInst *LI = dyn_cast<LoadInst>(I);
3109 Type *ValTy = (SI ? SI->getValueOperand()->getType() :
3111 VectorTy = ToVectorTy(ValTy, VF);
3113 unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment();
3114 unsigned AS = SI ? SI->getPointerAddressSpace() :
3115 LI->getPointerAddressSpace();
3116 Value *Ptr = SI ? SI->getPointerOperand() : LI->getPointerOperand();
3117 // We add the cost of address computation here instead of with the gep
3118 // instruction because only here we know whether the operation is
3121 return TTI.getAddressComputationCost(VectorTy) +
3122 TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
3124 // Scalarized loads/stores.
3125 int Stride = Legal->isConsecutivePtr(Ptr);
3126 bool Reverse = Stride < 0;
3129 // The cost of extracting from the value vector and pointer vector.
3130 Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
3131 for (unsigned i = 0; i < VF; ++i) {
3132 // The cost of extracting the pointer operand.
3133 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
3134 // In case of STORE, the cost of ExtractElement from the vector.
3135 // In case of LOAD, the cost of InsertElement into the returned
3137 Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement :
3138 Instruction::InsertElement,
3142 // The cost of the scalar loads/stores.
3143 Cost += VF * TTI.getAddressComputationCost(ValTy->getScalarType());
3144 Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
3149 // Wide load/stores.
3150 unsigned Cost = TTI.getAddressComputationCost(VectorTy);
3151 Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
3154 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
3158 case Instruction::ZExt:
3159 case Instruction::SExt:
3160 case Instruction::FPToUI:
3161 case Instruction::FPToSI:
3162 case Instruction::FPExt:
3163 case Instruction::PtrToInt:
3164 case Instruction::IntToPtr:
3165 case Instruction::SIToFP:
3166 case Instruction::UIToFP:
3167 case Instruction::Trunc:
3168 case Instruction::FPTrunc:
3169 case Instruction::BitCast: {
3170 // We optimize the truncation of induction variable.
3171 // The cost of these is the same as the scalar operation.
3172 if (I->getOpcode() == Instruction::Trunc &&
3173 Legal->isInductionVariable(I->getOperand(0)))
3174 return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
3175 I->getOperand(0)->getType());
3177 Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
3178 return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
3180 case Instruction::Call: {
3181 assert(isTriviallyVectorizableIntrinsic(I));
3182 IntrinsicInst *II = cast<IntrinsicInst>(I);
3183 Type *RetTy = ToVectorTy(II->getType(), VF);
3184 SmallVector<Type*, 4> Tys;
3185 for (unsigned i = 0, ie = II->getNumArgOperands(); i != ie; ++i)
3186 Tys.push_back(ToVectorTy(II->getArgOperand(i)->getType(), VF));
3187 return TTI.getIntrinsicInstrCost(II->getIntrinsicID(), RetTy, Tys);
3190 // We are scalarizing the instruction. Return the cost of the scalar
3191 // instruction, plus the cost of insert and extract into vector
3192 // elements, times the vector width.
3195 if (!RetTy->isVoidTy() && VF != 1) {
3196 unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
3198 unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
3201 // The cost of inserting the results plus extracting each one of the
3203 Cost += VF * (InsCost + ExtCost * I->getNumOperands());
3206 // The cost of executing VF copies of the scalar instruction. This opcode
3207 // is unknown. Assume that it is the same as 'mul'.
3208 Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
3214 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
3215 if (Scalar->isVoidTy() || VF == 1)
3217 return VectorType::get(Scalar, VF);
3220 char LoopVectorize::ID = 0;
3221 static const char lv_name[] = "Loop Vectorization";
3222 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
3223 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3224 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
3225 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
3226 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
3227 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
3230 Pass *createLoopVectorizePass() {
3231 return new LoopVectorize();
3235 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
3236 // Check for a store.
3237 StoreInst *ST = dyn_cast<StoreInst>(Inst);
3239 return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0;
3241 // Check for a load.
3242 LoadInst *LI = dyn_cast<LoadInst>(Inst);
3244 return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0;