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 /// We don't unroll loops that are larget than this threshold.
110 static const unsigned MaxLoopSizeThreshold = 32;
112 /// When performing a runtime memory check, do not check more than this
113 /// number of pointers. Notice that the check is quadratic!
114 static const unsigned RuntimeMemoryCheckThreshold = 4;
116 /// This is the highest vector width that we try to generate.
117 static const unsigned MaxVectorSize = 8;
119 /// This is the highest Unroll Factor.
120 static const unsigned MaxUnrollSize = 4;
124 // Forward declarations.
125 class LoopVectorizationLegality;
126 class LoopVectorizationCostModel;
128 /// InnerLoopVectorizer vectorizes loops which contain only one basic
129 /// block to a specified vectorization factor (VF).
130 /// This class performs the widening of scalars into vectors, or multiple
131 /// scalars. This class also implements the following features:
132 /// * It inserts an epilogue loop for handling loops that don't have iteration
133 /// counts that are known to be a multiple of the vectorization factor.
134 /// * It handles the code generation for reduction variables.
135 /// * Scalarization (implementation using scalars) of un-vectorizable
137 /// InnerLoopVectorizer does not perform any vectorization-legality
138 /// checks, and relies on the caller to check for the different legality
139 /// aspects. The InnerLoopVectorizer relies on the
140 /// LoopVectorizationLegality class to provide information about the induction
141 /// and reduction variables that were found to a given vectorization factor.
142 class InnerLoopVectorizer {
144 InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
145 DominatorTree *DT, DataLayout *DL, unsigned VecWidth,
146 unsigned UnrollFactor)
147 : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), DL(DL), VF(VecWidth),
148 UF(UnrollFactor), Builder(SE->getContext()), Induction(0),
149 OldInduction(0), WidenMap(UnrollFactor) {}
151 // Perform the actual loop widening (vectorization).
152 void vectorize(LoopVectorizationLegality *Legal) {
153 // Create a new empty loop. Unlink the old loop and connect the new one.
154 createEmptyLoop(Legal);
155 // Widen each instruction in the old loop to a new one in the new loop.
156 // Use the Legality module to find the induction and reduction variables.
157 vectorizeLoop(Legal);
158 // Register the new loop and update the analysis passes.
163 /// A small list of PHINodes.
164 typedef SmallVector<PHINode*, 4> PhiVector;
165 /// When we unroll loops we have multiple vector values for each scalar.
166 /// This data structure holds the unrolled and vectorized values that
167 /// originated from one scalar instruction.
168 typedef SmallVector<Value*, 2> VectorParts;
170 /// Add code that checks at runtime if the accessed arrays overlap.
171 /// Returns the comparator value or NULL if no check is needed.
172 Value *addRuntimeCheck(LoopVectorizationLegality *Legal,
174 /// Create an empty loop, based on the loop ranges of the old loop.
175 void createEmptyLoop(LoopVectorizationLegality *Legal);
176 /// Copy and widen the instructions from the old loop.
177 void vectorizeLoop(LoopVectorizationLegality *Legal);
179 /// A helper function that computes the predicate of the block BB, assuming
180 /// that the header block of the loop is set to True. It returns the *entry*
181 /// mask for the block BB.
182 VectorParts createBlockInMask(BasicBlock *BB);
183 /// A helper function that computes the predicate of the edge between SRC
185 VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
187 /// A helper function to vectorize a single BB within the innermost loop.
188 void vectorizeBlockInLoop(LoopVectorizationLegality *Legal, BasicBlock *BB,
191 /// Insert the new loop to the loop hierarchy and pass manager
192 /// and update the analysis passes.
193 void updateAnalysis();
195 /// This instruction is un-vectorizable. Implement it as a sequence
197 void scalarizeInstruction(Instruction *Instr);
199 /// Create a broadcast instruction. This method generates a broadcast
200 /// instruction (shuffle) for loop invariant values and for the induction
201 /// value. If this is the induction variable then we extend it to N, N+1, ...
202 /// this is needed because each iteration in the loop corresponds to a SIMD
204 Value *getBroadcastInstrs(Value *V);
206 /// This function adds 0, 1, 2 ... to each vector element, starting at zero.
207 /// If Negate is set then negative numbers are added e.g. (0, -1, -2, ...).
208 /// The sequence starts at StartIndex.
209 Value *getConsecutiveVector(Value* Val, unsigned StartIdx, bool Negate);
211 /// When we go over instructions in the basic block we rely on previous
212 /// values within the current basic block or on loop invariant values.
213 /// When we widen (vectorize) values we place them in the map. If the values
214 /// are not within the map, they have to be loop invariant, so we simply
215 /// broadcast them into a vector.
216 VectorParts &getVectorValue(Value *V);
218 /// Get a uniform vector of constant integers. We use this to get
219 /// vectors of ones and zeros for the reduction code.
220 Constant* getUniformVector(unsigned Val, Type* ScalarTy);
222 /// Generate a shuffle sequence that will reverse the vector Vec.
223 Value *reverseVector(Value *Vec);
225 /// This is a helper class that holds the vectorizer state. It maps scalar
226 /// instructions to vector instructions. When the code is 'unrolled' then
227 /// then a single scalar value is mapped to multiple vector parts. The parts
228 /// are stored in the VectorPart type.
230 /// C'tor. UnrollFactor controls the number of vectors ('parts') that
232 ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
234 /// \return True if 'Key' is saved in the Value Map.
235 bool has(Value *Key) { return MapStoreage.count(Key); }
237 /// Initializes a new entry in the map. Sets all of the vector parts to the
238 /// save value in 'Val'.
239 /// \return A reference to a vector with splat values.
240 VectorParts &splat(Value *Key, Value *Val) {
241 MapStoreage[Key].clear();
242 MapStoreage[Key].append(UF, Val);
243 return MapStoreage[Key];
246 ///\return A reference to the value that is stored at 'Key'.
247 VectorParts &get(Value *Key) {
249 MapStoreage[Key].resize(UF);
250 return MapStoreage[Key];
253 /// The unroll factor. Each entry in the map stores this number of vector
257 /// Map storage. We use std::map and not DenseMap because insertions to a
258 /// dense map invalidates its iterators.
259 std::map<Value*, VectorParts> MapStoreage;
262 /// The original loop.
264 /// Scev analysis to use.
272 /// The vectorization SIMD factor to use. Each vector will have this many
275 /// The vectorization unroll factor to use. Each scalar is vectorized to this
276 /// many different vector instructions.
279 /// The builder that we use
282 // --- Vectorization state ---
284 /// The vector-loop preheader.
285 BasicBlock *LoopVectorPreHeader;
286 /// The scalar-loop preheader.
287 BasicBlock *LoopScalarPreHeader;
288 /// Middle Block between the vector and the scalar.
289 BasicBlock *LoopMiddleBlock;
290 ///The ExitBlock of the scalar loop.
291 BasicBlock *LoopExitBlock;
292 ///The vector loop body.
293 BasicBlock *LoopVectorBody;
294 ///The scalar loop body.
295 BasicBlock *LoopScalarBody;
296 ///The first bypass block.
297 BasicBlock *LoopBypassBlock;
299 /// The new Induction variable which was added to the new block.
301 /// The induction variable of the old basic block.
302 PHINode *OldInduction;
303 /// Maps scalars to widened vectors.
307 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
308 /// to what vectorization factor.
309 /// This class does not look at the profitability of vectorization, only the
310 /// legality. This class has two main kinds of checks:
311 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
312 /// will change the order of memory accesses in a way that will change the
313 /// correctness of the program.
314 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
315 /// checks for a number of different conditions, such as the availability of a
316 /// single induction variable, that all types are supported and vectorize-able,
317 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
318 /// This class is also used by InnerLoopVectorizer for identifying
319 /// induction variable and the different reduction variables.
320 class LoopVectorizationLegality {
322 LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, DataLayout *DL,
324 : TheLoop(L), SE(SE), DL(DL), DT(DT), Induction(0) {}
326 /// This enum represents the kinds of reductions that we support.
328 NoReduction, ///< Not a reduction.
329 IntegerAdd, ///< Sum of numbers.
330 IntegerMult, ///< Product of numbers.
331 IntegerOr, ///< Bitwise or logical OR of numbers.
332 IntegerAnd, ///< Bitwise or logical AND of numbers.
333 IntegerXor ///< Bitwise or logical XOR of numbers.
336 /// This enum represents the kinds of inductions that we support.
338 NoInduction, ///< Not an induction variable.
339 IntInduction, ///< Integer induction variable. Step = 1.
340 ReverseIntInduction, ///< Reverse int induction variable. Step = -1.
341 PtrInduction ///< Pointer induction variable. Step = sizeof(elem).
344 /// This POD struct holds information about reduction variables.
345 struct ReductionDescriptor {
346 ReductionDescriptor() : StartValue(0), LoopExitInstr(0), Kind(NoReduction) {
349 ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K)
350 : StartValue(Start), LoopExitInstr(Exit), Kind(K) {}
352 // The starting value of the reduction.
353 // It does not have to be zero!
355 // The instruction who's value is used outside the loop.
356 Instruction *LoopExitInstr;
357 // The kind of the reduction.
361 // This POD struct holds information about the memory runtime legality
362 // check that a group of pointers do not overlap.
363 struct RuntimePointerCheck {
364 RuntimePointerCheck() : Need(false) {}
366 /// Reset the state of the pointer runtime information.
374 /// Insert a pointer and calculate the start and end SCEVs.
375 void insert(ScalarEvolution *SE, Loop *Lp, Value *Ptr);
377 /// This flag indicates if we need to add the runtime check.
379 /// Holds the pointers that we need to check.
380 SmallVector<Value*, 2> Pointers;
381 /// Holds the pointer value at the beginning of the loop.
382 SmallVector<const SCEV*, 2> Starts;
383 /// Holds the pointer value at the end of the loop.
384 SmallVector<const SCEV*, 2> Ends;
387 /// A POD for saving information about induction variables.
388 struct InductionInfo {
389 InductionInfo(Value *Start, InductionKind K) : StartValue(Start), IK(K) {}
390 InductionInfo() : StartValue(0), IK(NoInduction) {}
397 /// ReductionList contains the reduction descriptors for all
398 /// of the reductions that were found in the loop.
399 typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
401 /// InductionList saves induction variables and maps them to the
402 /// induction descriptor.
403 typedef MapVector<PHINode*, InductionInfo> InductionList;
405 /// Returns true if it is legal to vectorize this loop.
406 /// This does not mean that it is profitable to vectorize this
407 /// loop, only that it is legal to do so.
410 /// Returns the Induction variable.
411 PHINode *getInduction() { return Induction; }
413 /// Returns the reduction variables found in the loop.
414 ReductionList *getReductionVars() { return &Reductions; }
416 /// Returns the induction variables found in the loop.
417 InductionList *getInductionVars() { return &Inductions; }
419 /// Returns True if V is an induction variable in this loop.
420 bool isInductionVariable(const Value *V);
422 /// Return true if the block BB needs to be predicated in order for the loop
423 /// to be vectorized.
424 bool blockNeedsPredication(BasicBlock *BB);
426 /// Check if this pointer is consecutive when vectorizing. This happens
427 /// when the last index of the GEP is the induction variable, or that the
428 /// pointer itself is an induction variable.
429 /// This check allows us to vectorize A[idx] into a wide load/store.
431 /// 0 - Stride is unknown or non consecutive.
432 /// 1 - Address is consecutive.
433 /// -1 - Address is consecutive, and decreasing.
434 int isConsecutivePtr(Value *Ptr);
436 /// Returns true if the value V is uniform within the loop.
437 bool isUniform(Value *V);
439 /// Returns true if this instruction will remain scalar after vectorization.
440 bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
442 /// Returns the information that we collected about runtime memory check.
443 RuntimePointerCheck *getRuntimePointerCheck() { return &PtrRtCheck; }
445 /// Check if a single basic block loop is vectorizable.
446 /// At this point we know that this is a loop with a constant trip count
447 /// and we only need to check individual instructions.
448 bool canVectorizeInstrs();
450 /// When we vectorize loops we may change the order in which
451 /// we read and write from memory. This method checks if it is
452 /// legal to vectorize the code, considering only memory constrains.
453 /// Returns true if the loop is vectorizable
454 bool canVectorizeMemory();
456 /// Return true if we can vectorize this loop using the IF-conversion
458 bool canVectorizeWithIfConvert();
460 /// Collect the variables that need to stay uniform after vectorization.
461 void collectLoopUniforms();
463 /// Return true if all of the instructions in the block can be speculatively
465 bool blockCanBePredicated(BasicBlock *BB);
467 /// Returns True, if 'Phi' is the kind of reduction variable for type
468 /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
469 bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
470 /// Returns true if the instruction I can be a reduction variable of type
472 bool isReductionInstr(Instruction *I, ReductionKind Kind);
473 /// Returns the induction kind of Phi. This function may return NoInduction
474 /// if the PHI is not an induction variable.
475 InductionKind isInductionVariable(PHINode *Phi);
476 /// Return true if can compute the address bounds of Ptr within the loop.
477 bool hasComputableBounds(Value *Ptr);
479 /// The loop that we evaluate.
483 /// DataLayout analysis.
488 // --- vectorization state --- //
490 /// Holds the integer induction variable. This is the counter of the
493 /// Holds the reduction variables.
494 ReductionList Reductions;
495 /// Holds all of the induction variables that we found in the loop.
496 /// Notice that inductions don't need to start at zero and that induction
497 /// variables can be pointers.
498 InductionList Inductions;
500 /// Allowed outside users. This holds the reduction
501 /// vars which can be accessed from outside the loop.
502 SmallPtrSet<Value*, 4> AllowedExit;
503 /// This set holds the variables which are known to be uniform after
505 SmallPtrSet<Instruction*, 4> Uniforms;
506 /// We need to check that all of the pointers in this list are disjoint
508 RuntimePointerCheck PtrRtCheck;
511 /// LoopVectorizationCostModel - estimates the expected speedups due to
513 /// In many cases vectorization is not profitable. This can happen because of
514 /// a number of reasons. In this class we mainly attempt to predict the
515 /// expected speedup/slowdowns due to the supported instruction set. We use the
516 /// TargetTransformInfo to query the different backends for the cost of
517 /// different operations.
518 class LoopVectorizationCostModel {
520 LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
521 LoopVectorizationLegality *Legal,
522 const TargetTransformInfo &TTI)
523 : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI) {}
525 /// \return The most profitable vectorization factor.
526 /// This method checks every power of two up to VF. If UserVF is not ZERO
527 /// then this vectorization factor will be selected if vectorization is
529 unsigned selectVectorizationFactor(bool OptForSize, unsigned UserVF);
532 /// \return The most profitable unroll factor.
533 /// If UserUF is non-zero then this method finds the best unroll-factor
534 /// based on register pressure and other parameters.
535 unsigned selectUnrollFactor(bool OptForSize, unsigned UserUF);
537 /// \brief A struct that represents some properties of the register usage
539 struct RegisterUsage {
540 /// Holds the number of loop invariant values that are used in the loop.
541 unsigned LoopInvariantRegs;
542 /// Holds the maximum number of concurrent live intervals in the loop.
543 unsigned MaxLocalUsers;
544 /// Holds the number of instructions in the loop.
545 unsigned NumInstructions;
548 /// \return information about the register usage of the loop.
549 RegisterUsage calculateRegisterUsage();
552 /// Returns the expected execution cost. The unit of the cost does
553 /// not matter because we use the 'cost' units to compare different
554 /// vector widths. The cost that is returned is *not* normalized by
555 /// the factor width.
556 unsigned expectedCost(unsigned VF);
558 /// Returns the execution time cost of an instruction for a given vector
559 /// width. Vector width of one means scalar.
560 unsigned getInstructionCost(Instruction *I, unsigned VF);
562 /// A helper function for converting Scalar types to vector types.
563 /// If the incoming type is void, we return void. If the VF is 1, we return
565 static Type* ToVectorTy(Type *Scalar, unsigned VF);
567 /// The loop that we evaluate.
571 /// Loop Info analysis.
573 /// Vectorization legality.
574 LoopVectorizationLegality *Legal;
575 /// Vector target information.
576 const TargetTransformInfo &TTI;
579 /// The LoopVectorize Pass.
580 struct LoopVectorize : public LoopPass {
581 /// Pass identification, replacement for typeid
584 explicit LoopVectorize() : LoopPass(ID) {
585 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
591 TargetTransformInfo *TTI;
594 virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
595 // We only vectorize innermost loops.
599 SE = &getAnalysis<ScalarEvolution>();
600 DL = getAnalysisIfAvailable<DataLayout>();
601 LI = &getAnalysis<LoopInfo>();
602 TTI = &getAnalysis<TargetTransformInfo>();
603 DT = &getAnalysis<DominatorTree>();
605 DEBUG(dbgs() << "LV: Checking a loop in \"" <<
606 L->getHeader()->getParent()->getName() << "\"\n");
608 // Check if it is legal to vectorize the loop.
609 LoopVectorizationLegality LVL(L, SE, DL, DT);
610 if (!LVL.canVectorize()) {
611 DEBUG(dbgs() << "LV: Not vectorizing.\n");
615 // Use the cost model.
616 LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI);
618 // Check the function attribues to find out if this function should be
619 // optimized for size.
620 Function *F = L->getHeader()->getParent();
621 Attribute::AttrKind SzAttr = Attribute::OptimizeForSize;
622 Attribute::AttrKind FlAttr = Attribute::NoImplicitFloat;
623 unsigned FnIndex = AttributeSet::FunctionIndex;
624 bool OptForSize = F->getAttributes().hasAttribute(FnIndex, SzAttr);
625 bool NoFloat = F->getAttributes().hasAttribute(FnIndex, FlAttr);
628 DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
629 "attribute is used.\n");
633 unsigned VF = CM.selectVectorizationFactor(OptForSize, VectorizationFactor);
634 unsigned UF = CM.selectUnrollFactor(OptForSize, VectorizationUnroll);
637 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
641 DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< VF << ") in "<<
642 F->getParent()->getModuleIdentifier()<<"\n");
643 DEBUG(dbgs() << "LV: Unroll Factor is " << UF << "\n");
645 // If we decided that it is *legal* to vectorizer the loop then do it.
646 InnerLoopVectorizer LB(L, SE, LI, DT, DL, VF, UF);
649 DEBUG(verifyFunction(*L->getHeader()->getParent()));
653 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
654 LoopPass::getAnalysisUsage(AU);
655 AU.addRequiredID(LoopSimplifyID);
656 AU.addRequiredID(LCSSAID);
657 AU.addRequired<DominatorTree>();
658 AU.addRequired<LoopInfo>();
659 AU.addRequired<ScalarEvolution>();
660 AU.addRequired<TargetTransformInfo>();
661 AU.addPreserved<LoopInfo>();
662 AU.addPreserved<DominatorTree>();
667 } // end anonymous namespace
669 //===----------------------------------------------------------------------===//
670 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
671 // LoopVectorizationCostModel.
672 //===----------------------------------------------------------------------===//
675 LoopVectorizationLegality::RuntimePointerCheck::insert(ScalarEvolution *SE,
676 Loop *Lp, Value *Ptr) {
677 const SCEV *Sc = SE->getSCEV(Ptr);
678 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
679 assert(AR && "Invalid addrec expression");
680 const SCEV *Ex = SE->getExitCount(Lp, Lp->getLoopLatch());
681 const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
682 Pointers.push_back(Ptr);
683 Starts.push_back(AR->getStart());
684 Ends.push_back(ScEnd);
687 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
688 // Save the current insertion location.
689 Instruction *Loc = Builder.GetInsertPoint();
691 // We need to place the broadcast of invariant variables outside the loop.
692 Instruction *Instr = dyn_cast<Instruction>(V);
693 bool NewInstr = (Instr && Instr->getParent() == LoopVectorBody);
694 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
696 // Place the code for broadcasting invariant variables in the new preheader.
698 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
700 // Broadcast the scalar into all locations in the vector.
701 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
703 // Restore the builder insertion point.
705 Builder.SetInsertPoint(Loc);
710 Value *InnerLoopVectorizer::getConsecutiveVector(Value* Val, unsigned StartIdx,
712 assert(Val->getType()->isVectorTy() && "Must be a vector");
713 assert(Val->getType()->getScalarType()->isIntegerTy() &&
714 "Elem must be an integer");
716 Type *ITy = Val->getType()->getScalarType();
717 VectorType *Ty = cast<VectorType>(Val->getType());
718 int VLen = Ty->getNumElements();
719 SmallVector<Constant*, 8> Indices;
721 // Create a vector of consecutive numbers from zero to VF.
722 for (int i = 0; i < VLen; ++i) {
723 int Idx = Negate ? (-i): i;
724 Indices.push_back(ConstantInt::get(ITy, StartIdx + Idx));
727 // Add the consecutive indices to the vector value.
728 Constant *Cv = ConstantVector::get(Indices);
729 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
730 return Builder.CreateAdd(Val, Cv, "induction");
733 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
734 assert(Ptr->getType()->isPointerTy() && "Unexpected non ptr");
736 // If this value is a pointer induction variable we know it is consecutive.
737 PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
738 if (Phi && Inductions.count(Phi)) {
739 InductionInfo II = Inductions[Phi];
740 if (PtrInduction == II.IK)
744 GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
748 unsigned NumOperands = Gep->getNumOperands();
749 Value *LastIndex = Gep->getOperand(NumOperands - 1);
751 // Check that all of the gep indices are uniform except for the last.
752 for (unsigned i = 0; i < NumOperands - 1; ++i)
753 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
756 // We can emit wide load/stores only if the last index is the induction
758 const SCEV *Last = SE->getSCEV(LastIndex);
759 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
760 const SCEV *Step = AR->getStepRecurrence(*SE);
762 // The memory is consecutive because the last index is consecutive
763 // and all other indices are loop invariant.
766 if (Step->isAllOnesValue())
773 bool LoopVectorizationLegality::isUniform(Value *V) {
774 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
777 InnerLoopVectorizer::VectorParts&
778 InnerLoopVectorizer::getVectorValue(Value *V) {
779 assert(V != Induction && "The new induction variable should not be used.");
780 assert(!V->getType()->isVectorTy() && "Can't widen a vector");
782 // If we have this scalar in the map, return it.
784 return WidenMap.get(V);
786 // If this scalar is unknown, assume that it is a constant or that it is
787 // loop invariant. Broadcast V and save the value for future uses.
788 Value *B = getBroadcastInstrs(V);
789 WidenMap.splat(V, B);
790 return WidenMap.get(V);
794 InnerLoopVectorizer::getUniformVector(unsigned Val, Type* ScalarTy) {
795 return ConstantVector::getSplat(VF, ConstantInt::get(ScalarTy, Val, true));
798 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
799 assert(Vec->getType()->isVectorTy() && "Invalid type");
800 SmallVector<Constant*, 8> ShuffleMask;
801 for (unsigned i = 0; i < VF; ++i)
802 ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
804 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
805 ConstantVector::get(ShuffleMask),
809 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr) {
810 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
811 // Holds vector parameters or scalars, in case of uniform vals.
812 SmallVector<VectorParts, 4> Params;
814 // Find all of the vectorized parameters.
815 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
816 Value *SrcOp = Instr->getOperand(op);
818 // If we are accessing the old induction variable, use the new one.
819 if (SrcOp == OldInduction) {
820 Params.push_back(getVectorValue(SrcOp));
824 // Try using previously calculated values.
825 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
827 // If the src is an instruction that appeared earlier in the basic block
828 // then it should already be vectorized.
829 if (SrcInst && OrigLoop->contains(SrcInst)) {
830 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
831 // The parameter is a vector value from earlier.
832 Params.push_back(WidenMap.get(SrcInst));
834 // The parameter is a scalar from outside the loop. Maybe even a constant.
836 Scalars.append(UF, SrcOp);
837 Params.push_back(Scalars);
841 assert(Params.size() == Instr->getNumOperands() &&
842 "Invalid number of operands");
844 // Does this instruction return a value ?
845 bool IsVoidRetTy = Instr->getType()->isVoidTy();
847 Value *UndefVec = IsVoidRetTy ? 0 :
848 UndefValue::get(VectorType::get(Instr->getType(), VF));
849 // Create a new entry in the WidenMap and initialize it to Undef or Null.
850 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
852 // For each scalar that we create:
853 for (unsigned Width = 0; Width < VF; ++Width) {
854 // For each vector unroll 'part':
855 for (unsigned Part = 0; Part < UF; ++Part) {
856 Instruction *Cloned = Instr->clone();
858 Cloned->setName(Instr->getName() + ".cloned");
859 // Replace the operands of the cloned instrucions with extracted scalars.
860 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
861 Value *Op = Params[op][Part];
862 // Param is a vector. Need to extract the right lane.
863 if (Op->getType()->isVectorTy())
864 Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
865 Cloned->setOperand(op, Op);
868 // Place the cloned scalar in the new loop.
869 Builder.Insert(Cloned);
871 // If the original scalar returns a value we need to place it in a vector
872 // so that future users will be able to use it.
874 VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
875 Builder.getInt32(Width));
881 InnerLoopVectorizer::addRuntimeCheck(LoopVectorizationLegality *Legal,
883 LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck =
884 Legal->getRuntimePointerCheck();
886 if (!PtrRtCheck->Need)
889 Value *MemoryRuntimeCheck = 0;
890 unsigned NumPointers = PtrRtCheck->Pointers.size();
891 SmallVector<Value* , 2> Starts;
892 SmallVector<Value* , 2> Ends;
894 SCEVExpander Exp(*SE, "induction");
896 // Use this type for pointer arithmetic.
897 Type* PtrArithTy = Type::getInt8PtrTy(Loc->getContext(), 0);
899 for (unsigned i = 0; i < NumPointers; ++i) {
900 Value *Ptr = PtrRtCheck->Pointers[i];
901 const SCEV *Sc = SE->getSCEV(Ptr);
903 if (SE->isLoopInvariant(Sc, OrigLoop)) {
904 DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" <<
906 Starts.push_back(Ptr);
909 DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr <<"\n");
911 Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc);
912 Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
913 Starts.push_back(Start);
918 for (unsigned i = 0; i < NumPointers; ++i) {
919 for (unsigned j = i+1; j < NumPointers; ++j) {
920 Instruction::CastOps Op = Instruction::BitCast;
921 Value *Start0 = CastInst::Create(Op, Starts[i], PtrArithTy, "bc", Loc);
922 Value *Start1 = CastInst::Create(Op, Starts[j], PtrArithTy, "bc", Loc);
923 Value *End0 = CastInst::Create(Op, Ends[i], PtrArithTy, "bc", Loc);
924 Value *End1 = CastInst::Create(Op, Ends[j], PtrArithTy, "bc", Loc);
926 Value *Cmp0 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_ULE,
927 Start0, End1, "bound0", Loc);
928 Value *Cmp1 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_ULE,
929 Start1, End0, "bound1", Loc);
930 Value *IsConflict = BinaryOperator::Create(Instruction::And, Cmp0, Cmp1,
931 "found.conflict", Loc);
932 if (MemoryRuntimeCheck)
933 MemoryRuntimeCheck = BinaryOperator::Create(Instruction::Or,
936 "conflict.rdx", Loc);
938 MemoryRuntimeCheck = IsConflict;
943 return MemoryRuntimeCheck;
947 InnerLoopVectorizer::createEmptyLoop(LoopVectorizationLegality *Legal) {
949 In this function we generate a new loop. The new loop will contain
950 the vectorized instructions while the old loop will continue to run the
953 [ ] <-- vector loop bypass.
956 | [ ] <-- vector pre header.
960 | [ ]_| <-- vector loop.
963 >[ ] <--- middle-block.
966 | [ ] <--- new preheader.
970 | [ ]_| <-- old scalar loop to handle remainder.
977 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
978 BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
979 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
980 assert(ExitBlock && "Must have an exit block");
982 // Some loops have a single integer induction variable, while other loops
983 // don't. One example is c++ iterators that often have multiple pointer
984 // induction variables. In the code below we also support a case where we
985 // don't have a single induction variable.
986 OldInduction = Legal->getInduction();
987 Type *IdxTy = OldInduction ? OldInduction->getType() :
988 DL->getIntPtrType(SE->getContext());
990 // Find the loop boundaries.
991 const SCEV *ExitCount = SE->getExitCount(OrigLoop, OrigLoop->getLoopLatch());
992 assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
994 // Get the total trip count from the count by adding 1.
995 ExitCount = SE->getAddExpr(ExitCount,
996 SE->getConstant(ExitCount->getType(), 1));
998 // Expand the trip count and place the new instructions in the preheader.
999 // Notice that the pre-header does not change, only the loop body.
1000 SCEVExpander Exp(*SE, "induction");
1002 // Count holds the overall loop count (N).
1003 Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
1004 BypassBlock->getTerminator());
1006 // The loop index does not have to start at Zero. Find the original start
1007 // value from the induction PHI node. If we don't have an induction variable
1008 // then we know that it starts at zero.
1009 Value *StartIdx = OldInduction ?
1010 OldInduction->getIncomingValueForBlock(BypassBlock):
1011 ConstantInt::get(IdxTy, 0);
1013 assert(BypassBlock && "Invalid loop structure");
1015 // Generate the code that checks in runtime if arrays overlap.
1016 Value *MemoryRuntimeCheck = addRuntimeCheck(Legal,
1017 BypassBlock->getTerminator());
1019 // Split the single block loop into the two loop structure described above.
1020 BasicBlock *VectorPH =
1021 BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
1022 BasicBlock *VecBody =
1023 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
1024 BasicBlock *MiddleBlock =
1025 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
1026 BasicBlock *ScalarPH =
1027 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
1029 // This is the location in which we add all of the logic for bypassing
1030 // the new vector loop.
1031 Instruction *Loc = BypassBlock->getTerminator();
1033 // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
1035 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
1037 // Generate the induction variable.
1038 Induction = Builder.CreatePHI(IdxTy, 2, "index");
1039 // The loop step is equal to the vectorization factor (num of SIMD elements)
1040 // times the unroll factor (num of SIMD instructions).
1041 Constant *Step = ConstantInt::get(IdxTy, VF * UF);
1043 // We may need to extend the index in case there is a type mismatch.
1044 // We know that the count starts at zero and does not overflow.
1045 if (Count->getType() != IdxTy) {
1046 // The exit count can be of pointer type. Convert it to the correct
1048 if (ExitCount->getType()->isPointerTy())
1049 Count = CastInst::CreatePointerCast(Count, IdxTy, "ptrcnt.to.int", Loc);
1051 Count = CastInst::CreateZExtOrBitCast(Count, IdxTy, "zext.cnt", Loc);
1054 // Add the start index to the loop count to get the new end index.
1055 Value *IdxEnd = BinaryOperator::CreateAdd(Count, StartIdx, "end.idx", Loc);
1057 // Now we need to generate the expression for N - (N % VF), which is
1058 // the part that the vectorized body will execute.
1059 Value *R = BinaryOperator::CreateURem(Count, Step, "n.mod.vf", Loc);
1060 Value *CountRoundDown = BinaryOperator::CreateSub(Count, R, "n.vec", Loc);
1061 Value *IdxEndRoundDown = BinaryOperator::CreateAdd(CountRoundDown, StartIdx,
1062 "end.idx.rnd.down", Loc);
1064 // Now, compare the new count to zero. If it is zero skip the vector loop and
1065 // jump to the scalar loop.
1066 Value *Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
1071 // If we are using memory runtime checks, include them in.
1072 if (MemoryRuntimeCheck)
1073 Cmp = BinaryOperator::Create(Instruction::Or, Cmp, MemoryRuntimeCheck,
1076 BranchInst::Create(MiddleBlock, VectorPH, Cmp, Loc);
1077 // Remove the old terminator.
1078 Loc->eraseFromParent();
1080 // We are going to resume the execution of the scalar loop.
1081 // Go over all of the induction variables that we found and fix the
1082 // PHIs that are left in the scalar version of the loop.
1083 // The starting values of PHI nodes depend on the counter of the last
1084 // iteration in the vectorized loop.
1085 // If we come from a bypass edge then we need to start from the original
1088 // This variable saves the new starting index for the scalar loop.
1089 PHINode *ResumeIndex = 0;
1090 LoopVectorizationLegality::InductionList::iterator I, E;
1091 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
1092 for (I = List->begin(), E = List->end(); I != E; ++I) {
1093 PHINode *OrigPhi = I->first;
1094 LoopVectorizationLegality::InductionInfo II = I->second;
1095 PHINode *ResumeVal = PHINode::Create(OrigPhi->getType(), 2, "resume.val",
1096 MiddleBlock->getTerminator());
1097 Value *EndValue = 0;
1099 case LoopVectorizationLegality::NoInduction:
1100 llvm_unreachable("Unknown induction");
1101 case LoopVectorizationLegality::IntInduction: {
1102 // Handle the integer induction counter:
1103 assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
1104 assert(OrigPhi == OldInduction && "Unknown integer PHI");
1105 // We know what the end value is.
1106 EndValue = IdxEndRoundDown;
1107 // We also know which PHI node holds it.
1108 ResumeIndex = ResumeVal;
1111 case LoopVectorizationLegality::ReverseIntInduction: {
1112 // Convert the CountRoundDown variable to the PHI size.
1113 unsigned CRDSize = CountRoundDown->getType()->getScalarSizeInBits();
1114 unsigned IISize = II.StartValue->getType()->getScalarSizeInBits();
1115 Value *CRD = CountRoundDown;
1116 if (CRDSize > IISize)
1117 CRD = CastInst::Create(Instruction::Trunc, CountRoundDown,
1118 II.StartValue->getType(),
1119 "tr.crd", BypassBlock->getTerminator());
1120 else if (CRDSize < IISize)
1121 CRD = CastInst::Create(Instruction::SExt, CountRoundDown,
1122 II.StartValue->getType(),
1123 "sext.crd", BypassBlock->getTerminator());
1124 // Handle reverse integer induction counter:
1125 EndValue = BinaryOperator::CreateSub(II.StartValue, CRD, "rev.ind.end",
1126 BypassBlock->getTerminator());
1129 case LoopVectorizationLegality::PtrInduction: {
1130 // For pointer induction variables, calculate the offset using
1132 EndValue = GetElementPtrInst::Create(II.StartValue, CountRoundDown,
1134 BypassBlock->getTerminator());
1139 // The new PHI merges the original incoming value, in case of a bypass,
1140 // or the value at the end of the vectorized loop.
1141 ResumeVal->addIncoming(II.StartValue, BypassBlock);
1142 ResumeVal->addIncoming(EndValue, VecBody);
1144 // Fix the scalar body counter (PHI node).
1145 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
1146 OrigPhi->setIncomingValue(BlockIdx, ResumeVal);
1149 // If we are generating a new induction variable then we also need to
1150 // generate the code that calculates the exit value. This value is not
1151 // simply the end of the counter because we may skip the vectorized body
1152 // in case of a runtime check.
1154 assert(!ResumeIndex && "Unexpected resume value found");
1155 ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
1156 MiddleBlock->getTerminator());
1157 ResumeIndex->addIncoming(StartIdx, BypassBlock);
1158 ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
1161 // Make sure that we found the index where scalar loop needs to continue.
1162 assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
1163 "Invalid resume Index");
1165 // Add a check in the middle block to see if we have completed
1166 // all of the iterations in the first vector loop.
1167 // If (N - N%VF) == N, then we *don't* need to run the remainder.
1168 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
1169 ResumeIndex, "cmp.n",
1170 MiddleBlock->getTerminator());
1172 BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
1173 // Remove the old terminator.
1174 MiddleBlock->getTerminator()->eraseFromParent();
1176 // Create i+1 and fill the PHINode.
1177 Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
1178 Induction->addIncoming(StartIdx, VectorPH);
1179 Induction->addIncoming(NextIdx, VecBody);
1180 // Create the compare.
1181 Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
1182 Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
1184 // Now we have two terminators. Remove the old one from the block.
1185 VecBody->getTerminator()->eraseFromParent();
1187 // Get ready to start creating new instructions into the vectorized body.
1188 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
1190 // Create and register the new vector loop.
1191 Loop* Lp = new Loop();
1192 Loop *ParentLoop = OrigLoop->getParentLoop();
1194 // Insert the new loop into the loop nest and register the new basic blocks.
1196 ParentLoop->addChildLoop(Lp);
1197 ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
1198 ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
1199 ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
1201 LI->addTopLevelLoop(Lp);
1204 Lp->addBasicBlockToLoop(VecBody, LI->getBase());
1207 LoopVectorPreHeader = VectorPH;
1208 LoopScalarPreHeader = ScalarPH;
1209 LoopMiddleBlock = MiddleBlock;
1210 LoopExitBlock = ExitBlock;
1211 LoopVectorBody = VecBody;
1212 LoopScalarBody = OldBasicBlock;
1213 LoopBypassBlock = BypassBlock;
1216 /// This function returns the identity element (or neutral element) for
1217 /// the operation K.
1219 getReductionIdentity(LoopVectorizationLegality::ReductionKind K) {
1221 case LoopVectorizationLegality::IntegerXor:
1222 case LoopVectorizationLegality::IntegerAdd:
1223 case LoopVectorizationLegality::IntegerOr:
1224 // Adding, Xoring, Oring zero to a number does not change it.
1226 case LoopVectorizationLegality::IntegerMult:
1227 // Multiplying a number by 1 does not change it.
1229 case LoopVectorizationLegality::IntegerAnd:
1230 // AND-ing a number with an all-1 value does not change it.
1233 llvm_unreachable("Unknown reduction kind");
1238 isTriviallyVectorizableIntrinsic(Instruction *Inst) {
1239 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst);
1242 switch (II->getIntrinsicID()) {
1243 case Intrinsic::sqrt:
1244 case Intrinsic::sin:
1245 case Intrinsic::cos:
1246 case Intrinsic::exp:
1247 case Intrinsic::exp2:
1248 case Intrinsic::log:
1249 case Intrinsic::log10:
1250 case Intrinsic::log2:
1251 case Intrinsic::fabs:
1252 case Intrinsic::floor:
1253 case Intrinsic::ceil:
1254 case Intrinsic::trunc:
1255 case Intrinsic::rint:
1256 case Intrinsic::nearbyint:
1257 case Intrinsic::pow:
1258 case Intrinsic::fma:
1259 case Intrinsic::fmuladd:
1268 InnerLoopVectorizer::vectorizeLoop(LoopVectorizationLegality *Legal) {
1269 //===------------------------------------------------===//
1271 // Notice: any optimization or new instruction that go
1272 // into the code below should be also be implemented in
1275 //===------------------------------------------------===//
1276 BasicBlock &BB = *OrigLoop->getHeader();
1278 ConstantInt::get(IntegerType::getInt32Ty(BB.getContext()), 0);
1280 // In order to support reduction variables we need to be able to vectorize
1281 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
1282 // stages. First, we create a new vector PHI node with no incoming edges.
1283 // We use this value when we vectorize all of the instructions that use the
1284 // PHI. Next, after all of the instructions in the block are complete we
1285 // add the new incoming edges to the PHI. At this point all of the
1286 // instructions in the basic block are vectorized, so we can use them to
1287 // construct the PHI.
1288 PhiVector RdxPHIsToFix;
1290 // Scan the loop in a topological order to ensure that defs are vectorized
1292 LoopBlocksDFS DFS(OrigLoop);
1295 // Vectorize all of the blocks in the original loop.
1296 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
1297 be = DFS.endRPO(); bb != be; ++bb)
1298 vectorizeBlockInLoop(Legal, *bb, &RdxPHIsToFix);
1300 // At this point every instruction in the original loop is widened to
1301 // a vector form. We are almost done. Now, we need to fix the PHI nodes
1302 // that we vectorized. The PHI nodes are currently empty because we did
1303 // not want to introduce cycles. Notice that the remaining PHI nodes
1304 // that we need to fix are reduction variables.
1306 // Create the 'reduced' values for each of the induction vars.
1307 // The reduced values are the vector values that we scalarize and combine
1308 // after the loop is finished.
1309 for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
1311 PHINode *RdxPhi = *it;
1312 assert(RdxPhi && "Unable to recover vectorized PHI");
1314 // Find the reduction variable descriptor.
1315 assert(Legal->getReductionVars()->count(RdxPhi) &&
1316 "Unable to find the reduction variable");
1317 LoopVectorizationLegality::ReductionDescriptor RdxDesc =
1318 (*Legal->getReductionVars())[RdxPhi];
1320 // We need to generate a reduction vector from the incoming scalar.
1321 // To do so, we need to generate the 'identity' vector and overide
1322 // one of the elements with the incoming scalar reduction. We need
1323 // to do it in the vector-loop preheader.
1324 Builder.SetInsertPoint(LoopBypassBlock->getTerminator());
1326 // This is the vector-clone of the value that leaves the loop.
1327 VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
1328 Type *VecTy = VectorExit[0]->getType();
1330 // Find the reduction identity variable. Zero for addition, or, xor,
1331 // one for multiplication, -1 for And.
1332 Constant *Identity = getUniformVector(getReductionIdentity(RdxDesc.Kind),
1333 VecTy->getScalarType());
1335 // This vector is the Identity vector where the first element is the
1336 // incoming scalar reduction.
1337 Value *VectorStart = Builder.CreateInsertElement(Identity,
1338 RdxDesc.StartValue, Zero);
1340 // Fix the vector-loop phi.
1341 // We created the induction variable so we know that the
1342 // preheader is the first entry.
1343 BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
1345 // Reductions do not have to start at zero. They can start with
1346 // any loop invariant values.
1347 VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
1348 BasicBlock *Latch = OrigLoop->getLoopLatch();
1349 Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
1350 VectorParts &Val = getVectorValue(LoopVal);
1351 for (unsigned part = 0; part < UF; ++part) {
1352 // Make sure to add the reduction stat value only to the
1353 // first unroll part.
1354 Value *StartVal = (part == 0) ? VectorStart : Identity;
1355 cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal, VecPreheader);
1356 cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part], LoopVectorBody);
1359 // Before each round, move the insertion point right between
1360 // the PHIs and the values we are going to write.
1361 // This allows us to write both PHINodes and the extractelement
1363 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
1365 VectorParts RdxParts;
1366 for (unsigned part = 0; part < UF; ++part) {
1367 // This PHINode contains the vectorized reduction variable, or
1368 // the initial value vector, if we bypass the vector loop.
1369 VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr);
1370 PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
1371 Value *StartVal = (part == 0) ? VectorStart : Identity;
1372 NewPhi->addIncoming(StartVal, LoopBypassBlock);
1373 NewPhi->addIncoming(RdxExitVal[part], LoopVectorBody);
1374 RdxParts.push_back(NewPhi);
1377 // Reduce all of the unrolled parts into a single vector.
1378 Value *ReducedPartRdx = RdxParts[0];
1379 for (unsigned part = 1; part < UF; ++part) {
1380 switch (RdxDesc.Kind) {
1381 case LoopVectorizationLegality::IntegerAdd:
1383 Builder.CreateAdd(RdxParts[part], ReducedPartRdx, "add.rdx");
1385 case LoopVectorizationLegality::IntegerMult:
1387 Builder.CreateMul(RdxParts[part], ReducedPartRdx, "mul.rdx");
1389 case LoopVectorizationLegality::IntegerOr:
1391 Builder.CreateOr(RdxParts[part], ReducedPartRdx, "or.rdx");
1393 case LoopVectorizationLegality::IntegerAnd:
1395 Builder.CreateAnd(RdxParts[part], ReducedPartRdx, "and.rdx");
1397 case LoopVectorizationLegality::IntegerXor:
1399 Builder.CreateXor(RdxParts[part], ReducedPartRdx, "xor.rdx");
1402 llvm_unreachable("Unknown reduction operation");
1407 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
1408 // and vector ops, reducing the set of values being computed by half each
1410 assert(isPowerOf2_32(VF) &&
1411 "Reduction emission only supported for pow2 vectors!");
1412 Value *TmpVec = ReducedPartRdx;
1413 SmallVector<Constant*, 32> ShuffleMask(VF, 0);
1414 for (unsigned i = VF; i != 1; i >>= 1) {
1415 // Move the upper half of the vector to the lower half.
1416 for (unsigned j = 0; j != i/2; ++j)
1417 ShuffleMask[j] = Builder.getInt32(i/2 + j);
1419 // Fill the rest of the mask with undef.
1420 std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
1421 UndefValue::get(Builder.getInt32Ty()));
1424 Builder.CreateShuffleVector(TmpVec,
1425 UndefValue::get(TmpVec->getType()),
1426 ConstantVector::get(ShuffleMask),
1429 // Emit the operation on the shuffled value.
1430 switch (RdxDesc.Kind) {
1431 case LoopVectorizationLegality::IntegerAdd:
1432 TmpVec = Builder.CreateAdd(TmpVec, Shuf, "add.rdx");
1434 case LoopVectorizationLegality::IntegerMult:
1435 TmpVec = Builder.CreateMul(TmpVec, Shuf, "mul.rdx");
1437 case LoopVectorizationLegality::IntegerOr:
1438 TmpVec = Builder.CreateOr(TmpVec, Shuf, "or.rdx");
1440 case LoopVectorizationLegality::IntegerAnd:
1441 TmpVec = Builder.CreateAnd(TmpVec, Shuf, "and.rdx");
1443 case LoopVectorizationLegality::IntegerXor:
1444 TmpVec = Builder.CreateXor(TmpVec, Shuf, "xor.rdx");
1447 llvm_unreachable("Unknown reduction operation");
1451 // The result is in the first element of the vector.
1452 Value *Scalar0 = Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
1454 // Now, we need to fix the users of the reduction variable
1455 // inside and outside of the scalar remainder loop.
1456 // We know that the loop is in LCSSA form. We need to update the
1457 // PHI nodes in the exit blocks.
1458 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
1459 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
1460 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
1461 if (!LCSSAPhi) continue;
1463 // All PHINodes need to have a single entry edge, or two if
1464 // we already fixed them.
1465 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
1467 // We found our reduction value exit-PHI. Update it with the
1468 // incoming bypass edge.
1469 if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
1470 // Add an edge coming from the bypass.
1471 LCSSAPhi->addIncoming(Scalar0, LoopMiddleBlock);
1474 }// end of the LCSSA phi scan.
1476 // Fix the scalar loop reduction variable with the incoming reduction sum
1477 // from the vector body and from the backedge value.
1478 int IncomingEdgeBlockIdx =
1479 (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
1480 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
1481 // Pick the other block.
1482 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
1483 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, Scalar0);
1484 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
1485 }// end of for each redux variable.
1487 // The Loop exit block may have single value PHI nodes where the incoming
1488 // value is 'undef'. While vectorizing we only handled real values that
1489 // were defined inside the loop. Here we handle the 'undef case'.
1491 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
1492 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
1493 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
1494 if (!LCSSAPhi) continue;
1495 if (LCSSAPhi->getNumIncomingValues() == 1)
1496 LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
1501 InnerLoopVectorizer::VectorParts
1502 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
1503 assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
1506 VectorParts SrcMask = createBlockInMask(Src);
1508 // The terminator has to be a branch inst!
1509 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
1510 assert(BI && "Unexpected terminator found");
1512 if (BI->isConditional()) {
1513 VectorParts EdgeMask = getVectorValue(BI->getCondition());
1515 if (BI->getSuccessor(0) != Dst)
1516 for (unsigned part = 0; part < UF; ++part)
1517 EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
1519 for (unsigned part = 0; part < UF; ++part)
1520 EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
1527 InnerLoopVectorizer::VectorParts
1528 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
1529 assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
1531 // Loop incoming mask is all-one.
1532 if (OrigLoop->getHeader() == BB) {
1533 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
1534 return getVectorValue(C);
1537 // This is the block mask. We OR all incoming edges, and with zero.
1538 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
1539 VectorParts BlockMask = getVectorValue(Zero);
1542 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
1543 VectorParts EM = createEdgeMask(*it, BB);
1544 for (unsigned part = 0; part < UF; ++part)
1545 BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
1552 InnerLoopVectorizer::vectorizeBlockInLoop(LoopVectorizationLegality *Legal,
1553 BasicBlock *BB, PhiVector *PV) {
1554 Constant *Zero = Builder.getInt32(0);
1556 // For each instruction in the old loop.
1557 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1558 VectorParts &Entry = WidenMap.get(it);
1559 switch (it->getOpcode()) {
1560 case Instruction::Br:
1561 // Nothing to do for PHIs and BR, since we already took care of the
1562 // loop control flow instructions.
1564 case Instruction::PHI:{
1565 PHINode* P = cast<PHINode>(it);
1566 // Handle reduction variables:
1567 if (Legal->getReductionVars()->count(P)) {
1568 for (unsigned part = 0; part < UF; ++part) {
1569 // This is phase one of vectorizing PHIs.
1570 Type *VecTy = VectorType::get(it->getType(), VF);
1571 Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
1572 LoopVectorBody-> getFirstInsertionPt());
1578 // Check for PHI nodes that are lowered to vector selects.
1579 if (P->getParent() != OrigLoop->getHeader()) {
1580 // We know that all PHIs in non header blocks are converted into
1581 // selects, so we don't have to worry about the insertion order and we
1582 // can just use the builder.
1584 // At this point we generate the predication tree. There may be
1585 // duplications since this is a simple recursive scan, but future
1586 // optimizations will clean it up.
1587 VectorParts Cond = createEdgeMask(P->getIncomingBlock(0),
1590 for (unsigned part = 0; part < UF; ++part) {
1591 VectorParts &In0 = getVectorValue(P->getIncomingValue(0));
1592 VectorParts &In1 = getVectorValue(P->getIncomingValue(1));
1593 Entry[part] = Builder.CreateSelect(Cond[part], In0[part], In1[part],
1599 // This PHINode must be an induction variable.
1600 // Make sure that we know about it.
1601 assert(Legal->getInductionVars()->count(P) &&
1602 "Not an induction variable");
1604 LoopVectorizationLegality::InductionInfo II =
1605 Legal->getInductionVars()->lookup(P);
1608 case LoopVectorizationLegality::NoInduction:
1609 llvm_unreachable("Unknown induction");
1610 case LoopVectorizationLegality::IntInduction: {
1611 assert(P == OldInduction && "Unexpected PHI");
1612 Value *Broadcasted = getBroadcastInstrs(Induction);
1613 // After broadcasting the induction variable we need to make the
1614 // vector consecutive by adding 0, 1, 2 ...
1615 for (unsigned part = 0; part < UF; ++part)
1616 Entry[part] = getConsecutiveVector(Broadcasted, VF * part, false);
1619 case LoopVectorizationLegality::ReverseIntInduction:
1620 case LoopVectorizationLegality::PtrInduction:
1621 // Handle reverse integer and pointer inductions.
1622 Value *StartIdx = 0;
1623 // If we have a single integer induction variable then use it.
1624 // Otherwise, start counting at zero.
1626 LoopVectorizationLegality::InductionInfo OldII =
1627 Legal->getInductionVars()->lookup(OldInduction);
1628 StartIdx = OldII.StartValue;
1630 StartIdx = ConstantInt::get(Induction->getType(), 0);
1632 // This is the normalized GEP that starts counting at zero.
1633 Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
1636 // Handle the reverse integer induction variable case.
1637 if (LoopVectorizationLegality::ReverseIntInduction == II.IK) {
1638 IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType());
1639 Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy,
1641 Value *ReverseInd = Builder.CreateSub(II.StartValue, CNI,
1644 // This is a new value so do not hoist it out.
1645 Value *Broadcasted = getBroadcastInstrs(ReverseInd);
1646 // After broadcasting the induction variable we need to make the
1647 // vector consecutive by adding ... -3, -2, -1, 0.
1648 for (unsigned part = 0; part < UF; ++part)
1649 Entry[part] = getConsecutiveVector(Broadcasted, -VF * part, true);
1653 // Handle the pointer induction variable case.
1654 assert(P->getType()->isPointerTy() && "Unexpected type.");
1656 // This is the vector of results. Notice that we don't generate
1657 // vector geps because scalar geps result in better code.
1658 for (unsigned part = 0; part < UF; ++part) {
1659 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
1660 for (unsigned int i = 0; i < VF; ++i) {
1661 Constant *Idx = ConstantInt::get(Induction->getType(),
1663 Value *GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx,
1665 Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
1667 VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
1668 Builder.getInt32(i),
1671 Entry[part] = VecVal;
1678 case Instruction::Add:
1679 case Instruction::FAdd:
1680 case Instruction::Sub:
1681 case Instruction::FSub:
1682 case Instruction::Mul:
1683 case Instruction::FMul:
1684 case Instruction::UDiv:
1685 case Instruction::SDiv:
1686 case Instruction::FDiv:
1687 case Instruction::URem:
1688 case Instruction::SRem:
1689 case Instruction::FRem:
1690 case Instruction::Shl:
1691 case Instruction::LShr:
1692 case Instruction::AShr:
1693 case Instruction::And:
1694 case Instruction::Or:
1695 case Instruction::Xor: {
1696 // Just widen binops.
1697 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
1698 VectorParts &A = getVectorValue(it->getOperand(0));
1699 VectorParts &B = getVectorValue(it->getOperand(1));
1701 // Use this vector value for all users of the original instruction.
1702 for (unsigned Part = 0; Part < UF; ++Part) {
1703 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
1705 // Update the NSW, NUW and Exact flags.
1706 BinaryOperator *VecOp = cast<BinaryOperator>(V);
1707 if (isa<OverflowingBinaryOperator>(BinOp)) {
1708 VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap());
1709 VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap());
1711 if (isa<PossiblyExactOperator>(VecOp))
1712 VecOp->setIsExact(BinOp->isExact());
1718 case Instruction::Select: {
1720 // If the selector is loop invariant we can create a select
1721 // instruction with a scalar condition. Otherwise, use vector-select.
1722 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
1725 // The condition can be loop invariant but still defined inside the
1726 // loop. This means that we can't just use the original 'cond' value.
1727 // We have to take the 'vectorized' value and pick the first lane.
1728 // Instcombine will make this a no-op.
1729 VectorParts &Cond = getVectorValue(it->getOperand(0));
1730 VectorParts &Op0 = getVectorValue(it->getOperand(1));
1731 VectorParts &Op1 = getVectorValue(it->getOperand(2));
1732 Value *ScalarCond = Builder.CreateExtractElement(Cond[0],
1733 Builder.getInt32(0));
1734 for (unsigned Part = 0; Part < UF; ++Part) {
1735 Entry[Part] = Builder.CreateSelect(
1736 InvariantCond ? ScalarCond : Cond[Part],
1743 case Instruction::ICmp:
1744 case Instruction::FCmp: {
1745 // Widen compares. Generate vector compares.
1746 bool FCmp = (it->getOpcode() == Instruction::FCmp);
1747 CmpInst *Cmp = dyn_cast<CmpInst>(it);
1748 VectorParts &A = getVectorValue(it->getOperand(0));
1749 VectorParts &B = getVectorValue(it->getOperand(1));
1750 for (unsigned Part = 0; Part < UF; ++Part) {
1753 C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
1755 C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
1761 case Instruction::Store: {
1762 // Attempt to issue a wide store.
1763 StoreInst *SI = dyn_cast<StoreInst>(it);
1764 Type *StTy = VectorType::get(SI->getValueOperand()->getType(), VF);
1765 Value *Ptr = SI->getPointerOperand();
1766 unsigned Alignment = SI->getAlignment();
1768 assert(!Legal->isUniform(Ptr) &&
1769 "We do not allow storing to uniform addresses");
1772 int Stride = Legal->isConsecutivePtr(Ptr);
1773 bool Reverse = Stride < 0;
1775 scalarizeInstruction(it);
1779 // Handle consecutive stores.
1781 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1783 // The last index does not have to be the induction. It can be
1784 // consecutive and be a function of the index. For example A[I+1];
1785 unsigned NumOperands = Gep->getNumOperands();
1787 Value *LastGepOperand = Gep->getOperand(NumOperands - 1);
1788 VectorParts &GEPParts = getVectorValue(LastGepOperand);
1789 Value *LastIndex = GEPParts[0];
1790 LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
1792 // Create the new GEP with the new induction variable.
1793 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1794 Gep2->setOperand(NumOperands - 1, LastIndex);
1795 Ptr = Builder.Insert(Gep2);
1797 // Use the induction element ptr.
1798 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1799 VectorParts &PtrVal = getVectorValue(Ptr);
1800 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
1803 VectorParts &StoredVal = getVectorValue(SI->getValueOperand());
1804 for (unsigned Part = 0; Part < UF; ++Part) {
1805 // Calculate the pointer for the specific unroll-part.
1806 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1809 // If we store to reverse consecutive memory locations then we need
1810 // to reverse the order of elements in the stored value.
1811 StoredVal[Part] = reverseVector(StoredVal[Part]);
1812 // If the address is consecutive but reversed, then the
1813 // wide store needs to start at the last vector element.
1814 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1815 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1818 Value *VecPtr = Builder.CreateBitCast(PartPtr, StTy->getPointerTo());
1819 Builder.CreateStore(StoredVal[Part], VecPtr)->setAlignment(Alignment);
1823 case Instruction::Load: {
1824 // Attempt to issue a wide load.
1825 LoadInst *LI = dyn_cast<LoadInst>(it);
1826 Type *RetTy = VectorType::get(LI->getType(), VF);
1827 Value *Ptr = LI->getPointerOperand();
1828 unsigned Alignment = LI->getAlignment();
1830 // If the pointer is loop invariant or if it is non consecutive,
1831 // scalarize the load.
1832 int Stride = Legal->isConsecutivePtr(Ptr);
1833 bool Reverse = Stride < 0;
1834 if (Legal->isUniform(Ptr) || Stride == 0) {
1835 scalarizeInstruction(it);
1839 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1841 // The last index does not have to be the induction. It can be
1842 // consecutive and be a function of the index. For example A[I+1];
1843 unsigned NumOperands = Gep->getNumOperands();
1845 Value *LastGepOperand = Gep->getOperand(NumOperands - 1);
1846 VectorParts &GEPParts = getVectorValue(LastGepOperand);
1847 Value *LastIndex = GEPParts[0];
1848 LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
1850 // Create the new GEP with the new induction variable.
1851 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1852 Gep2->setOperand(NumOperands - 1, LastIndex);
1853 Ptr = Builder.Insert(Gep2);
1855 // Use the induction element ptr.
1856 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1857 VectorParts &PtrVal = getVectorValue(Ptr);
1858 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
1861 for (unsigned Part = 0; Part < UF; ++Part) {
1862 // Calculate the pointer for the specific unroll-part.
1863 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1866 // If the address is consecutive but reversed, then the
1867 // wide store needs to start at the last vector element.
1868 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1869 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1872 Value *VecPtr = Builder.CreateBitCast(PartPtr, RetTy->getPointerTo());
1873 Value *LI = Builder.CreateLoad(VecPtr, "wide.load");
1874 cast<LoadInst>(LI)->setAlignment(Alignment);
1875 Entry[Part] = Reverse ? reverseVector(LI) : LI;
1879 case Instruction::ZExt:
1880 case Instruction::SExt:
1881 case Instruction::FPToUI:
1882 case Instruction::FPToSI:
1883 case Instruction::FPExt:
1884 case Instruction::PtrToInt:
1885 case Instruction::IntToPtr:
1886 case Instruction::SIToFP:
1887 case Instruction::UIToFP:
1888 case Instruction::Trunc:
1889 case Instruction::FPTrunc:
1890 case Instruction::BitCast: {
1891 CastInst *CI = dyn_cast<CastInst>(it);
1892 /// Optimize the special case where the source is the induction
1893 /// variable. Notice that we can only optimize the 'trunc' case
1894 /// because: a. FP conversions lose precision, b. sext/zext may wrap,
1895 /// c. other casts depend on pointer size.
1896 if (CI->getOperand(0) == OldInduction &&
1897 it->getOpcode() == Instruction::Trunc) {
1898 Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
1900 Value *Broadcasted = getBroadcastInstrs(ScalarCast);
1901 for (unsigned Part = 0; Part < UF; ++Part)
1902 Entry[Part] = getConsecutiveVector(Broadcasted, VF * Part, false);
1905 /// Vectorize casts.
1906 Type *DestTy = VectorType::get(CI->getType()->getScalarType(), VF);
1908 VectorParts &A = getVectorValue(it->getOperand(0));
1909 for (unsigned Part = 0; Part < UF; ++Part)
1910 Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
1914 case Instruction::Call: {
1915 assert(isTriviallyVectorizableIntrinsic(it));
1916 Module *M = BB->getParent()->getParent();
1917 IntrinsicInst *II = cast<IntrinsicInst>(it);
1918 Intrinsic::ID ID = II->getIntrinsicID();
1919 for (unsigned Part = 0; Part < UF; ++Part) {
1920 SmallVector<Value*, 4> Args;
1921 for (unsigned i = 0, ie = II->getNumArgOperands(); i != ie; ++i) {
1922 VectorParts &Arg = getVectorValue(II->getArgOperand(i));
1923 Args.push_back(Arg[Part]);
1925 Type *Tys[] = { VectorType::get(II->getType()->getScalarType(), VF) };
1926 Function *F = Intrinsic::getDeclaration(M, ID, Tys);
1927 Entry[Part] = Builder.CreateCall(F, Args);
1933 // All other instructions are unsupported. Scalarize them.
1934 scalarizeInstruction(it);
1937 }// end of for_each instr.
1940 void InnerLoopVectorizer::updateAnalysis() {
1941 // Forget the original basic block.
1942 SE->forgetLoop(OrigLoop);
1944 // Update the dominator tree information.
1945 assert(DT->properlyDominates(LoopBypassBlock, LoopExitBlock) &&
1946 "Entry does not dominate exit.");
1948 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlock);
1949 DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader);
1950 DT->addNewBlock(LoopMiddleBlock, LoopBypassBlock);
1951 DT->addNewBlock(LoopScalarPreHeader, LoopMiddleBlock);
1952 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
1953 DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
1955 DEBUG(DT->verifyAnalysis());
1958 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
1959 if (!EnableIfConversion)
1962 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
1963 std::vector<BasicBlock*> &LoopBlocks = TheLoop->getBlocksVector();
1965 // Collect the blocks that need predication.
1966 for (unsigned i = 0, e = LoopBlocks.size(); i < e; ++i) {
1967 BasicBlock *BB = LoopBlocks[i];
1969 // We don't support switch statements inside loops.
1970 if (!isa<BranchInst>(BB->getTerminator()))
1973 // We must have at most two predecessors because we need to convert
1974 // all PHIs to selects.
1975 unsigned Preds = std::distance(pred_begin(BB), pred_end(BB));
1979 // We must be able to predicate all blocks that need to be predicated.
1980 if (blockNeedsPredication(BB) && !blockCanBePredicated(BB))
1984 // We can if-convert this loop.
1988 bool LoopVectorizationLegality::canVectorize() {
1989 assert(TheLoop->getLoopPreheader() && "No preheader!!");
1991 // We can only vectorize innermost loops.
1992 if (TheLoop->getSubLoopsVector().size())
1995 // We must have a single backedge.
1996 if (TheLoop->getNumBackEdges() != 1)
1999 // We must have a single exiting block.
2000 if (!TheLoop->getExitingBlock())
2003 unsigned NumBlocks = TheLoop->getNumBlocks();
2005 // Check if we can if-convert non single-bb loops.
2006 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
2007 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
2011 // We need to have a loop header.
2012 BasicBlock *Latch = TheLoop->getLoopLatch();
2013 DEBUG(dbgs() << "LV: Found a loop: " <<
2014 TheLoop->getHeader()->getName() << "\n");
2016 // ScalarEvolution needs to be able to find the exit count.
2017 const SCEV *ExitCount = SE->getExitCount(TheLoop, Latch);
2018 if (ExitCount == SE->getCouldNotCompute()) {
2019 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
2023 // Do not loop-vectorize loops with a tiny trip count.
2024 unsigned TC = SE->getSmallConstantTripCount(TheLoop, Latch);
2025 if (TC > 0u && TC < TinyTripCountVectorThreshold) {
2026 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " <<
2027 "This loop is not worth vectorizing.\n");
2031 // Check if we can vectorize the instructions and CFG in this loop.
2032 if (!canVectorizeInstrs()) {
2033 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
2037 // Go over each instruction and look at memory deps.
2038 if (!canVectorizeMemory()) {
2039 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
2043 // Collect all of the variables that remain uniform after vectorization.
2044 collectLoopUniforms();
2046 DEBUG(dbgs() << "LV: We can vectorize this loop" <<
2047 (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
2050 // Okay! We can vectorize. At this point we don't have any other mem analysis
2051 // which may limit our maximum vectorization factor, so just return true with
2056 bool LoopVectorizationLegality::canVectorizeInstrs() {
2057 BasicBlock *PreHeader = TheLoop->getLoopPreheader();
2058 BasicBlock *Header = TheLoop->getHeader();
2060 // For each block in the loop.
2061 for (Loop::block_iterator bb = TheLoop->block_begin(),
2062 be = TheLoop->block_end(); bb != be; ++bb) {
2064 // Scan the instructions in the block and look for hazards.
2065 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
2068 if (PHINode *Phi = dyn_cast<PHINode>(it)) {
2069 // This should not happen because the loop should be normalized.
2070 if (Phi->getNumIncomingValues() != 2) {
2071 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
2075 // Check that this PHI type is allowed.
2076 if (!Phi->getType()->isIntegerTy() &&
2077 !Phi->getType()->isPointerTy()) {
2078 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
2082 // If this PHINode is not in the header block, then we know that we
2083 // can convert it to select during if-conversion. No need to check if
2084 // the PHIs in this block are induction or reduction variables.
2088 // This is the value coming from the preheader.
2089 Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
2090 // Check if this is an induction variable.
2091 InductionKind IK = isInductionVariable(Phi);
2093 if (NoInduction != IK) {
2094 // Int inductions are special because we only allow one IV.
2095 if (IK == IntInduction) {
2097 DEBUG(dbgs() << "LV: Found too many inductions."<< *Phi <<"\n");
2103 DEBUG(dbgs() << "LV: Found an induction variable.\n");
2104 Inductions[Phi] = InductionInfo(StartValue, IK);
2108 if (AddReductionVar(Phi, IntegerAdd)) {
2109 DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
2112 if (AddReductionVar(Phi, IntegerMult)) {
2113 DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
2116 if (AddReductionVar(Phi, IntegerOr)) {
2117 DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
2120 if (AddReductionVar(Phi, IntegerAnd)) {
2121 DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
2124 if (AddReductionVar(Phi, IntegerXor)) {
2125 DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
2129 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
2131 }// end of PHI handling
2133 // We still don't handle functions.
2134 CallInst *CI = dyn_cast<CallInst>(it);
2135 if (CI && !isTriviallyVectorizableIntrinsic(it)) {
2136 DEBUG(dbgs() << "LV: Found a call site.\n");
2140 // Check that the instruction return type is vectorizable.
2141 if (!VectorType::isValidElementType(it->getType()) &&
2142 !it->getType()->isVoidTy()) {
2143 DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n");
2147 // Check that the stored type is vectorizable.
2148 if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
2149 Type *T = ST->getValueOperand()->getType();
2150 if (!VectorType::isValidElementType(T))
2154 // Reduction instructions are allowed to have exit users.
2155 // All other instructions must not have external users.
2156 if (!AllowedExit.count(it))
2157 //Check that all of the users of the loop are inside the BB.
2158 for (Value::use_iterator I = it->use_begin(), E = it->use_end();
2160 Instruction *U = cast<Instruction>(*I);
2161 // This user may be a reduction exit value.
2162 if (!TheLoop->contains(U)) {
2163 DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n");
2172 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
2173 assert(getInductionVars()->size() && "No induction variables");
2179 void LoopVectorizationLegality::collectLoopUniforms() {
2180 // We now know that the loop is vectorizable!
2181 // Collect variables that will remain uniform after vectorization.
2182 std::vector<Value*> Worklist;
2183 BasicBlock *Latch = TheLoop->getLoopLatch();
2185 // Start with the conditional branch and walk up the block.
2186 Worklist.push_back(Latch->getTerminator()->getOperand(0));
2188 while (Worklist.size()) {
2189 Instruction *I = dyn_cast<Instruction>(Worklist.back());
2190 Worklist.pop_back();
2192 // Look at instructions inside this loop.
2193 // Stop when reaching PHI nodes.
2194 // TODO: we need to follow values all over the loop, not only in this block.
2195 if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
2198 // This is a known uniform.
2201 // Insert all operands.
2202 for (int i = 0, Op = I->getNumOperands(); i < Op; ++i) {
2203 Worklist.push_back(I->getOperand(i));
2208 bool LoopVectorizationLegality::canVectorizeMemory() {
2209 typedef SmallVector<Value*, 16> ValueVector;
2210 typedef SmallPtrSet<Value*, 16> ValueSet;
2211 // Holds the Load and Store *instructions*.
2214 PtrRtCheck.Pointers.clear();
2215 PtrRtCheck.Need = false;
2218 for (Loop::block_iterator bb = TheLoop->block_begin(),
2219 be = TheLoop->block_end(); bb != be; ++bb) {
2221 // Scan the BB and collect legal loads and stores.
2222 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
2225 // If this is a load, save it. If this instruction can read from memory
2226 // but is not a load, then we quit. Notice that we don't handle function
2227 // calls that read or write.
2228 if (it->mayReadFromMemory()) {
2229 LoadInst *Ld = dyn_cast<LoadInst>(it);
2230 if (!Ld) return false;
2231 if (!Ld->isSimple()) {
2232 DEBUG(dbgs() << "LV: Found a non-simple load.\n");
2235 Loads.push_back(Ld);
2239 // Save 'store' instructions. Abort if other instructions write to memory.
2240 if (it->mayWriteToMemory()) {
2241 StoreInst *St = dyn_cast<StoreInst>(it);
2242 if (!St) return false;
2243 if (!St->isSimple()) {
2244 DEBUG(dbgs() << "LV: Found a non-simple store.\n");
2247 Stores.push_back(St);
2252 // Now we have two lists that hold the loads and the stores.
2253 // Next, we find the pointers that they use.
2255 // Check if we see any stores. If there are no stores, then we don't
2256 // care if the pointers are *restrict*.
2257 if (!Stores.size()) {
2258 DEBUG(dbgs() << "LV: Found a read-only loop!\n");
2262 // Holds the read and read-write *pointers* that we find.
2264 ValueVector ReadWrites;
2266 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
2267 // multiple times on the same object. If the ptr is accessed twice, once
2268 // for read and once for write, it will only appear once (on the write
2269 // list). This is okay, since we are going to check for conflicts between
2270 // writes and between reads and writes, but not between reads and reads.
2273 ValueVector::iterator I, IE;
2274 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
2275 StoreInst *ST = cast<StoreInst>(*I);
2276 Value* Ptr = ST->getPointerOperand();
2278 if (isUniform(Ptr)) {
2279 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
2283 // If we did *not* see this pointer before, insert it to
2284 // the read-write list. At this phase it is only a 'write' list.
2285 if (Seen.insert(Ptr))
2286 ReadWrites.push_back(Ptr);
2289 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
2290 LoadInst *LD = cast<LoadInst>(*I);
2291 Value* Ptr = LD->getPointerOperand();
2292 // If we did *not* see this pointer before, insert it to the
2293 // read list. If we *did* see it before, then it is already in
2294 // the read-write list. This allows us to vectorize expressions
2295 // such as A[i] += x; Because the address of A[i] is a read-write
2296 // pointer. This only works if the index of A[i] is consecutive.
2297 // If the address of i is unknown (for example A[B[i]]) then we may
2298 // read a few words, modify, and write a few words, and some of the
2299 // words may be written to the same address.
2300 if (Seen.insert(Ptr) || 0 == isConsecutivePtr(Ptr))
2301 Reads.push_back(Ptr);
2304 // If we write (or read-write) to a single destination and there are no
2305 // other reads in this loop then is it safe to vectorize.
2306 if (ReadWrites.size() == 1 && Reads.size() == 0) {
2307 DEBUG(dbgs() << "LV: Found a write-only loop!\n");
2311 // Find pointers with computable bounds. We are going to use this information
2312 // to place a runtime bound check.
2313 bool CanDoRT = true;
2314 for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I)
2315 if (hasComputableBounds(*I)) {
2316 PtrRtCheck.insert(SE, TheLoop, *I);
2317 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n");
2322 for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I)
2323 if (hasComputableBounds(*I)) {
2324 PtrRtCheck.insert(SE, TheLoop, *I);
2325 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n");
2331 // Check that we did not collect too many pointers or found a
2332 // unsizeable pointer.
2333 if (!CanDoRT || PtrRtCheck.Pointers.size() > RuntimeMemoryCheckThreshold) {
2339 DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
2342 bool NeedRTCheck = false;
2344 // Now that the pointers are in two lists (Reads and ReadWrites), we
2345 // can check that there are no conflicts between each of the writes and
2346 // between the writes to the reads.
2347 ValueSet WriteObjects;
2348 ValueVector TempObjects;
2350 // Check that the read-writes do not conflict with other read-write
2352 bool AllWritesIdentified = true;
2353 for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I) {
2354 GetUnderlyingObjects(*I, TempObjects, DL);
2355 for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
2357 if (!isIdentifiedObject(*it)) {
2358 DEBUG(dbgs() << "LV: Found an unidentified write ptr:"<< **it <<"\n");
2360 AllWritesIdentified = false;
2362 if (!WriteObjects.insert(*it)) {
2363 DEBUG(dbgs() << "LV: Found a possible write-write reorder:"
2368 TempObjects.clear();
2371 /// Check that the reads don't conflict with the read-writes.
2372 for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I) {
2373 GetUnderlyingObjects(*I, TempObjects, DL);
2374 for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
2376 // If all of the writes are identified then we don't care if the read
2377 // pointer is identified or not.
2378 if (!AllWritesIdentified && !isIdentifiedObject(*it)) {
2379 DEBUG(dbgs() << "LV: Found an unidentified read ptr:"<< **it <<"\n");
2382 if (WriteObjects.count(*it)) {
2383 DEBUG(dbgs() << "LV: Found a possible read/write reorder:"
2388 TempObjects.clear();
2391 PtrRtCheck.Need = NeedRTCheck;
2392 if (NeedRTCheck && !CanDoRT) {
2393 DEBUG(dbgs() << "LV: We can't vectorize because we can't find " <<
2394 "the array bounds.\n");
2399 DEBUG(dbgs() << "LV: We "<< (NeedRTCheck ? "" : "don't") <<
2400 " need a runtime memory check.\n");
2404 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
2405 ReductionKind Kind) {
2406 if (Phi->getNumIncomingValues() != 2)
2409 // Reduction variables are only found in the loop header block.
2410 if (Phi->getParent() != TheLoop->getHeader())
2413 // Obtain the reduction start value from the value that comes from the loop
2415 Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
2417 // ExitInstruction is the single value which is used outside the loop.
2418 // We only allow for a single reduction value to be used outside the loop.
2419 // This includes users of the reduction, variables (which form a cycle
2420 // which ends in the phi node).
2421 Instruction *ExitInstruction = 0;
2423 // Iter is our iterator. We start with the PHI node and scan for all of the
2424 // users of this instruction. All users must be instructions that can be
2425 // used as reduction variables (such as ADD). We may have a single
2426 // out-of-block user. The cycle must end with the original PHI.
2427 Instruction *Iter = Phi;
2429 // If the instruction has no users then this is a broken
2430 // chain and can't be a reduction variable.
2431 if (Iter->use_empty())
2434 // Did we find a user inside this loop already ?
2435 bool FoundInBlockUser = false;
2436 // Did we reach the initial PHI node already ?
2437 bool FoundStartPHI = false;
2439 // For each of the *users* of iter.
2440 for (Value::use_iterator it = Iter->use_begin(), e = Iter->use_end();
2442 Instruction *U = cast<Instruction>(*it);
2443 // We already know that the PHI is a user.
2445 FoundStartPHI = true;
2449 // Check if we found the exit user.
2450 BasicBlock *Parent = U->getParent();
2451 if (!TheLoop->contains(Parent)) {
2452 // Exit if you find multiple outside users.
2453 if (ExitInstruction != 0)
2455 ExitInstruction = Iter;
2458 // We allow in-loop PHINodes which are not the original reduction PHI
2459 // node. If this PHI is the only user of Iter (happens in IF w/ no ELSE
2460 // structure) then don't skip this PHI.
2461 if (isa<PHINode>(Iter) && isa<PHINode>(U) &&
2462 U->getParent() != TheLoop->getHeader() &&
2463 TheLoop->contains(U) &&
2464 Iter->getNumUses() > 1)
2467 // We can't have multiple inside users.
2468 if (FoundInBlockUser)
2470 FoundInBlockUser = true;
2472 // Any reduction instr must be of one of the allowed kinds.
2473 if (!isReductionInstr(U, Kind))
2476 // Reductions of instructions such as Div, and Sub is only
2477 // possible if the LHS is the reduction variable.
2478 if (!U->isCommutative() && U->getOperand(0) != Iter)
2484 // We found a reduction var if we have reached the original
2485 // phi node and we only have a single instruction with out-of-loop
2487 if (FoundStartPHI && ExitInstruction) {
2488 // This instruction is allowed to have out-of-loop users.
2489 AllowedExit.insert(ExitInstruction);
2491 // Save the description of this reduction variable.
2492 ReductionDescriptor RD(RdxStart, ExitInstruction, Kind);
2493 Reductions[Phi] = RD;
2497 // If we've reached the start PHI but did not find an outside user then
2498 // this is dead code. Abort.
2505 LoopVectorizationLegality::isReductionInstr(Instruction *I,
2506 ReductionKind Kind) {
2507 switch (I->getOpcode()) {
2510 case Instruction::PHI:
2513 case Instruction::Sub:
2514 case Instruction::Add:
2515 return Kind == IntegerAdd;
2516 case Instruction::SDiv:
2517 case Instruction::UDiv:
2518 case Instruction::Mul:
2519 return Kind == IntegerMult;
2520 case Instruction::And:
2521 return Kind == IntegerAnd;
2522 case Instruction::Or:
2523 return Kind == IntegerOr;
2524 case Instruction::Xor:
2525 return Kind == IntegerXor;
2529 LoopVectorizationLegality::InductionKind
2530 LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
2531 Type *PhiTy = Phi->getType();
2532 // We only handle integer and pointer inductions variables.
2533 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
2536 // Check that the PHI is consecutive and starts at zero.
2537 const SCEV *PhiScev = SE->getSCEV(Phi);
2538 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
2540 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
2543 const SCEV *Step = AR->getStepRecurrence(*SE);
2545 // Integer inductions need to have a stride of one.
2546 if (PhiTy->isIntegerTy()) {
2548 return IntInduction;
2549 if (Step->isAllOnesValue())
2550 return ReverseIntInduction;
2554 // Calculate the pointer stride and check if it is consecutive.
2555 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
2559 assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
2560 uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType());
2561 if (C->getValue()->equalsInt(Size))
2562 return PtrInduction;
2567 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
2568 Value *In0 = const_cast<Value*>(V);
2569 PHINode *PN = dyn_cast_or_null<PHINode>(In0);
2573 return Inductions.count(PN);
2576 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
2577 assert(TheLoop->contains(BB) && "Unknown block used");
2579 // Blocks that do not dominate the latch need predication.
2580 BasicBlock* Latch = TheLoop->getLoopLatch();
2581 return !DT->dominates(BB, Latch);
2584 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB) {
2585 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2586 // We don't predicate loads/stores at the moment.
2587 if (it->mayReadFromMemory() || it->mayWriteToMemory() || it->mayThrow())
2590 // The instructions below can trap.
2591 switch (it->getOpcode()) {
2593 case Instruction::UDiv:
2594 case Instruction::SDiv:
2595 case Instruction::URem:
2596 case Instruction::SRem:
2604 bool LoopVectorizationLegality::hasComputableBounds(Value *Ptr) {
2605 const SCEV *PhiScev = SE->getSCEV(Ptr);
2606 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
2610 return AR->isAffine();
2614 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize,
2616 if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
2617 DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
2621 // Find the trip count.
2622 unsigned TC = SE->getSmallConstantTripCount(TheLoop, TheLoop->getLoopLatch());
2623 DEBUG(dbgs() << "LV: Found trip count:"<<TC<<"\n");
2625 unsigned VF = MaxVectorSize;
2627 // If we optimize the program for size, avoid creating the tail loop.
2629 // If we are unable to calculate the trip count then don't try to vectorize.
2631 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
2635 // Find the maximum SIMD width that can fit within the trip count.
2636 VF = TC % MaxVectorSize;
2641 // If the trip count that we found modulo the vectorization factor is not
2642 // zero then we require a tail.
2644 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
2650 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
2651 DEBUG(dbgs() << "LV: Using user VF "<<UserVF<<".\n");
2656 float Cost = expectedCost(1);
2658 DEBUG(dbgs() << "LV: Scalar loop costs: "<< (int)Cost << ".\n");
2659 for (unsigned i=2; i <= VF; i*=2) {
2660 // Notice that the vector loop needs to be executed less times, so
2661 // we need to divide the cost of the vector loops by the width of
2662 // the vector elements.
2663 float VectorCost = expectedCost(i) / (float)i;
2664 DEBUG(dbgs() << "LV: Vector loop of width "<< i << " costs: " <<
2665 (int)VectorCost << ".\n");
2666 if (VectorCost < Cost) {
2672 DEBUG(dbgs() << "LV: Selecting VF = : "<< Width << ".\n");
2677 LoopVectorizationCostModel::selectUnrollFactor(bool OptForSize,
2679 // Use the user preference, unless 'auto' is selected.
2683 // When we optimize for size we don't unroll.
2687 // Do not unroll loops with a relatively small trip count.
2688 unsigned TC = SE->getSmallConstantTripCount(TheLoop,
2689 TheLoop->getLoopLatch());
2690 if (TC > 1 && TC < TinyTripCountUnrollThreshold)
2693 unsigned TargetVectorRegisters = TTI.getNumberOfRegisters(true);
2694 DEBUG(dbgs() << "LV: The target has " << TargetVectorRegisters <<
2695 " vector registers\n");
2697 LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
2698 // We divide by these constants so assume that we have at least one
2699 // instruction that uses at least one register.
2700 R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
2701 R.NumInstructions = std::max(R.NumInstructions, 1U);
2703 // We calculate the unroll factor using the following formula.
2704 // Subtract the number of loop invariants from the number of available
2705 // registers. These registers are used by all of the unrolled instances.
2706 // Next, divide the remaining registers by the number of registers that is
2707 // required by the loop, in order to estimate how many parallel instances
2708 // fit without causing spills.
2709 unsigned UF = (TargetVectorRegisters - R.LoopInvariantRegs) / R.MaxLocalUsers;
2711 // We don't want to unroll the loops to the point where they do not fit into
2712 // the decoded cache. Assume that we only allow 32 IR instructions.
2713 UF = std::min(UF, (MaxLoopSizeThreshold / R.NumInstructions));
2715 // Clamp the unroll factor ranges to reasonable factors.
2716 if (UF > MaxUnrollSize)
2724 LoopVectorizationCostModel::RegisterUsage
2725 LoopVectorizationCostModel::calculateRegisterUsage() {
2726 // This function calculates the register usage by measuring the highest number
2727 // of values that are alive at a single location. Obviously, this is a very
2728 // rough estimation. We scan the loop in a topological order in order and
2729 // assign a number to each instruction. We use RPO to ensure that defs are
2730 // met before their users. We assume that each instruction that has in-loop
2731 // users starts an interval. We record every time that an in-loop value is
2732 // used, so we have a list of the first and last occurrences of each
2733 // instruction. Next, we transpose this data structure into a multi map that
2734 // holds the list of intervals that *end* at a specific location. This multi
2735 // map allows us to perform a linear search. We scan the instructions linearly
2736 // and record each time that a new interval starts, by placing it in a set.
2737 // If we find this value in the multi-map then we remove it from the set.
2738 // The max register usage is the maximum size of the set.
2739 // We also search for instructions that are defined outside the loop, but are
2740 // used inside the loop. We need this number separately from the max-interval
2741 // usage number because when we unroll, loop-invariant values do not take
2743 LoopBlocksDFS DFS(TheLoop);
2747 R.NumInstructions = 0;
2749 // Each 'key' in the map opens a new interval. The values
2750 // of the map are the index of the 'last seen' usage of the
2751 // instruction that is the key.
2752 typedef DenseMap<Instruction*, unsigned> IntervalMap;
2753 // Maps instruction to its index.
2754 DenseMap<unsigned, Instruction*> IdxToInstr;
2755 // Marks the end of each interval.
2756 IntervalMap EndPoint;
2757 // Saves the list of instruction indices that are used in the loop.
2758 SmallSet<Instruction*, 8> Ends;
2759 // Saves the list of values that are used in the loop but are
2760 // defined outside the loop, such as arguments and constants.
2761 SmallPtrSet<Value*, 8> LoopInvariants;
2764 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
2765 be = DFS.endRPO(); bb != be; ++bb) {
2766 R.NumInstructions += (*bb)->size();
2767 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
2769 Instruction *I = it;
2770 IdxToInstr[Index++] = I;
2772 // Save the end location of each USE.
2773 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
2774 Value *U = I->getOperand(i);
2775 Instruction *Instr = dyn_cast<Instruction>(U);
2777 // Ignore non-instruction values such as arguments, constants, etc.
2778 if (!Instr) continue;
2780 // If this instruction is outside the loop then record it and continue.
2781 if (!TheLoop->contains(Instr)) {
2782 LoopInvariants.insert(Instr);
2786 // Overwrite previous end points.
2787 EndPoint[Instr] = Index;
2793 // Saves the list of intervals that end with the index in 'key'.
2794 typedef SmallVector<Instruction*, 2> InstrList;
2795 DenseMap<unsigned, InstrList> TransposeEnds;
2797 // Transpose the EndPoints to a list of values that end at each index.
2798 for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
2800 TransposeEnds[it->second].push_back(it->first);
2802 SmallSet<Instruction*, 8> OpenIntervals;
2803 unsigned MaxUsage = 0;
2806 DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
2807 for (unsigned int i = 0; i < Index; ++i) {
2808 Instruction *I = IdxToInstr[i];
2809 // Ignore instructions that are never used within the loop.
2810 if (!Ends.count(I)) continue;
2812 // Remove all of the instructions that end at this location.
2813 InstrList &List = TransposeEnds[i];
2814 for (unsigned int j=0, e = List.size(); j < e; ++j)
2815 OpenIntervals.erase(List[j]);
2817 // Count the number of live interals.
2818 MaxUsage = std::max(MaxUsage, OpenIntervals.size());
2820 DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
2821 OpenIntervals.size() <<"\n");
2823 // Add the current instruction to the list of open intervals.
2824 OpenIntervals.insert(I);
2827 unsigned Invariant = LoopInvariants.size();
2828 DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << " \n");
2829 DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << " \n");
2830 DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << " \n");
2832 R.LoopInvariantRegs = Invariant;
2833 R.MaxLocalUsers = MaxUsage;
2837 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
2841 for (Loop::block_iterator bb = TheLoop->block_begin(),
2842 be = TheLoop->block_end(); bb != be; ++bb) {
2843 unsigned BlockCost = 0;
2844 BasicBlock *BB = *bb;
2846 // For each instruction in the old loop.
2847 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2848 unsigned C = getInstructionCost(it, VF);
2850 DEBUG(dbgs() << "LV: Found an estimated cost of "<< C <<" for VF " <<
2851 VF << " For instruction: "<< *it << "\n");
2854 // We assume that if-converted blocks have a 50% chance of being executed.
2855 // When the code is scalar then some of the blocks are avoided due to CF.
2856 // When the code is vectorized we execute all code paths.
2857 if (Legal->blockNeedsPredication(*bb) && VF == 1)
2867 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
2868 // If we know that this instruction will remain uniform, check the cost of
2869 // the scalar version.
2870 if (Legal->isUniformAfterVectorization(I))
2873 Type *RetTy = I->getType();
2874 Type *VectorTy = ToVectorTy(RetTy, VF);
2876 // TODO: We need to estimate the cost of intrinsic calls.
2877 switch (I->getOpcode()) {
2878 case Instruction::GetElementPtr:
2879 // We mark this instruction as zero-cost because scalar GEPs are usually
2880 // lowered to the intruction addressing mode. At the moment we don't
2881 // generate vector geps.
2883 case Instruction::Br: {
2884 return TTI.getCFInstrCost(I->getOpcode());
2886 case Instruction::PHI:
2887 //TODO: IF-converted IFs become selects.
2889 case Instruction::Add:
2890 case Instruction::FAdd:
2891 case Instruction::Sub:
2892 case Instruction::FSub:
2893 case Instruction::Mul:
2894 case Instruction::FMul:
2895 case Instruction::UDiv:
2896 case Instruction::SDiv:
2897 case Instruction::FDiv:
2898 case Instruction::URem:
2899 case Instruction::SRem:
2900 case Instruction::FRem:
2901 case Instruction::Shl:
2902 case Instruction::LShr:
2903 case Instruction::AShr:
2904 case Instruction::And:
2905 case Instruction::Or:
2906 case Instruction::Xor:
2907 return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy);
2908 case Instruction::Select: {
2909 SelectInst *SI = cast<SelectInst>(I);
2910 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
2911 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
2912 Type *CondTy = SI->getCondition()->getType();
2914 CondTy = VectorType::get(CondTy, VF);
2916 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
2918 case Instruction::ICmp:
2919 case Instruction::FCmp: {
2920 Type *ValTy = I->getOperand(0)->getType();
2921 VectorTy = ToVectorTy(ValTy, VF);
2922 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
2924 case Instruction::Store: {
2925 StoreInst *SI = cast<StoreInst>(I);
2926 Type *ValTy = SI->getValueOperand()->getType();
2927 VectorTy = ToVectorTy(ValTy, VF);
2930 return TTI.getMemoryOpCost(I->getOpcode(), VectorTy,
2932 SI->getPointerAddressSpace());
2934 // Scalarized stores.
2935 int Stride = Legal->isConsecutivePtr(SI->getPointerOperand());
2936 bool Reverse = Stride < 0;
2940 // The cost of extracting from the value vector and pointer vector.
2941 Type *PtrTy = ToVectorTy(I->getOperand(0)->getType(), VF);
2942 for (unsigned i = 0; i < VF; ++i) {
2943 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, VectorTy,
2945 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
2948 // The cost of the scalar stores.
2949 Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
2951 SI->getPointerAddressSpace());
2956 unsigned Cost = TTI.getMemoryOpCost(I->getOpcode(), VectorTy,
2958 SI->getPointerAddressSpace());
2960 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
2964 case Instruction::Load: {
2965 LoadInst *LI = cast<LoadInst>(I);
2968 return TTI.getMemoryOpCost(I->getOpcode(), VectorTy, LI->getAlignment(),
2969 LI->getPointerAddressSpace());
2971 // Scalarized loads.
2972 int Stride = Legal->isConsecutivePtr(LI->getPointerOperand());
2973 bool Reverse = Stride < 0;
2976 Type *PtrTy = ToVectorTy(I->getOperand(0)->getType(), VF);
2978 // The cost of extracting from the pointer vector.
2979 for (unsigned i = 0; i < VF; ++i)
2980 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
2982 // The cost of inserting data to the result vector.
2983 for (unsigned i = 0; i < VF; ++i)
2984 Cost += TTI.getVectorInstrCost(Instruction::InsertElement, VectorTy, i);
2986 // The cost of the scalar stores.
2987 Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), RetTy->getScalarType(),
2989 LI->getPointerAddressSpace());
2994 unsigned Cost = TTI.getMemoryOpCost(I->getOpcode(), VectorTy,
2996 LI->getPointerAddressSpace());
2998 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0);
3001 case Instruction::ZExt:
3002 case Instruction::SExt:
3003 case Instruction::FPToUI:
3004 case Instruction::FPToSI:
3005 case Instruction::FPExt:
3006 case Instruction::PtrToInt:
3007 case Instruction::IntToPtr:
3008 case Instruction::SIToFP:
3009 case Instruction::UIToFP:
3010 case Instruction::Trunc:
3011 case Instruction::FPTrunc:
3012 case Instruction::BitCast: {
3013 // We optimize the truncation of induction variable.
3014 // The cost of these is the same as the scalar operation.
3015 if (I->getOpcode() == Instruction::Trunc &&
3016 Legal->isInductionVariable(I->getOperand(0)))
3017 return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
3018 I->getOperand(0)->getType());
3020 Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
3021 return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
3023 case Instruction::Call: {
3024 assert(isTriviallyVectorizableIntrinsic(I));
3025 IntrinsicInst *II = cast<IntrinsicInst>(I);
3026 Type *RetTy = ToVectorTy(II->getType(), VF);
3027 SmallVector<Type*, 4> Tys;
3028 for (unsigned i = 0, ie = II->getNumArgOperands(); i != ie; ++i)
3029 Tys.push_back(ToVectorTy(II->getArgOperand(i)->getType(), VF));
3030 return TTI.getIntrinsicInstrCost(II->getIntrinsicID(), RetTy, Tys);
3033 // We are scalarizing the instruction. Return the cost of the scalar
3034 // instruction, plus the cost of insert and extract into vector
3035 // elements, times the vector width.
3038 if (!RetTy->isVoidTy() && VF != 1) {
3039 unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
3041 unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
3044 // The cost of inserting the results plus extracting each one of the
3046 Cost += VF * (InsCost + ExtCost * I->getNumOperands());
3049 // The cost of executing VF copies of the scalar instruction. This opcode
3050 // is unknown. Assume that it is the same as 'mul'.
3051 Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
3057 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
3058 if (Scalar->isVoidTy() || VF == 1)
3060 return VectorType::get(Scalar, VF);
3063 char LoopVectorize::ID = 0;
3064 static const char lv_name[] = "Loop Vectorization";
3065 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
3066 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3067 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
3068 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
3069 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
3070 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
3073 Pass *createLoopVectorizePass() {
3074 return new LoopVectorize();