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. SingleBlockLoopVectorizer - 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.
28 //===----------------------------------------------------------------------===//
30 // The reduction-variable vectorization is based on the paper:
31 // D. Nuzman and R. Henderson. Multi-platform Auto-vectorization.
33 // Variable uniformity checks are inspired by:
34 // Karrenberg, R. and Hack, S. Whole Function Vectorization.
36 // Other ideas/concepts are from:
37 // A. Zaks and D. Nuzman. Autovectorization in GCC-two years later.
39 //===----------------------------------------------------------------------===//
40 #define LV_NAME "loop-vectorize"
41 #define DEBUG_TYPE LV_NAME
42 #include "llvm/Constants.h"
43 #include "llvm/DerivedTypes.h"
44 #include "llvm/Instructions.h"
45 #include "llvm/LLVMContext.h"
46 #include "llvm/Pass.h"
47 #include "llvm/Analysis/LoopPass.h"
48 #include "llvm/Value.h"
49 #include "llvm/Function.h"
50 #include "llvm/Analysis/Verifier.h"
51 #include "llvm/Module.h"
52 #include "llvm/Type.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/ScalarEvolution.h"
58 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
59 #include "llvm/Analysis/ScalarEvolutionExpander.h"
60 #include "llvm/Analysis/LoopInfo.h"
61 #include "llvm/Analysis/ValueTracking.h"
62 #include "llvm/Transforms/Scalar.h"
63 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
64 #include "llvm/TargetTransformInfo.h"
65 #include "llvm/Support/CommandLine.h"
66 #include "llvm/Support/Debug.h"
67 #include "llvm/Support/raw_ostream.h"
68 #include "llvm/DataLayout.h"
69 #include "llvm/Transforms/Utils/Local.h"
73 static cl::opt<unsigned>
74 VectorizationFactor("force-vector-width", cl::init(0), cl::Hidden,
75 cl::desc("Set the default vectorization width. Zero is autoselect."));
79 // Forward declarations.
80 class LoopVectorizationLegality;
81 class LoopVectorizationCostModel;
83 /// SingleBlockLoopVectorizer vectorizes loops which contain only one basic
84 /// block to a specified vectorization factor (VF).
85 /// This class performs the widening of scalars into vectors, or multiple
86 /// scalars. This class also implements the following features:
87 /// * It inserts an epilogue loop for handling loops that don't have iteration
88 /// counts that are known to be a multiple of the vectorization factor.
89 /// * It handles the code generation for reduction variables.
90 /// * Scalarization (implementation using scalars) of un-vectorizable
92 /// SingleBlockLoopVectorizer does not perform any vectorization-legality
93 /// checks, and relies on the caller to check for the different legality
94 /// aspects. The SingleBlockLoopVectorizer relies on the
95 /// LoopVectorizationLegality class to provide information about the induction
96 /// and reduction variables that were found to a given vectorization factor.
97 class SingleBlockLoopVectorizer {
100 SingleBlockLoopVectorizer(Loop *Orig, ScalarEvolution *Se, LoopInfo *Li,
101 LPPassManager *Lpm, unsigned VecWidth):
102 OrigLoop(Orig), SE(Se), LI(Li), LPM(Lpm), VF(VecWidth),
103 Builder(Se->getContext()), Induction(0), OldInduction(0) { }
105 // Perform the actual loop widening (vectorization).
106 void vectorize(LoopVectorizationLegality *Legal) {
107 ///Create a new empty loop. Unlink the old loop and connect the new one.
108 createEmptyLoop(Legal);
109 /// Widen each instruction in the old loop to a new one in the new loop.
110 /// Use the Legality module to find the induction and reduction variables.
111 vectorizeLoop(Legal);
112 // register the new loop.
117 /// Create an empty loop, based on the loop ranges of the old loop.
118 void createEmptyLoop(LoopVectorizationLegality *Legal);
119 /// Copy and widen the instructions from the old loop.
120 void vectorizeLoop(LoopVectorizationLegality *Legal);
121 /// Insert the new loop to the loop hierarchy and pass manager.
124 /// This instruction is un-vectorizable. Implement it as a sequence
126 void scalarizeInstruction(Instruction *Instr);
128 /// Create a broadcast instruction. This method generates a broadcast
129 /// instruction (shuffle) for loop invariant values and for the induction
130 /// value. If this is the induction variable then we extend it to N, N+1, ...
131 /// this is needed because each iteration in the loop corresponds to a SIMD
133 Value *getBroadcastInstrs(Value *V);
135 /// This is a helper function used by getBroadcastInstrs. It adds 0, 1, 2 ..
136 /// for each element in the vector. Starting from zero.
137 Value *getConsecutiveVector(Value* Val);
139 /// When we go over instructions in the basic block we rely on previous
140 /// values within the current basic block or on loop invariant values.
141 /// When we widen (vectorize) values we place them in the map. If the values
142 /// are not within the map, they have to be loop invariant, so we simply
143 /// broadcast them into a vector.
144 Value *getVectorValue(Value *V);
146 /// Get a uniform vector of constant integers. We use this to get
147 /// vectors of ones and zeros for the reduction code.
148 Constant* getUniformVector(unsigned Val, Type* ScalarTy);
150 typedef DenseMap<Value*, Value*> ValueMap;
152 /// The original loop.
154 // Scev analysis to use.
158 // Loop Pass Manager;
160 // The vectorization factor to use.
163 // The builder that we use
166 // --- Vectorization state ---
168 /// Middle Block between the vector and the scalar.
169 BasicBlock *LoopMiddleBlock;
170 ///The ExitBlock of the scalar loop.
171 BasicBlock *LoopExitBlock;
172 ///The vector loop body.
173 BasicBlock *LoopVectorBody;
174 ///The scalar loop body.
175 BasicBlock *LoopScalarBody;
176 ///The first bypass block.
177 BasicBlock *LoopBypassBlock;
179 /// The new Induction variable which was added to the new block.
181 /// The induction variable of the old basic block.
182 PHINode *OldInduction;
183 // Maps scalars to widened vectors.
187 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
188 /// to what vectorization factor.
189 /// This class does not look at the profitability of vectorization, only the
190 /// legality. This class has two main kinds of checks:
191 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
192 /// will change the order of memory accesses in a way that will change the
193 /// correctness of the program.
194 /// * Scalars checks - The code in canVectorizeBlock checks for a number
195 /// of different conditions, such as the availability of a single induction
196 /// variable, that all types are supported and vectorize-able, etc.
197 /// This code reflects the capabilities of SingleBlockLoopVectorizer.
198 /// This class is also used by SingleBlockLoopVectorizer for identifying
199 /// induction variable and the different reduction variables.
200 class LoopVectorizationLegality {
202 LoopVectorizationLegality(Loop *Lp, ScalarEvolution *Se, DataLayout *Dl):
203 TheLoop(Lp), SE(Se), DL(Dl), Induction(0) { }
205 /// This represents the kinds of reductions that we support.
206 /// We use the enum values to hold the 'identity' value for
207 /// each operand. This value does not change the result if applied.
209 NoReduction = -1, /// Not a reduction.
210 IntegerAdd = 0, /// Sum of numbers.
211 IntegerMult = 1 /// Product of numbers.
214 /// This POD struct holds information about reduction variables.
215 struct ReductionDescriptor {
217 ReductionDescriptor():
218 StartValue(0), LoopExitInstr(0), Kind(NoReduction) {}
221 ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K):
222 StartValue(Start), LoopExitInstr(Exit), Kind(K) {}
224 // The starting value of the reduction.
225 // It does not have to be zero!
227 // The instruction who's value is used outside the loop.
228 Instruction *LoopExitInstr;
229 // The kind of the reduction.
233 /// ReductionList contains the reduction descriptors for all
234 /// of the reductions that were found in the loop.
235 typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
237 /// Returns true if it is legal to vectorize this loop.
238 /// This does not mean that it is profitable to vectorize this
239 /// loop, only that it is legal to do so.
242 /// Returns the Induction variable.
243 PHINode *getInduction() {return Induction;}
245 /// Returns the reduction variables found in the loop.
246 ReductionList *getReductionVars() { return &Reductions; }
248 /// Check if the pointer returned by this GEP is consecutive
249 /// when the index is vectorized. This happens when the last
250 /// index of the GEP is consecutive, like the induction variable.
251 /// This check allows us to vectorize A[idx] into a wide load/store.
252 bool isConsecutiveGep(Value *Ptr);
255 /// Check if a single basic block loop is vectorizable.
256 /// At this point we know that this is a loop with a constant trip count
257 /// and we only need to check individual instructions.
258 bool canVectorizeBlock(BasicBlock &BB);
260 /// When we vectorize loops we may change the order in which
261 /// we read and write from memory. This method checks if it is
262 /// legal to vectorize the code, considering only memory constrains.
263 /// Returns true if BB is vectorizable
264 bool canVectorizeMemory(BasicBlock &BB);
266 /// Returns True, if 'Phi' is the kind of reduction variable for type
267 /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
268 bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
269 /// Returns true if the instruction I can be a reduction variable of type
271 bool isReductionInstr(Instruction *I, ReductionKind Kind);
272 /// Returns True, if 'Phi' is an induction variable.
273 bool isInductionVariable(PHINode *Phi);
275 /// The loop that we evaluate.
279 /// DataLayout analysis.
282 // --- vectorization state --- //
284 /// Holds the induction variable.
286 /// Holds the reduction variables.
287 ReductionList Reductions;
288 /// Allowed outside users. This holds the reduction
289 /// vars which can be accessed from outside the loop.
290 SmallPtrSet<Value*, 4> AllowedExit;
293 /// LoopVectorizationCostModel - estimates the expected speedups due to
295 /// In many cases vectorization is not profitable. This can happen because
296 /// of a number of reasons. In this class we mainly attempt to predict
297 /// the expected speedup/slowdowns due to the supported instruction set.
298 /// We use the VectorTargetTransformInfo to query the different backends
299 /// for the cost of different operations.
300 class LoopVectorizationCostModel {
303 LoopVectorizationCostModel(Loop *Lp, ScalarEvolution *Se, DataLayout *Dl,
304 LoopVectorizationLegality *Leg,
305 const VectorTargetTransformInfo *Vtti):
306 TheLoop(Lp), SE(Se), DL(Dl), Legal(Leg), VTTI(Vtti) { }
308 /// Returns the most profitable vectorization factor for the loop that is
309 /// smaller or equal to the VF argument. This method checks every power
311 unsigned findBestVectorizationFactor(unsigned VF = 4);
314 /// Returns the expected execution cost. The unit of the cost does
315 /// not matter because we use the 'cost' units to compare different
316 /// vector widths. The cost that is returned is *not* normalized by
317 /// the factor width.
318 unsigned expectedCost(unsigned VF);
320 /// Returns the execution time cost of an instruction for a given vector
321 /// width. Vector width of one means scalar.
322 unsigned getInstructionCost(Instruction *I, unsigned VF);
324 /// The loop that we evaluate.
328 /// DataLayout analysis.
330 /// Vectorization legality.
331 LoopVectorizationLegality *Legal;
332 /// Vector target information.
333 const VectorTargetTransformInfo *VTTI;
336 struct LoopVectorize : public LoopPass {
337 static char ID; // Pass identification, replacement for typeid
339 LoopVectorize() : LoopPass(ID) {
340 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
346 TargetTransformInfo *TTI;
348 virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
349 // We only vectorize innermost loops.
353 SE = &getAnalysis<ScalarEvolution>();
354 DL = getAnalysisIfAvailable<DataLayout>();
355 LI = &getAnalysis<LoopInfo>();
356 TTI = getAnalysisIfAvailable<TargetTransformInfo>();
358 DEBUG(dbgs() << "LV: Checking a loop in \"" <<
359 L->getHeader()->getParent()->getName() << "\"\n");
361 // Check if it is legal to vectorize the loop.
362 LoopVectorizationLegality LVL(L, SE, DL);
363 if (!LVL.canVectorize()) {
364 DEBUG(dbgs() << "LV: Not vectorizing.\n");
368 // Select the preffered vectorization factor.
370 if (VectorizationFactor == 0) {
371 const VectorTargetTransformInfo *VTTI = 0;
373 VTTI = TTI->getVectorTargetTransformInfo();
374 // Use the cost model.
375 LoopVectorizationCostModel CM(L, SE, DL, &LVL, VTTI);
376 VF = CM.findBestVectorizationFactor();
379 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
384 // Use the user command flag.
385 VF = VectorizationFactor;
388 DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< VF << ").\n");
390 // If we decided that it is *legal* to vectorizer the loop then do it.
391 SingleBlockLoopVectorizer LB(L, SE, LI, &LPM, VF);
394 DEBUG(verifyFunction(*L->getHeader()->getParent()));
398 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
399 LoopPass::getAnalysisUsage(AU);
400 AU.addRequiredID(LoopSimplifyID);
401 AU.addRequiredID(LCSSAID);
402 AU.addRequired<LoopInfo>();
403 AU.addRequired<ScalarEvolution>();
408 Value *SingleBlockLoopVectorizer::getBroadcastInstrs(Value *V) {
409 // Instructions that access the old induction variable
410 // actually want to get the new one.
411 if (V == OldInduction)
414 LLVMContext &C = V->getContext();
415 Type *VTy = VectorType::get(V->getType(), VF);
416 Type *I32 = IntegerType::getInt32Ty(C);
417 Constant *Zero = ConstantInt::get(I32, 0);
418 Value *Zeros = ConstantAggregateZero::get(VectorType::get(I32, VF));
419 Value *UndefVal = UndefValue::get(VTy);
420 // Insert the value into a new vector.
421 Value *SingleElem = Builder.CreateInsertElement(UndefVal, V, Zero);
422 // Broadcast the scalar into all locations in the vector.
423 Value *Shuf = Builder.CreateShuffleVector(SingleElem, UndefVal, Zeros,
425 // We are accessing the induction variable. Make sure to promote the
426 // index for each consecutive SIMD lane. This adds 0,1,2 ... to all lanes.
428 return getConsecutiveVector(Shuf);
432 Value *SingleBlockLoopVectorizer::getConsecutiveVector(Value* Val) {
433 assert(Val->getType()->isVectorTy() && "Must be a vector");
434 assert(Val->getType()->getScalarType()->isIntegerTy() &&
435 "Elem must be an integer");
437 Type *ITy = Val->getType()->getScalarType();
438 VectorType *Ty = cast<VectorType>(Val->getType());
439 unsigned VLen = Ty->getNumElements();
440 SmallVector<Constant*, 8> Indices;
442 // Create a vector of consecutive numbers from zero to VF.
443 for (unsigned i = 0; i < VLen; ++i)
444 Indices.push_back(ConstantInt::get(ITy, i));
446 // Add the consecutive indices to the vector value.
447 Constant *Cv = ConstantVector::get(Indices);
448 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
449 return Builder.CreateAdd(Val, Cv, "induction");
452 bool LoopVectorizationLegality::isConsecutiveGep(Value *Ptr) {
453 GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
457 unsigned NumOperands = Gep->getNumOperands();
458 Value *LastIndex = Gep->getOperand(NumOperands - 1);
460 // Check that all of the gep indices are uniform except for the last.
461 for (unsigned i = 0; i < NumOperands - 1; ++i)
462 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
465 // We can emit wide load/stores only of the last index is the induction
467 const SCEV *Last = SE->getSCEV(LastIndex);
468 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
469 const SCEV *Step = AR->getStepRecurrence(*SE);
471 // The memory is consecutive because the last index is consecutive
472 // and all other indices are loop invariant.
480 Value *SingleBlockLoopVectorizer::getVectorValue(Value *V) {
481 assert(!V->getType()->isVectorTy() && "Can't widen a vector");
482 // If we saved a vectorized copy of V, use it.
483 Value *&MapEntry = WidenMap[V];
487 // Broadcast V and save the value for future uses.
488 Value *B = getBroadcastInstrs(V);
494 SingleBlockLoopVectorizer::getUniformVector(unsigned Val, Type* ScalarTy) {
495 SmallVector<Constant*, 8> Indices;
496 // Create a vector of consecutive numbers from zero to VF.
497 for (unsigned i = 0; i < VF; ++i)
498 Indices.push_back(ConstantInt::get(ScalarTy, Val));
500 // Add the consecutive indices to the vector value.
501 return ConstantVector::get(Indices);
504 void SingleBlockLoopVectorizer::scalarizeInstruction(Instruction *Instr) {
505 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
506 // Holds vector parameters or scalars, in case of uniform vals.
507 SmallVector<Value*, 8> Params;
509 // Find all of the vectorized parameters.
510 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
511 Value *SrcOp = Instr->getOperand(op);
513 // If we are accessing the old induction variable, use the new one.
514 if (SrcOp == OldInduction) {
515 Params.push_back(getBroadcastInstrs(Induction));
519 // Try using previously calculated values.
520 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
522 // If the src is an instruction that appeared earlier in the basic block
523 // then it should already be vectorized.
524 if (SrcInst && SrcInst->getParent() == Instr->getParent()) {
525 assert(WidenMap.count(SrcInst) && "Source operand is unavailable");
526 // The parameter is a vector value from earlier.
527 Params.push_back(WidenMap[SrcInst]);
529 // The parameter is a scalar from outside the loop. Maybe even a constant.
530 Params.push_back(SrcOp);
534 assert(Params.size() == Instr->getNumOperands() &&
535 "Invalid number of operands");
537 // Does this instruction return a value ?
538 bool IsVoidRetTy = Instr->getType()->isVoidTy();
539 Value *VecResults = 0;
541 // If we have a return value, create an empty vector. We place the scalarized
542 // instructions in this vector.
544 VecResults = UndefValue::get(VectorType::get(Instr->getType(), VF));
546 // For each scalar that we create:
547 for (unsigned i = 0; i < VF; ++i) {
548 Instruction *Cloned = Instr->clone();
550 Cloned->setName(Instr->getName() + ".cloned");
551 // Replace the operands of the cloned instrucions with extracted scalars.
552 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
553 Value *Op = Params[op];
554 // Param is a vector. Need to extract the right lane.
555 if (Op->getType()->isVectorTy())
556 Op = Builder.CreateExtractElement(Op, Builder.getInt32(i));
557 Cloned->setOperand(op, Op);
560 // Place the cloned scalar in the new loop.
561 Builder.Insert(Cloned);
563 // If the original scalar returns a value we need to place it in a vector
564 // so that future users will be able to use it.
566 VecResults = Builder.CreateInsertElement(VecResults, Cloned,
567 Builder.getInt32(i));
571 WidenMap[Instr] = VecResults;
574 void SingleBlockLoopVectorizer::createEmptyLoop(LoopVectorizationLegality *Legal) {
576 In this function we generate a new loop. The new loop will contain
577 the vectorized instructions while the old loop will continue to run the
580 [ ] <-- vector loop bypass.
583 | [ ] <-- vector pre header.
587 | [ ]_| <-- vector loop.
590 >[ ] <--- middle-block.
593 | [ ] <--- new preheader.
597 | [ ]_| <-- old scalar loop to handle remainder.
604 // This is the original scalar-loop preheader.
605 BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
606 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
607 assert(ExitBlock && "Must have an exit block");
609 assert(OrigLoop->getNumBlocks() == 1 && "Invalid loop");
610 assert(BypassBlock && "Invalid loop structure");
612 BasicBlock *VectorPH =
613 BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
614 BasicBlock *VecBody = VectorPH->splitBasicBlock(VectorPH->getTerminator(),
617 BasicBlock *MiddleBlock = VecBody->splitBasicBlock(VecBody->getTerminator(),
619 BasicBlock *ScalarPH =
620 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(),
622 // Find the induction variable.
623 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
624 OldInduction = Legal->getInduction();
625 assert(OldInduction && "We must have a single phi node.");
626 Type *IdxTy = OldInduction->getType();
628 // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
630 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
632 // Generate the induction variable.
633 Induction = Builder.CreatePHI(IdxTy, 2, "index");
634 Constant *Zero = ConstantInt::get(IdxTy, 0);
635 Constant *Step = ConstantInt::get(IdxTy, VF);
637 // Find the loop boundaries.
638 const SCEV *ExitCount = SE->getExitCount(OrigLoop, OrigLoop->getHeader());
639 assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
641 // Get the total trip count from the count by adding 1.
642 ExitCount = SE->getAddExpr(ExitCount,
643 SE->getConstant(ExitCount->getType(), 1));
645 // Expand the trip count and place the new instructions in the preheader.
646 // Notice that the pre-header does not change, only the loop body.
647 SCEVExpander Exp(*SE, "induction");
648 Instruction *Loc = BypassBlock->getTerminator();
650 // We may need to extend the index in case there is a type mismatch.
651 // We know that the count starts at zero and does not overflow.
652 // We are using Zext because it should be less expensive.
653 if (ExitCount->getType() != Induction->getType())
654 ExitCount = SE->getZeroExtendExpr(ExitCount, IdxTy);
656 // Count holds the overall loop count (N).
657 Value *Count = Exp.expandCodeFor(ExitCount, Induction->getType(), Loc);
658 // Now we need to generate the expression for N - (N % VF), which is
659 // the part that the vectorized body will execute.
660 Constant *CIVF = ConstantInt::get(IdxTy, VF);
661 Value *R = BinaryOperator::CreateURem(Count, CIVF, "n.mod.vf", Loc);
662 Value *CountRoundDown = BinaryOperator::CreateSub(Count, R, "n.vec", Loc);
664 // Now, compare the new count to zero. If it is zero, jump to the scalar part.
665 Value *Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
666 CountRoundDown, ConstantInt::getNullValue(IdxTy),
668 BranchInst::Create(MiddleBlock, VectorPH, Cmp, Loc);
669 // Remove the old terminator.
670 Loc->eraseFromParent();
672 // Add a check in the middle block to see if we have completed
673 // all of the iterations in the first vector loop.
674 // If (N - N%VF) == N, then we *don't* need to run the remainder.
675 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, Count,
676 CountRoundDown, "cmp.n",
677 MiddleBlock->getTerminator());
679 BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
680 // Remove the old terminator.
681 MiddleBlock->getTerminator()->eraseFromParent();
683 // Create i+1 and fill the PHINode.
684 Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
685 Induction->addIncoming(Zero, VectorPH);
686 Induction->addIncoming(NextIdx, VecBody);
687 // Create the compare.
688 Value *ICmp = Builder.CreateICmpEQ(NextIdx, CountRoundDown);
689 Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
691 // Now we have two terminators. Remove the old one from the block.
692 VecBody->getTerminator()->eraseFromParent();
694 // Fix the scalar body iteration count.
695 unsigned BlockIdx = OldInduction->getBasicBlockIndex(ScalarPH);
696 OldInduction->setIncomingValue(BlockIdx, CountRoundDown);
698 // Get ready to start creating new instructions into the vectorized body.
699 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
701 // Register the new loop.
702 Loop* Lp = new Loop();
703 LPM->insertLoop(Lp, OrigLoop->getParentLoop());
705 Lp->addBasicBlockToLoop(VecBody, LI->getBase());
707 Loop *ParentLoop = OrigLoop->getParentLoop();
709 ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
710 ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
711 ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
715 LoopMiddleBlock = MiddleBlock;
716 LoopExitBlock = ExitBlock;
717 LoopVectorBody = VecBody;
718 LoopScalarBody = OldBasicBlock;
719 LoopBypassBlock = BypassBlock;
723 SingleBlockLoopVectorizer::vectorizeLoop(LoopVectorizationLegality *Legal) {
724 //===------------------------------------------------===//
726 // Notice: any optimization or new instruction that go
727 // into the code below should be also be implemented in
730 //===------------------------------------------------===//
731 typedef SmallVector<PHINode*, 4> PhiVector;
732 BasicBlock &BB = *OrigLoop->getHeader();
733 Constant *Zero = ConstantInt::get(
734 IntegerType::getInt32Ty(BB.getContext()), 0);
736 // In order to support reduction variables we need to be able to vectorize
737 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
738 // steages. First, we create a new vector PHI node with no incoming edges.
739 // We use this value when we vectorize all of the instructions that use the
740 // PHI. Next, after all of the instructions in the block are complete we
741 // add the new incoming edges to the PHI. At this point all of the
742 // instructions in the basic block are vectorized, so we can use them to
743 // construct the PHI.
746 // For each instruction in the old loop.
747 for (BasicBlock::iterator it = BB.begin(), e = BB.end(); it != e; ++it) {
748 Instruction *Inst = it;
750 switch (Inst->getOpcode()) {
751 case Instruction::Br:
752 // Nothing to do for PHIs and BR, since we already took care of the
753 // loop control flow instructions.
755 case Instruction::PHI:{
756 PHINode* P = cast<PHINode>(Inst);
757 // Special handling for the induction var.
758 if (OldInduction == Inst)
760 // This is phase one of vectorizing PHIs.
761 // This has to be a reduction variable.
762 assert(Legal->getReductionVars()->count(P) && "Not a Reduction");
763 Type *VecTy = VectorType::get(Inst->getType(), VF);
764 WidenMap[Inst] = Builder.CreatePHI(VecTy, 2, "vec.phi");
765 PHIsToFix.push_back(P);
768 case Instruction::Add:
769 case Instruction::FAdd:
770 case Instruction::Sub:
771 case Instruction::FSub:
772 case Instruction::Mul:
773 case Instruction::FMul:
774 case Instruction::UDiv:
775 case Instruction::SDiv:
776 case Instruction::FDiv:
777 case Instruction::URem:
778 case Instruction::SRem:
779 case Instruction::FRem:
780 case Instruction::Shl:
781 case Instruction::LShr:
782 case Instruction::AShr:
783 case Instruction::And:
784 case Instruction::Or:
785 case Instruction::Xor: {
786 // Just widen binops.
787 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
788 Value *A = getVectorValue(Inst->getOperand(0));
789 Value *B = getVectorValue(Inst->getOperand(1));
790 // Use this vector value for all users of the original instruction.
791 WidenMap[Inst] = Builder.CreateBinOp(BinOp->getOpcode(), A, B);
794 case Instruction::Select: {
796 // If the selector is loop invariant we can create a select
797 // instruction with a scalar condition. Otherwise, use vector-select.
798 Value *Cond = Inst->getOperand(0);
799 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(Cond), OrigLoop);
801 // The condition can be loop invariant but still defined inside the
802 // loop. This means that we can't just use the original 'cond' value.
803 // We have to take the 'vectorized' value and pick the first lane.
804 // Instcombine will make this a no-op.
805 Cond = getVectorValue(Cond);
807 Cond = Builder.CreateExtractElement(Cond, Builder.getInt32(0));
809 Value *Op0 = getVectorValue(Inst->getOperand(1));
810 Value *Op1 = getVectorValue(Inst->getOperand(2));
811 WidenMap[Inst] = Builder.CreateSelect(Cond, Op0, Op1);
815 case Instruction::ICmp:
816 case Instruction::FCmp: {
817 // Widen compares. Generate vector compares.
818 bool FCmp = (Inst->getOpcode() == Instruction::FCmp);
819 CmpInst *Cmp = dyn_cast<CmpInst>(Inst);
820 Value *A = getVectorValue(Inst->getOperand(0));
821 Value *B = getVectorValue(Inst->getOperand(1));
823 WidenMap[Inst] = Builder.CreateFCmp(Cmp->getPredicate(), A, B);
825 WidenMap[Inst] = Builder.CreateICmp(Cmp->getPredicate(), A, B);
829 case Instruction::Store: {
830 // Attempt to issue a wide store.
831 StoreInst *SI = dyn_cast<StoreInst>(Inst);
832 Type *StTy = VectorType::get(SI->getValueOperand()->getType(), VF);
833 Value *Ptr = SI->getPointerOperand();
834 unsigned Alignment = SI->getAlignment();
835 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
836 // This store does not use GEPs.
837 if (!Legal->isConsecutiveGep(Gep)) {
838 scalarizeInstruction(Inst);
842 // The last index does not have to be the induction. It can be
843 // consecutive and be a function of the index. For example A[I+1];
844 unsigned NumOperands = Gep->getNumOperands();
845 Value *LastIndex = getVectorValue(Gep->getOperand(NumOperands -1));
846 LastIndex = Builder.CreateExtractElement(LastIndex, Builder.getInt32(0));
848 // Create the new GEP with the new induction variable.
849 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
850 Gep2->setOperand(NumOperands - 1, LastIndex);
851 Ptr = Builder.Insert(Gep2);
852 Ptr = Builder.CreateBitCast(Ptr, StTy->getPointerTo());
853 Value *Val = getVectorValue(SI->getValueOperand());
854 Builder.CreateStore(Val, Ptr)->setAlignment(Alignment);
857 case Instruction::Load: {
858 // Attempt to issue a wide load.
859 LoadInst *LI = dyn_cast<LoadInst>(Inst);
860 Type *RetTy = VectorType::get(LI->getType(), VF);
861 Value *Ptr = LI->getPointerOperand();
862 unsigned Alignment = LI->getAlignment();
863 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
865 // We don't have a gep. Scalarize the load.
866 if (!Legal->isConsecutiveGep(Gep)) {
867 scalarizeInstruction(Inst);
871 // The last index does not have to be the induction. It can be
872 // consecutive and be a function of the index. For example A[I+1];
873 unsigned NumOperands = Gep->getNumOperands();
874 Value *LastIndex = getVectorValue(Gep->getOperand(NumOperands -1));
875 LastIndex = Builder.CreateExtractElement(LastIndex, Builder.getInt32(0));
877 // Create the new GEP with the new induction variable.
878 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
879 Gep2->setOperand(NumOperands - 1, LastIndex);
880 Ptr = Builder.Insert(Gep2);
881 Ptr = Builder.CreateBitCast(Ptr, RetTy->getPointerTo());
882 LI = Builder.CreateLoad(Ptr);
883 LI->setAlignment(Alignment);
884 // Use this vector value for all users of the load.
888 case Instruction::ZExt:
889 case Instruction::SExt:
890 case Instruction::FPToUI:
891 case Instruction::FPToSI:
892 case Instruction::FPExt:
893 case Instruction::PtrToInt:
894 case Instruction::IntToPtr:
895 case Instruction::SIToFP:
896 case Instruction::UIToFP:
897 case Instruction::Trunc:
898 case Instruction::FPTrunc:
899 case Instruction::BitCast: {
900 /// Vectorize bitcasts.
901 CastInst *CI = dyn_cast<CastInst>(Inst);
902 Value *A = getVectorValue(Inst->getOperand(0));
903 Type *DestTy = VectorType::get(CI->getType()->getScalarType(), VF);
904 WidenMap[Inst] = Builder.CreateCast(CI->getOpcode(), A, DestTy);
909 /// All other instructions are unsupported. Scalarize them.
910 scalarizeInstruction(Inst);
913 }// end of for_each instr.
915 // At this point every instruction in the original loop is widended to
916 // a vector form. We are almost done. Now, we need to fix the PHI nodes
917 // that we vectorized. The PHI nodes are currently empty because we did
918 // not want to introduce cycles. Notice that the remaining PHI nodes
919 // that we need to fix are reduction variables.
921 // Create the 'reduced' values for each of the induction vars.
922 // The reduced values are the vector values that we scalarize and combine
923 // after the loop is finished.
924 for (PhiVector::iterator it = PHIsToFix.begin(), e = PHIsToFix.end();
926 PHINode *RdxPhi = *it;
927 PHINode *VecRdxPhi = dyn_cast<PHINode>(WidenMap[RdxPhi]);
928 assert(RdxPhi && "Unable to recover vectorized PHI");
930 // Find the reduction variable descriptor.
931 assert(Legal->getReductionVars()->count(RdxPhi) &&
932 "Unable to find the reduction variable");
933 LoopVectorizationLegality::ReductionDescriptor RdxDesc =
934 (*Legal->getReductionVars())[RdxPhi];
936 // We need to generate a reduction vector from the incoming scalar.
937 // To do so, we need to generate the 'identity' vector and overide
938 // one of the elements with the incoming scalar reduction. We need
939 // to do it in the vector-loop preheader.
940 Builder.SetInsertPoint(LoopBypassBlock->getTerminator());
942 // This is the vector-clone of the value that leaves the loop.
943 Value *VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
944 Type *VecTy = VectorExit->getType();
946 // Find the reduction identity variable. The value of the enum is the
947 // identity. Zero for addition. One for Multiplication.
948 unsigned IdentitySclr = RdxDesc.Kind;
949 Constant *Identity = getUniformVector(IdentitySclr,
950 VecTy->getScalarType());
952 // This vector is the Identity vector where the first element is the
953 // incoming scalar reduction.
954 Value *VectorStart = Builder.CreateInsertElement(Identity,
955 RdxDesc.StartValue, Zero);
958 // Fix the vector-loop phi.
959 // We created the induction variable so we know that the
960 // preheader is the first entry.
961 BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
963 // Reductions do not have to start at zero. They can start with
964 // any loop invariant values.
965 VecRdxPhi->addIncoming(VectorStart, VecPreheader);
966 unsigned SelfEdgeIdx = (RdxPhi)->getBasicBlockIndex(LoopScalarBody);
967 Value *Val = getVectorValue(RdxPhi->getIncomingValue(SelfEdgeIdx));
968 VecRdxPhi->addIncoming(Val, LoopVectorBody);
970 // Before each round, move the insertion point right between
971 // the PHIs and the values we are going to write.
972 // This allows us to write both PHINodes and the extractelement
974 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
976 // This PHINode contains the vectorized reduction variable, or
977 // the initial value vector, if we bypass the vector loop.
978 PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
979 NewPhi->addIncoming(VectorStart, LoopBypassBlock);
980 NewPhi->addIncoming(getVectorValue(RdxDesc.LoopExitInstr), LoopVectorBody);
982 // Extract the first scalar.
984 Builder.CreateExtractElement(NewPhi, Builder.getInt32(0));
985 // Extract and sum the remaining vector elements.
986 for (unsigned i=1; i < VF; ++i) {
988 Builder.CreateExtractElement(NewPhi, Builder.getInt32(i));
989 if (RdxDesc.Kind == LoopVectorizationLegality::IntegerAdd) {
990 Scalar0 = Builder.CreateAdd(Scalar0, Scalar1);
992 Scalar0 = Builder.CreateMul(Scalar0, Scalar1);
996 // Now, we need to fix the users of the reduction variable
997 // inside and outside of the scalar remainder loop.
998 // We know that the loop is in LCSSA form. We need to update the
999 // PHI nodes in the exit blocks.
1000 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
1001 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
1002 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
1003 if (!LCSSAPhi) continue;
1005 // All PHINodes need to have a single entry edge, or two if
1006 // we already fixed them.
1007 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
1009 // We found our reduction value exit-PHI. Update it with the
1010 // incoming bypass edge.
1011 if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
1012 // Add an edge coming from the bypass.
1013 LCSSAPhi->addIncoming(Scalar0, LoopMiddleBlock);
1016 }// end of the LCSSA phi scan.
1018 // Fix the scalar loop reduction variable with the incoming reduction sum
1019 // from the vector body and from the backedge value.
1020 int IncomingEdgeBlockIdx = (RdxPhi)->getBasicBlockIndex(LoopScalarBody);
1021 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1); // The other block.
1022 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, Scalar0);
1023 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
1024 }// end of for each redux variable.
1027 void SingleBlockLoopVectorizer::cleanup() {
1028 // The original basic block.
1029 SE->forgetLoop(OrigLoop);
1032 bool LoopVectorizationLegality::canVectorize() {
1033 if (!TheLoop->getLoopPreheader()) {
1034 assert(false && "No preheader!!");
1035 DEBUG(dbgs() << "LV: Loop not normalized." << "\n");
1039 // We can only vectorize single basic block loops.
1040 unsigned NumBlocks = TheLoop->getNumBlocks();
1041 if (NumBlocks != 1) {
1042 DEBUG(dbgs() << "LV: Too many blocks:" << NumBlocks << "\n");
1046 // We need to have a loop header.
1047 BasicBlock *BB = TheLoop->getHeader();
1048 DEBUG(dbgs() << "LV: Found a loop: " << BB->getName() << "\n");
1050 // Go over each instruction and look at memory deps.
1051 if (!canVectorizeBlock(*BB)) {
1052 DEBUG(dbgs() << "LV: Can't vectorize this loop header\n");
1056 // ScalarEvolution needs to be able to find the exit count.
1057 const SCEV *ExitCount = SE->getExitCount(TheLoop, BB);
1058 if (ExitCount == SE->getCouldNotCompute()) {
1059 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
1063 DEBUG(dbgs() << "LV: We can vectorize this loop!\n");
1065 // Okay! We can vectorize. At this point we don't have any other mem analysis
1066 // which may limit our maximum vectorization factor, so just return true with
1071 bool LoopVectorizationLegality::canVectorizeBlock(BasicBlock &BB) {
1072 // Scan the instructions in the block and look for hazards.
1073 for (BasicBlock::iterator it = BB.begin(), e = BB.end(); it != e; ++it) {
1074 Instruction *I = it;
1076 PHINode *Phi = dyn_cast<PHINode>(I);
1078 // This should not happen because the loop should be normalized.
1079 if (Phi->getNumIncomingValues() != 2) {
1080 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
1083 // We only look at integer phi nodes.
1084 if (!Phi->getType()->isIntegerTy()) {
1085 DEBUG(dbgs() << "LV: Found an non-int PHI.\n");
1089 if (isInductionVariable(Phi)) {
1091 DEBUG(dbgs() << "LV: Found too many inductions."<< *Phi <<"\n");
1094 DEBUG(dbgs() << "LV: Found the induction PHI."<< *Phi <<"\n");
1098 if (AddReductionVar(Phi, IntegerAdd)) {
1099 DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
1102 if (AddReductionVar(Phi, IntegerMult)) {
1103 DEBUG(dbgs() << "LV: Found an Mult reduction PHI."<< *Phi <<"\n");
1107 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
1109 }// end of PHI handling
1111 // We still don't handle functions.
1112 CallInst *CI = dyn_cast<CallInst>(I);
1114 DEBUG(dbgs() << "LV: Found a call site:"<<
1115 CI->getCalledFunction()->getName() << "\n");
1119 // We do not re-vectorize vectors.
1120 if (!VectorType::isValidElementType(I->getType()) &&
1121 !I->getType()->isVoidTy()) {
1122 DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n");
1126 // Reduction instructions are allowed to have exit users.
1127 // All other instructions must not have external users.
1128 if (!AllowedExit.count(I))
1129 //Check that all of the users of the loop are inside the BB.
1130 for (Value::use_iterator it = I->use_begin(), e = I->use_end();
1132 Instruction *U = cast<Instruction>(*it);
1133 // This user may be a reduction exit value.
1134 BasicBlock *Parent = U->getParent();
1135 if (Parent != &BB) {
1136 DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n");
1143 DEBUG(dbgs() << "LV: Did not find an induction var.\n");
1147 // If the memory dependencies do not prevent us from
1148 // vectorizing, then vectorize.
1149 return canVectorizeMemory(BB);
1152 bool LoopVectorizationLegality::canVectorizeMemory(BasicBlock &BB) {
1153 typedef SmallVector<Value*, 16> ValueVector;
1154 typedef SmallPtrSet<Value*, 16> ValueSet;
1155 // Holds the Load and Store *instructions*.
1159 // Scan the BB and collect legal loads and stores.
1160 for (BasicBlock::iterator it = BB.begin(), e = BB.end(); it != e; ++it) {
1161 Instruction *I = it;
1163 // If this is a load, save it. If this instruction can read from memory
1164 // but is not a load, then we quit. Notice that we don't handle function
1165 // calls that read or write.
1166 if (I->mayReadFromMemory()) {
1167 LoadInst *Ld = dyn_cast<LoadInst>(I);
1168 if (!Ld) return false;
1169 if (!Ld->isSimple()) {
1170 DEBUG(dbgs() << "LV: Found a non-simple load.\n");
1173 Loads.push_back(Ld);
1177 // Save store instructions. Abort if other instructions write to memory.
1178 if (I->mayWriteToMemory()) {
1179 StoreInst *St = dyn_cast<StoreInst>(I);
1180 if (!St) return false;
1181 if (!St->isSimple()) {
1182 DEBUG(dbgs() << "LV: Found a non-simple store.\n");
1185 Stores.push_back(St);
1189 // Now we have two lists that hold the loads and the stores.
1190 // Next, we find the pointers that they use.
1192 // Check if we see any stores. If there are no stores, then we don't
1193 // care if the pointers are *restrict*.
1194 if (!Stores.size()) {
1195 DEBUG(dbgs() << "LV: Found a read-only loop!\n");
1199 // Holds the read and read-write *pointers* that we find.
1201 ValueVector ReadWrites;
1203 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
1204 // multiple times on the same object. If the ptr is accessed twice, once
1205 // for read and once for write, it will only appear once (on the write
1206 // list). This is okay, since we are going to check for conflicts between
1207 // writes and between reads and writes, but not between reads and reads.
1210 ValueVector::iterator I, IE;
1211 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
1212 StoreInst *ST = dyn_cast<StoreInst>(*I);
1213 assert(ST && "Bad StoreInst");
1214 Value* Ptr = ST->getPointerOperand();
1215 // If we did *not* see this pointer before, insert it to
1216 // the read-write list. At this phase it is only a 'write' list.
1217 if (Seen.insert(Ptr))
1218 ReadWrites.push_back(Ptr);
1221 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
1222 LoadInst *LD = dyn_cast<LoadInst>(*I);
1223 assert(LD && "Bad LoadInst");
1224 Value* Ptr = LD->getPointerOperand();
1225 // If we did *not* see this pointer before, insert it to the
1226 // read list. If we *did* see it before, then it is already in
1227 // the read-write list. This allows us to vectorize expressions
1228 // such as A[i] += x; Because the address of A[i] is a read-write
1229 // pointer. This only works if the index of A[i] is consecutive.
1230 // If the address of i is unknown (for example A[B[i]]) then we may
1231 // read a few words, modify, and write a few words, and some of the
1232 // words may be written to the same address.
1233 if (Seen.insert(Ptr) || !isConsecutiveGep(Ptr))
1234 Reads.push_back(Ptr);
1237 // Now that the pointers are in two lists (Reads and ReadWrites), we
1238 // can check that there are no conflicts between each of the writes and
1239 // between the writes to the reads.
1240 ValueSet WriteObjects;
1241 ValueVector TempObjects;
1243 // Check that the read-writes do not conflict with other read-write
1245 for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I) {
1246 GetUnderlyingObjects(*I, TempObjects, DL);
1247 for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
1249 if (!isIdentifiedObject(*it)) {
1250 DEBUG(dbgs() << "LV: Found an unidentified write ptr:"<< **it <<"\n");
1253 if (!WriteObjects.insert(*it)) {
1254 DEBUG(dbgs() << "LV: Found a possible write-write reorder:"
1259 TempObjects.clear();
1262 /// Check that the reads don't conflict with the read-writes.
1263 for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I) {
1264 GetUnderlyingObjects(*I, TempObjects, DL);
1265 for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
1267 if (!isIdentifiedObject(*it)) {
1268 DEBUG(dbgs() << "LV: Found an unidentified read ptr:"<< **it <<"\n");
1271 if (WriteObjects.count(*it)) {
1272 DEBUG(dbgs() << "LV: Found a possible read/write reorder:"
1277 TempObjects.clear();
1284 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
1285 ReductionKind Kind) {
1286 if (Phi->getNumIncomingValues() != 2)
1289 // Find the possible incoming reduction variable.
1290 BasicBlock *BB = Phi->getParent();
1291 int SelfEdgeIdx = Phi->getBasicBlockIndex(BB);
1292 int InEdgeBlockIdx = (SelfEdgeIdx ? 0 : 1); // The other entry.
1293 Value *RdxStart = Phi->getIncomingValue(InEdgeBlockIdx);
1295 // ExitInstruction is the single value which is used outside the loop.
1296 // We only allow for a single reduction value to be used outside the loop.
1297 // This includes users of the reduction, variables (which form a cycle
1298 // which ends in the phi node).
1299 Instruction *ExitInstruction = 0;
1301 // Iter is our iterator. We start with the PHI node and scan for all of the
1302 // users of this instruction. All users must be instructions which can be
1303 // used as reduction variables (such as ADD). We may have a single
1304 // out-of-block user. They cycle must end with the original PHI.
1305 // Also, we can't have multiple block-local users.
1306 Instruction *Iter = Phi;
1308 // Any reduction instr must be of one of the allowed kinds.
1309 if (!isReductionInstr(Iter, Kind))
1312 // Did we found a user inside this block ?
1313 bool FoundInBlockUser = false;
1314 // Did we reach the initial PHI node ?
1315 bool FoundStartPHI = false;
1317 // If the instruction has no users then this is a broken
1318 // chain and can't be a reduction variable.
1319 if (Iter->use_empty())
1322 // For each of the *users* of iter.
1323 for (Value::use_iterator it = Iter->use_begin(), e = Iter->use_end();
1325 Instruction *U = cast<Instruction>(*it);
1326 // We already know that the PHI is a user.
1328 FoundStartPHI = true;
1331 // Check if we found the exit user.
1332 BasicBlock *Parent = U->getParent();
1334 // We must have a single exit instruction.
1335 if (ExitInstruction != 0)
1337 ExitInstruction = Iter;
1339 // We can't have multiple inside users.
1340 if (FoundInBlockUser)
1342 FoundInBlockUser = true;
1346 // We found a reduction var if we have reached the original
1347 // phi node and we only have a single instruction with out-of-loop
1349 if (FoundStartPHI && ExitInstruction) {
1350 // This instruction is allowed to have out-of-loop users.
1351 AllowedExit.insert(ExitInstruction);
1353 // Save the description of this reduction variable.
1354 ReductionDescriptor RD(RdxStart, ExitInstruction, Kind);
1355 Reductions[Phi] = RD;
1362 LoopVectorizationLegality::isReductionInstr(Instruction *I,
1363 ReductionKind Kind) {
1364 switch (I->getOpcode()) {
1367 case Instruction::PHI:
1370 case Instruction::Add:
1371 case Instruction::Sub:
1372 return Kind == IntegerAdd;
1373 case Instruction::Mul:
1374 case Instruction::UDiv:
1375 case Instruction::SDiv:
1376 return Kind == IntegerMult;
1380 bool LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
1381 // Check that the PHI is consecutive and starts at zero.
1382 const SCEV *PhiScev = SE->getSCEV(Phi);
1383 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
1385 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
1388 const SCEV *Step = AR->getStepRecurrence(*SE);
1389 const SCEV *Start = AR->getStart();
1391 if (!Step->isOne() || !Start->isZero()) {
1392 DEBUG(dbgs() << "LV: PHI does not start at zero or steps by one.\n");
1399 LoopVectorizationCostModel::findBestVectorizationFactor(unsigned VF) {
1401 DEBUG(dbgs() << "LV: No vector target information. Not vectorizing. \n");
1405 float Cost = expectedCost(1);
1407 DEBUG(dbgs() << "LV: Scalar loop costs: "<< (int)Cost << ".\n");
1408 for (unsigned i=2; i <= VF; i*=2) {
1409 // Notice that the vector loop needs to be executed less times, so
1410 // we need to divide the cost of the vector loops by the width of
1411 // the vector elements.
1412 float VectorCost = expectedCost(i) / (float)i;
1413 DEBUG(dbgs() << "LV: Vector loop of width "<< i << " costs: " <<
1414 (int)VectorCost << ".\n");
1415 if (VectorCost < Cost) {
1421 DEBUG(dbgs() << "LV: Selecting VF = : "<< Width << ".\n");
1425 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
1426 // We can only estimate the cost of single basic block loops.
1427 assert(1 == TheLoop->getNumBlocks() && "Too many blocks in loop");
1429 BasicBlock *BB = TheLoop->getHeader();
1432 // For each instruction in the old loop.
1433 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1434 Instruction *Inst = it;
1435 Cost += getInstructionCost(Inst, VF);
1438 // Return the cost divided by VF, because we will be executing
1439 // less iterations of the vector form.
1444 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
1445 assert(VTTI && "Invalid vector target transformation info");
1446 switch (I->getOpcode()) {
1447 case Instruction::Br: {
1448 return VTTI->getInstrCost(I->getOpcode());
1450 case Instruction::PHI:
1451 // PHIs are handled the same as the binary instructions below.
1452 case Instruction::Add:
1453 case Instruction::FAdd:
1454 case Instruction::Sub:
1455 case Instruction::FSub:
1456 case Instruction::Mul:
1457 case Instruction::FMul:
1458 case Instruction::UDiv:
1459 case Instruction::SDiv:
1460 case Instruction::FDiv:
1461 case Instruction::URem:
1462 case Instruction::SRem:
1463 case Instruction::FRem:
1464 case Instruction::Shl:
1465 case Instruction::LShr:
1466 case Instruction::AShr:
1467 case Instruction::And:
1468 case Instruction::Or:
1469 case Instruction::Xor: {
1470 Type *VTy = VectorType::get(I->getType(), VF);
1471 return VTTI->getInstrCost(I->getOpcode(), VTy);
1473 case Instruction::Select: {
1474 SelectInst *SI = cast<SelectInst>(I);
1475 Type *VTy = VectorType::get(I->getType(), VF);
1476 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
1477 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
1478 Type *CondTy = SI->getCondition()->getType();
1480 CondTy = VectorType::get(CondTy, VF);
1482 return VTTI->getInstrCost(I->getOpcode(), VTy, CondTy);
1484 case Instruction::ICmp:
1485 case Instruction::FCmp: {
1486 Type *VTy = VectorType::get(I->getOperand(0)->getType(), VF);
1487 return VTTI->getInstrCost(I->getOpcode(), VTy);
1489 case Instruction::Store: {
1490 StoreInst *SI = cast<StoreInst>(I);
1491 Type *VTy = VectorType::get(SI->getValueOperand()->getType(), VF);
1493 // Scalarized stores.
1494 if (!Legal->isConsecutiveGep(SI->getPointerOperand())) {
1496 unsigned ExtCost = VTTI->getInstrCost(Instruction::ExtractElement, VTy);
1497 // The cost of extracting from the vector value.
1498 Cost += VF * ExtCost;
1499 // The cost of the scalar stores.
1500 Cost += VF * VTTI->getInstrCost(I->getOpcode(), VTy->getScalarType());
1505 return VTTI->getMemoryOpCost(I->getOpcode(), VTy, SI->getAlignment(),
1506 SI->getPointerAddressSpace());
1508 case Instruction::Load: {
1509 LoadInst *LI = cast<LoadInst>(I);
1510 Type *VTy = VectorType::get(I->getType(), VF);
1512 // Scalarized loads.
1513 if (!Legal->isConsecutiveGep(LI->getPointerOperand())) {
1515 unsigned InCost = VTTI->getInstrCost(Instruction::InsertElement, VTy);
1516 // The cost of inserting the loaded value into the result vector.
1517 Cost += VF * InCost;
1518 // The cost of the scalar stores.
1519 Cost += VF * VTTI->getInstrCost(I->getOpcode(), VTy->getScalarType());
1524 return VTTI->getMemoryOpCost(I->getOpcode(), VTy, LI->getAlignment(),
1525 LI->getPointerAddressSpace());
1527 case Instruction::ZExt:
1528 case Instruction::SExt:
1529 case Instruction::FPToUI:
1530 case Instruction::FPToSI:
1531 case Instruction::FPExt:
1532 case Instruction::PtrToInt:
1533 case Instruction::IntToPtr:
1534 case Instruction::SIToFP:
1535 case Instruction::UIToFP:
1536 case Instruction::Trunc:
1537 case Instruction::FPTrunc:
1538 case Instruction::BitCast: {
1539 Type *SrcTy = VectorType::get(I->getOperand(0)->getType(), VF);
1540 Type *DstTy = VectorType::get(I->getType(), VF);
1541 return VTTI->getInstrCost(I->getOpcode(), DstTy, SrcTy);
1544 // We are scalarizing the instruction. Return the cost of the scalar
1545 // instruction, plus the cost of insert and extract into vector
1546 // elements, times the vector width.
1548 Type *Ty = I->getType();
1550 if (!Ty->isVoidTy()) {
1551 Type *VTy = VectorType::get(Ty, VF);
1552 unsigned InsCost = VTTI->getInstrCost(Instruction::InsertElement, VTy);
1553 unsigned ExtCost = VTTI->getInstrCost(Instruction::ExtractElement, VTy);
1554 Cost += VF * (InsCost + ExtCost);
1557 /// We don't have any information on the scalar instruction, but maybe
1559 /// TODO: This may be a target-specific intrinsic.
1560 /// Need to add API for that.
1561 Cost += VF * VTTI->getInstrCost(I->getOpcode(), Ty);
1571 char LoopVectorize::ID = 0;
1572 static const char lv_name[] = "Loop Vectorization";
1573 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
1574 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
1575 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1576 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
1577 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
1580 Pass *createLoopVectorizePass() {
1581 return new LoopVectorize();