1 //===- LoopVectorize.cpp - A Loop Vectorizer ------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This is the LLVM loop vectorizer. This pass modifies 'vectorizable' loops
11 // and generates target-independent LLVM-IR. Legalization of the IR is done
12 // in the codegen. However, the vectorizes uses (will use) the codegen
13 // interfaces to generate IR that is likely to result in an optimal binary.
15 // The loop vectorizer combines consecutive loop iteration into a single
16 // 'wide' iteration. After this transformation the index is incremented
17 // by the SIMD vector width, and not by one.
19 // This pass has three parts:
20 // 1. The main loop pass that drives the different parts.
21 // 2. LoopVectorizationLegality - A unit that checks for the legality
22 // of the vectorization.
23 // 3. InnerLoopVectorizer - A unit that performs the actual
24 // widening of instructions.
25 // 4. LoopVectorizationCostModel - A unit that checks for the profitability
26 // of vectorization. It decides on the optimal vector width, which
27 // can be one, if vectorization is not profitable.
29 //===----------------------------------------------------------------------===//
31 // The reduction-variable vectorization is based on the paper:
32 // D. Nuzman and R. Henderson. Multi-platform Auto-vectorization.
34 // Variable uniformity checks are inspired by:
35 // Karrenberg, R. and Hack, S. Whole Function Vectorization.
37 // Other ideas/concepts are from:
38 // A. Zaks and D. Nuzman. Autovectorization in GCC-two years later.
40 // S. Maleki, Y. Gao, M. Garzaran, T. Wong and D. Padua. An Evaluation of
41 // Vectorizing Compilers.
43 //===----------------------------------------------------------------------===//
45 #define LV_NAME "loop-vectorize"
46 #define DEBUG_TYPE LV_NAME
48 #include "llvm/Transforms/Vectorize.h"
49 #include "llvm/ADT/DenseMap.h"
50 #include "llvm/ADT/MapVector.h"
51 #include "llvm/ADT/SmallPtrSet.h"
52 #include "llvm/ADT/SmallSet.h"
53 #include "llvm/ADT/SmallVector.h"
54 #include "llvm/ADT/StringExtras.h"
55 #include "llvm/Analysis/AliasAnalysis.h"
56 #include "llvm/Analysis/AliasSetTracker.h"
57 #include "llvm/Analysis/Dominators.h"
58 #include "llvm/Analysis/LoopInfo.h"
59 #include "llvm/Analysis/LoopIterator.h"
60 #include "llvm/Analysis/LoopPass.h"
61 #include "llvm/Analysis/ScalarEvolution.h"
62 #include "llvm/Analysis/ScalarEvolutionExpander.h"
63 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
64 #include "llvm/Analysis/TargetTransformInfo.h"
65 #include "llvm/Analysis/ValueTracking.h"
66 #include "llvm/Analysis/Verifier.h"
67 #include "llvm/IR/Constants.h"
68 #include "llvm/IR/DataLayout.h"
69 #include "llvm/IR/DerivedTypes.h"
70 #include "llvm/IR/Function.h"
71 #include "llvm/IR/IRBuilder.h"
72 #include "llvm/IR/Instructions.h"
73 #include "llvm/IR/IntrinsicInst.h"
74 #include "llvm/IR/LLVMContext.h"
75 #include "llvm/IR/Module.h"
76 #include "llvm/IR/Type.h"
77 #include "llvm/IR/Value.h"
78 #include "llvm/Pass.h"
79 #include "llvm/Support/CommandLine.h"
80 #include "llvm/Support/Debug.h"
81 #include "llvm/Support/raw_ostream.h"
82 #include "llvm/Transforms/Scalar.h"
83 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
84 #include "llvm/Transforms/Utils/Local.h"
90 static cl::opt<unsigned>
91 VectorizationFactor("force-vector-width", cl::init(0), cl::Hidden,
92 cl::desc("Sets the SIMD width. Zero is autoselect."));
94 static cl::opt<unsigned>
95 VectorizationUnroll("force-vector-unroll", cl::init(0), cl::Hidden,
96 cl::desc("Sets the vectorization unroll count. "
97 "Zero is autoselect."));
100 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
101 cl::desc("Enable if-conversion during vectorization."));
103 /// We don't vectorize loops with a known constant trip count below this number.
104 static const unsigned TinyTripCountVectorThreshold = 16;
106 /// We don't unroll loops with a known constant trip count below this number.
107 static const unsigned TinyTripCountUnrollThreshold = 128;
109 /// When performing a runtime memory check, do not check more than this
110 /// number of pointers. Notice that the check is quadratic!
111 static const unsigned RuntimeMemoryCheckThreshold = 4;
115 // Forward declarations.
116 class LoopVectorizationLegality;
117 class LoopVectorizationCostModel;
119 /// InnerLoopVectorizer vectorizes loops which contain only one basic
120 /// block to a specified vectorization factor (VF).
121 /// This class performs the widening of scalars into vectors, or multiple
122 /// scalars. This class also implements the following features:
123 /// * It inserts an epilogue loop for handling loops that don't have iteration
124 /// counts that are known to be a multiple of the vectorization factor.
125 /// * It handles the code generation for reduction variables.
126 /// * Scalarization (implementation using scalars) of un-vectorizable
128 /// InnerLoopVectorizer does not perform any vectorization-legality
129 /// checks, and relies on the caller to check for the different legality
130 /// aspects. The InnerLoopVectorizer relies on the
131 /// LoopVectorizationLegality class to provide information about the induction
132 /// and reduction variables that were found to a given vectorization factor.
133 class InnerLoopVectorizer {
135 InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
136 DominatorTree *DT, DataLayout *DL, unsigned VecWidth,
137 unsigned UnrollFactor)
138 : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), DL(DL), VF(VecWidth),
139 UF(UnrollFactor), Builder(SE->getContext()), Induction(0),
140 OldInduction(0), WidenMap(UnrollFactor) {}
142 // Perform the actual loop widening (vectorization).
143 void vectorize(LoopVectorizationLegality *Legal) {
144 // Create a new empty loop. Unlink the old loop and connect the new one.
145 createEmptyLoop(Legal);
146 // Widen each instruction in the old loop to a new one in the new loop.
147 // Use the Legality module to find the induction and reduction variables.
148 vectorizeLoop(Legal);
149 // Register the new loop and update the analysis passes.
154 /// A small list of PHINodes.
155 typedef SmallVector<PHINode*, 4> PhiVector;
156 /// When we unroll loops we have multiple vector values for each scalar.
157 /// This data structure holds the unrolled and vectorized values that
158 /// originated from one scalar instruction.
159 typedef SmallVector<Value*, 2> VectorParts;
161 /// Add code that checks at runtime if the accessed arrays overlap.
162 /// Returns the comparator value or NULL if no check is needed.
163 Instruction *addRuntimeCheck(LoopVectorizationLegality *Legal,
165 /// Create an empty loop, based on the loop ranges of the old loop.
166 void createEmptyLoop(LoopVectorizationLegality *Legal);
167 /// Copy and widen the instructions from the old loop.
168 void vectorizeLoop(LoopVectorizationLegality *Legal);
170 /// A helper function that computes the predicate of the block BB, assuming
171 /// that the header block of the loop is set to True. It returns the *entry*
172 /// mask for the block BB.
173 VectorParts createBlockInMask(BasicBlock *BB);
174 /// A helper function that computes the predicate of the edge between SRC
176 VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
178 /// A helper function to vectorize a single BB within the innermost loop.
179 void vectorizeBlockInLoop(LoopVectorizationLegality *Legal, BasicBlock *BB,
182 /// Insert the new loop to the loop hierarchy and pass manager
183 /// and update the analysis passes.
184 void updateAnalysis();
186 /// This instruction is un-vectorizable. Implement it as a sequence
188 void scalarizeInstruction(Instruction *Instr);
190 /// Create a broadcast instruction. This method generates a broadcast
191 /// instruction (shuffle) for loop invariant values and for the induction
192 /// value. If this is the induction variable then we extend it to N, N+1, ...
193 /// this is needed because each iteration in the loop corresponds to a SIMD
195 Value *getBroadcastInstrs(Value *V);
197 /// This function adds 0, 1, 2 ... to each vector element, starting at zero.
198 /// If Negate is set then negative numbers are added e.g. (0, -1, -2, ...).
199 /// The sequence starts at StartIndex.
200 Value *getConsecutiveVector(Value* Val, unsigned StartIdx, bool Negate);
202 /// When we go over instructions in the basic block we rely on previous
203 /// values within the current basic block or on loop invariant values.
204 /// When we widen (vectorize) values we place them in the map. If the values
205 /// are not within the map, they have to be loop invariant, so we simply
206 /// broadcast them into a vector.
207 VectorParts &getVectorValue(Value *V);
209 /// Generate a shuffle sequence that will reverse the vector Vec.
210 Value *reverseVector(Value *Vec);
212 /// This is a helper class that holds the vectorizer state. It maps scalar
213 /// instructions to vector instructions. When the code is 'unrolled' then
214 /// then a single scalar value is mapped to multiple vector parts. The parts
215 /// are stored in the VectorPart type.
217 /// C'tor. UnrollFactor controls the number of vectors ('parts') that
219 ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
221 /// \return True if 'Key' is saved in the Value Map.
222 bool has(Value *Key) { return MapStoreage.count(Key); }
224 /// Initializes a new entry in the map. Sets all of the vector parts to the
225 /// save value in 'Val'.
226 /// \return A reference to a vector with splat values.
227 VectorParts &splat(Value *Key, Value *Val) {
228 MapStoreage[Key].clear();
229 MapStoreage[Key].append(UF, Val);
230 return MapStoreage[Key];
233 ///\return A reference to the value that is stored at 'Key'.
234 VectorParts &get(Value *Key) {
236 MapStoreage[Key].resize(UF);
237 return MapStoreage[Key];
240 /// The unroll factor. Each entry in the map stores this number of vector
244 /// Map storage. We use std::map and not DenseMap because insertions to a
245 /// dense map invalidates its iterators.
246 std::map<Value*, VectorParts> MapStoreage;
249 /// The original loop.
251 /// Scev analysis to use.
259 /// The vectorization SIMD factor to use. Each vector will have this many
262 /// The vectorization unroll factor to use. Each scalar is vectorized to this
263 /// many different vector instructions.
266 /// The builder that we use
269 // --- Vectorization state ---
271 /// The vector-loop preheader.
272 BasicBlock *LoopVectorPreHeader;
273 /// The scalar-loop preheader.
274 BasicBlock *LoopScalarPreHeader;
275 /// Middle Block between the vector and the scalar.
276 BasicBlock *LoopMiddleBlock;
277 ///The ExitBlock of the scalar loop.
278 BasicBlock *LoopExitBlock;
279 ///The vector loop body.
280 BasicBlock *LoopVectorBody;
281 ///The scalar loop body.
282 BasicBlock *LoopScalarBody;
283 /// A list of all bypass blocks. The first block is the entry of the loop.
284 SmallVector<BasicBlock *, 4> LoopBypassBlocks;
286 /// The new Induction variable which was added to the new block.
288 /// The induction variable of the old basic block.
289 PHINode *OldInduction;
290 /// Maps scalars to widened vectors.
294 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
295 /// to what vectorization factor.
296 /// This class does not look at the profitability of vectorization, only the
297 /// legality. This class has two main kinds of checks:
298 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
299 /// will change the order of memory accesses in a way that will change the
300 /// correctness of the program.
301 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
302 /// checks for a number of different conditions, such as the availability of a
303 /// single induction variable, that all types are supported and vectorize-able,
304 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
305 /// This class is also used by InnerLoopVectorizer for identifying
306 /// induction variable and the different reduction variables.
307 class LoopVectorizationLegality {
309 LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, DataLayout *DL,
311 : TheLoop(L), SE(SE), DL(DL), DT(DT), Induction(0) {}
313 /// This enum represents the kinds of reductions that we support.
315 RK_NoReduction, ///< Not a reduction.
316 RK_IntegerAdd, ///< Sum of integers.
317 RK_IntegerMult, ///< Product of integers.
318 RK_IntegerOr, ///< Bitwise or logical OR of numbers.
319 RK_IntegerAnd, ///< Bitwise or logical AND of numbers.
320 RK_IntegerXor, ///< Bitwise or logical XOR of numbers.
321 RK_FloatAdd, ///< Sum of floats.
322 RK_FloatMult ///< Product of floats.
325 /// This enum represents the kinds of inductions that we support.
327 IK_NoInduction, ///< Not an induction variable.
328 IK_IntInduction, ///< Integer induction variable. Step = 1.
329 IK_ReverseIntInduction, ///< Reverse int induction variable. Step = -1.
330 IK_PtrInduction, ///< Pointer induction var. Step = sizeof(elem).
331 IK_ReversePtrInduction ///< Reverse ptr indvar. Step = - sizeof(elem).
334 /// This POD struct holds information about reduction variables.
335 struct ReductionDescriptor {
336 ReductionDescriptor() : StartValue(0), LoopExitInstr(0),
337 Kind(RK_NoReduction) {}
339 ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K)
340 : StartValue(Start), LoopExitInstr(Exit), Kind(K) {}
342 // The starting value of the reduction.
343 // It does not have to be zero!
345 // The instruction who's value is used outside the loop.
346 Instruction *LoopExitInstr;
347 // The kind of the reduction.
351 // This POD struct holds information about the memory runtime legality
352 // check that a group of pointers do not overlap.
353 struct RuntimePointerCheck {
354 RuntimePointerCheck() : Need(false) {}
356 /// Reset the state of the pointer runtime information.
364 /// Insert a pointer and calculate the start and end SCEVs.
365 void insert(ScalarEvolution *SE, Loop *Lp, Value *Ptr);
367 /// This flag indicates if we need to add the runtime check.
369 /// Holds the pointers that we need to check.
370 SmallVector<Value*, 2> Pointers;
371 /// Holds the pointer value at the beginning of the loop.
372 SmallVector<const SCEV*, 2> Starts;
373 /// Holds the pointer value at the end of the loop.
374 SmallVector<const SCEV*, 2> Ends;
377 /// A POD for saving information about induction variables.
378 struct InductionInfo {
379 InductionInfo(Value *Start, InductionKind K) : StartValue(Start), IK(K) {}
380 InductionInfo() : StartValue(0), IK(IK_NoInduction) {}
387 /// ReductionList contains the reduction descriptors for all
388 /// of the reductions that were found in the loop.
389 typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
391 /// InductionList saves induction variables and maps them to the
392 /// induction descriptor.
393 typedef MapVector<PHINode*, InductionInfo> InductionList;
395 /// Returns true if it is legal to vectorize this loop.
396 /// This does not mean that it is profitable to vectorize this
397 /// loop, only that it is legal to do so.
400 /// Returns the Induction variable.
401 PHINode *getInduction() { return Induction; }
403 /// Returns the reduction variables found in the loop.
404 ReductionList *getReductionVars() { return &Reductions; }
406 /// Returns the induction variables found in the loop.
407 InductionList *getInductionVars() { return &Inductions; }
409 /// Returns True if V is an induction variable in this loop.
410 bool isInductionVariable(const Value *V);
412 /// Return true if the block BB needs to be predicated in order for the loop
413 /// to be vectorized.
414 bool blockNeedsPredication(BasicBlock *BB);
416 /// Check if this pointer is consecutive when vectorizing. This happens
417 /// when the last index of the GEP is the induction variable, or that the
418 /// pointer itself is an induction variable.
419 /// This check allows us to vectorize A[idx] into a wide load/store.
421 /// 0 - Stride is unknown or non consecutive.
422 /// 1 - Address is consecutive.
423 /// -1 - Address is consecutive, and decreasing.
424 int isConsecutivePtr(Value *Ptr);
426 /// Returns true if the value V is uniform within the loop.
427 bool isUniform(Value *V);
429 /// Returns true if this instruction will remain scalar after vectorization.
430 bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
432 /// Returns the information that we collected about runtime memory check.
433 RuntimePointerCheck *getRuntimePointerCheck() { return &PtrRtCheck; }
435 /// Check if a single basic block loop is vectorizable.
436 /// At this point we know that this is a loop with a constant trip count
437 /// and we only need to check individual instructions.
438 bool canVectorizeInstrs();
440 /// When we vectorize loops we may change the order in which
441 /// we read and write from memory. This method checks if it is
442 /// legal to vectorize the code, considering only memory constrains.
443 /// Returns true if the loop is vectorizable
444 bool canVectorizeMemory();
446 /// Return true if we can vectorize this loop using the IF-conversion
448 bool canVectorizeWithIfConvert();
450 /// Collect the variables that need to stay uniform after vectorization.
451 void collectLoopUniforms();
453 /// Return true if all of the instructions in the block can be speculatively
455 bool blockCanBePredicated(BasicBlock *BB);
457 /// Returns True, if 'Phi' is the kind of reduction variable for type
458 /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
459 bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
460 /// Returns true if the instruction I can be a reduction variable of type
462 bool isReductionInstr(Instruction *I, ReductionKind Kind);
463 /// Returns the induction kind of Phi. This function may return NoInduction
464 /// if the PHI is not an induction variable.
465 InductionKind isInductionVariable(PHINode *Phi);
466 /// Return true if can compute the address bounds of Ptr within the loop.
467 bool hasComputableBounds(Value *Ptr);
469 /// The loop that we evaluate.
473 /// DataLayout analysis.
478 // --- vectorization state --- //
480 /// Holds the integer induction variable. This is the counter of the
483 /// Holds the reduction variables.
484 ReductionList Reductions;
485 /// Holds all of the induction variables that we found in the loop.
486 /// Notice that inductions don't need to start at zero and that induction
487 /// variables can be pointers.
488 InductionList Inductions;
490 /// Allowed outside users. This holds the reduction
491 /// vars which can be accessed from outside the loop.
492 SmallPtrSet<Value*, 4> AllowedExit;
493 /// This set holds the variables which are known to be uniform after
495 SmallPtrSet<Instruction*, 4> Uniforms;
496 /// We need to check that all of the pointers in this list are disjoint
498 RuntimePointerCheck PtrRtCheck;
501 /// LoopVectorizationCostModel - estimates the expected speedups due to
503 /// In many cases vectorization is not profitable. This can happen because of
504 /// a number of reasons. In this class we mainly attempt to predict the
505 /// expected speedup/slowdowns due to the supported instruction set. We use the
506 /// TargetTransformInfo to query the different backends for the cost of
507 /// different operations.
508 class LoopVectorizationCostModel {
510 LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
511 LoopVectorizationLegality *Legal,
512 const TargetTransformInfo &TTI)
513 : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI) {}
515 /// \return The most profitable vectorization factor and the cost of that VF.
516 /// This method checks every power of two up to VF. If UserVF is not ZERO
517 /// then this vectorization factor will be selected if vectorization is
519 std::pair<unsigned, unsigned>
520 selectVectorizationFactor(bool OptForSize, unsigned UserVF);
522 /// \returns The size (in bits) of the widest type in the code that
523 /// needs to be vectorized. We ignore values that remain scalar such as
524 /// 64 bit loop indices.
525 unsigned getWidestType();
527 /// \return The most profitable unroll factor.
528 /// If UserUF is non-zero then this method finds the best unroll-factor
529 /// based on register pressure and other parameters.
530 /// VF and LoopCost are the selected vectorization factor and the cost of the
532 unsigned selectUnrollFactor(bool OptForSize, unsigned UserUF, unsigned VF,
535 /// \brief A struct that represents some properties of the register usage
537 struct RegisterUsage {
538 /// Holds the number of loop invariant values that are used in the loop.
539 unsigned LoopInvariantRegs;
540 /// Holds the maximum number of concurrent live intervals in the loop.
541 unsigned MaxLocalUsers;
542 /// Holds the number of instructions in the loop.
543 unsigned NumInstructions;
546 /// \return information about the register usage of the loop.
547 RegisterUsage calculateRegisterUsage();
550 /// Returns the expected execution cost. The unit of the cost does
551 /// not matter because we use the 'cost' units to compare different
552 /// vector widths. The cost that is returned is *not* normalized by
553 /// the factor width.
554 unsigned expectedCost(unsigned VF);
556 /// Returns the execution time cost of an instruction for a given vector
557 /// width. Vector width of one means scalar.
558 unsigned getInstructionCost(Instruction *I, unsigned VF);
560 /// A helper function for converting Scalar types to vector types.
561 /// If the incoming type is void, we return void. If the VF is 1, we return
563 static Type* ToVectorTy(Type *Scalar, unsigned VF);
565 /// The loop that we evaluate.
569 /// Loop Info analysis.
571 /// Vectorization legality.
572 LoopVectorizationLegality *Legal;
573 /// Vector target information.
574 const TargetTransformInfo &TTI;
577 /// The LoopVectorize Pass.
578 struct LoopVectorize : public LoopPass {
579 /// Pass identification, replacement for typeid
582 explicit LoopVectorize() : LoopPass(ID) {
583 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
589 TargetTransformInfo *TTI;
592 virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
593 // We only vectorize innermost loops.
597 SE = &getAnalysis<ScalarEvolution>();
598 DL = getAnalysisIfAvailable<DataLayout>();
599 LI = &getAnalysis<LoopInfo>();
600 TTI = &getAnalysis<TargetTransformInfo>();
601 DT = &getAnalysis<DominatorTree>();
603 DEBUG(dbgs() << "LV: Checking a loop in \"" <<
604 L->getHeader()->getParent()->getName() << "\"\n");
606 // Check if it is legal to vectorize the loop.
607 LoopVectorizationLegality LVL(L, SE, DL, DT);
608 if (!LVL.canVectorize()) {
609 DEBUG(dbgs() << "LV: Not vectorizing.\n");
613 // Use the cost model.
614 LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI);
616 // Check the function attribues to find out if this function should be
617 // optimized for size.
618 Function *F = L->getHeader()->getParent();
619 Attribute::AttrKind SzAttr = Attribute::OptimizeForSize;
620 Attribute::AttrKind FlAttr = Attribute::NoImplicitFloat;
621 unsigned FnIndex = AttributeSet::FunctionIndex;
622 bool OptForSize = F->getAttributes().hasAttribute(FnIndex, SzAttr);
623 bool NoFloat = F->getAttributes().hasAttribute(FnIndex, FlAttr);
626 DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
627 "attribute is used.\n");
631 // Select the optimal vectorization factor.
632 std::pair<unsigned, unsigned> VFPair;
633 VFPair = CM.selectVectorizationFactor(OptForSize, VectorizationFactor);
634 // Select the unroll factor.
635 unsigned UF = CM.selectUnrollFactor(OptForSize, VectorizationUnroll,
636 VFPair.first, VFPair.second);
637 unsigned VF = VFPair.first;
640 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
644 DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< VF << ") in "<<
645 F->getParent()->getModuleIdentifier()<<"\n");
646 DEBUG(dbgs() << "LV: Unroll Factor is " << UF << "\n");
648 // If we decided that it is *legal* to vectorizer the loop then do it.
649 InnerLoopVectorizer LB(L, SE, LI, DT, DL, VF, UF);
652 DEBUG(verifyFunction(*L->getHeader()->getParent()));
656 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
657 LoopPass::getAnalysisUsage(AU);
658 AU.addRequiredID(LoopSimplifyID);
659 AU.addRequiredID(LCSSAID);
660 AU.addRequired<DominatorTree>();
661 AU.addRequired<LoopInfo>();
662 AU.addRequired<ScalarEvolution>();
663 AU.addRequired<TargetTransformInfo>();
664 AU.addPreserved<LoopInfo>();
665 AU.addPreserved<DominatorTree>();
670 } // end anonymous namespace
672 //===----------------------------------------------------------------------===//
673 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
674 // LoopVectorizationCostModel.
675 //===----------------------------------------------------------------------===//
678 LoopVectorizationLegality::RuntimePointerCheck::insert(ScalarEvolution *SE,
679 Loop *Lp, Value *Ptr) {
680 const SCEV *Sc = SE->getSCEV(Ptr);
681 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
682 assert(AR && "Invalid addrec expression");
683 const SCEV *Ex = SE->getExitCount(Lp, Lp->getLoopLatch());
684 const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
685 Pointers.push_back(Ptr);
686 Starts.push_back(AR->getStart());
687 Ends.push_back(ScEnd);
690 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
691 // Save the current insertion location.
692 Instruction *Loc = Builder.GetInsertPoint();
694 // We need to place the broadcast of invariant variables outside the loop.
695 Instruction *Instr = dyn_cast<Instruction>(V);
696 bool NewInstr = (Instr && Instr->getParent() == LoopVectorBody);
697 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
699 // Place the code for broadcasting invariant variables in the new preheader.
701 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
703 // Broadcast the scalar into all locations in the vector.
704 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
706 // Restore the builder insertion point.
708 Builder.SetInsertPoint(Loc);
713 Value *InnerLoopVectorizer::getConsecutiveVector(Value* Val, unsigned StartIdx,
715 assert(Val->getType()->isVectorTy() && "Must be a vector");
716 assert(Val->getType()->getScalarType()->isIntegerTy() &&
717 "Elem must be an integer");
719 Type *ITy = Val->getType()->getScalarType();
720 VectorType *Ty = cast<VectorType>(Val->getType());
721 int VLen = Ty->getNumElements();
722 SmallVector<Constant*, 8> Indices;
724 // Create a vector of consecutive numbers from zero to VF.
725 for (int i = 0; i < VLen; ++i) {
726 int Idx = Negate ? (-i): i;
727 Indices.push_back(ConstantInt::get(ITy, StartIdx + Idx));
730 // Add the consecutive indices to the vector value.
731 Constant *Cv = ConstantVector::get(Indices);
732 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
733 return Builder.CreateAdd(Val, Cv, "induction");
736 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
737 assert(Ptr->getType()->isPointerTy() && "Unexpected non ptr");
738 // Make sure that the pointer does not point to structs.
739 if (cast<PointerType>(Ptr->getType())->getElementType()->isAggregateType())
742 // If this value is a pointer induction variable we know it is consecutive.
743 PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
744 if (Phi && Inductions.count(Phi)) {
745 InductionInfo II = Inductions[Phi];
746 if (IK_PtrInduction == II.IK)
748 else if (IK_ReversePtrInduction == II.IK)
752 GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
756 unsigned NumOperands = Gep->getNumOperands();
757 Value *LastIndex = Gep->getOperand(NumOperands - 1);
759 Value *GpPtr = Gep->getPointerOperand();
760 // If this GEP value is a consecutive pointer induction variable and all of
761 // the indices are constant then we know it is consecutive. We can
762 Phi = dyn_cast<PHINode>(GpPtr);
763 if (Phi && Inductions.count(Phi)) {
765 // Make sure that the pointer does not point to structs.
766 PointerType *GepPtrType = cast<PointerType>(GpPtr->getType());
767 if (GepPtrType->getElementType()->isAggregateType())
770 // Make sure that all of the index operands are loop invariant.
771 for (unsigned i = 1; i < NumOperands; ++i)
772 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
775 InductionInfo II = Inductions[Phi];
776 if (IK_PtrInduction == II.IK)
778 else if (IK_ReversePtrInduction == II.IK)
782 // Check that all of the gep indices are uniform except for the last.
783 for (unsigned i = 0; i < NumOperands - 1; ++i)
784 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
787 // We can emit wide load/stores only if the last index is the induction
789 const SCEV *Last = SE->getSCEV(LastIndex);
790 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
791 const SCEV *Step = AR->getStepRecurrence(*SE);
793 // The memory is consecutive because the last index is consecutive
794 // and all other indices are loop invariant.
797 if (Step->isAllOnesValue())
804 bool LoopVectorizationLegality::isUniform(Value *V) {
805 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
808 InnerLoopVectorizer::VectorParts&
809 InnerLoopVectorizer::getVectorValue(Value *V) {
810 assert(V != Induction && "The new induction variable should not be used.");
811 assert(!V->getType()->isVectorTy() && "Can't widen a vector");
813 // If we have this scalar in the map, return it.
815 return WidenMap.get(V);
817 // If this scalar is unknown, assume that it is a constant or that it is
818 // loop invariant. Broadcast V and save the value for future uses.
819 Value *B = getBroadcastInstrs(V);
820 WidenMap.splat(V, B);
821 return WidenMap.get(V);
824 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
825 assert(Vec->getType()->isVectorTy() && "Invalid type");
826 SmallVector<Constant*, 8> ShuffleMask;
827 for (unsigned i = 0; i < VF; ++i)
828 ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
830 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
831 ConstantVector::get(ShuffleMask),
835 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr) {
836 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
837 // Holds vector parameters or scalars, in case of uniform vals.
838 SmallVector<VectorParts, 4> Params;
840 // Find all of the vectorized parameters.
841 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
842 Value *SrcOp = Instr->getOperand(op);
844 // If we are accessing the old induction variable, use the new one.
845 if (SrcOp == OldInduction) {
846 Params.push_back(getVectorValue(SrcOp));
850 // Try using previously calculated values.
851 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
853 // If the src is an instruction that appeared earlier in the basic block
854 // then it should already be vectorized.
855 if (SrcInst && OrigLoop->contains(SrcInst)) {
856 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
857 // The parameter is a vector value from earlier.
858 Params.push_back(WidenMap.get(SrcInst));
860 // The parameter is a scalar from outside the loop. Maybe even a constant.
862 Scalars.append(UF, SrcOp);
863 Params.push_back(Scalars);
867 assert(Params.size() == Instr->getNumOperands() &&
868 "Invalid number of operands");
870 // Does this instruction return a value ?
871 bool IsVoidRetTy = Instr->getType()->isVoidTy();
873 Value *UndefVec = IsVoidRetTy ? 0 :
874 UndefValue::get(VectorType::get(Instr->getType(), VF));
875 // Create a new entry in the WidenMap and initialize it to Undef or Null.
876 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
878 // For each scalar that we create:
879 for (unsigned Width = 0; Width < VF; ++Width) {
880 // For each vector unroll 'part':
881 for (unsigned Part = 0; Part < UF; ++Part) {
882 Instruction *Cloned = Instr->clone();
884 Cloned->setName(Instr->getName() + ".cloned");
885 // Replace the operands of the cloned instrucions with extracted scalars.
886 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
887 Value *Op = Params[op][Part];
888 // Param is a vector. Need to extract the right lane.
889 if (Op->getType()->isVectorTy())
890 Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
891 Cloned->setOperand(op, Op);
894 // Place the cloned scalar in the new loop.
895 Builder.Insert(Cloned);
897 // If the original scalar returns a value we need to place it in a vector
898 // so that future users will be able to use it.
900 VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
901 Builder.getInt32(Width));
907 InnerLoopVectorizer::addRuntimeCheck(LoopVectorizationLegality *Legal,
909 LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck =
910 Legal->getRuntimePointerCheck();
912 if (!PtrRtCheck->Need)
915 Instruction *MemoryRuntimeCheck = 0;
916 unsigned NumPointers = PtrRtCheck->Pointers.size();
917 SmallVector<Value* , 2> Starts;
918 SmallVector<Value* , 2> Ends;
920 SCEVExpander Exp(*SE, "induction");
922 // Use this type for pointer arithmetic.
923 Type* PtrArithTy = Type::getInt8PtrTy(Loc->getContext(), 0);
925 for (unsigned i = 0; i < NumPointers; ++i) {
926 Value *Ptr = PtrRtCheck->Pointers[i];
927 const SCEV *Sc = SE->getSCEV(Ptr);
929 if (SE->isLoopInvariant(Sc, OrigLoop)) {
930 DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" <<
932 Starts.push_back(Ptr);
935 DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr <<"\n");
937 Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc);
938 Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
939 Starts.push_back(Start);
944 IRBuilder<> ChkBuilder(Loc->getContext());
945 ChkBuilder.SetInsertPoint(Loc);
947 for (unsigned i = 0; i < NumPointers; ++i) {
948 for (unsigned j = i+1; j < NumPointers; ++j) {
949 Instruction::CastOps Op = Instruction::BitCast;
950 Value *Start0 = ChkBuilder.CreateCast(Op, Starts[i], PtrArithTy, "bc");
951 Value *Start1 = ChkBuilder.CreateCast(Op, Starts[j], PtrArithTy, "bc");
952 Value *End0 = ChkBuilder.CreateCast(Op, Ends[i], PtrArithTy, "bc");
953 Value *End1 = ChkBuilder.CreateCast(Op, Ends[j], PtrArithTy, "bc");
955 Value *Cmp0 = ChkBuilder.CreateICmp(CmpInst::ICMP_ULE,
956 Start0, End1, "bound0");
957 Value *Cmp1 = ChkBuilder.CreateICmp(CmpInst::ICMP_ULE,
958 Start1, End0, "bound1");
959 Value *IsConflict = ChkBuilder.CreateBinOp(Instruction::And, Cmp0, Cmp1,
961 if (MemoryRuntimeCheck) {
962 Value *B = ChkBuilder.CreateBinOp(Instruction::Or, MemoryRuntimeCheck,
963 IsConflict, "conflict.rdx");
964 MemoryRuntimeCheck = cast<Instruction>(B);
966 MemoryRuntimeCheck = cast<Instruction>(IsConflict);
971 return MemoryRuntimeCheck;
975 InnerLoopVectorizer::createEmptyLoop(LoopVectorizationLegality *Legal) {
977 In this function we generate a new loop. The new loop will contain
978 the vectorized instructions while the old loop will continue to run the
981 [ ] <-- vector loop bypass (may consist of multiple blocks).
984 | [ ] <-- vector pre header.
988 | [ ]_| <-- vector loop.
991 >[ ] <--- middle-block.
994 | [ ] <--- new preheader.
998 | [ ]_| <-- old scalar loop to handle remainder.
1001 >[ ] <-- exit block.
1005 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
1006 BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
1007 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
1008 assert(ExitBlock && "Must have an exit block");
1010 // Some loops have a single integer induction variable, while other loops
1011 // don't. One example is c++ iterators that often have multiple pointer
1012 // induction variables. In the code below we also support a case where we
1013 // don't have a single induction variable.
1014 OldInduction = Legal->getInduction();
1015 Type *IdxTy = OldInduction ? OldInduction->getType() :
1016 DL->getIntPtrType(SE->getContext());
1018 // Find the loop boundaries.
1019 const SCEV *ExitCount = SE->getExitCount(OrigLoop, OrigLoop->getLoopLatch());
1020 assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
1022 // Get the total trip count from the count by adding 1.
1023 ExitCount = SE->getAddExpr(ExitCount,
1024 SE->getConstant(ExitCount->getType(), 1));
1026 // Expand the trip count and place the new instructions in the preheader.
1027 // Notice that the pre-header does not change, only the loop body.
1028 SCEVExpander Exp(*SE, "induction");
1030 // Count holds the overall loop count (N).
1031 Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
1032 BypassBlock->getTerminator());
1034 // The loop index does not have to start at Zero. Find the original start
1035 // value from the induction PHI node. If we don't have an induction variable
1036 // then we know that it starts at zero.
1037 Value *StartIdx = OldInduction ?
1038 OldInduction->getIncomingValueForBlock(BypassBlock):
1039 ConstantInt::get(IdxTy, 0);
1041 assert(BypassBlock && "Invalid loop structure");
1042 LoopBypassBlocks.push_back(BypassBlock);
1044 // Split the single block loop into the two loop structure described above.
1045 BasicBlock *VectorPH =
1046 BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
1047 BasicBlock *VecBody =
1048 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
1049 BasicBlock *MiddleBlock =
1050 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
1051 BasicBlock *ScalarPH =
1052 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
1054 // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
1056 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
1058 // Generate the induction variable.
1059 Induction = Builder.CreatePHI(IdxTy, 2, "index");
1060 // The loop step is equal to the vectorization factor (num of SIMD elements)
1061 // times the unroll factor (num of SIMD instructions).
1062 Constant *Step = ConstantInt::get(IdxTy, VF * UF);
1064 // This is the IR builder that we use to add all of the logic for bypassing
1065 // the new vector loop.
1066 IRBuilder<> BypassBuilder(OldBasicBlock->getContext());
1067 BypassBuilder.SetInsertPoint(BypassBlock->getTerminator());
1069 // We may need to extend the index in case there is a type mismatch.
1070 // We know that the count starts at zero and does not overflow.
1071 unsigned IdxTyBW = IdxTy->getScalarSizeInBits();
1072 if (Count->getType() != IdxTy) {
1073 // The exit count can be of pointer type. Convert it to the correct
1075 if (ExitCount->getType()->isPointerTy())
1076 Count = BypassBuilder.CreatePointerCast(Count, IdxTy, "ptrcnt.to.int");
1078 Count = BypassBuilder.CreateZExtOrTrunc(Count, IdxTy, "cnt.cast");
1081 // Add the start index to the loop count to get the new end index.
1082 Value *IdxEnd = BypassBuilder.CreateAdd(Count, StartIdx, "end.idx");
1084 // Now we need to generate the expression for N - (N % VF), which is
1085 // the part that the vectorized body will execute.
1086 Value *R = BypassBuilder.CreateURem(Count, Step, "n.mod.vf");
1087 Value *CountRoundDown = BypassBuilder.CreateSub(Count, R, "n.vec");
1088 Value *IdxEndRoundDown = BypassBuilder.CreateAdd(CountRoundDown, StartIdx,
1089 "end.idx.rnd.down");
1091 // Now, compare the new count to zero. If it is zero skip the vector loop and
1092 // jump to the scalar loop.
1093 Value *Cmp = BypassBuilder.CreateICmp(CmpInst::ICMP_EQ, IdxEndRoundDown,
1094 StartIdx, "cmp.zero");
1096 BasicBlock *LastBypassBlock = BypassBlock;
1098 // Generate the code that checks in runtime if arrays overlap. We put the
1099 // checks into a separate block to make the more common case of few elements
1101 Instruction *MemRuntimeCheck = addRuntimeCheck(Legal,
1102 BypassBlock->getTerminator());
1103 if (MemRuntimeCheck) {
1104 // Create a new block containing the memory check.
1105 BasicBlock *CheckBlock = BypassBlock->splitBasicBlock(MemRuntimeCheck,
1107 LoopBypassBlocks.push_back(CheckBlock);
1109 // Replace the branch into the memory check block with a conditional branch
1110 // for the "few elements case".
1111 Instruction *OldTerm = BypassBlock->getTerminator();
1112 BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
1113 OldTerm->eraseFromParent();
1115 Cmp = MemRuntimeCheck;
1116 LastBypassBlock = CheckBlock;
1119 LastBypassBlock->getTerminator()->eraseFromParent();
1120 BranchInst::Create(MiddleBlock, VectorPH, Cmp,
1123 // We are going to resume the execution of the scalar loop.
1124 // Go over all of the induction variables that we found and fix the
1125 // PHIs that are left in the scalar version of the loop.
1126 // The starting values of PHI nodes depend on the counter of the last
1127 // iteration in the vectorized loop.
1128 // If we come from a bypass edge then we need to start from the original
1131 // This variable saves the new starting index for the scalar loop.
1132 PHINode *ResumeIndex = 0;
1133 LoopVectorizationLegality::InductionList::iterator I, E;
1134 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
1135 for (I = List->begin(), E = List->end(); I != E; ++I) {
1136 PHINode *OrigPhi = I->first;
1137 LoopVectorizationLegality::InductionInfo II = I->second;
1138 PHINode *ResumeVal = PHINode::Create(OrigPhi->getType(), 2, "resume.val",
1139 MiddleBlock->getTerminator());
1140 Value *EndValue = 0;
1142 case LoopVectorizationLegality::IK_NoInduction:
1143 llvm_unreachable("Unknown induction");
1144 case LoopVectorizationLegality::IK_IntInduction: {
1145 // Handle the integer induction counter:
1146 assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
1147 assert(OrigPhi == OldInduction && "Unknown integer PHI");
1148 // We know what the end value is.
1149 EndValue = IdxEndRoundDown;
1150 // We also know which PHI node holds it.
1151 ResumeIndex = ResumeVal;
1154 case LoopVectorizationLegality::IK_ReverseIntInduction: {
1155 // Convert the CountRoundDown variable to the PHI size.
1156 unsigned CRDSize = CountRoundDown->getType()->getScalarSizeInBits();
1157 unsigned IISize = II.StartValue->getType()->getScalarSizeInBits();
1158 Value *CRD = CountRoundDown;
1159 if (CRDSize > IISize)
1160 CRD = CastInst::Create(Instruction::Trunc, CountRoundDown,
1161 II.StartValue->getType(), "tr.crd",
1162 LoopBypassBlocks.back()->getTerminator());
1163 else if (CRDSize < IISize)
1164 CRD = CastInst::Create(Instruction::SExt, CountRoundDown,
1165 II.StartValue->getType(),
1167 LoopBypassBlocks.back()->getTerminator());
1168 // Handle reverse integer induction counter:
1170 BinaryOperator::CreateSub(II.StartValue, CRD, "rev.ind.end",
1171 LoopBypassBlocks.back()->getTerminator());
1174 case LoopVectorizationLegality::IK_PtrInduction: {
1175 // For pointer induction variables, calculate the offset using
1178 GetElementPtrInst::Create(II.StartValue, CountRoundDown, "ptr.ind.end",
1179 LoopBypassBlocks.back()->getTerminator());
1182 case LoopVectorizationLegality::IK_ReversePtrInduction: {
1183 // The value at the end of the loop for the reverse pointer is calculated
1184 // by creating a GEP with a negative index starting from the start value.
1185 Value *Zero = ConstantInt::get(CountRoundDown->getType(), 0);
1186 Value *NegIdx = BinaryOperator::CreateSub(Zero, CountRoundDown,
1188 LoopBypassBlocks.back()->getTerminator());
1189 EndValue = GetElementPtrInst::Create(II.StartValue, NegIdx,
1191 LoopBypassBlocks.back()->getTerminator());
1196 // The new PHI merges the original incoming value, in case of a bypass,
1197 // or the value at the end of the vectorized loop.
1198 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
1199 ResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
1200 ResumeVal->addIncoming(EndValue, VecBody);
1202 // Fix the scalar body counter (PHI node).
1203 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
1204 OrigPhi->setIncomingValue(BlockIdx, ResumeVal);
1207 // If we are generating a new induction variable then we also need to
1208 // generate the code that calculates the exit value. This value is not
1209 // simply the end of the counter because we may skip the vectorized body
1210 // in case of a runtime check.
1212 assert(!ResumeIndex && "Unexpected resume value found");
1213 ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
1214 MiddleBlock->getTerminator());
1215 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
1216 ResumeIndex->addIncoming(StartIdx, LoopBypassBlocks[I]);
1217 ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
1220 // Make sure that we found the index where scalar loop needs to continue.
1221 assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
1222 "Invalid resume Index");
1224 // Add a check in the middle block to see if we have completed
1225 // all of the iterations in the first vector loop.
1226 // If (N - N%VF) == N, then we *don't* need to run the remainder.
1227 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
1228 ResumeIndex, "cmp.n",
1229 MiddleBlock->getTerminator());
1231 BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
1232 // Remove the old terminator.
1233 MiddleBlock->getTerminator()->eraseFromParent();
1235 // Create i+1 and fill the PHINode.
1236 Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
1237 Induction->addIncoming(StartIdx, VectorPH);
1238 Induction->addIncoming(NextIdx, VecBody);
1239 // Create the compare.
1240 Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
1241 Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
1243 // Now we have two terminators. Remove the old one from the block.
1244 VecBody->getTerminator()->eraseFromParent();
1246 // Get ready to start creating new instructions into the vectorized body.
1247 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
1249 // Create and register the new vector loop.
1250 Loop* Lp = new Loop();
1251 Loop *ParentLoop = OrigLoop->getParentLoop();
1253 // Insert the new loop into the loop nest and register the new basic blocks.
1255 ParentLoop->addChildLoop(Lp);
1256 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
1257 ParentLoop->addBasicBlockToLoop(LoopBypassBlocks[I], LI->getBase());
1258 ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
1259 ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
1260 ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
1262 LI->addTopLevelLoop(Lp);
1265 Lp->addBasicBlockToLoop(VecBody, LI->getBase());
1268 LoopVectorPreHeader = VectorPH;
1269 LoopScalarPreHeader = ScalarPH;
1270 LoopMiddleBlock = MiddleBlock;
1271 LoopExitBlock = ExitBlock;
1272 LoopVectorBody = VecBody;
1273 LoopScalarBody = OldBasicBlock;
1276 /// This function returns the identity element (or neutral element) for
1277 /// the operation K.
1279 getReductionIdentity(LoopVectorizationLegality::ReductionKind K, Type *Tp) {
1281 case LoopVectorizationLegality:: RK_IntegerXor:
1282 case LoopVectorizationLegality:: RK_IntegerAdd:
1283 case LoopVectorizationLegality:: RK_IntegerOr:
1284 // Adding, Xoring, Oring zero to a number does not change it.
1285 return ConstantInt::get(Tp, 0);
1286 case LoopVectorizationLegality:: RK_IntegerMult:
1287 // Multiplying a number by 1 does not change it.
1288 return ConstantInt::get(Tp, 1);
1289 case LoopVectorizationLegality:: RK_IntegerAnd:
1290 // AND-ing a number with an all-1 value does not change it.
1291 return ConstantInt::get(Tp, -1, true);
1292 case LoopVectorizationLegality:: RK_FloatMult:
1293 // Multiplying a number by 1 does not change it.
1294 return ConstantFP::get(Tp, 1.0L);
1295 case LoopVectorizationLegality:: RK_FloatAdd:
1296 // Adding zero to a number does not change it.
1297 return ConstantFP::get(Tp, 0.0L);
1299 llvm_unreachable("Unknown reduction kind");
1304 isTriviallyVectorizableIntrinsic(Instruction *Inst) {
1305 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst);
1308 switch (II->getIntrinsicID()) {
1309 case Intrinsic::sqrt:
1310 case Intrinsic::sin:
1311 case Intrinsic::cos:
1312 case Intrinsic::exp:
1313 case Intrinsic::exp2:
1314 case Intrinsic::log:
1315 case Intrinsic::log10:
1316 case Intrinsic::log2:
1317 case Intrinsic::fabs:
1318 case Intrinsic::floor:
1319 case Intrinsic::ceil:
1320 case Intrinsic::trunc:
1321 case Intrinsic::rint:
1322 case Intrinsic::nearbyint:
1323 case Intrinsic::pow:
1324 case Intrinsic::fma:
1325 case Intrinsic::fmuladd:
1333 /// This function translates the reduction kind to an LLVM binary operator.
1334 static Instruction::BinaryOps
1335 getReductionBinOp(LoopVectorizationLegality::ReductionKind Kind) {
1337 case LoopVectorizationLegality::RK_IntegerAdd:
1338 return Instruction::Add;
1339 case LoopVectorizationLegality::RK_IntegerMult:
1340 return Instruction::Mul;
1341 case LoopVectorizationLegality::RK_IntegerOr:
1342 return Instruction::Or;
1343 case LoopVectorizationLegality::RK_IntegerAnd:
1344 return Instruction::And;
1345 case LoopVectorizationLegality::RK_IntegerXor:
1346 return Instruction::Xor;
1347 case LoopVectorizationLegality::RK_FloatMult:
1348 return Instruction::FMul;
1349 case LoopVectorizationLegality::RK_FloatAdd:
1350 return Instruction::FAdd;
1352 llvm_unreachable("Unknown reduction operation");
1357 InnerLoopVectorizer::vectorizeLoop(LoopVectorizationLegality *Legal) {
1358 //===------------------------------------------------===//
1360 // Notice: any optimization or new instruction that go
1361 // into the code below should be also be implemented in
1364 //===------------------------------------------------===//
1365 BasicBlock &BB = *OrigLoop->getHeader();
1367 ConstantInt::get(IntegerType::getInt32Ty(BB.getContext()), 0);
1369 // In order to support reduction variables we need to be able to vectorize
1370 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
1371 // stages. First, we create a new vector PHI node with no incoming edges.
1372 // We use this value when we vectorize all of the instructions that use the
1373 // PHI. Next, after all of the instructions in the block are complete we
1374 // add the new incoming edges to the PHI. At this point all of the
1375 // instructions in the basic block are vectorized, so we can use them to
1376 // construct the PHI.
1377 PhiVector RdxPHIsToFix;
1379 // Scan the loop in a topological order to ensure that defs are vectorized
1381 LoopBlocksDFS DFS(OrigLoop);
1384 // Vectorize all of the blocks in the original loop.
1385 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
1386 be = DFS.endRPO(); bb != be; ++bb)
1387 vectorizeBlockInLoop(Legal, *bb, &RdxPHIsToFix);
1389 // At this point every instruction in the original loop is widened to
1390 // a vector form. We are almost done. Now, we need to fix the PHI nodes
1391 // that we vectorized. The PHI nodes are currently empty because we did
1392 // not want to introduce cycles. Notice that the remaining PHI nodes
1393 // that we need to fix are reduction variables.
1395 // Create the 'reduced' values for each of the induction vars.
1396 // The reduced values are the vector values that we scalarize and combine
1397 // after the loop is finished.
1398 for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
1400 PHINode *RdxPhi = *it;
1401 assert(RdxPhi && "Unable to recover vectorized PHI");
1403 // Find the reduction variable descriptor.
1404 assert(Legal->getReductionVars()->count(RdxPhi) &&
1405 "Unable to find the reduction variable");
1406 LoopVectorizationLegality::ReductionDescriptor RdxDesc =
1407 (*Legal->getReductionVars())[RdxPhi];
1409 // We need to generate a reduction vector from the incoming scalar.
1410 // To do so, we need to generate the 'identity' vector and overide
1411 // one of the elements with the incoming scalar reduction. We need
1412 // to do it in the vector-loop preheader.
1413 Builder.SetInsertPoint(LoopBypassBlocks.back()->getTerminator());
1415 // This is the vector-clone of the value that leaves the loop.
1416 VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
1417 Type *VecTy = VectorExit[0]->getType();
1419 // Find the reduction identity variable. Zero for addition, or, xor,
1420 // one for multiplication, -1 for And.
1421 Constant *Iden = getReductionIdentity(RdxDesc.Kind, VecTy->getScalarType());
1422 Constant *Identity = ConstantVector::getSplat(VF, Iden);
1424 // This vector is the Identity vector where the first element is the
1425 // incoming scalar reduction.
1426 Value *VectorStart = Builder.CreateInsertElement(Identity,
1427 RdxDesc.StartValue, Zero);
1429 // Fix the vector-loop phi.
1430 // We created the induction variable so we know that the
1431 // preheader is the first entry.
1432 BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
1434 // Reductions do not have to start at zero. They can start with
1435 // any loop invariant values.
1436 VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
1437 BasicBlock *Latch = OrigLoop->getLoopLatch();
1438 Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
1439 VectorParts &Val = getVectorValue(LoopVal);
1440 for (unsigned part = 0; part < UF; ++part) {
1441 // Make sure to add the reduction stat value only to the
1442 // first unroll part.
1443 Value *StartVal = (part == 0) ? VectorStart : Identity;
1444 cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal, VecPreheader);
1445 cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part], LoopVectorBody);
1448 // Before each round, move the insertion point right between
1449 // the PHIs and the values we are going to write.
1450 // This allows us to write both PHINodes and the extractelement
1452 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
1454 VectorParts RdxParts;
1455 for (unsigned part = 0; part < UF; ++part) {
1456 // This PHINode contains the vectorized reduction variable, or
1457 // the initial value vector, if we bypass the vector loop.
1458 VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr);
1459 PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
1460 Value *StartVal = (part == 0) ? VectorStart : Identity;
1461 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
1462 NewPhi->addIncoming(StartVal, LoopBypassBlocks[I]);
1463 NewPhi->addIncoming(RdxExitVal[part], LoopVectorBody);
1464 RdxParts.push_back(NewPhi);
1467 // Reduce all of the unrolled parts into a single vector.
1468 Value *ReducedPartRdx = RdxParts[0];
1469 for (unsigned part = 1; part < UF; ++part) {
1470 Instruction::BinaryOps Op = getReductionBinOp(RdxDesc.Kind);
1471 ReducedPartRdx = Builder.CreateBinOp(Op, RdxParts[part], ReducedPartRdx,
1475 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
1476 // and vector ops, reducing the set of values being computed by half each
1478 assert(isPowerOf2_32(VF) &&
1479 "Reduction emission only supported for pow2 vectors!");
1480 Value *TmpVec = ReducedPartRdx;
1481 SmallVector<Constant*, 32> ShuffleMask(VF, 0);
1482 for (unsigned i = VF; i != 1; i >>= 1) {
1483 // Move the upper half of the vector to the lower half.
1484 for (unsigned j = 0; j != i/2; ++j)
1485 ShuffleMask[j] = Builder.getInt32(i/2 + j);
1487 // Fill the rest of the mask with undef.
1488 std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
1489 UndefValue::get(Builder.getInt32Ty()));
1492 Builder.CreateShuffleVector(TmpVec,
1493 UndefValue::get(TmpVec->getType()),
1494 ConstantVector::get(ShuffleMask),
1497 Instruction::BinaryOps Op = getReductionBinOp(RdxDesc.Kind);
1498 TmpVec = Builder.CreateBinOp(Op, TmpVec, Shuf, "bin.rdx");
1501 // The result is in the first element of the vector.
1502 Value *Scalar0 = Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
1504 // Now, we need to fix the users of the reduction variable
1505 // inside and outside of the scalar remainder loop.
1506 // We know that the loop is in LCSSA form. We need to update the
1507 // PHI nodes in the exit blocks.
1508 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
1509 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
1510 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
1511 if (!LCSSAPhi) continue;
1513 // All PHINodes need to have a single entry edge, or two if
1514 // we already fixed them.
1515 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
1517 // We found our reduction value exit-PHI. Update it with the
1518 // incoming bypass edge.
1519 if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
1520 // Add an edge coming from the bypass.
1521 LCSSAPhi->addIncoming(Scalar0, LoopMiddleBlock);
1524 }// end of the LCSSA phi scan.
1526 // Fix the scalar loop reduction variable with the incoming reduction sum
1527 // from the vector body and from the backedge value.
1528 int IncomingEdgeBlockIdx =
1529 (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
1530 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
1531 // Pick the other block.
1532 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
1533 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, Scalar0);
1534 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
1535 }// end of for each redux variable.
1537 // The Loop exit block may have single value PHI nodes where the incoming
1538 // value is 'undef'. While vectorizing we only handled real values that
1539 // were defined inside the loop. Here we handle the 'undef case'.
1541 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
1542 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
1543 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
1544 if (!LCSSAPhi) continue;
1545 if (LCSSAPhi->getNumIncomingValues() == 1)
1546 LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
1551 InnerLoopVectorizer::VectorParts
1552 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
1553 assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
1556 VectorParts SrcMask = createBlockInMask(Src);
1558 // The terminator has to be a branch inst!
1559 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
1560 assert(BI && "Unexpected terminator found");
1562 if (BI->isConditional()) {
1563 VectorParts EdgeMask = getVectorValue(BI->getCondition());
1565 if (BI->getSuccessor(0) != Dst)
1566 for (unsigned part = 0; part < UF; ++part)
1567 EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
1569 for (unsigned part = 0; part < UF; ++part)
1570 EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
1577 InnerLoopVectorizer::VectorParts
1578 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
1579 assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
1581 // Loop incoming mask is all-one.
1582 if (OrigLoop->getHeader() == BB) {
1583 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
1584 return getVectorValue(C);
1587 // This is the block mask. We OR all incoming edges, and with zero.
1588 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
1589 VectorParts BlockMask = getVectorValue(Zero);
1592 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
1593 VectorParts EM = createEdgeMask(*it, BB);
1594 for (unsigned part = 0; part < UF; ++part)
1595 BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
1602 InnerLoopVectorizer::vectorizeBlockInLoop(LoopVectorizationLegality *Legal,
1603 BasicBlock *BB, PhiVector *PV) {
1604 Constant *Zero = Builder.getInt32(0);
1606 // For each instruction in the old loop.
1607 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1608 VectorParts &Entry = WidenMap.get(it);
1609 switch (it->getOpcode()) {
1610 case Instruction::Br:
1611 // Nothing to do for PHIs and BR, since we already took care of the
1612 // loop control flow instructions.
1614 case Instruction::PHI:{
1615 PHINode* P = cast<PHINode>(it);
1616 // Handle reduction variables:
1617 if (Legal->getReductionVars()->count(P)) {
1618 for (unsigned part = 0; part < UF; ++part) {
1619 // This is phase one of vectorizing PHIs.
1620 Type *VecTy = VectorType::get(it->getType(), VF);
1621 Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
1622 LoopVectorBody-> getFirstInsertionPt());
1628 // Check for PHI nodes that are lowered to vector selects.
1629 if (P->getParent() != OrigLoop->getHeader()) {
1630 // We know that all PHIs in non header blocks are converted into
1631 // selects, so we don't have to worry about the insertion order and we
1632 // can just use the builder.
1634 // At this point we generate the predication tree. There may be
1635 // duplications since this is a simple recursive scan, but future
1636 // optimizations will clean it up.
1637 VectorParts Cond = createEdgeMask(P->getIncomingBlock(0),
1640 for (unsigned part = 0; part < UF; ++part) {
1641 VectorParts &In0 = getVectorValue(P->getIncomingValue(0));
1642 VectorParts &In1 = getVectorValue(P->getIncomingValue(1));
1643 Entry[part] = Builder.CreateSelect(Cond[part], In0[part], In1[part],
1649 // This PHINode must be an induction variable.
1650 // Make sure that we know about it.
1651 assert(Legal->getInductionVars()->count(P) &&
1652 "Not an induction variable");
1654 LoopVectorizationLegality::InductionInfo II =
1655 Legal->getInductionVars()->lookup(P);
1658 case LoopVectorizationLegality::IK_NoInduction:
1659 llvm_unreachable("Unknown induction");
1660 case LoopVectorizationLegality::IK_IntInduction: {
1661 assert(P == OldInduction && "Unexpected PHI");
1662 Value *Broadcasted = getBroadcastInstrs(Induction);
1663 // After broadcasting the induction variable we need to make the
1664 // vector consecutive by adding 0, 1, 2 ...
1665 for (unsigned part = 0; part < UF; ++part)
1666 Entry[part] = getConsecutiveVector(Broadcasted, VF * part, false);
1669 case LoopVectorizationLegality::IK_ReverseIntInduction:
1670 case LoopVectorizationLegality::IK_PtrInduction:
1671 case LoopVectorizationLegality::IK_ReversePtrInduction:
1672 // Handle reverse integer and pointer inductions.
1673 Value *StartIdx = 0;
1674 // If we have a single integer induction variable then use it.
1675 // Otherwise, start counting at zero.
1677 LoopVectorizationLegality::InductionInfo OldII =
1678 Legal->getInductionVars()->lookup(OldInduction);
1679 StartIdx = OldII.StartValue;
1681 StartIdx = ConstantInt::get(Induction->getType(), 0);
1683 // This is the normalized GEP that starts counting at zero.
1684 Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
1687 // Handle the reverse integer induction variable case.
1688 if (LoopVectorizationLegality::IK_ReverseIntInduction == II.IK) {
1689 IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType());
1690 Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy,
1692 Value *ReverseInd = Builder.CreateSub(II.StartValue, CNI,
1695 // This is a new value so do not hoist it out.
1696 Value *Broadcasted = getBroadcastInstrs(ReverseInd);
1697 // After broadcasting the induction variable we need to make the
1698 // vector consecutive by adding ... -3, -2, -1, 0.
1699 for (unsigned part = 0; part < UF; ++part)
1700 Entry[part] = getConsecutiveVector(Broadcasted, -VF * part, true);
1704 // Handle the pointer induction variable case.
1705 assert(P->getType()->isPointerTy() && "Unexpected type.");
1707 // Is this a reverse induction ptr or a consecutive induction ptr.
1708 bool Reverse = (LoopVectorizationLegality::IK_ReversePtrInduction ==
1711 // This is the vector of results. Notice that we don't generate
1712 // vector geps because scalar geps result in better code.
1713 for (unsigned part = 0; part < UF; ++part) {
1714 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
1715 for (unsigned int i = 0; i < VF; ++i) {
1716 int EltIndex = (i + part * VF) * (Reverse ? -1 : 1);
1717 Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
1720 GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
1722 GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx");
1724 Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
1726 VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
1727 Builder.getInt32(i),
1730 Entry[part] = VecVal;
1737 case Instruction::Add:
1738 case Instruction::FAdd:
1739 case Instruction::Sub:
1740 case Instruction::FSub:
1741 case Instruction::Mul:
1742 case Instruction::FMul:
1743 case Instruction::UDiv:
1744 case Instruction::SDiv:
1745 case Instruction::FDiv:
1746 case Instruction::URem:
1747 case Instruction::SRem:
1748 case Instruction::FRem:
1749 case Instruction::Shl:
1750 case Instruction::LShr:
1751 case Instruction::AShr:
1752 case Instruction::And:
1753 case Instruction::Or:
1754 case Instruction::Xor: {
1755 // Just widen binops.
1756 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
1757 VectorParts &A = getVectorValue(it->getOperand(0));
1758 VectorParts &B = getVectorValue(it->getOperand(1));
1760 // Use this vector value for all users of the original instruction.
1761 for (unsigned Part = 0; Part < UF; ++Part) {
1762 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
1764 // Update the NSW, NUW and Exact flags. Notice: V can be an Undef.
1765 BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V);
1766 if (VecOp && isa<OverflowingBinaryOperator>(BinOp)) {
1767 VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap());
1768 VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap());
1770 if (VecOp && isa<PossiblyExactOperator>(VecOp))
1771 VecOp->setIsExact(BinOp->isExact());
1777 case Instruction::Select: {
1779 // If the selector is loop invariant we can create a select
1780 // instruction with a scalar condition. Otherwise, use vector-select.
1781 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
1784 // The condition can be loop invariant but still defined inside the
1785 // loop. This means that we can't just use the original 'cond' value.
1786 // We have to take the 'vectorized' value and pick the first lane.
1787 // Instcombine will make this a no-op.
1788 VectorParts &Cond = getVectorValue(it->getOperand(0));
1789 VectorParts &Op0 = getVectorValue(it->getOperand(1));
1790 VectorParts &Op1 = getVectorValue(it->getOperand(2));
1791 Value *ScalarCond = Builder.CreateExtractElement(Cond[0],
1792 Builder.getInt32(0));
1793 for (unsigned Part = 0; Part < UF; ++Part) {
1794 Entry[Part] = Builder.CreateSelect(
1795 InvariantCond ? ScalarCond : Cond[Part],
1802 case Instruction::ICmp:
1803 case Instruction::FCmp: {
1804 // Widen compares. Generate vector compares.
1805 bool FCmp = (it->getOpcode() == Instruction::FCmp);
1806 CmpInst *Cmp = dyn_cast<CmpInst>(it);
1807 VectorParts &A = getVectorValue(it->getOperand(0));
1808 VectorParts &B = getVectorValue(it->getOperand(1));
1809 for (unsigned Part = 0; Part < UF; ++Part) {
1812 C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
1814 C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
1820 case Instruction::Store: {
1821 // Attempt to issue a wide store.
1822 StoreInst *SI = dyn_cast<StoreInst>(it);
1823 Type *StTy = VectorType::get(SI->getValueOperand()->getType(), VF);
1824 Value *Ptr = SI->getPointerOperand();
1825 unsigned Alignment = SI->getAlignment();
1827 assert(!Legal->isUniform(Ptr) &&
1828 "We do not allow storing to uniform addresses");
1831 int Stride = Legal->isConsecutivePtr(Ptr);
1832 bool Reverse = Stride < 0;
1834 scalarizeInstruction(it);
1838 // Handle consecutive stores.
1840 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1841 if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) {
1842 Value *PtrOperand = Gep->getPointerOperand();
1843 Value *FirstBasePtr = getVectorValue(PtrOperand)[0];
1844 FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero);
1846 // Create the new GEP with the new induction variable.
1847 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1848 Gep2->setOperand(0, FirstBasePtr);
1849 Ptr = Builder.Insert(Gep2);
1851 assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()),
1852 OrigLoop) && "Base ptr must be invariant");
1854 // The last index does not have to be the induction. It can be
1855 // consecutive and be a function of the index. For example A[I+1];
1856 unsigned NumOperands = Gep->getNumOperands();
1858 Value *LastGepOperand = Gep->getOperand(NumOperands - 1);
1859 VectorParts &GEPParts = getVectorValue(LastGepOperand);
1860 Value *LastIndex = GEPParts[0];
1861 LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
1863 // Create the new GEP with the new induction variable.
1864 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1865 Gep2->setOperand(NumOperands - 1, LastIndex);
1866 Ptr = Builder.Insert(Gep2);
1868 // Use the induction element ptr.
1869 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1870 VectorParts &PtrVal = getVectorValue(Ptr);
1871 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
1874 VectorParts &StoredVal = getVectorValue(SI->getValueOperand());
1875 for (unsigned Part = 0; Part < UF; ++Part) {
1876 // Calculate the pointer for the specific unroll-part.
1877 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1880 // If we store to reverse consecutive memory locations then we need
1881 // to reverse the order of elements in the stored value.
1882 StoredVal[Part] = reverseVector(StoredVal[Part]);
1883 // If the address is consecutive but reversed, then the
1884 // wide store needs to start at the last vector element.
1885 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1886 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1889 Value *VecPtr = Builder.CreateBitCast(PartPtr, StTy->getPointerTo());
1890 Builder.CreateStore(StoredVal[Part], VecPtr)->setAlignment(Alignment);
1894 case Instruction::Load: {
1895 // Attempt to issue a wide load.
1896 LoadInst *LI = dyn_cast<LoadInst>(it);
1897 Type *RetTy = VectorType::get(LI->getType(), VF);
1898 Value *Ptr = LI->getPointerOperand();
1899 unsigned Alignment = LI->getAlignment();
1901 // If the pointer is loop invariant or if it is non consecutive,
1902 // scalarize the load.
1903 int Stride = Legal->isConsecutivePtr(Ptr);
1904 bool Reverse = Stride < 0;
1905 if (Legal->isUniform(Ptr) || Stride == 0) {
1906 scalarizeInstruction(it);
1910 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1911 if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) {
1912 Value *PtrOperand = Gep->getPointerOperand();
1913 Value *FirstBasePtr = getVectorValue(PtrOperand)[0];
1914 FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero);
1915 // Create the new GEP with the new induction variable.
1916 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1917 Gep2->setOperand(0, FirstBasePtr);
1918 Ptr = Builder.Insert(Gep2);
1920 assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()),
1921 OrigLoop) && "Base ptr must be invariant");
1923 // The last index does not have to be the induction. It can be
1924 // consecutive and be a function of the index. For example A[I+1];
1925 unsigned NumOperands = Gep->getNumOperands();
1927 Value *LastGepOperand = Gep->getOperand(NumOperands - 1);
1928 VectorParts &GEPParts = getVectorValue(LastGepOperand);
1929 Value *LastIndex = GEPParts[0];
1930 LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
1932 // Create the new GEP with the new induction variable.
1933 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1934 Gep2->setOperand(NumOperands - 1, LastIndex);
1935 Ptr = Builder.Insert(Gep2);
1937 // Use the induction element ptr.
1938 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1939 VectorParts &PtrVal = getVectorValue(Ptr);
1940 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
1943 for (unsigned Part = 0; Part < UF; ++Part) {
1944 // Calculate the pointer for the specific unroll-part.
1945 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1948 // If the address is consecutive but reversed, then the
1949 // wide store needs to start at the last vector element.
1950 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1951 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1954 Value *VecPtr = Builder.CreateBitCast(PartPtr, RetTy->getPointerTo());
1955 Value *LI = Builder.CreateLoad(VecPtr, "wide.load");
1956 cast<LoadInst>(LI)->setAlignment(Alignment);
1957 Entry[Part] = Reverse ? reverseVector(LI) : LI;
1961 case Instruction::ZExt:
1962 case Instruction::SExt:
1963 case Instruction::FPToUI:
1964 case Instruction::FPToSI:
1965 case Instruction::FPExt:
1966 case Instruction::PtrToInt:
1967 case Instruction::IntToPtr:
1968 case Instruction::SIToFP:
1969 case Instruction::UIToFP:
1970 case Instruction::Trunc:
1971 case Instruction::FPTrunc:
1972 case Instruction::BitCast: {
1973 CastInst *CI = dyn_cast<CastInst>(it);
1974 /// Optimize the special case where the source is the induction
1975 /// variable. Notice that we can only optimize the 'trunc' case
1976 /// because: a. FP conversions lose precision, b. sext/zext may wrap,
1977 /// c. other casts depend on pointer size.
1978 if (CI->getOperand(0) == OldInduction &&
1979 it->getOpcode() == Instruction::Trunc) {
1980 Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
1982 Value *Broadcasted = getBroadcastInstrs(ScalarCast);
1983 for (unsigned Part = 0; Part < UF; ++Part)
1984 Entry[Part] = getConsecutiveVector(Broadcasted, VF * Part, false);
1987 /// Vectorize casts.
1988 Type *DestTy = VectorType::get(CI->getType()->getScalarType(), VF);
1990 VectorParts &A = getVectorValue(it->getOperand(0));
1991 for (unsigned Part = 0; Part < UF; ++Part)
1992 Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
1996 case Instruction::Call: {
1997 assert(isTriviallyVectorizableIntrinsic(it));
1998 Module *M = BB->getParent()->getParent();
1999 IntrinsicInst *II = cast<IntrinsicInst>(it);
2000 Intrinsic::ID ID = II->getIntrinsicID();
2001 for (unsigned Part = 0; Part < UF; ++Part) {
2002 SmallVector<Value*, 4> Args;
2003 for (unsigned i = 0, ie = II->getNumArgOperands(); i != ie; ++i) {
2004 VectorParts &Arg = getVectorValue(II->getArgOperand(i));
2005 Args.push_back(Arg[Part]);
2007 Type *Tys[] = { VectorType::get(II->getType()->getScalarType(), VF) };
2008 Function *F = Intrinsic::getDeclaration(M, ID, Tys);
2009 Entry[Part] = Builder.CreateCall(F, Args);
2015 // All other instructions are unsupported. Scalarize them.
2016 scalarizeInstruction(it);
2019 }// end of for_each instr.
2022 void InnerLoopVectorizer::updateAnalysis() {
2023 // Forget the original basic block.
2024 SE->forgetLoop(OrigLoop);
2026 // Update the dominator tree information.
2027 assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
2028 "Entry does not dominate exit.");
2030 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2031 DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]);
2032 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back());
2033 DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader);
2034 DT->addNewBlock(LoopMiddleBlock, LoopBypassBlocks.front());
2035 DT->addNewBlock(LoopScalarPreHeader, LoopMiddleBlock);
2036 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
2037 DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
2039 DEBUG(DT->verifyAnalysis());
2042 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
2043 if (!EnableIfConversion)
2046 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
2047 std::vector<BasicBlock*> &LoopBlocks = TheLoop->getBlocksVector();
2049 // Collect the blocks that need predication.
2050 for (unsigned i = 0, e = LoopBlocks.size(); i < e; ++i) {
2051 BasicBlock *BB = LoopBlocks[i];
2053 // We don't support switch statements inside loops.
2054 if (!isa<BranchInst>(BB->getTerminator()))
2057 // We must have at most two predecessors because we need to convert
2058 // all PHIs to selects.
2059 unsigned Preds = std::distance(pred_begin(BB), pred_end(BB));
2063 // We must be able to predicate all blocks that need to be predicated.
2064 if (blockNeedsPredication(BB) && !blockCanBePredicated(BB))
2068 // We can if-convert this loop.
2072 bool LoopVectorizationLegality::canVectorize() {
2073 assert(TheLoop->getLoopPreheader() && "No preheader!!");
2075 // We can only vectorize innermost loops.
2076 if (TheLoop->getSubLoopsVector().size())
2079 // We must have a single backedge.
2080 if (TheLoop->getNumBackEdges() != 1)
2083 // We must have a single exiting block.
2084 if (!TheLoop->getExitingBlock())
2087 unsigned NumBlocks = TheLoop->getNumBlocks();
2089 // Check if we can if-convert non single-bb loops.
2090 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
2091 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
2095 // We need to have a loop header.
2096 BasicBlock *Latch = TheLoop->getLoopLatch();
2097 DEBUG(dbgs() << "LV: Found a loop: " <<
2098 TheLoop->getHeader()->getName() << "\n");
2100 // ScalarEvolution needs to be able to find the exit count.
2101 const SCEV *ExitCount = SE->getExitCount(TheLoop, Latch);
2102 if (ExitCount == SE->getCouldNotCompute()) {
2103 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
2107 // Do not loop-vectorize loops with a tiny trip count.
2108 unsigned TC = SE->getSmallConstantTripCount(TheLoop, Latch);
2109 if (TC > 0u && TC < TinyTripCountVectorThreshold) {
2110 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " <<
2111 "This loop is not worth vectorizing.\n");
2115 // Check if we can vectorize the instructions and CFG in this loop.
2116 if (!canVectorizeInstrs()) {
2117 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
2121 // Go over each instruction and look at memory deps.
2122 if (!canVectorizeMemory()) {
2123 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
2127 // Collect all of the variables that remain uniform after vectorization.
2128 collectLoopUniforms();
2130 DEBUG(dbgs() << "LV: We can vectorize this loop" <<
2131 (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
2134 // Okay! We can vectorize. At this point we don't have any other mem analysis
2135 // which may limit our maximum vectorization factor, so just return true with
2140 bool LoopVectorizationLegality::canVectorizeInstrs() {
2141 BasicBlock *PreHeader = TheLoop->getLoopPreheader();
2142 BasicBlock *Header = TheLoop->getHeader();
2144 // For each block in the loop.
2145 for (Loop::block_iterator bb = TheLoop->block_begin(),
2146 be = TheLoop->block_end(); bb != be; ++bb) {
2148 // Scan the instructions in the block and look for hazards.
2149 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
2152 if (PHINode *Phi = dyn_cast<PHINode>(it)) {
2153 // This should not happen because the loop should be normalized.
2154 if (Phi->getNumIncomingValues() != 2) {
2155 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
2159 // Check that this PHI type is allowed.
2160 if (!Phi->getType()->isIntegerTy() &&
2161 !Phi->getType()->isFloatingPointTy() &&
2162 !Phi->getType()->isPointerTy()) {
2163 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
2167 // If this PHINode is not in the header block, then we know that we
2168 // can convert it to select during if-conversion. No need to check if
2169 // the PHIs in this block are induction or reduction variables.
2173 // This is the value coming from the preheader.
2174 Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
2175 // Check if this is an induction variable.
2176 InductionKind IK = isInductionVariable(Phi);
2178 if (IK_NoInduction != IK) {
2179 // Int inductions are special because we only allow one IV.
2180 if (IK == IK_IntInduction) {
2182 DEBUG(dbgs() << "LV: Found too many inductions."<< *Phi <<"\n");
2188 DEBUG(dbgs() << "LV: Found an induction variable.\n");
2189 Inductions[Phi] = InductionInfo(StartValue, IK);
2193 if (AddReductionVar(Phi, RK_IntegerAdd)) {
2194 DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
2197 if (AddReductionVar(Phi, RK_IntegerMult)) {
2198 DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
2201 if (AddReductionVar(Phi, RK_IntegerOr)) {
2202 DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
2205 if (AddReductionVar(Phi, RK_IntegerAnd)) {
2206 DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
2209 if (AddReductionVar(Phi, RK_IntegerXor)) {
2210 DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
2213 if (AddReductionVar(Phi, RK_FloatMult)) {
2214 DEBUG(dbgs() << "LV: Found an FMult reduction PHI."<< *Phi <<"\n");
2217 if (AddReductionVar(Phi, RK_FloatAdd)) {
2218 DEBUG(dbgs() << "LV: Found an FAdd reduction PHI."<< *Phi <<"\n");
2222 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
2224 }// end of PHI handling
2226 // We still don't handle functions.
2227 CallInst *CI = dyn_cast<CallInst>(it);
2228 if (CI && !isTriviallyVectorizableIntrinsic(it)) {
2229 DEBUG(dbgs() << "LV: Found a call site.\n");
2233 // Check that the instruction return type is vectorizable.
2234 if (!VectorType::isValidElementType(it->getType()) &&
2235 !it->getType()->isVoidTy()) {
2236 DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n");
2240 // Check that the stored type is vectorizable.
2241 if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
2242 Type *T = ST->getValueOperand()->getType();
2243 if (!VectorType::isValidElementType(T))
2247 // Reduction instructions are allowed to have exit users.
2248 // All other instructions must not have external users.
2249 if (!AllowedExit.count(it))
2250 //Check that all of the users of the loop are inside the BB.
2251 for (Value::use_iterator I = it->use_begin(), E = it->use_end();
2253 Instruction *U = cast<Instruction>(*I);
2254 // This user may be a reduction exit value.
2255 if (!TheLoop->contains(U)) {
2256 DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n");
2265 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
2266 assert(getInductionVars()->size() && "No induction variables");
2272 void LoopVectorizationLegality::collectLoopUniforms() {
2273 // We now know that the loop is vectorizable!
2274 // Collect variables that will remain uniform after vectorization.
2275 std::vector<Value*> Worklist;
2276 BasicBlock *Latch = TheLoop->getLoopLatch();
2278 // Start with the conditional branch and walk up the block.
2279 Worklist.push_back(Latch->getTerminator()->getOperand(0));
2281 while (Worklist.size()) {
2282 Instruction *I = dyn_cast<Instruction>(Worklist.back());
2283 Worklist.pop_back();
2285 // Look at instructions inside this loop.
2286 // Stop when reaching PHI nodes.
2287 // TODO: we need to follow values all over the loop, not only in this block.
2288 if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
2291 // This is a known uniform.
2294 // Insert all operands.
2295 for (int i = 0, Op = I->getNumOperands(); i < Op; ++i) {
2296 Worklist.push_back(I->getOperand(i));
2301 bool LoopVectorizationLegality::canVectorizeMemory() {
2302 typedef SmallVector<Value*, 16> ValueVector;
2303 typedef SmallPtrSet<Value*, 16> ValueSet;
2304 // Holds the Load and Store *instructions*.
2307 PtrRtCheck.Pointers.clear();
2308 PtrRtCheck.Need = false;
2311 for (Loop::block_iterator bb = TheLoop->block_begin(),
2312 be = TheLoop->block_end(); bb != be; ++bb) {
2314 // Scan the BB and collect legal loads and stores.
2315 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
2318 // If this is a load, save it. If this instruction can read from memory
2319 // but is not a load, then we quit. Notice that we don't handle function
2320 // calls that read or write.
2321 if (it->mayReadFromMemory()) {
2322 LoadInst *Ld = dyn_cast<LoadInst>(it);
2323 if (!Ld) return false;
2324 if (!Ld->isSimple()) {
2325 DEBUG(dbgs() << "LV: Found a non-simple load.\n");
2328 Loads.push_back(Ld);
2332 // Save 'store' instructions. Abort if other instructions write to memory.
2333 if (it->mayWriteToMemory()) {
2334 StoreInst *St = dyn_cast<StoreInst>(it);
2335 if (!St) return false;
2336 if (!St->isSimple()) {
2337 DEBUG(dbgs() << "LV: Found a non-simple store.\n");
2340 Stores.push_back(St);
2345 // Now we have two lists that hold the loads and the stores.
2346 // Next, we find the pointers that they use.
2348 // Check if we see any stores. If there are no stores, then we don't
2349 // care if the pointers are *restrict*.
2350 if (!Stores.size()) {
2351 DEBUG(dbgs() << "LV: Found a read-only loop!\n");
2355 // Holds the read and read-write *pointers* that we find.
2357 ValueVector ReadWrites;
2359 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
2360 // multiple times on the same object. If the ptr is accessed twice, once
2361 // for read and once for write, it will only appear once (on the write
2362 // list). This is okay, since we are going to check for conflicts between
2363 // writes and between reads and writes, but not between reads and reads.
2366 ValueVector::iterator I, IE;
2367 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
2368 StoreInst *ST = cast<StoreInst>(*I);
2369 Value* Ptr = ST->getPointerOperand();
2371 if (isUniform(Ptr)) {
2372 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
2376 // If we did *not* see this pointer before, insert it to
2377 // the read-write list. At this phase it is only a 'write' list.
2378 if (Seen.insert(Ptr))
2379 ReadWrites.push_back(Ptr);
2382 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
2383 LoadInst *LD = cast<LoadInst>(*I);
2384 Value* Ptr = LD->getPointerOperand();
2385 // If we did *not* see this pointer before, insert it to the
2386 // read list. If we *did* see it before, then it is already in
2387 // the read-write list. This allows us to vectorize expressions
2388 // such as A[i] += x; Because the address of A[i] is a read-write
2389 // pointer. This only works if the index of A[i] is consecutive.
2390 // If the address of i is unknown (for example A[B[i]]) then we may
2391 // read a few words, modify, and write a few words, and some of the
2392 // words may be written to the same address.
2393 if (Seen.insert(Ptr) || 0 == isConsecutivePtr(Ptr))
2394 Reads.push_back(Ptr);
2397 // If we write (or read-write) to a single destination and there are no
2398 // other reads in this loop then is it safe to vectorize.
2399 if (ReadWrites.size() == 1 && Reads.size() == 0) {
2400 DEBUG(dbgs() << "LV: Found a write-only loop!\n");
2404 // Find pointers with computable bounds. We are going to use this information
2405 // to place a runtime bound check.
2406 bool CanDoRT = true;
2407 for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I)
2408 if (hasComputableBounds(*I)) {
2409 PtrRtCheck.insert(SE, TheLoop, *I);
2410 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n");
2415 for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I)
2416 if (hasComputableBounds(*I)) {
2417 PtrRtCheck.insert(SE, TheLoop, *I);
2418 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n");
2424 // Check that we did not collect too many pointers or found a
2425 // unsizeable pointer.
2426 if (!CanDoRT || PtrRtCheck.Pointers.size() > RuntimeMemoryCheckThreshold) {
2432 DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
2435 bool NeedRTCheck = false;
2437 // Now that the pointers are in two lists (Reads and ReadWrites), we
2438 // can check that there are no conflicts between each of the writes and
2439 // between the writes to the reads.
2440 ValueSet WriteObjects;
2441 ValueVector TempObjects;
2443 // Check that the read-writes do not conflict with other read-write
2445 bool AllWritesIdentified = true;
2446 for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I) {
2447 GetUnderlyingObjects(*I, TempObjects, DL);
2448 for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
2450 if (!isIdentifiedObject(*it)) {
2451 DEBUG(dbgs() << "LV: Found an unidentified write ptr:"<< **it <<"\n");
2453 AllWritesIdentified = false;
2455 if (!WriteObjects.insert(*it)) {
2456 DEBUG(dbgs() << "LV: Found a possible write-write reorder:"
2461 TempObjects.clear();
2464 /// Check that the reads don't conflict with the read-writes.
2465 for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I) {
2466 GetUnderlyingObjects(*I, TempObjects, DL);
2467 for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
2469 // If all of the writes are identified then we don't care if the read
2470 // pointer is identified or not.
2471 if (!AllWritesIdentified && !isIdentifiedObject(*it)) {
2472 DEBUG(dbgs() << "LV: Found an unidentified read ptr:"<< **it <<"\n");
2475 if (WriteObjects.count(*it)) {
2476 DEBUG(dbgs() << "LV: Found a possible read/write reorder:"
2481 TempObjects.clear();
2484 PtrRtCheck.Need = NeedRTCheck;
2485 if (NeedRTCheck && !CanDoRT) {
2486 DEBUG(dbgs() << "LV: We can't vectorize because we can't find " <<
2487 "the array bounds.\n");
2492 DEBUG(dbgs() << "LV: We "<< (NeedRTCheck ? "" : "don't") <<
2493 " need a runtime memory check.\n");
2497 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
2498 ReductionKind Kind) {
2499 if (Phi->getNumIncomingValues() != 2)
2502 // Reduction variables are only found in the loop header block.
2503 if (Phi->getParent() != TheLoop->getHeader())
2506 // Obtain the reduction start value from the value that comes from the loop
2508 Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
2510 // ExitInstruction is the single value which is used outside the loop.
2511 // We only allow for a single reduction value to be used outside the loop.
2512 // This includes users of the reduction, variables (which form a cycle
2513 // which ends in the phi node).
2514 Instruction *ExitInstruction = 0;
2515 // Indicates that we found a binary operation in our scan.
2516 bool FoundBinOp = false;
2518 // Iter is our iterator. We start with the PHI node and scan for all of the
2519 // users of this instruction. All users must be instructions that can be
2520 // used as reduction variables (such as ADD). We may have a single
2521 // out-of-block user. The cycle must end with the original PHI.
2522 Instruction *Iter = Phi;
2524 // If the instruction has no users then this is a broken
2525 // chain and can't be a reduction variable.
2526 if (Iter->use_empty())
2529 // Did we find a user inside this loop already ?
2530 bool FoundInBlockUser = false;
2531 // Did we reach the initial PHI node already ?
2532 bool FoundStartPHI = false;
2534 // Is this a bin op ?
2535 FoundBinOp |= !isa<PHINode>(Iter);
2537 // For each of the *users* of iter.
2538 for (Value::use_iterator it = Iter->use_begin(), e = Iter->use_end();
2540 Instruction *U = cast<Instruction>(*it);
2541 // We already know that the PHI is a user.
2543 FoundStartPHI = true;
2547 // Check if we found the exit user.
2548 BasicBlock *Parent = U->getParent();
2549 if (!TheLoop->contains(Parent)) {
2550 // Exit if you find multiple outside users.
2551 if (ExitInstruction != 0)
2553 ExitInstruction = Iter;
2556 // We allow in-loop PHINodes which are not the original reduction PHI
2557 // node. If this PHI is the only user of Iter (happens in IF w/ no ELSE
2558 // structure) then don't skip this PHI.
2559 if (isa<PHINode>(Iter) && isa<PHINode>(U) &&
2560 U->getParent() != TheLoop->getHeader() &&
2561 TheLoop->contains(U) &&
2562 Iter->getNumUses() > 1)
2565 // We can't have multiple inside users.
2566 if (FoundInBlockUser)
2568 FoundInBlockUser = true;
2570 // Any reduction instr must be of one of the allowed kinds.
2571 if (!isReductionInstr(U, Kind))
2574 // Reductions of instructions such as Div, and Sub is only
2575 // possible if the LHS is the reduction variable.
2576 if (!U->isCommutative() && !isa<PHINode>(U) && U->getOperand(0) != Iter)
2582 // We found a reduction var if we have reached the original
2583 // phi node and we only have a single instruction with out-of-loop
2585 if (FoundStartPHI) {
2586 // This instruction is allowed to have out-of-loop users.
2587 AllowedExit.insert(ExitInstruction);
2589 // Save the description of this reduction variable.
2590 ReductionDescriptor RD(RdxStart, ExitInstruction, Kind);
2591 Reductions[Phi] = RD;
2592 // We've ended the cycle. This is a reduction variable if we have an
2593 // outside user and it has a binary op.
2594 return FoundBinOp && ExitInstruction;
2600 LoopVectorizationLegality::isReductionInstr(Instruction *I,
2601 ReductionKind Kind) {
2602 bool FP = I->getType()->isFloatingPointTy();
2603 bool FastMath = (FP && I->isCommutative() && I->isAssociative());
2605 switch (I->getOpcode()) {
2608 case Instruction::PHI:
2609 if (FP && (Kind != RK_FloatMult && Kind != RK_FloatAdd))
2613 case Instruction::Sub:
2614 case Instruction::Add:
2615 return Kind == RK_IntegerAdd;
2616 case Instruction::SDiv:
2617 case Instruction::UDiv:
2618 case Instruction::Mul:
2619 return Kind == RK_IntegerMult;
2620 case Instruction::And:
2621 return Kind == RK_IntegerAnd;
2622 case Instruction::Or:
2623 return Kind == RK_IntegerOr;
2624 case Instruction::Xor:
2625 return Kind == RK_IntegerXor;
2626 case Instruction::FMul:
2627 return Kind == RK_FloatMult && FastMath;
2628 case Instruction::FAdd:
2629 return Kind == RK_FloatAdd && FastMath;
2633 LoopVectorizationLegality::InductionKind
2634 LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
2635 Type *PhiTy = Phi->getType();
2636 // We only handle integer and pointer inductions variables.
2637 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
2638 return IK_NoInduction;
2640 // Check that the PHI is consecutive.
2641 const SCEV *PhiScev = SE->getSCEV(Phi);
2642 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
2644 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
2645 return IK_NoInduction;
2647 const SCEV *Step = AR->getStepRecurrence(*SE);
2649 // Integer inductions need to have a stride of one.
2650 if (PhiTy->isIntegerTy()) {
2652 return IK_IntInduction;
2653 if (Step->isAllOnesValue())
2654 return IK_ReverseIntInduction;
2655 return IK_NoInduction;
2658 // Calculate the pointer stride and check if it is consecutive.
2659 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
2661 return IK_NoInduction;
2663 assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
2664 uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType());
2665 if (C->getValue()->equalsInt(Size))
2666 return IK_PtrInduction;
2667 else if (C->getValue()->equalsInt(0 - Size))
2668 return IK_ReversePtrInduction;
2670 return IK_NoInduction;
2673 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
2674 Value *In0 = const_cast<Value*>(V);
2675 PHINode *PN = dyn_cast_or_null<PHINode>(In0);
2679 return Inductions.count(PN);
2682 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
2683 assert(TheLoop->contains(BB) && "Unknown block used");
2685 // Blocks that do not dominate the latch need predication.
2686 BasicBlock* Latch = TheLoop->getLoopLatch();
2687 return !DT->dominates(BB, Latch);
2690 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB) {
2691 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2692 // We don't predicate loads/stores at the moment.
2693 if (it->mayReadFromMemory() || it->mayWriteToMemory() || it->mayThrow())
2696 // The instructions below can trap.
2697 switch (it->getOpcode()) {
2699 case Instruction::UDiv:
2700 case Instruction::SDiv:
2701 case Instruction::URem:
2702 case Instruction::SRem:
2710 bool LoopVectorizationLegality::hasComputableBounds(Value *Ptr) {
2711 const SCEV *PhiScev = SE->getSCEV(Ptr);
2712 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
2716 return AR->isAffine();
2719 std::pair<unsigned, unsigned>
2720 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize,
2722 if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
2723 DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
2724 return std::make_pair(1U, 0U);
2727 // Find the trip count.
2728 unsigned TC = SE->getSmallConstantTripCount(TheLoop, TheLoop->getLoopLatch());
2729 DEBUG(dbgs() << "LV: Found trip count:"<<TC<<"\n");
2731 unsigned WidestType = getWidestType();
2732 unsigned WidestRegister = TTI.getRegisterBitWidth(true);
2733 unsigned MaxVectorSize = WidestRegister / WidestType;
2734 DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n");
2735 DEBUG(dbgs() << "LV: The Widest register is:" << WidestRegister << "bits.\n");
2737 if (MaxVectorSize == 0) {
2738 DEBUG(dbgs() << "LV: The target has no vector registers.\n");
2742 assert(MaxVectorSize <= 32 && "Did not expect to pack so many elements"
2743 " into one vector!");
2745 unsigned VF = MaxVectorSize;
2747 // If we optimize the program for size, avoid creating the tail loop.
2749 // If we are unable to calculate the trip count then don't try to vectorize.
2751 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
2752 return std::make_pair(1U, 0U);
2755 // Find the maximum SIMD width that can fit within the trip count.
2756 VF = TC % MaxVectorSize;
2761 // If the trip count that we found modulo the vectorization factor is not
2762 // zero then we require a tail.
2764 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
2765 return std::make_pair(1U, 0U);
2770 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
2771 DEBUG(dbgs() << "LV: Using user VF "<<UserVF<<".\n");
2773 return std::make_pair(UserVF, 0U);
2776 float Cost = expectedCost(1);
2778 DEBUG(dbgs() << "LV: Scalar loop costs: "<< (int)Cost << ".\n");
2779 for (unsigned i=2; i <= VF; i*=2) {
2780 // Notice that the vector loop needs to be executed less times, so
2781 // we need to divide the cost of the vector loops by the width of
2782 // the vector elements.
2783 float VectorCost = expectedCost(i) / (float)i;
2784 DEBUG(dbgs() << "LV: Vector loop of width "<< i << " costs: " <<
2785 (int)VectorCost << ".\n");
2786 if (VectorCost < Cost) {
2792 DEBUG(dbgs() << "LV: Selecting VF = : "<< Width << ".\n");
2793 unsigned LoopCost = VF * Cost;
2794 return std::make_pair(Width, LoopCost);
2797 unsigned LoopVectorizationCostModel::getWidestType() {
2798 unsigned MaxWidth = 8;
2801 for (Loop::block_iterator bb = TheLoop->block_begin(),
2802 be = TheLoop->block_end(); bb != be; ++bb) {
2803 BasicBlock *BB = *bb;
2805 // For each instruction in the loop.
2806 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2807 Type *T = it->getType();
2809 // Only examine Loads, Stores and PHINodes.
2810 if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
2813 // Examine PHI nodes that are reduction variables.
2814 if (PHINode *PN = dyn_cast<PHINode>(it))
2815 if (!Legal->getReductionVars()->count(PN))
2818 // Examine the stored values.
2819 if (StoreInst *ST = dyn_cast<StoreInst>(it))
2820 T = ST->getValueOperand()->getType();
2822 // Ignore stored/loaded pointer types.
2823 if (T->isPointerTy())
2826 MaxWidth = std::max(MaxWidth, T->getScalarSizeInBits());
2834 LoopVectorizationCostModel::selectUnrollFactor(bool OptForSize,
2837 unsigned LoopCost) {
2839 // -- The unroll heuristics --
2840 // We unroll the loop in order to expose ILP and reduce the loop overhead.
2841 // There are many micro-architectural considerations that we can't predict
2842 // at this level. For example frontend pressure (on decode or fetch) due to
2843 // code size, or the number and capabilities of the execution ports.
2845 // We use the following heuristics to select the unroll factor:
2846 // 1. If the code has reductions the we unroll in order to break the cross
2847 // iteration dependency.
2848 // 2. If the loop is really small then we unroll in order to reduce the loop
2850 // 3. We don't unroll if we think that we will spill registers to memory due
2851 // to the increased register pressure.
2853 // Use the user preference, unless 'auto' is selected.
2857 // When we optimize for size we don't unroll.
2861 // Do not unroll loops with a relatively small trip count.
2862 unsigned TC = SE->getSmallConstantTripCount(TheLoop,
2863 TheLoop->getLoopLatch());
2864 if (TC > 1 && TC < TinyTripCountUnrollThreshold)
2867 unsigned TargetVectorRegisters = TTI.getNumberOfRegisters(true);
2868 DEBUG(dbgs() << "LV: The target has " << TargetVectorRegisters <<
2869 " vector registers\n");
2871 LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
2872 // We divide by these constants so assume that we have at least one
2873 // instruction that uses at least one register.
2874 R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
2875 R.NumInstructions = std::max(R.NumInstructions, 1U);
2877 // We calculate the unroll factor using the following formula.
2878 // Subtract the number of loop invariants from the number of available
2879 // registers. These registers are used by all of the unrolled instances.
2880 // Next, divide the remaining registers by the number of registers that is
2881 // required by the loop, in order to estimate how many parallel instances
2882 // fit without causing spills.
2883 unsigned UF = (TargetVectorRegisters - R.LoopInvariantRegs) / R.MaxLocalUsers;
2885 // Clamp the unroll factor ranges to reasonable factors.
2886 unsigned MaxUnrollSize = TTI.getMaximumUnrollFactor();
2888 // If we did not calculate the cost for VF (because the user selected the VF)
2889 // then we calculate the cost of VF here.
2891 LoopCost = expectedCost(VF);
2893 // Clamp the calculated UF to be between the 1 and the max unroll factor
2894 // that the target allows.
2895 if (UF > MaxUnrollSize)
2900 if (Legal->getReductionVars()->size()) {
2901 DEBUG(dbgs() << "LV: Unrolling because of reductions. \n");
2905 // We want to unroll tiny loops in order to reduce the loop overhead.
2906 // We assume that the cost overhead is 1 and we use the cost model
2907 // to estimate the cost of the loop and unroll until the cost of the
2908 // loop overhead is about 5% of the cost of the loop.
2909 DEBUG(dbgs() << "LV: Loop cost is "<< LoopCost <<" \n");
2910 if (LoopCost < 20) {
2911 DEBUG(dbgs() << "LV: Unrolling to reduce branch cost. \n");
2912 unsigned NewUF = 20/LoopCost + 1;
2913 return std::min(NewUF, UF);
2916 DEBUG(dbgs() << "LV: Not Unrolling. \n");
2920 LoopVectorizationCostModel::RegisterUsage
2921 LoopVectorizationCostModel::calculateRegisterUsage() {
2922 // This function calculates the register usage by measuring the highest number
2923 // of values that are alive at a single location. Obviously, this is a very
2924 // rough estimation. We scan the loop in a topological order in order and
2925 // assign a number to each instruction. We use RPO to ensure that defs are
2926 // met before their users. We assume that each instruction that has in-loop
2927 // users starts an interval. We record every time that an in-loop value is
2928 // used, so we have a list of the first and last occurrences of each
2929 // instruction. Next, we transpose this data structure into a multi map that
2930 // holds the list of intervals that *end* at a specific location. This multi
2931 // map allows us to perform a linear search. We scan the instructions linearly
2932 // and record each time that a new interval starts, by placing it in a set.
2933 // If we find this value in the multi-map then we remove it from the set.
2934 // The max register usage is the maximum size of the set.
2935 // We also search for instructions that are defined outside the loop, but are
2936 // used inside the loop. We need this number separately from the max-interval
2937 // usage number because when we unroll, loop-invariant values do not take
2939 LoopBlocksDFS DFS(TheLoop);
2943 R.NumInstructions = 0;
2945 // Each 'key' in the map opens a new interval. The values
2946 // of the map are the index of the 'last seen' usage of the
2947 // instruction that is the key.
2948 typedef DenseMap<Instruction*, unsigned> IntervalMap;
2949 // Maps instruction to its index.
2950 DenseMap<unsigned, Instruction*> IdxToInstr;
2951 // Marks the end of each interval.
2952 IntervalMap EndPoint;
2953 // Saves the list of instruction indices that are used in the loop.
2954 SmallSet<Instruction*, 8> Ends;
2955 // Saves the list of values that are used in the loop but are
2956 // defined outside the loop, such as arguments and constants.
2957 SmallPtrSet<Value*, 8> LoopInvariants;
2960 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
2961 be = DFS.endRPO(); bb != be; ++bb) {
2962 R.NumInstructions += (*bb)->size();
2963 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
2965 Instruction *I = it;
2966 IdxToInstr[Index++] = I;
2968 // Save the end location of each USE.
2969 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
2970 Value *U = I->getOperand(i);
2971 Instruction *Instr = dyn_cast<Instruction>(U);
2973 // Ignore non-instruction values such as arguments, constants, etc.
2974 if (!Instr) continue;
2976 // If this instruction is outside the loop then record it and continue.
2977 if (!TheLoop->contains(Instr)) {
2978 LoopInvariants.insert(Instr);
2982 // Overwrite previous end points.
2983 EndPoint[Instr] = Index;
2989 // Saves the list of intervals that end with the index in 'key'.
2990 typedef SmallVector<Instruction*, 2> InstrList;
2991 DenseMap<unsigned, InstrList> TransposeEnds;
2993 // Transpose the EndPoints to a list of values that end at each index.
2994 for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
2996 TransposeEnds[it->second].push_back(it->first);
2998 SmallSet<Instruction*, 8> OpenIntervals;
2999 unsigned MaxUsage = 0;
3002 DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
3003 for (unsigned int i = 0; i < Index; ++i) {
3004 Instruction *I = IdxToInstr[i];
3005 // Ignore instructions that are never used within the loop.
3006 if (!Ends.count(I)) continue;
3008 // Remove all of the instructions that end at this location.
3009 InstrList &List = TransposeEnds[i];
3010 for (unsigned int j=0, e = List.size(); j < e; ++j)
3011 OpenIntervals.erase(List[j]);
3013 // Count the number of live interals.
3014 MaxUsage = std::max(MaxUsage, OpenIntervals.size());
3016 DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
3017 OpenIntervals.size() <<"\n");
3019 // Add the current instruction to the list of open intervals.
3020 OpenIntervals.insert(I);
3023 unsigned Invariant = LoopInvariants.size();
3024 DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << " \n");
3025 DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << " \n");
3026 DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << " \n");
3028 R.LoopInvariantRegs = Invariant;
3029 R.MaxLocalUsers = MaxUsage;
3033 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
3037 for (Loop::block_iterator bb = TheLoop->block_begin(),
3038 be = TheLoop->block_end(); bb != be; ++bb) {
3039 unsigned BlockCost = 0;
3040 BasicBlock *BB = *bb;
3042 // For each instruction in the old loop.
3043 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
3044 unsigned C = getInstructionCost(it, VF);
3046 DEBUG(dbgs() << "LV: Found an estimated cost of "<< C <<" for VF " <<
3047 VF << " For instruction: "<< *it << "\n");
3050 // We assume that if-converted blocks have a 50% chance of being executed.
3051 // When the code is scalar then some of the blocks are avoided due to CF.
3052 // When the code is vectorized we execute all code paths.
3053 if (Legal->blockNeedsPredication(*bb) && VF == 1)
3063 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
3064 // If we know that this instruction will remain uniform, check the cost of
3065 // the scalar version.
3066 if (Legal->isUniformAfterVectorization(I))
3069 Type *RetTy = I->getType();
3070 Type *VectorTy = ToVectorTy(RetTy, VF);
3072 // TODO: We need to estimate the cost of intrinsic calls.
3073 switch (I->getOpcode()) {
3074 case Instruction::GetElementPtr:
3075 // We mark this instruction as zero-cost because scalar GEPs are usually
3076 // lowered to the intruction addressing mode. At the moment we don't
3077 // generate vector geps.
3079 case Instruction::Br: {
3080 return TTI.getCFInstrCost(I->getOpcode());
3082 case Instruction::PHI:
3083 //TODO: IF-converted IFs become selects.
3085 case Instruction::Add:
3086 case Instruction::FAdd:
3087 case Instruction::Sub:
3088 case Instruction::FSub:
3089 case Instruction::Mul:
3090 case Instruction::FMul:
3091 case Instruction::UDiv:
3092 case Instruction::SDiv:
3093 case Instruction::FDiv:
3094 case Instruction::URem:
3095 case Instruction::SRem:
3096 case Instruction::FRem:
3097 case Instruction::Shl:
3098 case Instruction::LShr:
3099 case Instruction::AShr:
3100 case Instruction::And:
3101 case Instruction::Or:
3102 case Instruction::Xor:
3103 return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy);
3104 case Instruction::Select: {
3105 SelectInst *SI = cast<SelectInst>(I);
3106 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
3107 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
3108 Type *CondTy = SI->getCondition()->getType();
3110 CondTy = VectorType::get(CondTy, VF);
3112 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
3114 case Instruction::ICmp:
3115 case Instruction::FCmp: {
3116 Type *ValTy = I->getOperand(0)->getType();
3117 VectorTy = ToVectorTy(ValTy, VF);
3118 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
3120 case Instruction::Store: {
3121 StoreInst *SI = cast<StoreInst>(I);
3122 Type *ValTy = SI->getValueOperand()->getType();
3123 VectorTy = ToVectorTy(ValTy, VF);
3126 return TTI.getMemoryOpCost(I->getOpcode(), VectorTy,
3128 SI->getPointerAddressSpace());
3130 // Scalarized stores.
3131 int Stride = Legal->isConsecutivePtr(SI->getPointerOperand());
3132 bool Reverse = Stride < 0;
3136 // The cost of extracting from the value vector and pointer vector.
3137 Type *PtrTy = ToVectorTy(I->getOperand(0)->getType(), VF);
3138 for (unsigned i = 0; i < VF; ++i) {
3139 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, VectorTy,
3141 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
3144 // The cost of the scalar stores.
3145 Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
3147 SI->getPointerAddressSpace());
3152 unsigned Cost = TTI.getMemoryOpCost(I->getOpcode(), VectorTy,
3154 SI->getPointerAddressSpace());
3156 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
3160 case Instruction::Load: {
3161 LoadInst *LI = cast<LoadInst>(I);
3164 return TTI.getMemoryOpCost(I->getOpcode(), VectorTy, LI->getAlignment(),
3165 LI->getPointerAddressSpace());
3167 // Scalarized loads.
3168 int Stride = Legal->isConsecutivePtr(LI->getPointerOperand());
3169 bool Reverse = Stride < 0;
3172 Type *PtrTy = ToVectorTy(I->getOperand(0)->getType(), VF);
3174 // The cost of extracting from the pointer vector.
3175 for (unsigned i = 0; i < VF; ++i)
3176 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
3178 // The cost of inserting data to the result vector.
3179 for (unsigned i = 0; i < VF; ++i)
3180 Cost += TTI.getVectorInstrCost(Instruction::InsertElement, VectorTy, i);
3182 // The cost of the scalar stores.
3183 Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), RetTy->getScalarType(),
3185 LI->getPointerAddressSpace());
3190 unsigned Cost = TTI.getMemoryOpCost(I->getOpcode(), VectorTy,
3192 LI->getPointerAddressSpace());
3194 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0);
3197 case Instruction::ZExt:
3198 case Instruction::SExt:
3199 case Instruction::FPToUI:
3200 case Instruction::FPToSI:
3201 case Instruction::FPExt:
3202 case Instruction::PtrToInt:
3203 case Instruction::IntToPtr:
3204 case Instruction::SIToFP:
3205 case Instruction::UIToFP:
3206 case Instruction::Trunc:
3207 case Instruction::FPTrunc:
3208 case Instruction::BitCast: {
3209 // We optimize the truncation of induction variable.
3210 // The cost of these is the same as the scalar operation.
3211 if (I->getOpcode() == Instruction::Trunc &&
3212 Legal->isInductionVariable(I->getOperand(0)))
3213 return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
3214 I->getOperand(0)->getType());
3216 Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
3217 return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
3219 case Instruction::Call: {
3220 assert(isTriviallyVectorizableIntrinsic(I));
3221 IntrinsicInst *II = cast<IntrinsicInst>(I);
3222 Type *RetTy = ToVectorTy(II->getType(), VF);
3223 SmallVector<Type*, 4> Tys;
3224 for (unsigned i = 0, ie = II->getNumArgOperands(); i != ie; ++i)
3225 Tys.push_back(ToVectorTy(II->getArgOperand(i)->getType(), VF));
3226 return TTI.getIntrinsicInstrCost(II->getIntrinsicID(), RetTy, Tys);
3229 // We are scalarizing the instruction. Return the cost of the scalar
3230 // instruction, plus the cost of insert and extract into vector
3231 // elements, times the vector width.
3234 if (!RetTy->isVoidTy() && VF != 1) {
3235 unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
3237 unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
3240 // The cost of inserting the results plus extracting each one of the
3242 Cost += VF * (InsCost + ExtCost * I->getNumOperands());
3245 // The cost of executing VF copies of the scalar instruction. This opcode
3246 // is unknown. Assume that it is the same as 'mul'.
3247 Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
3253 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
3254 if (Scalar->isVoidTy() || VF == 1)
3256 return VectorType::get(Scalar, VF);
3259 char LoopVectorize::ID = 0;
3260 static const char lv_name[] = "Loop Vectorization";
3261 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
3262 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3263 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
3264 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
3265 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
3266 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
3269 Pass *createLoopVectorizePass() {
3270 return new LoopVectorize();