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 /// Generate a shuffle sequence that will reverse the vector Vec.
219 Value *reverseVector(Value *Vec);
221 /// This is a helper class that holds the vectorizer state. It maps scalar
222 /// instructions to vector instructions. When the code is 'unrolled' then
223 /// then a single scalar value is mapped to multiple vector parts. The parts
224 /// are stored in the VectorPart type.
226 /// C'tor. UnrollFactor controls the number of vectors ('parts') that
228 ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
230 /// \return True if 'Key' is saved in the Value Map.
231 bool has(Value *Key) { return MapStoreage.count(Key); }
233 /// Initializes a new entry in the map. Sets all of the vector parts to the
234 /// save value in 'Val'.
235 /// \return A reference to a vector with splat values.
236 VectorParts &splat(Value *Key, Value *Val) {
237 MapStoreage[Key].clear();
238 MapStoreage[Key].append(UF, Val);
239 return MapStoreage[Key];
242 ///\return A reference to the value that is stored at 'Key'.
243 VectorParts &get(Value *Key) {
245 MapStoreage[Key].resize(UF);
246 return MapStoreage[Key];
249 /// The unroll factor. Each entry in the map stores this number of vector
253 /// Map storage. We use std::map and not DenseMap because insertions to a
254 /// dense map invalidates its iterators.
255 std::map<Value*, VectorParts> MapStoreage;
258 /// The original loop.
260 /// Scev analysis to use.
268 /// The vectorization SIMD factor to use. Each vector will have this many
271 /// The vectorization unroll factor to use. Each scalar is vectorized to this
272 /// many different vector instructions.
275 /// The builder that we use
278 // --- Vectorization state ---
280 /// The vector-loop preheader.
281 BasicBlock *LoopVectorPreHeader;
282 /// The scalar-loop preheader.
283 BasicBlock *LoopScalarPreHeader;
284 /// Middle Block between the vector and the scalar.
285 BasicBlock *LoopMiddleBlock;
286 ///The ExitBlock of the scalar loop.
287 BasicBlock *LoopExitBlock;
288 ///The vector loop body.
289 BasicBlock *LoopVectorBody;
290 ///The scalar loop body.
291 BasicBlock *LoopScalarBody;
292 ///The first bypass block.
293 BasicBlock *LoopBypassBlock;
295 /// The new Induction variable which was added to the new block.
297 /// The induction variable of the old basic block.
298 PHINode *OldInduction;
299 /// Maps scalars to widened vectors.
303 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
304 /// to what vectorization factor.
305 /// This class does not look at the profitability of vectorization, only the
306 /// legality. This class has two main kinds of checks:
307 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
308 /// will change the order of memory accesses in a way that will change the
309 /// correctness of the program.
310 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
311 /// checks for a number of different conditions, such as the availability of a
312 /// single induction variable, that all types are supported and vectorize-able,
313 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
314 /// This class is also used by InnerLoopVectorizer for identifying
315 /// induction variable and the different reduction variables.
316 class LoopVectorizationLegality {
318 LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, DataLayout *DL,
320 : TheLoop(L), SE(SE), DL(DL), DT(DT), Induction(0) {}
322 /// This enum represents the kinds of reductions that we support.
324 RK_NoReduction, ///< Not a reduction.
325 RK_IntegerAdd, ///< Sum of integers.
326 RK_IntegerMult, ///< Product of integers.
327 RK_IntegerOr, ///< Bitwise or logical OR of numbers.
328 RK_IntegerAnd, ///< Bitwise or logical AND of numbers.
329 RK_IntegerXor, ///< Bitwise or logical XOR of numbers.
330 RK_FloatAdd, ///< Sum of floats.
331 RK_FloatMult ///< Product of floats.
334 /// This enum represents the kinds of inductions that we support.
336 IK_NoInduction, ///< Not an induction variable.
337 IK_IntInduction, ///< Integer induction variable. Step = 1.
338 IK_ReverseIntInduction, ///< Reverse int induction variable. Step = -1.
339 IK_PtrInduction ///< Pointer induction variable. Step = sizeof(elem).
342 /// This POD struct holds information about reduction variables.
343 struct ReductionDescriptor {
344 ReductionDescriptor() : StartValue(0), LoopExitInstr(0),
345 Kind(RK_NoReduction) {}
347 ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K)
348 : StartValue(Start), LoopExitInstr(Exit), Kind(K) {}
350 // The starting value of the reduction.
351 // It does not have to be zero!
353 // The instruction who's value is used outside the loop.
354 Instruction *LoopExitInstr;
355 // The kind of the reduction.
359 // This POD struct holds information about the memory runtime legality
360 // check that a group of pointers do not overlap.
361 struct RuntimePointerCheck {
362 RuntimePointerCheck() : Need(false) {}
364 /// Reset the state of the pointer runtime information.
372 /// Insert a pointer and calculate the start and end SCEVs.
373 void insert(ScalarEvolution *SE, Loop *Lp, Value *Ptr);
375 /// This flag indicates if we need to add the runtime check.
377 /// Holds the pointers that we need to check.
378 SmallVector<Value*, 2> Pointers;
379 /// Holds the pointer value at the beginning of the loop.
380 SmallVector<const SCEV*, 2> Starts;
381 /// Holds the pointer value at the end of the loop.
382 SmallVector<const SCEV*, 2> Ends;
385 /// A POD for saving information about induction variables.
386 struct InductionInfo {
387 InductionInfo(Value *Start, InductionKind K) : StartValue(Start), IK(K) {}
388 InductionInfo() : StartValue(0), IK(IK_NoInduction) {}
395 /// ReductionList contains the reduction descriptors for all
396 /// of the reductions that were found in the loop.
397 typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
399 /// InductionList saves induction variables and maps them to the
400 /// induction descriptor.
401 typedef MapVector<PHINode*, InductionInfo> InductionList;
403 /// Returns true if it is legal to vectorize this loop.
404 /// This does not mean that it is profitable to vectorize this
405 /// loop, only that it is legal to do so.
408 /// Returns the Induction variable.
409 PHINode *getInduction() { return Induction; }
411 /// Returns the reduction variables found in the loop.
412 ReductionList *getReductionVars() { return &Reductions; }
414 /// Returns the induction variables found in the loop.
415 InductionList *getInductionVars() { return &Inductions; }
417 /// Returns True if V is an induction variable in this loop.
418 bool isInductionVariable(const Value *V);
420 /// Return true if the block BB needs to be predicated in order for the loop
421 /// to be vectorized.
422 bool blockNeedsPredication(BasicBlock *BB);
424 /// Check if this pointer is consecutive when vectorizing. This happens
425 /// when the last index of the GEP is the induction variable, or that the
426 /// pointer itself is an induction variable.
427 /// This check allows us to vectorize A[idx] into a wide load/store.
429 /// 0 - Stride is unknown or non consecutive.
430 /// 1 - Address is consecutive.
431 /// -1 - Address is consecutive, and decreasing.
432 int isConsecutivePtr(Value *Ptr);
434 /// Returns true if the value V is uniform within the loop.
435 bool isUniform(Value *V);
437 /// Returns true if this instruction will remain scalar after vectorization.
438 bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
440 /// Returns the information that we collected about runtime memory check.
441 RuntimePointerCheck *getRuntimePointerCheck() { return &PtrRtCheck; }
443 /// Check if a single basic block loop is vectorizable.
444 /// At this point we know that this is a loop with a constant trip count
445 /// and we only need to check individual instructions.
446 bool canVectorizeInstrs();
448 /// When we vectorize loops we may change the order in which
449 /// we read and write from memory. This method checks if it is
450 /// legal to vectorize the code, considering only memory constrains.
451 /// Returns true if the loop is vectorizable
452 bool canVectorizeMemory();
454 /// Return true if we can vectorize this loop using the IF-conversion
456 bool canVectorizeWithIfConvert();
458 /// Collect the variables that need to stay uniform after vectorization.
459 void collectLoopUniforms();
461 /// Return true if all of the instructions in the block can be speculatively
463 bool blockCanBePredicated(BasicBlock *BB);
465 /// Returns True, if 'Phi' is the kind of reduction variable for type
466 /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
467 bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
468 /// Returns true if the instruction I can be a reduction variable of type
470 bool isReductionInstr(Instruction *I, ReductionKind Kind);
471 /// Returns the induction kind of Phi. This function may return NoInduction
472 /// if the PHI is not an induction variable.
473 InductionKind isInductionVariable(PHINode *Phi);
474 /// Return true if can compute the address bounds of Ptr within the loop.
475 bool hasComputableBounds(Value *Ptr);
477 /// The loop that we evaluate.
481 /// DataLayout analysis.
486 // --- vectorization state --- //
488 /// Holds the integer induction variable. This is the counter of the
491 /// Holds the reduction variables.
492 ReductionList Reductions;
493 /// Holds all of the induction variables that we found in the loop.
494 /// Notice that inductions don't need to start at zero and that induction
495 /// variables can be pointers.
496 InductionList Inductions;
498 /// Allowed outside users. This holds the reduction
499 /// vars which can be accessed from outside the loop.
500 SmallPtrSet<Value*, 4> AllowedExit;
501 /// This set holds the variables which are known to be uniform after
503 SmallPtrSet<Instruction*, 4> Uniforms;
504 /// We need to check that all of the pointers in this list are disjoint
506 RuntimePointerCheck PtrRtCheck;
509 /// LoopVectorizationCostModel - estimates the expected speedups due to
511 /// In many cases vectorization is not profitable. This can happen because of
512 /// a number of reasons. In this class we mainly attempt to predict the
513 /// expected speedup/slowdowns due to the supported instruction set. We use the
514 /// TargetTransformInfo to query the different backends for the cost of
515 /// different operations.
516 class LoopVectorizationCostModel {
518 LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
519 LoopVectorizationLegality *Legal,
520 const TargetTransformInfo &TTI)
521 : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI) {}
523 /// \return The most profitable vectorization factor.
524 /// This method checks every power of two up to VF. If UserVF is not ZERO
525 /// then this vectorization factor will be selected if vectorization is
527 unsigned selectVectorizationFactor(bool OptForSize, unsigned UserVF);
530 /// \return The most profitable unroll factor.
531 /// If UserUF is non-zero then this method finds the best unroll-factor
532 /// based on register pressure and other parameters.
533 unsigned selectUnrollFactor(bool OptForSize, unsigned UserUF);
535 /// \brief A struct that represents some properties of the register usage
537 struct RegisterUsage {
538 /// Holds the number of loop invariant values that are used in the loop.
539 unsigned LoopInvariantRegs;
540 /// Holds the maximum number of concurrent live intervals in the loop.
541 unsigned MaxLocalUsers;
542 /// Holds the number of instructions in the loop.
543 unsigned NumInstructions;
546 /// \return information about the register usage of the loop.
547 RegisterUsage calculateRegisterUsage();
550 /// Returns the expected execution cost. The unit of the cost does
551 /// not matter because we use the 'cost' units to compare different
552 /// vector widths. The cost that is returned is *not* normalized by
553 /// the factor width.
554 unsigned expectedCost(unsigned VF);
556 /// Returns the execution time cost of an instruction for a given vector
557 /// width. Vector width of one means scalar.
558 unsigned getInstructionCost(Instruction *I, unsigned VF);
560 /// A helper function for converting Scalar types to vector types.
561 /// If the incoming type is void, we return void. If the VF is 1, we return
563 static Type* ToVectorTy(Type *Scalar, unsigned VF);
565 /// The loop that we evaluate.
569 /// Loop Info analysis.
571 /// Vectorization legality.
572 LoopVectorizationLegality *Legal;
573 /// Vector target information.
574 const TargetTransformInfo &TTI;
577 /// The LoopVectorize Pass.
578 struct LoopVectorize : public LoopPass {
579 /// Pass identification, replacement for typeid
582 explicit LoopVectorize() : LoopPass(ID) {
583 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
589 TargetTransformInfo *TTI;
592 virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
593 // We only vectorize innermost loops.
597 SE = &getAnalysis<ScalarEvolution>();
598 DL = getAnalysisIfAvailable<DataLayout>();
599 LI = &getAnalysis<LoopInfo>();
600 TTI = &getAnalysis<TargetTransformInfo>();
601 DT = &getAnalysis<DominatorTree>();
603 DEBUG(dbgs() << "LV: Checking a loop in \"" <<
604 L->getHeader()->getParent()->getName() << "\"\n");
606 // Check if it is legal to vectorize the loop.
607 LoopVectorizationLegality LVL(L, SE, DL, DT);
608 if (!LVL.canVectorize()) {
609 DEBUG(dbgs() << "LV: Not vectorizing.\n");
613 // Use the cost model.
614 LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI);
616 // Check the function attribues to find out if this function should be
617 // optimized for size.
618 Function *F = L->getHeader()->getParent();
619 Attribute::AttrKind SzAttr = Attribute::OptimizeForSize;
620 Attribute::AttrKind FlAttr = Attribute::NoImplicitFloat;
621 unsigned FnIndex = AttributeSet::FunctionIndex;
622 bool OptForSize = F->getAttributes().hasAttribute(FnIndex, SzAttr);
623 bool NoFloat = F->getAttributes().hasAttribute(FnIndex, FlAttr);
626 DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
627 "attribute is used.\n");
631 unsigned VF = CM.selectVectorizationFactor(OptForSize, VectorizationFactor);
632 unsigned UF = CM.selectUnrollFactor(OptForSize, VectorizationUnroll);
635 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
639 DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< VF << ") in "<<
640 F->getParent()->getModuleIdentifier()<<"\n");
641 DEBUG(dbgs() << "LV: Unroll Factor is " << UF << "\n");
643 // If we decided that it is *legal* to vectorizer the loop then do it.
644 InnerLoopVectorizer LB(L, SE, LI, DT, DL, VF, UF);
647 DEBUG(verifyFunction(*L->getHeader()->getParent()));
651 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
652 LoopPass::getAnalysisUsage(AU);
653 AU.addRequiredID(LoopSimplifyID);
654 AU.addRequiredID(LCSSAID);
655 AU.addRequired<DominatorTree>();
656 AU.addRequired<LoopInfo>();
657 AU.addRequired<ScalarEvolution>();
658 AU.addRequired<TargetTransformInfo>();
659 AU.addPreserved<LoopInfo>();
660 AU.addPreserved<DominatorTree>();
665 } // end anonymous namespace
667 //===----------------------------------------------------------------------===//
668 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
669 // LoopVectorizationCostModel.
670 //===----------------------------------------------------------------------===//
673 LoopVectorizationLegality::RuntimePointerCheck::insert(ScalarEvolution *SE,
674 Loop *Lp, Value *Ptr) {
675 const SCEV *Sc = SE->getSCEV(Ptr);
676 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
677 assert(AR && "Invalid addrec expression");
678 const SCEV *Ex = SE->getExitCount(Lp, Lp->getLoopLatch());
679 const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
680 Pointers.push_back(Ptr);
681 Starts.push_back(AR->getStart());
682 Ends.push_back(ScEnd);
685 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
686 // Save the current insertion location.
687 Instruction *Loc = Builder.GetInsertPoint();
689 // We need to place the broadcast of invariant variables outside the loop.
690 Instruction *Instr = dyn_cast<Instruction>(V);
691 bool NewInstr = (Instr && Instr->getParent() == LoopVectorBody);
692 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
694 // Place the code for broadcasting invariant variables in the new preheader.
696 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
698 // Broadcast the scalar into all locations in the vector.
699 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
701 // Restore the builder insertion point.
703 Builder.SetInsertPoint(Loc);
708 Value *InnerLoopVectorizer::getConsecutiveVector(Value* Val, unsigned StartIdx,
710 assert(Val->getType()->isVectorTy() && "Must be a vector");
711 assert(Val->getType()->getScalarType()->isIntegerTy() &&
712 "Elem must be an integer");
714 Type *ITy = Val->getType()->getScalarType();
715 VectorType *Ty = cast<VectorType>(Val->getType());
716 int VLen = Ty->getNumElements();
717 SmallVector<Constant*, 8> Indices;
719 // Create a vector of consecutive numbers from zero to VF.
720 for (int i = 0; i < VLen; ++i) {
721 int Idx = Negate ? (-i): i;
722 Indices.push_back(ConstantInt::get(ITy, StartIdx + Idx));
725 // Add the consecutive indices to the vector value.
726 Constant *Cv = ConstantVector::get(Indices);
727 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
728 return Builder.CreateAdd(Val, Cv, "induction");
731 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
732 assert(Ptr->getType()->isPointerTy() && "Unexpected non ptr");
734 // If this value is a pointer induction variable we know it is consecutive.
735 PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
736 if (Phi && Inductions.count(Phi)) {
737 InductionInfo II = Inductions[Phi];
738 if (IK_PtrInduction == II.IK)
742 GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
746 unsigned NumOperands = Gep->getNumOperands();
747 Value *LastIndex = Gep->getOperand(NumOperands - 1);
749 // Check that all of the gep indices are uniform except for the last.
750 for (unsigned i = 0; i < NumOperands - 1; ++i)
751 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
754 // We can emit wide load/stores only if the last index is the induction
756 const SCEV *Last = SE->getSCEV(LastIndex);
757 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
758 const SCEV *Step = AR->getStepRecurrence(*SE);
760 // The memory is consecutive because the last index is consecutive
761 // and all other indices are loop invariant.
764 if (Step->isAllOnesValue())
771 bool LoopVectorizationLegality::isUniform(Value *V) {
772 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
775 InnerLoopVectorizer::VectorParts&
776 InnerLoopVectorizer::getVectorValue(Value *V) {
777 assert(V != Induction && "The new induction variable should not be used.");
778 assert(!V->getType()->isVectorTy() && "Can't widen a vector");
780 // If we have this scalar in the map, return it.
782 return WidenMap.get(V);
784 // If this scalar is unknown, assume that it is a constant or that it is
785 // loop invariant. Broadcast V and save the value for future uses.
786 Value *B = getBroadcastInstrs(V);
787 WidenMap.splat(V, B);
788 return WidenMap.get(V);
791 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
792 assert(Vec->getType()->isVectorTy() && "Invalid type");
793 SmallVector<Constant*, 8> ShuffleMask;
794 for (unsigned i = 0; i < VF; ++i)
795 ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
797 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
798 ConstantVector::get(ShuffleMask),
802 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr) {
803 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
804 // Holds vector parameters or scalars, in case of uniform vals.
805 SmallVector<VectorParts, 4> Params;
807 // Find all of the vectorized parameters.
808 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
809 Value *SrcOp = Instr->getOperand(op);
811 // If we are accessing the old induction variable, use the new one.
812 if (SrcOp == OldInduction) {
813 Params.push_back(getVectorValue(SrcOp));
817 // Try using previously calculated values.
818 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
820 // If the src is an instruction that appeared earlier in the basic block
821 // then it should already be vectorized.
822 if (SrcInst && OrigLoop->contains(SrcInst)) {
823 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
824 // The parameter is a vector value from earlier.
825 Params.push_back(WidenMap.get(SrcInst));
827 // The parameter is a scalar from outside the loop. Maybe even a constant.
829 Scalars.append(UF, SrcOp);
830 Params.push_back(Scalars);
834 assert(Params.size() == Instr->getNumOperands() &&
835 "Invalid number of operands");
837 // Does this instruction return a value ?
838 bool IsVoidRetTy = Instr->getType()->isVoidTy();
840 Value *UndefVec = IsVoidRetTy ? 0 :
841 UndefValue::get(VectorType::get(Instr->getType(), VF));
842 // Create a new entry in the WidenMap and initialize it to Undef or Null.
843 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
845 // For each scalar that we create:
846 for (unsigned Width = 0; Width < VF; ++Width) {
847 // For each vector unroll 'part':
848 for (unsigned Part = 0; Part < UF; ++Part) {
849 Instruction *Cloned = Instr->clone();
851 Cloned->setName(Instr->getName() + ".cloned");
852 // Replace the operands of the cloned instrucions with extracted scalars.
853 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
854 Value *Op = Params[op][Part];
855 // Param is a vector. Need to extract the right lane.
856 if (Op->getType()->isVectorTy())
857 Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
858 Cloned->setOperand(op, Op);
861 // Place the cloned scalar in the new loop.
862 Builder.Insert(Cloned);
864 // If the original scalar returns a value we need to place it in a vector
865 // so that future users will be able to use it.
867 VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
868 Builder.getInt32(Width));
874 InnerLoopVectorizer::addRuntimeCheck(LoopVectorizationLegality *Legal,
876 LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck =
877 Legal->getRuntimePointerCheck();
879 if (!PtrRtCheck->Need)
882 Value *MemoryRuntimeCheck = 0;
883 unsigned NumPointers = PtrRtCheck->Pointers.size();
884 SmallVector<Value* , 2> Starts;
885 SmallVector<Value* , 2> Ends;
887 SCEVExpander Exp(*SE, "induction");
889 // Use this type for pointer arithmetic.
890 Type* PtrArithTy = Type::getInt8PtrTy(Loc->getContext(), 0);
892 for (unsigned i = 0; i < NumPointers; ++i) {
893 Value *Ptr = PtrRtCheck->Pointers[i];
894 const SCEV *Sc = SE->getSCEV(Ptr);
896 if (SE->isLoopInvariant(Sc, OrigLoop)) {
897 DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" <<
899 Starts.push_back(Ptr);
902 DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr <<"\n");
904 Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc);
905 Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
906 Starts.push_back(Start);
911 for (unsigned i = 0; i < NumPointers; ++i) {
912 for (unsigned j = i+1; j < NumPointers; ++j) {
913 Instruction::CastOps Op = Instruction::BitCast;
914 Value *Start0 = CastInst::Create(Op, Starts[i], PtrArithTy, "bc", Loc);
915 Value *Start1 = CastInst::Create(Op, Starts[j], PtrArithTy, "bc", Loc);
916 Value *End0 = CastInst::Create(Op, Ends[i], PtrArithTy, "bc", Loc);
917 Value *End1 = CastInst::Create(Op, Ends[j], PtrArithTy, "bc", Loc);
919 Value *Cmp0 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_ULE,
920 Start0, End1, "bound0", Loc);
921 Value *Cmp1 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_ULE,
922 Start1, End0, "bound1", Loc);
923 Value *IsConflict = BinaryOperator::Create(Instruction::And, Cmp0, Cmp1,
924 "found.conflict", Loc);
925 if (MemoryRuntimeCheck)
926 MemoryRuntimeCheck = BinaryOperator::Create(Instruction::Or,
929 "conflict.rdx", Loc);
931 MemoryRuntimeCheck = IsConflict;
936 return MemoryRuntimeCheck;
940 InnerLoopVectorizer::createEmptyLoop(LoopVectorizationLegality *Legal) {
942 In this function we generate a new loop. The new loop will contain
943 the vectorized instructions while the old loop will continue to run the
946 [ ] <-- vector loop bypass.
949 | [ ] <-- vector pre header.
953 | [ ]_| <-- vector loop.
956 >[ ] <--- middle-block.
959 | [ ] <--- new preheader.
963 | [ ]_| <-- old scalar loop to handle remainder.
970 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
971 BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
972 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
973 assert(ExitBlock && "Must have an exit block");
975 // Some loops have a single integer induction variable, while other loops
976 // don't. One example is c++ iterators that often have multiple pointer
977 // induction variables. In the code below we also support a case where we
978 // don't have a single induction variable.
979 OldInduction = Legal->getInduction();
980 Type *IdxTy = OldInduction ? OldInduction->getType() :
981 DL->getIntPtrType(SE->getContext());
983 // Find the loop boundaries.
984 const SCEV *ExitCount = SE->getExitCount(OrigLoop, OrigLoop->getLoopLatch());
985 assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
987 // Get the total trip count from the count by adding 1.
988 ExitCount = SE->getAddExpr(ExitCount,
989 SE->getConstant(ExitCount->getType(), 1));
991 // Expand the trip count and place the new instructions in the preheader.
992 // Notice that the pre-header does not change, only the loop body.
993 SCEVExpander Exp(*SE, "induction");
995 // Count holds the overall loop count (N).
996 Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
997 BypassBlock->getTerminator());
999 // The loop index does not have to start at Zero. Find the original start
1000 // value from the induction PHI node. If we don't have an induction variable
1001 // then we know that it starts at zero.
1002 Value *StartIdx = OldInduction ?
1003 OldInduction->getIncomingValueForBlock(BypassBlock):
1004 ConstantInt::get(IdxTy, 0);
1006 assert(BypassBlock && "Invalid loop structure");
1008 // Generate the code that checks in runtime if arrays overlap.
1009 Value *MemoryRuntimeCheck = addRuntimeCheck(Legal,
1010 BypassBlock->getTerminator());
1012 // Split the single block loop into the two loop structure described above.
1013 BasicBlock *VectorPH =
1014 BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
1015 BasicBlock *VecBody =
1016 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
1017 BasicBlock *MiddleBlock =
1018 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
1019 BasicBlock *ScalarPH =
1020 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
1022 // This is the location in which we add all of the logic for bypassing
1023 // the new vector loop.
1024 Instruction *Loc = BypassBlock->getTerminator();
1026 // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
1028 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
1030 // Generate the induction variable.
1031 Induction = Builder.CreatePHI(IdxTy, 2, "index");
1032 // The loop step is equal to the vectorization factor (num of SIMD elements)
1033 // times the unroll factor (num of SIMD instructions).
1034 Constant *Step = ConstantInt::get(IdxTy, VF * UF);
1036 // We may need to extend the index in case there is a type mismatch.
1037 // We know that the count starts at zero and does not overflow.
1038 if (Count->getType() != IdxTy) {
1039 // The exit count can be of pointer type. Convert it to the correct
1041 if (ExitCount->getType()->isPointerTy())
1042 Count = CastInst::CreatePointerCast(Count, IdxTy, "ptrcnt.to.int", Loc);
1044 Count = CastInst::CreateZExtOrBitCast(Count, IdxTy, "zext.cnt", Loc);
1047 // Add the start index to the loop count to get the new end index.
1048 Value *IdxEnd = BinaryOperator::CreateAdd(Count, StartIdx, "end.idx", Loc);
1050 // Now we need to generate the expression for N - (N % VF), which is
1051 // the part that the vectorized body will execute.
1052 Value *R = BinaryOperator::CreateURem(Count, Step, "n.mod.vf", Loc);
1053 Value *CountRoundDown = BinaryOperator::CreateSub(Count, R, "n.vec", Loc);
1054 Value *IdxEndRoundDown = BinaryOperator::CreateAdd(CountRoundDown, StartIdx,
1055 "end.idx.rnd.down", Loc);
1057 // Now, compare the new count to zero. If it is zero skip the vector loop and
1058 // jump to the scalar loop.
1059 Value *Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
1064 // If we are using memory runtime checks, include them in.
1065 if (MemoryRuntimeCheck)
1066 Cmp = BinaryOperator::Create(Instruction::Or, Cmp, MemoryRuntimeCheck,
1069 BranchInst::Create(MiddleBlock, VectorPH, Cmp, Loc);
1070 // Remove the old terminator.
1071 Loc->eraseFromParent();
1073 // We are going to resume the execution of the scalar loop.
1074 // Go over all of the induction variables that we found and fix the
1075 // PHIs that are left in the scalar version of the loop.
1076 // The starting values of PHI nodes depend on the counter of the last
1077 // iteration in the vectorized loop.
1078 // If we come from a bypass edge then we need to start from the original
1081 // This variable saves the new starting index for the scalar loop.
1082 PHINode *ResumeIndex = 0;
1083 LoopVectorizationLegality::InductionList::iterator I, E;
1084 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
1085 for (I = List->begin(), E = List->end(); I != E; ++I) {
1086 PHINode *OrigPhi = I->first;
1087 LoopVectorizationLegality::InductionInfo II = I->second;
1088 PHINode *ResumeVal = PHINode::Create(OrigPhi->getType(), 2, "resume.val",
1089 MiddleBlock->getTerminator());
1090 Value *EndValue = 0;
1092 case LoopVectorizationLegality::IK_NoInduction:
1093 llvm_unreachable("Unknown induction");
1094 case LoopVectorizationLegality::IK_IntInduction: {
1095 // Handle the integer induction counter:
1096 assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
1097 assert(OrigPhi == OldInduction && "Unknown integer PHI");
1098 // We know what the end value is.
1099 EndValue = IdxEndRoundDown;
1100 // We also know which PHI node holds it.
1101 ResumeIndex = ResumeVal;
1104 case LoopVectorizationLegality::IK_ReverseIntInduction: {
1105 // Convert the CountRoundDown variable to the PHI size.
1106 unsigned CRDSize = CountRoundDown->getType()->getScalarSizeInBits();
1107 unsigned IISize = II.StartValue->getType()->getScalarSizeInBits();
1108 Value *CRD = CountRoundDown;
1109 if (CRDSize > IISize)
1110 CRD = CastInst::Create(Instruction::Trunc, CountRoundDown,
1111 II.StartValue->getType(),
1112 "tr.crd", BypassBlock->getTerminator());
1113 else if (CRDSize < IISize)
1114 CRD = CastInst::Create(Instruction::SExt, CountRoundDown,
1115 II.StartValue->getType(),
1116 "sext.crd", BypassBlock->getTerminator());
1117 // Handle reverse integer induction counter:
1118 EndValue = BinaryOperator::CreateSub(II.StartValue, CRD, "rev.ind.end",
1119 BypassBlock->getTerminator());
1122 case LoopVectorizationLegality::IK_PtrInduction: {
1123 // For pointer induction variables, calculate the offset using
1125 EndValue = GetElementPtrInst::Create(II.StartValue, CountRoundDown,
1127 BypassBlock->getTerminator());
1132 // The new PHI merges the original incoming value, in case of a bypass,
1133 // or the value at the end of the vectorized loop.
1134 ResumeVal->addIncoming(II.StartValue, BypassBlock);
1135 ResumeVal->addIncoming(EndValue, VecBody);
1137 // Fix the scalar body counter (PHI node).
1138 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
1139 OrigPhi->setIncomingValue(BlockIdx, ResumeVal);
1142 // If we are generating a new induction variable then we also need to
1143 // generate the code that calculates the exit value. This value is not
1144 // simply the end of the counter because we may skip the vectorized body
1145 // in case of a runtime check.
1147 assert(!ResumeIndex && "Unexpected resume value found");
1148 ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
1149 MiddleBlock->getTerminator());
1150 ResumeIndex->addIncoming(StartIdx, BypassBlock);
1151 ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
1154 // Make sure that we found the index where scalar loop needs to continue.
1155 assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
1156 "Invalid resume Index");
1158 // Add a check in the middle block to see if we have completed
1159 // all of the iterations in the first vector loop.
1160 // If (N - N%VF) == N, then we *don't* need to run the remainder.
1161 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
1162 ResumeIndex, "cmp.n",
1163 MiddleBlock->getTerminator());
1165 BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
1166 // Remove the old terminator.
1167 MiddleBlock->getTerminator()->eraseFromParent();
1169 // Create i+1 and fill the PHINode.
1170 Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
1171 Induction->addIncoming(StartIdx, VectorPH);
1172 Induction->addIncoming(NextIdx, VecBody);
1173 // Create the compare.
1174 Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
1175 Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
1177 // Now we have two terminators. Remove the old one from the block.
1178 VecBody->getTerminator()->eraseFromParent();
1180 // Get ready to start creating new instructions into the vectorized body.
1181 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
1183 // Create and register the new vector loop.
1184 Loop* Lp = new Loop();
1185 Loop *ParentLoop = OrigLoop->getParentLoop();
1187 // Insert the new loop into the loop nest and register the new basic blocks.
1189 ParentLoop->addChildLoop(Lp);
1190 ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
1191 ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
1192 ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
1194 LI->addTopLevelLoop(Lp);
1197 Lp->addBasicBlockToLoop(VecBody, LI->getBase());
1200 LoopVectorPreHeader = VectorPH;
1201 LoopScalarPreHeader = ScalarPH;
1202 LoopMiddleBlock = MiddleBlock;
1203 LoopExitBlock = ExitBlock;
1204 LoopVectorBody = VecBody;
1205 LoopScalarBody = OldBasicBlock;
1206 LoopBypassBlock = BypassBlock;
1209 /// This function returns the identity element (or neutral element) for
1210 /// the operation K.
1212 getReductionIdentity(LoopVectorizationLegality::ReductionKind K, Type *Tp) {
1214 case LoopVectorizationLegality:: RK_IntegerXor:
1215 case LoopVectorizationLegality:: RK_IntegerAdd:
1216 case LoopVectorizationLegality:: RK_IntegerOr:
1217 // Adding, Xoring, Oring zero to a number does not change it.
1218 return ConstantInt::get(Tp, 0);
1219 case LoopVectorizationLegality:: RK_IntegerMult:
1220 // Multiplying a number by 1 does not change it.
1221 return ConstantInt::get(Tp, 1);
1222 case LoopVectorizationLegality:: RK_IntegerAnd:
1223 // AND-ing a number with an all-1 value does not change it.
1224 return ConstantInt::get(Tp, -1, true);
1225 case LoopVectorizationLegality:: RK_FloatMult:
1226 // Multiplying a number by 1 does not change it.
1227 return ConstantFP::get(Tp, 1.0L);
1228 case LoopVectorizationLegality:: RK_FloatAdd:
1229 // Adding zero to a number does not change it.
1230 return ConstantFP::get(Tp, 0.0L);
1232 llvm_unreachable("Unknown reduction kind");
1237 isTriviallyVectorizableIntrinsic(Instruction *Inst) {
1238 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst);
1241 switch (II->getIntrinsicID()) {
1242 case Intrinsic::sqrt:
1243 case Intrinsic::sin:
1244 case Intrinsic::cos:
1245 case Intrinsic::exp:
1246 case Intrinsic::exp2:
1247 case Intrinsic::log:
1248 case Intrinsic::log10:
1249 case Intrinsic::log2:
1250 case Intrinsic::fabs:
1251 case Intrinsic::floor:
1252 case Intrinsic::ceil:
1253 case Intrinsic::trunc:
1254 case Intrinsic::rint:
1255 case Intrinsic::nearbyint:
1256 case Intrinsic::pow:
1257 case Intrinsic::fma:
1258 case Intrinsic::fmuladd:
1267 InnerLoopVectorizer::vectorizeLoop(LoopVectorizationLegality *Legal) {
1268 //===------------------------------------------------===//
1270 // Notice: any optimization or new instruction that go
1271 // into the code below should be also be implemented in
1274 //===------------------------------------------------===//
1275 BasicBlock &BB = *OrigLoop->getHeader();
1277 ConstantInt::get(IntegerType::getInt32Ty(BB.getContext()), 0);
1279 // In order to support reduction variables we need to be able to vectorize
1280 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
1281 // stages. First, we create a new vector PHI node with no incoming edges.
1282 // We use this value when we vectorize all of the instructions that use the
1283 // PHI. Next, after all of the instructions in the block are complete we
1284 // add the new incoming edges to the PHI. At this point all of the
1285 // instructions in the basic block are vectorized, so we can use them to
1286 // construct the PHI.
1287 PhiVector RdxPHIsToFix;
1289 // Scan the loop in a topological order to ensure that defs are vectorized
1291 LoopBlocksDFS DFS(OrigLoop);
1294 // Vectorize all of the blocks in the original loop.
1295 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
1296 be = DFS.endRPO(); bb != be; ++bb)
1297 vectorizeBlockInLoop(Legal, *bb, &RdxPHIsToFix);
1299 // At this point every instruction in the original loop is widened to
1300 // a vector form. We are almost done. Now, we need to fix the PHI nodes
1301 // that we vectorized. The PHI nodes are currently empty because we did
1302 // not want to introduce cycles. Notice that the remaining PHI nodes
1303 // that we need to fix are reduction variables.
1305 // Create the 'reduced' values for each of the induction vars.
1306 // The reduced values are the vector values that we scalarize and combine
1307 // after the loop is finished.
1308 for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
1310 PHINode *RdxPhi = *it;
1311 assert(RdxPhi && "Unable to recover vectorized PHI");
1313 // Find the reduction variable descriptor.
1314 assert(Legal->getReductionVars()->count(RdxPhi) &&
1315 "Unable to find the reduction variable");
1316 LoopVectorizationLegality::ReductionDescriptor RdxDesc =
1317 (*Legal->getReductionVars())[RdxPhi];
1319 // We need to generate a reduction vector from the incoming scalar.
1320 // To do so, we need to generate the 'identity' vector and overide
1321 // one of the elements with the incoming scalar reduction. We need
1322 // to do it in the vector-loop preheader.
1323 Builder.SetInsertPoint(LoopBypassBlock->getTerminator());
1325 // This is the vector-clone of the value that leaves the loop.
1326 VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
1327 Type *VecTy = VectorExit[0]->getType();
1329 // Find the reduction identity variable. Zero for addition, or, xor,
1330 // one for multiplication, -1 for And.
1331 Constant *Iden = getReductionIdentity(RdxDesc.Kind, VecTy->getScalarType());
1332 Constant *Identity = ConstantVector::getSplat(VF, Iden);
1334 // This vector is the Identity vector where the first element is the
1335 // incoming scalar reduction.
1336 Value *VectorStart = Builder.CreateInsertElement(Identity,
1337 RdxDesc.StartValue, Zero);
1339 // Fix the vector-loop phi.
1340 // We created the induction variable so we know that the
1341 // preheader is the first entry.
1342 BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
1344 // Reductions do not have to start at zero. They can start with
1345 // any loop invariant values.
1346 VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
1347 BasicBlock *Latch = OrigLoop->getLoopLatch();
1348 Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
1349 VectorParts &Val = getVectorValue(LoopVal);
1350 for (unsigned part = 0; part < UF; ++part) {
1351 // Make sure to add the reduction stat value only to the
1352 // first unroll part.
1353 Value *StartVal = (part == 0) ? VectorStart : Identity;
1354 cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal, VecPreheader);
1355 cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part], LoopVectorBody);
1358 // Before each round, move the insertion point right between
1359 // the PHIs and the values we are going to write.
1360 // This allows us to write both PHINodes and the extractelement
1362 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
1364 VectorParts RdxParts;
1365 for (unsigned part = 0; part < UF; ++part) {
1366 // This PHINode contains the vectorized reduction variable, or
1367 // the initial value vector, if we bypass the vector loop.
1368 VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr);
1369 PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
1370 Value *StartVal = (part == 0) ? VectorStart : Identity;
1371 NewPhi->addIncoming(StartVal, LoopBypassBlock);
1372 NewPhi->addIncoming(RdxExitVal[part], LoopVectorBody);
1373 RdxParts.push_back(NewPhi);
1376 // Reduce all of the unrolled parts into a single vector.
1377 Value *ReducedPartRdx = RdxParts[0];
1378 for (unsigned part = 1; part < UF; ++part) {
1379 switch (RdxDesc.Kind) {
1380 case LoopVectorizationLegality::RK_IntegerAdd:
1382 Builder.CreateAdd(RdxParts[part], ReducedPartRdx, "add.rdx");
1384 case LoopVectorizationLegality::RK_IntegerMult:
1386 Builder.CreateMul(RdxParts[part], ReducedPartRdx, "mul.rdx");
1388 case LoopVectorizationLegality::RK_IntegerOr:
1390 Builder.CreateOr(RdxParts[part], ReducedPartRdx, "or.rdx");
1392 case LoopVectorizationLegality::RK_IntegerAnd:
1394 Builder.CreateAnd(RdxParts[part], ReducedPartRdx, "and.rdx");
1396 case LoopVectorizationLegality::RK_IntegerXor:
1398 Builder.CreateXor(RdxParts[part], ReducedPartRdx, "xor.rdx");
1400 case LoopVectorizationLegality::RK_FloatMult:
1402 Builder.CreateFMul(RdxParts[part], ReducedPartRdx, "fmul.rdx");
1404 case LoopVectorizationLegality::RK_FloatAdd:
1406 Builder.CreateFAdd(RdxParts[part], ReducedPartRdx, "fadd.rdx");
1409 llvm_unreachable("Unknown reduction operation");
1414 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
1415 // and vector ops, reducing the set of values being computed by half each
1417 assert(isPowerOf2_32(VF) &&
1418 "Reduction emission only supported for pow2 vectors!");
1419 Value *TmpVec = ReducedPartRdx;
1420 SmallVector<Constant*, 32> ShuffleMask(VF, 0);
1421 for (unsigned i = VF; i != 1; i >>= 1) {
1422 // Move the upper half of the vector to the lower half.
1423 for (unsigned j = 0; j != i/2; ++j)
1424 ShuffleMask[j] = Builder.getInt32(i/2 + j);
1426 // Fill the rest of the mask with undef.
1427 std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
1428 UndefValue::get(Builder.getInt32Ty()));
1431 Builder.CreateShuffleVector(TmpVec,
1432 UndefValue::get(TmpVec->getType()),
1433 ConstantVector::get(ShuffleMask),
1436 // Emit the operation on the shuffled value.
1437 switch (RdxDesc.Kind) {
1438 case LoopVectorizationLegality::RK_IntegerAdd:
1439 TmpVec = Builder.CreateAdd(TmpVec, Shuf, "add.rdx");
1441 case LoopVectorizationLegality::RK_IntegerMult:
1442 TmpVec = Builder.CreateMul(TmpVec, Shuf, "mul.rdx");
1444 case LoopVectorizationLegality::RK_IntegerOr:
1445 TmpVec = Builder.CreateOr(TmpVec, Shuf, "or.rdx");
1447 case LoopVectorizationLegality::RK_IntegerAnd:
1448 TmpVec = Builder.CreateAnd(TmpVec, Shuf, "and.rdx");
1450 case LoopVectorizationLegality::RK_IntegerXor:
1451 TmpVec = Builder.CreateXor(TmpVec, Shuf, "xor.rdx");
1453 case LoopVectorizationLegality::RK_FloatMult:
1454 TmpVec = Builder.CreateFMul(TmpVec, Shuf, "fmul.rdx");
1456 case LoopVectorizationLegality::RK_FloatAdd:
1457 TmpVec = Builder.CreateFAdd(TmpVec, Shuf, "fadd.rdx");
1460 llvm_unreachable("Unknown reduction operation");
1464 // The result is in the first element of the vector.
1465 Value *Scalar0 = Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
1467 // Now, we need to fix the users of the reduction variable
1468 // inside and outside of the scalar remainder loop.
1469 // We know that the loop is in LCSSA form. We need to update the
1470 // PHI nodes in the exit blocks.
1471 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
1472 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
1473 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
1474 if (!LCSSAPhi) continue;
1476 // All PHINodes need to have a single entry edge, or two if
1477 // we already fixed them.
1478 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
1480 // We found our reduction value exit-PHI. Update it with the
1481 // incoming bypass edge.
1482 if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
1483 // Add an edge coming from the bypass.
1484 LCSSAPhi->addIncoming(Scalar0, LoopMiddleBlock);
1487 }// end of the LCSSA phi scan.
1489 // Fix the scalar loop reduction variable with the incoming reduction sum
1490 // from the vector body and from the backedge value.
1491 int IncomingEdgeBlockIdx =
1492 (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
1493 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
1494 // Pick the other block.
1495 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
1496 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, Scalar0);
1497 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
1498 }// end of for each redux variable.
1500 // The Loop exit block may have single value PHI nodes where the incoming
1501 // value is 'undef'. While vectorizing we only handled real values that
1502 // were defined inside the loop. Here we handle the 'undef case'.
1504 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
1505 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
1506 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
1507 if (!LCSSAPhi) continue;
1508 if (LCSSAPhi->getNumIncomingValues() == 1)
1509 LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
1514 InnerLoopVectorizer::VectorParts
1515 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
1516 assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
1519 VectorParts SrcMask = createBlockInMask(Src);
1521 // The terminator has to be a branch inst!
1522 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
1523 assert(BI && "Unexpected terminator found");
1525 if (BI->isConditional()) {
1526 VectorParts EdgeMask = getVectorValue(BI->getCondition());
1528 if (BI->getSuccessor(0) != Dst)
1529 for (unsigned part = 0; part < UF; ++part)
1530 EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
1532 for (unsigned part = 0; part < UF; ++part)
1533 EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
1540 InnerLoopVectorizer::VectorParts
1541 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
1542 assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
1544 // Loop incoming mask is all-one.
1545 if (OrigLoop->getHeader() == BB) {
1546 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
1547 return getVectorValue(C);
1550 // This is the block mask. We OR all incoming edges, and with zero.
1551 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
1552 VectorParts BlockMask = getVectorValue(Zero);
1555 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
1556 VectorParts EM = createEdgeMask(*it, BB);
1557 for (unsigned part = 0; part < UF; ++part)
1558 BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
1565 InnerLoopVectorizer::vectorizeBlockInLoop(LoopVectorizationLegality *Legal,
1566 BasicBlock *BB, PhiVector *PV) {
1567 Constant *Zero = Builder.getInt32(0);
1569 // For each instruction in the old loop.
1570 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1571 VectorParts &Entry = WidenMap.get(it);
1572 switch (it->getOpcode()) {
1573 case Instruction::Br:
1574 // Nothing to do for PHIs and BR, since we already took care of the
1575 // loop control flow instructions.
1577 case Instruction::PHI:{
1578 PHINode* P = cast<PHINode>(it);
1579 // Handle reduction variables:
1580 if (Legal->getReductionVars()->count(P)) {
1581 for (unsigned part = 0; part < UF; ++part) {
1582 // This is phase one of vectorizing PHIs.
1583 Type *VecTy = VectorType::get(it->getType(), VF);
1584 Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
1585 LoopVectorBody-> getFirstInsertionPt());
1591 // Check for PHI nodes that are lowered to vector selects.
1592 if (P->getParent() != OrigLoop->getHeader()) {
1593 // We know that all PHIs in non header blocks are converted into
1594 // selects, so we don't have to worry about the insertion order and we
1595 // can just use the builder.
1597 // At this point we generate the predication tree. There may be
1598 // duplications since this is a simple recursive scan, but future
1599 // optimizations will clean it up.
1600 VectorParts Cond = createEdgeMask(P->getIncomingBlock(0),
1603 for (unsigned part = 0; part < UF; ++part) {
1604 VectorParts &In0 = getVectorValue(P->getIncomingValue(0));
1605 VectorParts &In1 = getVectorValue(P->getIncomingValue(1));
1606 Entry[part] = Builder.CreateSelect(Cond[part], In0[part], In1[part],
1612 // This PHINode must be an induction variable.
1613 // Make sure that we know about it.
1614 assert(Legal->getInductionVars()->count(P) &&
1615 "Not an induction variable");
1617 LoopVectorizationLegality::InductionInfo II =
1618 Legal->getInductionVars()->lookup(P);
1621 case LoopVectorizationLegality::IK_NoInduction:
1622 llvm_unreachable("Unknown induction");
1623 case LoopVectorizationLegality::IK_IntInduction: {
1624 assert(P == OldInduction && "Unexpected PHI");
1625 Value *Broadcasted = getBroadcastInstrs(Induction);
1626 // After broadcasting the induction variable we need to make the
1627 // vector consecutive by adding 0, 1, 2 ...
1628 for (unsigned part = 0; part < UF; ++part)
1629 Entry[part] = getConsecutiveVector(Broadcasted, VF * part, false);
1632 case LoopVectorizationLegality::IK_ReverseIntInduction:
1633 case LoopVectorizationLegality::IK_PtrInduction:
1634 // Handle reverse integer and pointer inductions.
1635 Value *StartIdx = 0;
1636 // If we have a single integer induction variable then use it.
1637 // Otherwise, start counting at zero.
1639 LoopVectorizationLegality::InductionInfo OldII =
1640 Legal->getInductionVars()->lookup(OldInduction);
1641 StartIdx = OldII.StartValue;
1643 StartIdx = ConstantInt::get(Induction->getType(), 0);
1645 // This is the normalized GEP that starts counting at zero.
1646 Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
1649 // Handle the reverse integer induction variable case.
1650 if (LoopVectorizationLegality::IK_ReverseIntInduction == II.IK) {
1651 IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType());
1652 Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy,
1654 Value *ReverseInd = Builder.CreateSub(II.StartValue, CNI,
1657 // This is a new value so do not hoist it out.
1658 Value *Broadcasted = getBroadcastInstrs(ReverseInd);
1659 // After broadcasting the induction variable we need to make the
1660 // vector consecutive by adding ... -3, -2, -1, 0.
1661 for (unsigned part = 0; part < UF; ++part)
1662 Entry[part] = getConsecutiveVector(Broadcasted, -VF * part, true);
1666 // Handle the pointer induction variable case.
1667 assert(P->getType()->isPointerTy() && "Unexpected type.");
1669 // This is the vector of results. Notice that we don't generate
1670 // vector geps because scalar geps result in better code.
1671 for (unsigned part = 0; part < UF; ++part) {
1672 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
1673 for (unsigned int i = 0; i < VF; ++i) {
1674 Constant *Idx = ConstantInt::get(Induction->getType(),
1676 Value *GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx,
1678 Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
1680 VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
1681 Builder.getInt32(i),
1684 Entry[part] = VecVal;
1691 case Instruction::Add:
1692 case Instruction::FAdd:
1693 case Instruction::Sub:
1694 case Instruction::FSub:
1695 case Instruction::Mul:
1696 case Instruction::FMul:
1697 case Instruction::UDiv:
1698 case Instruction::SDiv:
1699 case Instruction::FDiv:
1700 case Instruction::URem:
1701 case Instruction::SRem:
1702 case Instruction::FRem:
1703 case Instruction::Shl:
1704 case Instruction::LShr:
1705 case Instruction::AShr:
1706 case Instruction::And:
1707 case Instruction::Or:
1708 case Instruction::Xor: {
1709 // Just widen binops.
1710 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
1711 VectorParts &A = getVectorValue(it->getOperand(0));
1712 VectorParts &B = getVectorValue(it->getOperand(1));
1714 // Use this vector value for all users of the original instruction.
1715 for (unsigned Part = 0; Part < UF; ++Part) {
1716 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
1718 // Update the NSW, NUW and Exact flags.
1719 BinaryOperator *VecOp = cast<BinaryOperator>(V);
1720 if (isa<OverflowingBinaryOperator>(BinOp)) {
1721 VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap());
1722 VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap());
1724 if (isa<PossiblyExactOperator>(VecOp))
1725 VecOp->setIsExact(BinOp->isExact());
1731 case Instruction::Select: {
1733 // If the selector is loop invariant we can create a select
1734 // instruction with a scalar condition. Otherwise, use vector-select.
1735 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
1738 // The condition can be loop invariant but still defined inside the
1739 // loop. This means that we can't just use the original 'cond' value.
1740 // We have to take the 'vectorized' value and pick the first lane.
1741 // Instcombine will make this a no-op.
1742 VectorParts &Cond = getVectorValue(it->getOperand(0));
1743 VectorParts &Op0 = getVectorValue(it->getOperand(1));
1744 VectorParts &Op1 = getVectorValue(it->getOperand(2));
1745 Value *ScalarCond = Builder.CreateExtractElement(Cond[0],
1746 Builder.getInt32(0));
1747 for (unsigned Part = 0; Part < UF; ++Part) {
1748 Entry[Part] = Builder.CreateSelect(
1749 InvariantCond ? ScalarCond : Cond[Part],
1756 case Instruction::ICmp:
1757 case Instruction::FCmp: {
1758 // Widen compares. Generate vector compares.
1759 bool FCmp = (it->getOpcode() == Instruction::FCmp);
1760 CmpInst *Cmp = dyn_cast<CmpInst>(it);
1761 VectorParts &A = getVectorValue(it->getOperand(0));
1762 VectorParts &B = getVectorValue(it->getOperand(1));
1763 for (unsigned Part = 0; Part < UF; ++Part) {
1766 C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
1768 C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
1774 case Instruction::Store: {
1775 // Attempt to issue a wide store.
1776 StoreInst *SI = dyn_cast<StoreInst>(it);
1777 Type *StTy = VectorType::get(SI->getValueOperand()->getType(), VF);
1778 Value *Ptr = SI->getPointerOperand();
1779 unsigned Alignment = SI->getAlignment();
1781 assert(!Legal->isUniform(Ptr) &&
1782 "We do not allow storing to uniform addresses");
1785 int Stride = Legal->isConsecutivePtr(Ptr);
1786 bool Reverse = Stride < 0;
1788 scalarizeInstruction(it);
1792 // Handle consecutive stores.
1794 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1796 // The last index does not have to be the induction. It can be
1797 // consecutive and be a function of the index. For example A[I+1];
1798 unsigned NumOperands = Gep->getNumOperands();
1800 Value *LastGepOperand = Gep->getOperand(NumOperands - 1);
1801 VectorParts &GEPParts = getVectorValue(LastGepOperand);
1802 Value *LastIndex = GEPParts[0];
1803 LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
1805 // Create the new GEP with the new induction variable.
1806 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1807 Gep2->setOperand(NumOperands - 1, LastIndex);
1808 Ptr = Builder.Insert(Gep2);
1810 // Use the induction element ptr.
1811 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1812 VectorParts &PtrVal = getVectorValue(Ptr);
1813 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
1816 VectorParts &StoredVal = getVectorValue(SI->getValueOperand());
1817 for (unsigned Part = 0; Part < UF; ++Part) {
1818 // Calculate the pointer for the specific unroll-part.
1819 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1822 // If we store to reverse consecutive memory locations then we need
1823 // to reverse the order of elements in the stored value.
1824 StoredVal[Part] = reverseVector(StoredVal[Part]);
1825 // If the address is consecutive but reversed, then the
1826 // wide store needs to start at the last vector element.
1827 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1828 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1831 Value *VecPtr = Builder.CreateBitCast(PartPtr, StTy->getPointerTo());
1832 Builder.CreateStore(StoredVal[Part], VecPtr)->setAlignment(Alignment);
1836 case Instruction::Load: {
1837 // Attempt to issue a wide load.
1838 LoadInst *LI = dyn_cast<LoadInst>(it);
1839 Type *RetTy = VectorType::get(LI->getType(), VF);
1840 Value *Ptr = LI->getPointerOperand();
1841 unsigned Alignment = LI->getAlignment();
1843 // If the pointer is loop invariant or if it is non consecutive,
1844 // scalarize the load.
1845 int Stride = Legal->isConsecutivePtr(Ptr);
1846 bool Reverse = Stride < 0;
1847 if (Legal->isUniform(Ptr) || Stride == 0) {
1848 scalarizeInstruction(it);
1852 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1854 // The last index does not have to be the induction. It can be
1855 // consecutive and be a function of the index. For example A[I+1];
1856 unsigned NumOperands = Gep->getNumOperands();
1858 Value *LastGepOperand = Gep->getOperand(NumOperands - 1);
1859 VectorParts &GEPParts = getVectorValue(LastGepOperand);
1860 Value *LastIndex = GEPParts[0];
1861 LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
1863 // Create the new GEP with the new induction variable.
1864 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1865 Gep2->setOperand(NumOperands - 1, LastIndex);
1866 Ptr = Builder.Insert(Gep2);
1868 // Use the induction element ptr.
1869 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1870 VectorParts &PtrVal = getVectorValue(Ptr);
1871 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
1874 for (unsigned Part = 0; Part < UF; ++Part) {
1875 // Calculate the pointer for the specific unroll-part.
1876 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1879 // If the address is consecutive but reversed, then the
1880 // wide store needs to start at the last vector element.
1881 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1882 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1885 Value *VecPtr = Builder.CreateBitCast(PartPtr, RetTy->getPointerTo());
1886 Value *LI = Builder.CreateLoad(VecPtr, "wide.load");
1887 cast<LoadInst>(LI)->setAlignment(Alignment);
1888 Entry[Part] = Reverse ? reverseVector(LI) : LI;
1892 case Instruction::ZExt:
1893 case Instruction::SExt:
1894 case Instruction::FPToUI:
1895 case Instruction::FPToSI:
1896 case Instruction::FPExt:
1897 case Instruction::PtrToInt:
1898 case Instruction::IntToPtr:
1899 case Instruction::SIToFP:
1900 case Instruction::UIToFP:
1901 case Instruction::Trunc:
1902 case Instruction::FPTrunc:
1903 case Instruction::BitCast: {
1904 CastInst *CI = dyn_cast<CastInst>(it);
1905 /// Optimize the special case where the source is the induction
1906 /// variable. Notice that we can only optimize the 'trunc' case
1907 /// because: a. FP conversions lose precision, b. sext/zext may wrap,
1908 /// c. other casts depend on pointer size.
1909 if (CI->getOperand(0) == OldInduction &&
1910 it->getOpcode() == Instruction::Trunc) {
1911 Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
1913 Value *Broadcasted = getBroadcastInstrs(ScalarCast);
1914 for (unsigned Part = 0; Part < UF; ++Part)
1915 Entry[Part] = getConsecutiveVector(Broadcasted, VF * Part, false);
1918 /// Vectorize casts.
1919 Type *DestTy = VectorType::get(CI->getType()->getScalarType(), VF);
1921 VectorParts &A = getVectorValue(it->getOperand(0));
1922 for (unsigned Part = 0; Part < UF; ++Part)
1923 Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
1927 case Instruction::Call: {
1928 assert(isTriviallyVectorizableIntrinsic(it));
1929 Module *M = BB->getParent()->getParent();
1930 IntrinsicInst *II = cast<IntrinsicInst>(it);
1931 Intrinsic::ID ID = II->getIntrinsicID();
1932 for (unsigned Part = 0; Part < UF; ++Part) {
1933 SmallVector<Value*, 4> Args;
1934 for (unsigned i = 0, ie = II->getNumArgOperands(); i != ie; ++i) {
1935 VectorParts &Arg = getVectorValue(II->getArgOperand(i));
1936 Args.push_back(Arg[Part]);
1938 Type *Tys[] = { VectorType::get(II->getType()->getScalarType(), VF) };
1939 Function *F = Intrinsic::getDeclaration(M, ID, Tys);
1940 Entry[Part] = Builder.CreateCall(F, Args);
1946 // All other instructions are unsupported. Scalarize them.
1947 scalarizeInstruction(it);
1950 }// end of for_each instr.
1953 void InnerLoopVectorizer::updateAnalysis() {
1954 // Forget the original basic block.
1955 SE->forgetLoop(OrigLoop);
1957 // Update the dominator tree information.
1958 assert(DT->properlyDominates(LoopBypassBlock, LoopExitBlock) &&
1959 "Entry does not dominate exit.");
1961 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlock);
1962 DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader);
1963 DT->addNewBlock(LoopMiddleBlock, LoopBypassBlock);
1964 DT->addNewBlock(LoopScalarPreHeader, LoopMiddleBlock);
1965 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
1966 DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
1968 DEBUG(DT->verifyAnalysis());
1971 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
1972 if (!EnableIfConversion)
1975 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
1976 std::vector<BasicBlock*> &LoopBlocks = TheLoop->getBlocksVector();
1978 // Collect the blocks that need predication.
1979 for (unsigned i = 0, e = LoopBlocks.size(); i < e; ++i) {
1980 BasicBlock *BB = LoopBlocks[i];
1982 // We don't support switch statements inside loops.
1983 if (!isa<BranchInst>(BB->getTerminator()))
1986 // We must have at most two predecessors because we need to convert
1987 // all PHIs to selects.
1988 unsigned Preds = std::distance(pred_begin(BB), pred_end(BB));
1992 // We must be able to predicate all blocks that need to be predicated.
1993 if (blockNeedsPredication(BB) && !blockCanBePredicated(BB))
1997 // We can if-convert this loop.
2001 bool LoopVectorizationLegality::canVectorize() {
2002 assert(TheLoop->getLoopPreheader() && "No preheader!!");
2004 // We can only vectorize innermost loops.
2005 if (TheLoop->getSubLoopsVector().size())
2008 // We must have a single backedge.
2009 if (TheLoop->getNumBackEdges() != 1)
2012 // We must have a single exiting block.
2013 if (!TheLoop->getExitingBlock())
2016 unsigned NumBlocks = TheLoop->getNumBlocks();
2018 // Check if we can if-convert non single-bb loops.
2019 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
2020 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
2024 // We need to have a loop header.
2025 BasicBlock *Latch = TheLoop->getLoopLatch();
2026 DEBUG(dbgs() << "LV: Found a loop: " <<
2027 TheLoop->getHeader()->getName() << "\n");
2029 // ScalarEvolution needs to be able to find the exit count.
2030 const SCEV *ExitCount = SE->getExitCount(TheLoop, Latch);
2031 if (ExitCount == SE->getCouldNotCompute()) {
2032 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
2036 // Do not loop-vectorize loops with a tiny trip count.
2037 unsigned TC = SE->getSmallConstantTripCount(TheLoop, Latch);
2038 if (TC > 0u && TC < TinyTripCountVectorThreshold) {
2039 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " <<
2040 "This loop is not worth vectorizing.\n");
2044 // Check if we can vectorize the instructions and CFG in this loop.
2045 if (!canVectorizeInstrs()) {
2046 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
2050 // Go over each instruction and look at memory deps.
2051 if (!canVectorizeMemory()) {
2052 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
2056 // Collect all of the variables that remain uniform after vectorization.
2057 collectLoopUniforms();
2059 DEBUG(dbgs() << "LV: We can vectorize this loop" <<
2060 (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
2063 // Okay! We can vectorize. At this point we don't have any other mem analysis
2064 // which may limit our maximum vectorization factor, so just return true with
2069 bool LoopVectorizationLegality::canVectorizeInstrs() {
2070 BasicBlock *PreHeader = TheLoop->getLoopPreheader();
2071 BasicBlock *Header = TheLoop->getHeader();
2073 // For each block in the loop.
2074 for (Loop::block_iterator bb = TheLoop->block_begin(),
2075 be = TheLoop->block_end(); bb != be; ++bb) {
2077 // Scan the instructions in the block and look for hazards.
2078 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
2081 if (PHINode *Phi = dyn_cast<PHINode>(it)) {
2082 // This should not happen because the loop should be normalized.
2083 if (Phi->getNumIncomingValues() != 2) {
2084 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
2088 // Check that this PHI type is allowed.
2089 if (!Phi->getType()->isIntegerTy() &&
2090 !Phi->getType()->isFloatingPointTy() &&
2091 !Phi->getType()->isPointerTy()) {
2092 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
2096 // If this PHINode is not in the header block, then we know that we
2097 // can convert it to select during if-conversion. No need to check if
2098 // the PHIs in this block are induction or reduction variables.
2102 // This is the value coming from the preheader.
2103 Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
2104 // Check if this is an induction variable.
2105 InductionKind IK = isInductionVariable(Phi);
2107 if (IK_NoInduction != IK) {
2108 // Int inductions are special because we only allow one IV.
2109 if (IK == IK_IntInduction) {
2111 DEBUG(dbgs() << "LV: Found too many inductions."<< *Phi <<"\n");
2117 DEBUG(dbgs() << "LV: Found an induction variable.\n");
2118 Inductions[Phi] = InductionInfo(StartValue, IK);
2122 if (AddReductionVar(Phi, RK_IntegerAdd)) {
2123 DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
2126 if (AddReductionVar(Phi, RK_IntegerMult)) {
2127 DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
2130 if (AddReductionVar(Phi, RK_IntegerOr)) {
2131 DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
2134 if (AddReductionVar(Phi, RK_IntegerAnd)) {
2135 DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
2138 if (AddReductionVar(Phi, RK_IntegerXor)) {
2139 DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
2142 if (AddReductionVar(Phi, RK_FloatMult)) {
2143 DEBUG(dbgs() << "LV: Found an FMult reduction PHI."<< *Phi <<"\n");
2146 if (AddReductionVar(Phi, RK_FloatAdd)) {
2147 DEBUG(dbgs() << "LV: Found an FAdd reduction PHI."<< *Phi <<"\n");
2151 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
2153 }// end of PHI handling
2155 // We still don't handle functions.
2156 CallInst *CI = dyn_cast<CallInst>(it);
2157 if (CI && !isTriviallyVectorizableIntrinsic(it)) {
2158 DEBUG(dbgs() << "LV: Found a call site.\n");
2162 // Check that the instruction return type is vectorizable.
2163 if (!VectorType::isValidElementType(it->getType()) &&
2164 !it->getType()->isVoidTy()) {
2165 DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n");
2169 // Check that the stored type is vectorizable.
2170 if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
2171 Type *T = ST->getValueOperand()->getType();
2172 if (!VectorType::isValidElementType(T))
2176 // Reduction instructions are allowed to have exit users.
2177 // All other instructions must not have external users.
2178 if (!AllowedExit.count(it))
2179 //Check that all of the users of the loop are inside the BB.
2180 for (Value::use_iterator I = it->use_begin(), E = it->use_end();
2182 Instruction *U = cast<Instruction>(*I);
2183 // This user may be a reduction exit value.
2184 if (!TheLoop->contains(U)) {
2185 DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n");
2194 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
2195 assert(getInductionVars()->size() && "No induction variables");
2201 void LoopVectorizationLegality::collectLoopUniforms() {
2202 // We now know that the loop is vectorizable!
2203 // Collect variables that will remain uniform after vectorization.
2204 std::vector<Value*> Worklist;
2205 BasicBlock *Latch = TheLoop->getLoopLatch();
2207 // Start with the conditional branch and walk up the block.
2208 Worklist.push_back(Latch->getTerminator()->getOperand(0));
2210 while (Worklist.size()) {
2211 Instruction *I = dyn_cast<Instruction>(Worklist.back());
2212 Worklist.pop_back();
2214 // Look at instructions inside this loop.
2215 // Stop when reaching PHI nodes.
2216 // TODO: we need to follow values all over the loop, not only in this block.
2217 if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
2220 // This is a known uniform.
2223 // Insert all operands.
2224 for (int i = 0, Op = I->getNumOperands(); i < Op; ++i) {
2225 Worklist.push_back(I->getOperand(i));
2230 bool LoopVectorizationLegality::canVectorizeMemory() {
2231 typedef SmallVector<Value*, 16> ValueVector;
2232 typedef SmallPtrSet<Value*, 16> ValueSet;
2233 // Holds the Load and Store *instructions*.
2236 PtrRtCheck.Pointers.clear();
2237 PtrRtCheck.Need = false;
2240 for (Loop::block_iterator bb = TheLoop->block_begin(),
2241 be = TheLoop->block_end(); bb != be; ++bb) {
2243 // Scan the BB and collect legal loads and stores.
2244 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
2247 // If this is a load, save it. If this instruction can read from memory
2248 // but is not a load, then we quit. Notice that we don't handle function
2249 // calls that read or write.
2250 if (it->mayReadFromMemory()) {
2251 LoadInst *Ld = dyn_cast<LoadInst>(it);
2252 if (!Ld) return false;
2253 if (!Ld->isSimple()) {
2254 DEBUG(dbgs() << "LV: Found a non-simple load.\n");
2257 Loads.push_back(Ld);
2261 // Save 'store' instructions. Abort if other instructions write to memory.
2262 if (it->mayWriteToMemory()) {
2263 StoreInst *St = dyn_cast<StoreInst>(it);
2264 if (!St) return false;
2265 if (!St->isSimple()) {
2266 DEBUG(dbgs() << "LV: Found a non-simple store.\n");
2269 Stores.push_back(St);
2274 // Now we have two lists that hold the loads and the stores.
2275 // Next, we find the pointers that they use.
2277 // Check if we see any stores. If there are no stores, then we don't
2278 // care if the pointers are *restrict*.
2279 if (!Stores.size()) {
2280 DEBUG(dbgs() << "LV: Found a read-only loop!\n");
2284 // Holds the read and read-write *pointers* that we find.
2286 ValueVector ReadWrites;
2288 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
2289 // multiple times on the same object. If the ptr is accessed twice, once
2290 // for read and once for write, it will only appear once (on the write
2291 // list). This is okay, since we are going to check for conflicts between
2292 // writes and between reads and writes, but not between reads and reads.
2295 ValueVector::iterator I, IE;
2296 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
2297 StoreInst *ST = cast<StoreInst>(*I);
2298 Value* Ptr = ST->getPointerOperand();
2300 if (isUniform(Ptr)) {
2301 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
2305 // If we did *not* see this pointer before, insert it to
2306 // the read-write list. At this phase it is only a 'write' list.
2307 if (Seen.insert(Ptr))
2308 ReadWrites.push_back(Ptr);
2311 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
2312 LoadInst *LD = cast<LoadInst>(*I);
2313 Value* Ptr = LD->getPointerOperand();
2314 // If we did *not* see this pointer before, insert it to the
2315 // read list. If we *did* see it before, then it is already in
2316 // the read-write list. This allows us to vectorize expressions
2317 // such as A[i] += x; Because the address of A[i] is a read-write
2318 // pointer. This only works if the index of A[i] is consecutive.
2319 // If the address of i is unknown (for example A[B[i]]) then we may
2320 // read a few words, modify, and write a few words, and some of the
2321 // words may be written to the same address.
2322 if (Seen.insert(Ptr) || 0 == isConsecutivePtr(Ptr))
2323 Reads.push_back(Ptr);
2326 // If we write (or read-write) to a single destination and there are no
2327 // other reads in this loop then is it safe to vectorize.
2328 if (ReadWrites.size() == 1 && Reads.size() == 0) {
2329 DEBUG(dbgs() << "LV: Found a write-only loop!\n");
2333 // Find pointers with computable bounds. We are going to use this information
2334 // to place a runtime bound check.
2335 bool CanDoRT = true;
2336 for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I)
2337 if (hasComputableBounds(*I)) {
2338 PtrRtCheck.insert(SE, TheLoop, *I);
2339 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n");
2344 for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I)
2345 if (hasComputableBounds(*I)) {
2346 PtrRtCheck.insert(SE, TheLoop, *I);
2347 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n");
2353 // Check that we did not collect too many pointers or found a
2354 // unsizeable pointer.
2355 if (!CanDoRT || PtrRtCheck.Pointers.size() > RuntimeMemoryCheckThreshold) {
2361 DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
2364 bool NeedRTCheck = false;
2366 // Now that the pointers are in two lists (Reads and ReadWrites), we
2367 // can check that there are no conflicts between each of the writes and
2368 // between the writes to the reads.
2369 ValueSet WriteObjects;
2370 ValueVector TempObjects;
2372 // Check that the read-writes do not conflict with other read-write
2374 bool AllWritesIdentified = true;
2375 for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I) {
2376 GetUnderlyingObjects(*I, TempObjects, DL);
2377 for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
2379 if (!isIdentifiedObject(*it)) {
2380 DEBUG(dbgs() << "LV: Found an unidentified write ptr:"<< **it <<"\n");
2382 AllWritesIdentified = false;
2384 if (!WriteObjects.insert(*it)) {
2385 DEBUG(dbgs() << "LV: Found a possible write-write reorder:"
2390 TempObjects.clear();
2393 /// Check that the reads don't conflict with the read-writes.
2394 for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I) {
2395 GetUnderlyingObjects(*I, TempObjects, DL);
2396 for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
2398 // If all of the writes are identified then we don't care if the read
2399 // pointer is identified or not.
2400 if (!AllWritesIdentified && !isIdentifiedObject(*it)) {
2401 DEBUG(dbgs() << "LV: Found an unidentified read ptr:"<< **it <<"\n");
2404 if (WriteObjects.count(*it)) {
2405 DEBUG(dbgs() << "LV: Found a possible read/write reorder:"
2410 TempObjects.clear();
2413 PtrRtCheck.Need = NeedRTCheck;
2414 if (NeedRTCheck && !CanDoRT) {
2415 DEBUG(dbgs() << "LV: We can't vectorize because we can't find " <<
2416 "the array bounds.\n");
2421 DEBUG(dbgs() << "LV: We "<< (NeedRTCheck ? "" : "don't") <<
2422 " need a runtime memory check.\n");
2426 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
2427 ReductionKind Kind) {
2428 if (Phi->getNumIncomingValues() != 2)
2431 // Reduction variables are only found in the loop header block.
2432 if (Phi->getParent() != TheLoop->getHeader())
2435 // Obtain the reduction start value from the value that comes from the loop
2437 Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
2439 // ExitInstruction is the single value which is used outside the loop.
2440 // We only allow for a single reduction value to be used outside the loop.
2441 // This includes users of the reduction, variables (which form a cycle
2442 // which ends in the phi node).
2443 Instruction *ExitInstruction = 0;
2444 // Indicates that we found a binary operation in our scan.
2445 bool FoundBinOp = false;
2447 // Iter is our iterator. We start with the PHI node and scan for all of the
2448 // users of this instruction. All users must be instructions that can be
2449 // used as reduction variables (such as ADD). We may have a single
2450 // out-of-block user. The cycle must end with the original PHI.
2451 Instruction *Iter = Phi;
2453 // If the instruction has no users then this is a broken
2454 // chain and can't be a reduction variable.
2455 if (Iter->use_empty())
2458 // Did we find a user inside this loop already ?
2459 bool FoundInBlockUser = false;
2460 // Did we reach the initial PHI node already ?
2461 bool FoundStartPHI = false;
2463 // Is this a bin op ?
2464 FoundBinOp |= !isa<PHINode>(Iter);
2466 // For each of the *users* of iter.
2467 for (Value::use_iterator it = Iter->use_begin(), e = Iter->use_end();
2469 Instruction *U = cast<Instruction>(*it);
2470 // We already know that the PHI is a user.
2472 FoundStartPHI = true;
2476 // Check if we found the exit user.
2477 BasicBlock *Parent = U->getParent();
2478 if (!TheLoop->contains(Parent)) {
2479 // Exit if you find multiple outside users.
2480 if (ExitInstruction != 0)
2482 ExitInstruction = Iter;
2485 // We allow in-loop PHINodes which are not the original reduction PHI
2486 // node. If this PHI is the only user of Iter (happens in IF w/ no ELSE
2487 // structure) then don't skip this PHI.
2488 if (isa<PHINode>(Iter) && isa<PHINode>(U) &&
2489 U->getParent() != TheLoop->getHeader() &&
2490 TheLoop->contains(U) &&
2491 Iter->getNumUses() > 1)
2494 // We can't have multiple inside users.
2495 if (FoundInBlockUser)
2497 FoundInBlockUser = true;
2499 // Any reduction instr must be of one of the allowed kinds.
2500 if (!isReductionInstr(U, Kind))
2503 // Reductions of instructions such as Div, and Sub is only
2504 // possible if the LHS is the reduction variable.
2505 if (!U->isCommutative() && !isa<PHINode>(U) && U->getOperand(0) != Iter)
2511 // We found a reduction var if we have reached the original
2512 // phi node and we only have a single instruction with out-of-loop
2514 if (FoundStartPHI) {
2515 // This instruction is allowed to have out-of-loop users.
2516 AllowedExit.insert(ExitInstruction);
2518 // Save the description of this reduction variable.
2519 ReductionDescriptor RD(RdxStart, ExitInstruction, Kind);
2520 Reductions[Phi] = RD;
2521 // We've ended the cycle. This is a reduction variable if we have an
2522 // outside user and it has a binary op.
2523 return FoundBinOp && ExitInstruction;
2529 LoopVectorizationLegality::isReductionInstr(Instruction *I,
2530 ReductionKind Kind) {
2531 bool FP = I->getType()->isFloatingPointTy();
2532 bool FastMath = (FP && I->isCommutative() && I->isAssociative());
2534 switch (I->getOpcode()) {
2537 case Instruction::PHI:
2538 if (FP && (Kind != RK_FloatMult && Kind != RK_FloatAdd))
2542 case Instruction::Sub:
2543 case Instruction::Add:
2544 return Kind == RK_IntegerAdd;
2545 case Instruction::SDiv:
2546 case Instruction::UDiv:
2547 case Instruction::Mul:
2548 return Kind == RK_IntegerMult;
2549 case Instruction::And:
2550 return Kind == RK_IntegerAnd;
2551 case Instruction::Or:
2552 return Kind == RK_IntegerOr;
2553 case Instruction::Xor:
2554 return Kind == RK_IntegerXor;
2555 case Instruction::FMul:
2556 return Kind == RK_FloatMult && FastMath;
2557 case Instruction::FAdd:
2558 return Kind == RK_FloatAdd && FastMath;
2562 LoopVectorizationLegality::InductionKind
2563 LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
2564 Type *PhiTy = Phi->getType();
2565 // We only handle integer and pointer inductions variables.
2566 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
2567 return IK_NoInduction;
2569 // Check that the PHI is consecutive and starts at zero.
2570 const SCEV *PhiScev = SE->getSCEV(Phi);
2571 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
2573 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
2574 return IK_NoInduction;
2576 const SCEV *Step = AR->getStepRecurrence(*SE);
2578 // Integer inductions need to have a stride of one.
2579 if (PhiTy->isIntegerTy()) {
2581 return IK_IntInduction;
2582 if (Step->isAllOnesValue())
2583 return IK_ReverseIntInduction;
2584 return IK_NoInduction;
2587 // Calculate the pointer stride and check if it is consecutive.
2588 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
2590 return IK_NoInduction;
2592 assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
2593 uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType());
2594 if (C->getValue()->equalsInt(Size))
2595 return IK_PtrInduction;
2597 return IK_NoInduction;
2600 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
2601 Value *In0 = const_cast<Value*>(V);
2602 PHINode *PN = dyn_cast_or_null<PHINode>(In0);
2606 return Inductions.count(PN);
2609 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
2610 assert(TheLoop->contains(BB) && "Unknown block used");
2612 // Blocks that do not dominate the latch need predication.
2613 BasicBlock* Latch = TheLoop->getLoopLatch();
2614 return !DT->dominates(BB, Latch);
2617 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB) {
2618 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2619 // We don't predicate loads/stores at the moment.
2620 if (it->mayReadFromMemory() || it->mayWriteToMemory() || it->mayThrow())
2623 // The instructions below can trap.
2624 switch (it->getOpcode()) {
2626 case Instruction::UDiv:
2627 case Instruction::SDiv:
2628 case Instruction::URem:
2629 case Instruction::SRem:
2637 bool LoopVectorizationLegality::hasComputableBounds(Value *Ptr) {
2638 const SCEV *PhiScev = SE->getSCEV(Ptr);
2639 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
2643 return AR->isAffine();
2647 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize,
2649 if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
2650 DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
2654 // Find the trip count.
2655 unsigned TC = SE->getSmallConstantTripCount(TheLoop, TheLoop->getLoopLatch());
2656 DEBUG(dbgs() << "LV: Found trip count:"<<TC<<"\n");
2658 unsigned VF = MaxVectorSize;
2660 // If we optimize the program for size, avoid creating the tail loop.
2662 // If we are unable to calculate the trip count then don't try to vectorize.
2664 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
2668 // Find the maximum SIMD width that can fit within the trip count.
2669 VF = TC % MaxVectorSize;
2674 // If the trip count that we found modulo the vectorization factor is not
2675 // zero then we require a tail.
2677 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
2683 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
2684 DEBUG(dbgs() << "LV: Using user VF "<<UserVF<<".\n");
2689 float Cost = expectedCost(1);
2691 DEBUG(dbgs() << "LV: Scalar loop costs: "<< (int)Cost << ".\n");
2692 for (unsigned i=2; i <= VF; i*=2) {
2693 // Notice that the vector loop needs to be executed less times, so
2694 // we need to divide the cost of the vector loops by the width of
2695 // the vector elements.
2696 float VectorCost = expectedCost(i) / (float)i;
2697 DEBUG(dbgs() << "LV: Vector loop of width "<< i << " costs: " <<
2698 (int)VectorCost << ".\n");
2699 if (VectorCost < Cost) {
2705 DEBUG(dbgs() << "LV: Selecting VF = : "<< Width << ".\n");
2710 LoopVectorizationCostModel::selectUnrollFactor(bool OptForSize,
2712 // Use the user preference, unless 'auto' is selected.
2716 // When we optimize for size we don't unroll.
2720 // Do not unroll loops with a relatively small trip count.
2721 unsigned TC = SE->getSmallConstantTripCount(TheLoop,
2722 TheLoop->getLoopLatch());
2723 if (TC > 1 && TC < TinyTripCountUnrollThreshold)
2726 unsigned TargetVectorRegisters = TTI.getNumberOfRegisters(true);
2727 DEBUG(dbgs() << "LV: The target has " << TargetVectorRegisters <<
2728 " vector registers\n");
2730 LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
2731 // We divide by these constants so assume that we have at least one
2732 // instruction that uses at least one register.
2733 R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
2734 R.NumInstructions = std::max(R.NumInstructions, 1U);
2736 // We calculate the unroll factor using the following formula.
2737 // Subtract the number of loop invariants from the number of available
2738 // registers. These registers are used by all of the unrolled instances.
2739 // Next, divide the remaining registers by the number of registers that is
2740 // required by the loop, in order to estimate how many parallel instances
2741 // fit without causing spills.
2742 unsigned UF = (TargetVectorRegisters - R.LoopInvariantRegs) / R.MaxLocalUsers;
2744 // We don't want to unroll the loops to the point where they do not fit into
2745 // the decoded cache. Assume that we only allow 32 IR instructions.
2746 UF = std::min(UF, (MaxLoopSizeThreshold / R.NumInstructions));
2748 // Clamp the unroll factor ranges to reasonable factors.
2749 if (UF > MaxUnrollSize)
2757 LoopVectorizationCostModel::RegisterUsage
2758 LoopVectorizationCostModel::calculateRegisterUsage() {
2759 // This function calculates the register usage by measuring the highest number
2760 // of values that are alive at a single location. Obviously, this is a very
2761 // rough estimation. We scan the loop in a topological order in order and
2762 // assign a number to each instruction. We use RPO to ensure that defs are
2763 // met before their users. We assume that each instruction that has in-loop
2764 // users starts an interval. We record every time that an in-loop value is
2765 // used, so we have a list of the first and last occurrences of each
2766 // instruction. Next, we transpose this data structure into a multi map that
2767 // holds the list of intervals that *end* at a specific location. This multi
2768 // map allows us to perform a linear search. We scan the instructions linearly
2769 // and record each time that a new interval starts, by placing it in a set.
2770 // If we find this value in the multi-map then we remove it from the set.
2771 // The max register usage is the maximum size of the set.
2772 // We also search for instructions that are defined outside the loop, but are
2773 // used inside the loop. We need this number separately from the max-interval
2774 // usage number because when we unroll, loop-invariant values do not take
2776 LoopBlocksDFS DFS(TheLoop);
2780 R.NumInstructions = 0;
2782 // Each 'key' in the map opens a new interval. The values
2783 // of the map are the index of the 'last seen' usage of the
2784 // instruction that is the key.
2785 typedef DenseMap<Instruction*, unsigned> IntervalMap;
2786 // Maps instruction to its index.
2787 DenseMap<unsigned, Instruction*> IdxToInstr;
2788 // Marks the end of each interval.
2789 IntervalMap EndPoint;
2790 // Saves the list of instruction indices that are used in the loop.
2791 SmallSet<Instruction*, 8> Ends;
2792 // Saves the list of values that are used in the loop but are
2793 // defined outside the loop, such as arguments and constants.
2794 SmallPtrSet<Value*, 8> LoopInvariants;
2797 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
2798 be = DFS.endRPO(); bb != be; ++bb) {
2799 R.NumInstructions += (*bb)->size();
2800 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
2802 Instruction *I = it;
2803 IdxToInstr[Index++] = I;
2805 // Save the end location of each USE.
2806 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
2807 Value *U = I->getOperand(i);
2808 Instruction *Instr = dyn_cast<Instruction>(U);
2810 // Ignore non-instruction values such as arguments, constants, etc.
2811 if (!Instr) continue;
2813 // If this instruction is outside the loop then record it and continue.
2814 if (!TheLoop->contains(Instr)) {
2815 LoopInvariants.insert(Instr);
2819 // Overwrite previous end points.
2820 EndPoint[Instr] = Index;
2826 // Saves the list of intervals that end with the index in 'key'.
2827 typedef SmallVector<Instruction*, 2> InstrList;
2828 DenseMap<unsigned, InstrList> TransposeEnds;
2830 // Transpose the EndPoints to a list of values that end at each index.
2831 for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
2833 TransposeEnds[it->second].push_back(it->first);
2835 SmallSet<Instruction*, 8> OpenIntervals;
2836 unsigned MaxUsage = 0;
2839 DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
2840 for (unsigned int i = 0; i < Index; ++i) {
2841 Instruction *I = IdxToInstr[i];
2842 // Ignore instructions that are never used within the loop.
2843 if (!Ends.count(I)) continue;
2845 // Remove all of the instructions that end at this location.
2846 InstrList &List = TransposeEnds[i];
2847 for (unsigned int j=0, e = List.size(); j < e; ++j)
2848 OpenIntervals.erase(List[j]);
2850 // Count the number of live interals.
2851 MaxUsage = std::max(MaxUsage, OpenIntervals.size());
2853 DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
2854 OpenIntervals.size() <<"\n");
2856 // Add the current instruction to the list of open intervals.
2857 OpenIntervals.insert(I);
2860 unsigned Invariant = LoopInvariants.size();
2861 DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << " \n");
2862 DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << " \n");
2863 DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << " \n");
2865 R.LoopInvariantRegs = Invariant;
2866 R.MaxLocalUsers = MaxUsage;
2870 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
2874 for (Loop::block_iterator bb = TheLoop->block_begin(),
2875 be = TheLoop->block_end(); bb != be; ++bb) {
2876 unsigned BlockCost = 0;
2877 BasicBlock *BB = *bb;
2879 // For each instruction in the old loop.
2880 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2881 unsigned C = getInstructionCost(it, VF);
2883 DEBUG(dbgs() << "LV: Found an estimated cost of "<< C <<" for VF " <<
2884 VF << " For instruction: "<< *it << "\n");
2887 // We assume that if-converted blocks have a 50% chance of being executed.
2888 // When the code is scalar then some of the blocks are avoided due to CF.
2889 // When the code is vectorized we execute all code paths.
2890 if (Legal->blockNeedsPredication(*bb) && VF == 1)
2900 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
2901 // If we know that this instruction will remain uniform, check the cost of
2902 // the scalar version.
2903 if (Legal->isUniformAfterVectorization(I))
2906 Type *RetTy = I->getType();
2907 Type *VectorTy = ToVectorTy(RetTy, VF);
2909 // TODO: We need to estimate the cost of intrinsic calls.
2910 switch (I->getOpcode()) {
2911 case Instruction::GetElementPtr:
2912 // We mark this instruction as zero-cost because scalar GEPs are usually
2913 // lowered to the intruction addressing mode. At the moment we don't
2914 // generate vector geps.
2916 case Instruction::Br: {
2917 return TTI.getCFInstrCost(I->getOpcode());
2919 case Instruction::PHI:
2920 //TODO: IF-converted IFs become selects.
2922 case Instruction::Add:
2923 case Instruction::FAdd:
2924 case Instruction::Sub:
2925 case Instruction::FSub:
2926 case Instruction::Mul:
2927 case Instruction::FMul:
2928 case Instruction::UDiv:
2929 case Instruction::SDiv:
2930 case Instruction::FDiv:
2931 case Instruction::URem:
2932 case Instruction::SRem:
2933 case Instruction::FRem:
2934 case Instruction::Shl:
2935 case Instruction::LShr:
2936 case Instruction::AShr:
2937 case Instruction::And:
2938 case Instruction::Or:
2939 case Instruction::Xor:
2940 return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy);
2941 case Instruction::Select: {
2942 SelectInst *SI = cast<SelectInst>(I);
2943 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
2944 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
2945 Type *CondTy = SI->getCondition()->getType();
2947 CondTy = VectorType::get(CondTy, VF);
2949 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
2951 case Instruction::ICmp:
2952 case Instruction::FCmp: {
2953 Type *ValTy = I->getOperand(0)->getType();
2954 VectorTy = ToVectorTy(ValTy, VF);
2955 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
2957 case Instruction::Store: {
2958 StoreInst *SI = cast<StoreInst>(I);
2959 Type *ValTy = SI->getValueOperand()->getType();
2960 VectorTy = ToVectorTy(ValTy, VF);
2963 return TTI.getMemoryOpCost(I->getOpcode(), VectorTy,
2965 SI->getPointerAddressSpace());
2967 // Scalarized stores.
2968 int Stride = Legal->isConsecutivePtr(SI->getPointerOperand());
2969 bool Reverse = Stride < 0;
2973 // The cost of extracting from the value vector and pointer vector.
2974 Type *PtrTy = ToVectorTy(I->getOperand(0)->getType(), VF);
2975 for (unsigned i = 0; i < VF; ++i) {
2976 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, VectorTy,
2978 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
2981 // The cost of the scalar stores.
2982 Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
2984 SI->getPointerAddressSpace());
2989 unsigned Cost = TTI.getMemoryOpCost(I->getOpcode(), VectorTy,
2991 SI->getPointerAddressSpace());
2993 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
2997 case Instruction::Load: {
2998 LoadInst *LI = cast<LoadInst>(I);
3001 return TTI.getMemoryOpCost(I->getOpcode(), VectorTy, LI->getAlignment(),
3002 LI->getPointerAddressSpace());
3004 // Scalarized loads.
3005 int Stride = Legal->isConsecutivePtr(LI->getPointerOperand());
3006 bool Reverse = Stride < 0;
3009 Type *PtrTy = ToVectorTy(I->getOperand(0)->getType(), VF);
3011 // The cost of extracting from the pointer vector.
3012 for (unsigned i = 0; i < VF; ++i)
3013 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
3015 // The cost of inserting data to the result vector.
3016 for (unsigned i = 0; i < VF; ++i)
3017 Cost += TTI.getVectorInstrCost(Instruction::InsertElement, VectorTy, i);
3019 // The cost of the scalar stores.
3020 Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), RetTy->getScalarType(),
3022 LI->getPointerAddressSpace());
3027 unsigned Cost = TTI.getMemoryOpCost(I->getOpcode(), VectorTy,
3029 LI->getPointerAddressSpace());
3031 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0);
3034 case Instruction::ZExt:
3035 case Instruction::SExt:
3036 case Instruction::FPToUI:
3037 case Instruction::FPToSI:
3038 case Instruction::FPExt:
3039 case Instruction::PtrToInt:
3040 case Instruction::IntToPtr:
3041 case Instruction::SIToFP:
3042 case Instruction::UIToFP:
3043 case Instruction::Trunc:
3044 case Instruction::FPTrunc:
3045 case Instruction::BitCast: {
3046 // We optimize the truncation of induction variable.
3047 // The cost of these is the same as the scalar operation.
3048 if (I->getOpcode() == Instruction::Trunc &&
3049 Legal->isInductionVariable(I->getOperand(0)))
3050 return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
3051 I->getOperand(0)->getType());
3053 Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
3054 return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
3056 case Instruction::Call: {
3057 assert(isTriviallyVectorizableIntrinsic(I));
3058 IntrinsicInst *II = cast<IntrinsicInst>(I);
3059 Type *RetTy = ToVectorTy(II->getType(), VF);
3060 SmallVector<Type*, 4> Tys;
3061 for (unsigned i = 0, ie = II->getNumArgOperands(); i != ie; ++i)
3062 Tys.push_back(ToVectorTy(II->getArgOperand(i)->getType(), VF));
3063 return TTI.getIntrinsicInstrCost(II->getIntrinsicID(), RetTy, Tys);
3066 // We are scalarizing the instruction. Return the cost of the scalar
3067 // instruction, plus the cost of insert and extract into vector
3068 // elements, times the vector width.
3071 if (!RetTy->isVoidTy() && VF != 1) {
3072 unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
3074 unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
3077 // The cost of inserting the results plus extracting each one of the
3079 Cost += VF * (InsCost + ExtCost * I->getNumOperands());
3082 // The cost of executing VF copies of the scalar instruction. This opcode
3083 // is unknown. Assume that it is the same as 'mul'.
3084 Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
3090 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
3091 if (Scalar->isVoidTy() || VF == 1)
3093 return VectorType::get(Scalar, VF);
3096 char LoopVectorize::ID = 0;
3097 static const char lv_name[] = "Loop Vectorization";
3098 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
3099 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3100 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
3101 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
3102 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
3103 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
3106 Pass *createLoopVectorizePass() {
3107 return new LoopVectorize();