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 a simple loop vectorizer. We currently only support single block
11 // loops. We have a very simple and restrictive legality check: we need to read
12 // and write from disjoint memory locations. We still don't have a cost model.
13 // We do support integer reductions.
15 // This pass has three parts:
16 // 1. The main loop pass that drives the different parts.
17 // 2. LoopVectorizationLegality - A helper class that checks for the legality
18 // of the vectorization.
19 // 3. SingleBlockLoopVectorizer - A helper class that performs the actual
20 // widening of instructions.
22 //===----------------------------------------------------------------------===//
23 #define LV_NAME "loop-vectorize"
24 #define DEBUG_TYPE LV_NAME
25 #include "llvm/Constants.h"
26 #include "llvm/DerivedTypes.h"
27 #include "llvm/Instructions.h"
28 #include "llvm/LLVMContext.h"
29 #include "llvm/Pass.h"
30 #include "llvm/Analysis/LoopPass.h"
31 #include "llvm/Value.h"
32 #include "llvm/Function.h"
33 #include "llvm/Analysis/Verifier.h"
34 #include "llvm/Module.h"
35 #include "llvm/Type.h"
36 #include "llvm/ADT/SmallVector.h"
37 #include "llvm/ADT/StringExtras.h"
38 #include "llvm/Analysis/AliasAnalysis.h"
39 #include "llvm/Analysis/AliasSetTracker.h"
40 #include "llvm/Transforms/Scalar.h"
41 #include "llvm/Analysis/ScalarEvolution.h"
42 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
43 #include "llvm/Analysis/ScalarEvolutionExpander.h"
44 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
45 #include "llvm/Analysis/ValueTracking.h"
46 #include "llvm/Analysis/LoopInfo.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include "llvm/DataLayout.h"
51 #include "llvm/Transforms/Utils/Local.h"
55 static cl::opt<unsigned>
56 DefaultVectorizationFactor("default-loop-vectorize-width",
57 cl::init(4), cl::Hidden,
58 cl::desc("Set the default loop vectorization width"));
61 // Forward declaration.
62 class LoopVectorizationLegality;
64 /// Vectorize a simple loop. This class performs the widening of simple single
65 /// basic block loops into vectors. It does not perform any
66 /// vectorization-legality checks, and just does it. It widens the vectors
67 /// to a given vectorization factor (VF).
68 class SingleBlockLoopVectorizer {
71 SingleBlockLoopVectorizer(Loop *OrigLoop, ScalarEvolution *Se, LoopInfo *Li,
72 LPPassManager *Lpm, unsigned VecWidth):
73 Orig(OrigLoop), SE(Se), LI(Li), LPM(Lpm), VF(VecWidth),
74 Builder(0), Induction(0), OldInduction(0) { }
76 ~SingleBlockLoopVectorizer() {
80 // Perform the actual loop widening (vectorization).
81 void vectorize(LoopVectorizationLegality *Legal) {
82 ///Create a new empty loop. Unlink the old loop and connect the new one.
84 /// Widen each instruction in the old loop to a new one in the new loop.
85 /// Use the Legality module to find the induction and reduction variables.
87 // register the new loop.
92 /// Create an empty loop, based on the loop ranges of the old loop.
93 void createEmptyLoop();
94 /// Copy and widen the instructions from the old loop.
95 void vectorizeLoop(LoopVectorizationLegality *Legal);
96 /// Insert the new loop to the loop hierarchy and pass manager.
99 /// This instruction is un-vectorizable. Implement it as a sequence
101 void scalarizeInstruction(Instruction *Instr);
103 /// Create a broadcast instruction. This method generates a broadcast
104 /// instruction (shuffle) for loop invariant values and for the induction
105 /// value. If this is the induction variable then we extend it to N, N+1, ...
106 /// this is needed because each iteration in the loop corresponds to a SIMD
108 Value *getBroadcastInstrs(Value *V);
110 /// This is a helper function used by getBroadcastInstrs. It adds 0, 1, 2 ..
111 /// for each element in the vector. Starting from zero.
112 Value *getConsecutiveVector(Value* Val);
114 /// Check that the GEP operands are all uniform except for the last index
115 /// which has to be the induction variable.
116 bool isConsecutiveGep(GetElementPtrInst *Gep);
118 /// When we go over instructions in the basic block we rely on previous
119 /// values within the current basic block or on loop invariant values.
120 /// When we widen (vectorize) values we place them in the map. If the values
121 /// are not within the map, they have to be loop invariant, so we simply
122 /// broadcast them into a vector.
123 Value *getVectorValue(Value *V);
125 /// Get a uniform vector of constant integers. We use this to get
126 /// vectors of ones and zeros for the reduction code.
127 Constant* getUniformVector(unsigned Val, Type* ScalarTy);
129 typedef DenseMap<Value*, Value*> ValueMap;
131 /// The original loop.
133 // Scev analysis to use.
137 // Loop Pass Manager;
139 // The vectorization factor to use.
142 // The builder that we use
143 IRBuilder<> *Builder;
145 // --- Vectorization state ---
147 /// Middle Block between the vector and the scalar.
148 BasicBlock *LoopMiddleBlock;
149 ///The ExitBlock of the scalar loop.
150 BasicBlock *LoopExitBlock;
151 ///The vector loop body.
152 BasicBlock *LoopVectorBody;
153 ///The scalar loop body.
154 BasicBlock *LoopScalarBody;
155 ///The first bypass block.
156 BasicBlock *LoopBypassBlock;
158 /// The new Induction variable which was added to the new block.
160 /// The induction variable of the old basic block.
161 PHINode *OldInduction;
162 // Maps scalars to widened vectors.
166 /// Perform the vectorization legality check. This class does not look at the
167 /// profitability of vectorization, only the legality. At the moment the checks
168 /// are very simple and focus on single basic block loops with a constant
169 /// iteration count and no reductions.
170 class LoopVectorizationLegality {
172 LoopVectorizationLegality(Loop *Lp, ScalarEvolution *Se, DataLayout *Dl):
173 TheLoop(Lp), SE(Se), DL(Dl), Induction(0) { }
175 /// This represents the kinds of reductions that we support.
177 IntegerAdd, /// Sum of numbers.
178 IntegerMult, /// Product of numbers.
179 NoReduction /// Not a reduction.
182 // Holds a pairing of reduction instruction and the reduction kind.
183 typedef std::pair<Instruction*, ReductionKind> ReductionPair;
185 /// ReductionList contains the reduction variables
186 /// as well as a single EXIT (from the block) value and the kind of
187 /// reduction variable..
188 /// Notice that the EXIT instruction can also be the PHI itself.
189 typedef DenseMap<PHINode*, ReductionPair> ReductionList;
191 /// Returns the maximum vectorization factor that we *can* use to vectorize
192 /// this loop. This does not mean that it is profitable to vectorize this
193 /// loop, only that it is legal to do so. This may be a large number. We
194 /// can vectorize to any SIMD width below this number.
195 unsigned getLoopMaxVF();
197 /// Returns the Induction variable.
198 PHINode *getInduction() {return Induction;}
200 /// Returns the reduction variables found in the loop.
201 ReductionList *getReductionVars() { return &Reductions; }
204 /// Check if a single basic block loop is vectorizable.
205 /// At this point we know that this is a loop with a constant trip count
206 /// and we only need to check individual instructions.
207 bool canVectorizeBlock(BasicBlock &BB);
209 // Check if a pointer value is known to be disjoint.
210 // Example: Alloca, Global, NoAlias.
211 bool isIdentifiedSafeObject(Value* Val);
213 /// Returns True, if 'Phi' is the kind of reduction variable for type
214 /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
215 bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
216 /// Checks if a constant matches the reduction kind.
217 /// Sums starts with zero. Products start at one.
218 bool isReductionConstant(Value *V, ReductionKind Kind);
219 /// Returns true if the instruction I can be a reduction variable of type
221 bool isReductionInstr(Instruction *I, ReductionKind Kind);
223 /// The loop that we evaluate.
227 /// DataLayout analysis.
230 // --- vectorization state --- //
232 /// Holds the induction variable.
234 /// Holds the reduction variables.
235 ReductionList Reductions;
236 /// Allowed outside users. This holds the reduction
237 /// vars which can be accessed from outside the loop.
238 SmallPtrSet<Value*, 4> AllowedExit;
241 struct LoopVectorize : public LoopPass {
242 static char ID; // Pass identification, replacement for typeid
244 LoopVectorize() : LoopPass(ID) {
245 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
252 virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
254 // Only vectorize innermost loops.
258 SE = &getAnalysis<ScalarEvolution>();
259 DL = getAnalysisIfAvailable<DataLayout>();
260 LI = &getAnalysis<LoopInfo>();
262 DEBUG(dbgs() << "LV: Checking a loop in \"" <<
263 L->getHeader()->getParent()->getName() << "\"\n");
265 // Check if it is legal to vectorize the loop.
266 LoopVectorizationLegality LVL(L, SE, DL);
267 unsigned MaxVF = LVL.getLoopMaxVF();
269 // Check that we can vectorize using the chosen vectorization width.
270 if (MaxVF < DefaultVectorizationFactor) {
271 DEBUG(dbgs() << "LV: non-vectorizable MaxVF ("<< MaxVF << ").\n");
275 DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< MaxVF << ").\n");
277 // If we decided that is is *legal* to vectorizer the loop. Do it.
278 SingleBlockLoopVectorizer LB(L, SE, LI, &LPM, DefaultVectorizationFactor);
281 DEBUG(verifyFunction(*L->getHeader()->getParent()));
285 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
286 LoopPass::getAnalysisUsage(AU);
287 AU.addRequiredID(LoopSimplifyID);
288 AU.addRequiredID(LCSSAID);
289 AU.addRequired<LoopInfo>();
290 AU.addRequired<ScalarEvolution>();
295 Value *SingleBlockLoopVectorizer::getBroadcastInstrs(Value *V) {
296 // Instructions that access the old induction variable
297 // actually want to get the new one.
298 if (V == OldInduction)
301 LLVMContext &C = V->getContext();
302 Type *VTy = VectorType::get(V->getType(), VF);
303 Type *I32 = IntegerType::getInt32Ty(C);
304 Constant *Zero = ConstantInt::get(I32, 0);
305 Value *Zeros = ConstantAggregateZero::get(VectorType::get(I32, VF));
306 Value *UndefVal = UndefValue::get(VTy);
307 // Insert the value into a new vector.
308 Value *SingleElem = Builder->CreateInsertElement(UndefVal, V, Zero);
309 // Broadcast the scalar into all locations in the vector.
310 Value *Shuf = Builder->CreateShuffleVector(SingleElem, UndefVal, Zeros,
312 // We are accessing the induction variable. Make sure to promote the
313 // index for each consecutive SIMD lane. This adds 0,1,2 ... to all lanes.
315 return getConsecutiveVector(Shuf);
319 Value *SingleBlockLoopVectorizer::getConsecutiveVector(Value* Val) {
320 assert(Val->getType()->isVectorTy() && "Must be a vector");
321 assert(Val->getType()->getScalarType()->isIntegerTy() &&
322 "Elem must be an integer");
324 Type *ITy = Val->getType()->getScalarType();
325 VectorType *Ty = cast<VectorType>(Val->getType());
326 unsigned VLen = Ty->getNumElements();
327 SmallVector<Constant*, 8> Indices;
329 // Create a vector of consecutive numbers from zero to VF.
330 for (unsigned i = 0; i < VLen; ++i)
331 Indices.push_back(ConstantInt::get(ITy, i));
333 // Add the consecutive indices to the vector value.
334 Constant *Cv = ConstantVector::get(Indices);
335 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
336 return Builder->CreateAdd(Val, Cv, "induction");
340 bool SingleBlockLoopVectorizer::isConsecutiveGep(GetElementPtrInst *Gep) {
344 unsigned NumOperands = Gep->getNumOperands();
345 Value *LastIndex = Gep->getOperand(NumOperands - 1);
347 // Check that all of the gep indices are uniform except for the last.
348 for (unsigned i = 0; i < NumOperands - 1; ++i)
349 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), Orig))
352 // We can emit wide load/stores only of the last index is the induction
354 const SCEV *Last = SE->getSCEV(LastIndex);
355 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
356 const SCEV *Step = AR->getStepRecurrence(*SE);
358 // The memory is consecutive because the last index is consecutive
359 // and all other indices are loop invariant.
367 Value *SingleBlockLoopVectorizer::getVectorValue(Value *V) {
368 assert(!V->getType()->isVectorTy() && "Can't widen a vector");
369 // If we saved a vectorized copy of V, use it.
370 ValueMap::iterator it = WidenMap.find(V);
371 if (it != WidenMap.end())
374 // Broadcast V and save the value for future uses.
375 Value *B = getBroadcastInstrs(V);
381 SingleBlockLoopVectorizer::getUniformVector(unsigned Val, Type* ScalarTy) {
382 SmallVector<Constant*, 8> Indices;
383 // Create a vector of consecutive numbers from zero to VF.
384 for (unsigned i = 0; i < VF; ++i)
385 Indices.push_back(ConstantInt::get(ScalarTy, Val));
387 // Add the consecutive indices to the vector value.
388 return ConstantVector::get(Indices);
391 void SingleBlockLoopVectorizer::scalarizeInstruction(Instruction *Instr) {
392 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
393 // Holds vector parameters or scalars, in case of uniform vals.
394 SmallVector<Value*, 8> Params;
396 // Find all of the vectorized parameters.
397 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
398 Value *SrcOp = Instr->getOperand(op);
400 // If we are accessing the old induction variable, use the new one.
401 if (SrcOp == OldInduction) {
402 Params.push_back(getBroadcastInstrs(Induction));
406 // Try using previously calculated values.
407 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
409 // If the src is an instruction that appeared earlier in the basic block
410 // then it should already be vectorized.
411 if (SrcInst && SrcInst->getParent() == Instr->getParent()) {
412 assert(WidenMap.count(SrcInst) && "Source operand is unavailable");
413 // The parameter is a vector value from earlier.
414 Params.push_back(WidenMap[SrcInst]);
416 // The parameter is a scalar from outside the loop. Maybe even a constant.
417 Params.push_back(SrcOp);
421 assert(Params.size() == Instr->getNumOperands() &&
422 "Invalid number of operands");
424 // Does this instruction return a value ?
425 bool IsVoidRetTy = Instr->getType()->isVoidTy();
426 Value *VecResults = 0;
428 // If we have a return value, create an empty vector. We place the scalarized
429 // instructions in this vector.
431 VecResults = UndefValue::get(VectorType::get(Instr->getType(), VF));
433 // For each scalar that we create.
434 for (unsigned i = 0; i < VF; ++i) {
435 Instruction *Cloned = Instr->clone();
437 Cloned->setName(Instr->getName() + ".cloned");
438 // Replace the operands of the cloned instrucions with extracted scalars.
439 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
440 Value *Op = Params[op];
441 // Param is a vector. Need to extract the right lane.
442 if (Op->getType()->isVectorTy())
443 Op = Builder->CreateExtractElement(Op, Builder->getInt32(i));
444 Cloned->setOperand(op, Op);
447 // Place the cloned scalar in the new loop.
448 Builder->Insert(Cloned);
450 // If the original scalar returns a value we need to place it in a vector
451 // so that future users will be able to use it.
453 VecResults = Builder->CreateInsertElement(VecResults, Cloned,
454 Builder->getInt32(i));
458 WidenMap[Instr] = VecResults;
461 void SingleBlockLoopVectorizer::createEmptyLoop() {
463 In this function we generate a new loop. The new loop will contain
464 the vectorized instructions while the old loop will continue to run the
467 [ ] <-- vector loop bypass.
470 | [ ] <-- vector pre header.
474 | [ ]_| <-- vector loop.
477 >[ ] <--- middle-block.
480 | [ ] <--- new preheader.
484 | [ ]_| <-- old scalar loop to handle remainder.
491 // This is the original scalar-loop preheader.
492 BasicBlock *BypassBlock = Orig->getLoopPreheader();
493 BasicBlock *ExitBlock = Orig->getExitBlock();
494 assert(ExitBlock && "Must have an exit block");
496 assert(Orig->getNumBlocks() == 1 && "Invalid loop");
497 assert(BypassBlock && "Invalid loop structure");
499 BasicBlock *VectorPH =
500 BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
501 BasicBlock *VecBody = VectorPH->splitBasicBlock(VectorPH->getTerminator(),
504 BasicBlock *MiddleBlock = VecBody->splitBasicBlock(VecBody->getTerminator(),
506 BasicBlock *ScalarPH =
507 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(),
509 // Find the induction variable.
510 BasicBlock *OldBasicBlock = Orig->getHeader();
511 OldInduction = dyn_cast<PHINode>(OldBasicBlock->begin());
512 assert(OldInduction && "We must have a single phi node.");
513 Type *IdxTy = OldInduction->getType();
515 // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
517 Builder = new IRBuilder<>(VecBody);
518 Builder->SetInsertPoint(VecBody->getFirstInsertionPt());
520 // Generate the induction variable.
521 Induction = Builder->CreatePHI(IdxTy, 2, "index");
522 Constant *Zero = ConstantInt::get(IdxTy, 0);
523 Constant *Step = ConstantInt::get(IdxTy, VF);
525 // Find the loop boundaries.
526 const SCEV *ExitCount = SE->getExitCount(Orig, Orig->getHeader());
527 assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
529 // Get the total trip count from the count by adding 1.
530 ExitCount = SE->getAddExpr(ExitCount,
531 SE->getConstant(ExitCount->getType(), 1));
533 // Expand the trip count and place the new instructions in the preheader.
534 // Notice that the pre-header does not change, only the loop body.
535 SCEVExpander Exp(*SE, "induction");
536 Instruction *Loc = BypassBlock->getTerminator();
538 // We may need to extend the index in case there is a type mismatch.
539 // We know that the count starts at zero and does not overflow.
540 // We are using Zext because it should be less expensive.
541 if (ExitCount->getType() != Induction->getType())
542 ExitCount = SE->getZeroExtendExpr(ExitCount, IdxTy);
544 // Count holds the overall loop count (N).
545 Value *Count = Exp.expandCodeFor(ExitCount, Induction->getType(), Loc);
546 // Now we need to generate the expression for N - (N % VF), which is
547 // the part that the vectorized body will execute.
548 Constant *CIVF = ConstantInt::get(IdxTy, VF);
549 Value *R = BinaryOperator::CreateURem(Count, CIVF, "n.mod.vf", Loc);
550 Value *CountRoundDown = BinaryOperator::CreateSub(Count, R, "n.vec", Loc);
552 // Now, compare the new count to zero. If it is zero, jump to the scalar part.
553 Value *Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
554 CountRoundDown, ConstantInt::getNullValue(IdxTy),
556 BranchInst::Create(MiddleBlock, VectorPH, Cmp, Loc);
557 // Remove the old terminator.
558 Loc->eraseFromParent();
560 // Add a check in the middle block to see if we have completed
561 // all of the iterations in the first vector loop.
562 // If (N - N%VF) == N, then we *don't* need to run the remainder.
563 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, Count,
564 CountRoundDown, "cmp.n",
565 MiddleBlock->getTerminator());
567 BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
568 // Remove the old terminator.
569 MiddleBlock->getTerminator()->eraseFromParent();
571 // Create i+1 and fill the PHINode.
572 Value *NextIdx = Builder->CreateAdd(Induction, Step, "index.next");
573 Induction->addIncoming(Zero, VectorPH);
574 Induction->addIncoming(NextIdx, VecBody);
575 // Create the compare.
576 Value *ICmp = Builder->CreateICmpEQ(NextIdx, CountRoundDown);
577 Builder->CreateCondBr(ICmp, MiddleBlock, VecBody);
579 // Now we have two terminators. Remove the old one from the block.
580 VecBody->getTerminator()->eraseFromParent();
582 // Fix the scalar body iteration count.
583 unsigned BlockIdx = OldInduction->getBasicBlockIndex(ScalarPH);
584 OldInduction->setIncomingValue(BlockIdx, CountRoundDown);
586 // Get ready to start creating new instructions into the vectorized body.
587 Builder->SetInsertPoint(VecBody->getFirstInsertionPt());
589 // Register the new loop.
590 Loop* Lp = new Loop();
591 LPM->insertLoop(Lp, Orig->getParentLoop());
593 Lp->addBasicBlockToLoop(VecBody, LI->getBase());
595 Loop *ParentLoop = Orig->getParentLoop();
597 ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
598 ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
599 ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
603 LoopMiddleBlock = MiddleBlock;
604 LoopExitBlock = ExitBlock;
605 LoopVectorBody = VecBody;
606 LoopScalarBody = OldBasicBlock;
607 LoopBypassBlock = BypassBlock;
611 SingleBlockLoopVectorizer::vectorizeLoop(LoopVectorizationLegality *Legal) {
612 typedef SmallVector<PHINode*, 4> PhiVector;
613 BasicBlock &BB = *Orig->getHeader();
615 // In order to support reduction variables we need to be able to vectorize
616 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
617 // steages. First, we create a new vector PHI node with no incoming edges.
618 // We use this value when we vectorize all of the instructions that use the
619 // PHI. Next, after all of the instructions in the block are complete we
620 // add the new incoming edges to the PHI. At this point all of the
621 // instructions in the basic block are vectorized, so we can use them to
622 // construct the PHI.
625 // For each instruction in the old loop.
626 for (BasicBlock::iterator it = BB.begin(), e = BB.end(); it != e; ++it) {
627 Instruction *Inst = it;
629 switch (Inst->getOpcode()) {
630 case Instruction::Br:
631 // Nothing to do for PHIs and BR, since we already took care of the
632 // loop control flow instructions.
634 case Instruction::PHI:{
635 PHINode* P = cast<PHINode>(Inst);
636 // Special handling for the induction var.
637 if (OldInduction == Inst)
639 // This is phase I of vectorizing PHIs.
640 // This has to be a reduction variable.
641 assert(Legal->getReductionVars()->count(P) && "Not a Reduction");
642 Type *VecTy = VectorType::get(Inst->getType(), VF);
643 WidenMap[Inst] = Builder->CreatePHI(VecTy, 2, "vec.phi");
644 PHIsToFix.push_back(P);
647 case Instruction::Add:
648 case Instruction::FAdd:
649 case Instruction::Sub:
650 case Instruction::FSub:
651 case Instruction::Mul:
652 case Instruction::FMul:
653 case Instruction::UDiv:
654 case Instruction::SDiv:
655 case Instruction::FDiv:
656 case Instruction::URem:
657 case Instruction::SRem:
658 case Instruction::FRem:
659 case Instruction::Shl:
660 case Instruction::LShr:
661 case Instruction::AShr:
662 case Instruction::And:
663 case Instruction::Or:
664 case Instruction::Xor: {
665 // Just widen binops.
666 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
667 Value *A = getVectorValue(Inst->getOperand(0));
668 Value *B = getVectorValue(Inst->getOperand(1));
669 // Use this vector value for all users of the original instruction.
670 WidenMap[Inst] = Builder->CreateBinOp(BinOp->getOpcode(), A, B);
673 case Instruction::Select: {
675 // TODO: If the selector is loop invariant we can issue a select
676 // instruction with a scalar condition.
677 Value *A = getVectorValue(Inst->getOperand(0));
678 Value *B = getVectorValue(Inst->getOperand(1));
679 Value *C = getVectorValue(Inst->getOperand(2));
680 WidenMap[Inst] = Builder->CreateSelect(A, B, C);
684 case Instruction::ICmp:
685 case Instruction::FCmp: {
686 // Widen compares. Generate vector compares.
687 bool FCmp = (Inst->getOpcode() == Instruction::FCmp);
688 CmpInst *Cmp = dyn_cast<CmpInst>(Inst);
689 Value *A = getVectorValue(Inst->getOperand(0));
690 Value *B = getVectorValue(Inst->getOperand(1));
692 WidenMap[Inst] = Builder->CreateFCmp(Cmp->getPredicate(), A, B);
694 WidenMap[Inst] = Builder->CreateICmp(Cmp->getPredicate(), A, B);
698 case Instruction::Store: {
699 // Attempt to issue a wide store.
700 StoreInst *SI = dyn_cast<StoreInst>(Inst);
701 Type *StTy = VectorType::get(SI->getValueOperand()->getType(), VF);
702 Value *Ptr = SI->getPointerOperand();
703 unsigned Alignment = SI->getAlignment();
704 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
705 // This store does not use GEPs.
706 if (!isConsecutiveGep(Gep)) {
707 scalarizeInstruction(Inst);
711 // Create the new GEP with the new induction variable.
712 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
713 unsigned NumOperands = Gep->getNumOperands();
714 Gep2->setOperand(NumOperands - 1, Induction);
715 Ptr = Builder->Insert(Gep2);
716 Ptr = Builder->CreateBitCast(Ptr, StTy->getPointerTo());
717 Value *Val = getVectorValue(SI->getValueOperand());
718 Builder->CreateStore(Val, Ptr)->setAlignment(Alignment);
721 case Instruction::Load: {
722 // Attempt to issue a wide load.
723 LoadInst *LI = dyn_cast<LoadInst>(Inst);
724 Type *RetTy = VectorType::get(LI->getType(), VF);
725 Value *Ptr = LI->getPointerOperand();
726 unsigned Alignment = LI->getAlignment();
727 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
729 // We don't have a gep. Scalarize the load.
730 if (!isConsecutiveGep(Gep)) {
731 scalarizeInstruction(Inst);
735 // Create the new GEP with the new induction variable.
736 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
737 unsigned NumOperands = Gep->getNumOperands();
738 Gep2->setOperand(NumOperands - 1, Induction);
739 Ptr = Builder->Insert(Gep2);
740 Ptr = Builder->CreateBitCast(Ptr, RetTy->getPointerTo());
741 LI = Builder->CreateLoad(Ptr);
742 LI->setAlignment(Alignment);
743 // Use this vector value for all users of the load.
747 case Instruction::ZExt:
748 case Instruction::SExt:
749 case Instruction::FPToUI:
750 case Instruction::FPToSI:
751 case Instruction::FPExt:
752 case Instruction::PtrToInt:
753 case Instruction::IntToPtr:
754 case Instruction::SIToFP:
755 case Instruction::UIToFP:
756 case Instruction::Trunc:
757 case Instruction::FPTrunc:
758 case Instruction::BitCast: {
759 /// Vectorize bitcasts.
760 CastInst *CI = dyn_cast<CastInst>(Inst);
761 Value *A = getVectorValue(Inst->getOperand(0));
762 Type *DestTy = VectorType::get(CI->getType()->getScalarType(), VF);
763 WidenMap[Inst] = Builder->CreateCast(CI->getOpcode(), A, DestTy);
768 /// All other instructions are unsupported. Scalarize them.
769 scalarizeInstruction(Inst);
772 }// end of for_each instr.
774 // At this point every instruction in the original loop is widended to
775 // a vector form. We are almost done. Now, we need to fix the PHI nodes
776 // that we vectorized. The PHI nodes are currently empty because we did
777 // not want to introduce cycles. Notice that the remaining PHI nodes
778 // that we need to fix are reduction variables.
780 // Create the 'reduced' values for each of the induction vars.
781 // The reduced values are the vector values that we scalarize and combine
782 // after the loop is finished.
783 for (PhiVector::iterator it = PHIsToFix.begin(), e = PHIsToFix.end();
785 PHINode *RdxPhi = *it;
786 PHINode *VecRdxPhi = dyn_cast<PHINode>(WidenMap[RdxPhi]);
787 assert(RdxPhi && "Unable to recover vectorized PHI");
789 // Find the reduction variable.
790 assert(Legal->getReductionVars()->count(RdxPhi) &&
791 "Unable to find the reduction variable");
792 LoopVectorizationLegality::ReductionPair ReductionVar =
793 (*Legal->getReductionVars())[RdxPhi];
795 // This is the vector-clone of the value that leaves the loop.
796 Value *VectorExit = getVectorValue(ReductionVar.first);
797 Type *VecTy = VectorExit->getType();
799 // This is the kind of reduction.
800 LoopVectorizationLegality::ReductionKind RdxKind = ReductionVar.second;
801 // Find the reduction identity variable.
802 // Zero for addition. One for Multiplication.
803 unsigned IdentitySclr =
804 (RdxKind == LoopVectorizationLegality::IntegerAdd ? 0 : 1);
805 Constant *Identity = getUniformVector(IdentitySclr, VecTy->getScalarType());
807 // Fix the vector-loop phi.
808 // We created the induction variable so we know that the
809 // preheader is the first entry.
810 BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
811 VecRdxPhi->addIncoming(Identity, VecPreheader);
812 unsigned SelfEdgeIdx = (RdxPhi)->getBasicBlockIndex(LoopScalarBody);
813 Value *Val = getVectorValue(RdxPhi->getIncomingValue(SelfEdgeIdx));
814 VecRdxPhi->addIncoming(Val, LoopVectorBody);
816 // Before each round, move the insertion point right between
817 // the PHIs and the values we are going to write.
818 // This allows us to write both PHINodes and the extractelement
820 Builder->SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
822 // This PHINode contains the vectorized reduction variable, or
823 // the identity vector, if we bypass the vector loop.
824 PHINode *NewPhi = Builder->CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
825 NewPhi->addIncoming(Identity, LoopBypassBlock);
826 NewPhi->addIncoming(getVectorValue(ReductionVar.first), LoopVectorBody);
828 // Extract the first scalar.
830 Builder->CreateExtractElement(NewPhi, Builder->getInt32(0));
831 // Extract and sum the remaining vector elements.
832 for (unsigned i=1; i < VF; ++i) {
834 Builder->CreateExtractElement(NewPhi, Builder->getInt32(i));
835 if (RdxKind == LoopVectorizationLegality::IntegerAdd) {
836 Scalar0 = Builder->CreateAdd(Scalar0, Scalar1);
838 Scalar0 = Builder->CreateMul(Scalar0, Scalar1);
842 // Now, we need to fix the users of the reduction variable
843 // inside and outside of the scalar remainder loop.
844 // We know that the loop is in LCSSA form. We need to update the
845 // PHI nodes in the exit blocks.
846 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
847 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
848 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
849 if (!LCSSAPhi) continue;
851 // All PHINodes need to have a single entry edge, or two if we already fixed them.
852 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
854 // We found our reduction value exit-PHI. Update it with the incoming bypass edge.
855 if (LCSSAPhi->getIncomingValue(0) == ReductionVar.first) {
856 // Add an edge coming from the bypass.
857 LCSSAPhi->addIncoming(Scalar0, LoopMiddleBlock);
860 }// end of the LCSSA phi scan.
862 // Fix the scalar loop reduction variable with the incoming reduction sum
863 // from the vector body and from the backedge value.
864 int IncomingEdgeBlockIdx = (RdxPhi)->getBasicBlockIndex(LoopScalarBody);
865 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1); // The other block.
866 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, Scalar0);
867 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, ReductionVar.first);
868 }// end of for each redux variable.
871 void SingleBlockLoopVectorizer::cleanup() {
872 // The original basic block.
873 SE->forgetLoop(Orig);
876 unsigned LoopVectorizationLegality::getLoopMaxVF() {
877 if (!TheLoop->getLoopPreheader()) {
878 assert(false && "No preheader!!");
879 DEBUG(dbgs() << "LV: Loop not normalized." << "\n");
883 // We can only vectorize single basic block loops.
884 unsigned NumBlocks = TheLoop->getNumBlocks();
885 if (NumBlocks != 1) {
886 DEBUG(dbgs() << "LV: Too many blocks:" << NumBlocks << "\n");
890 // We need to have a loop header.
891 BasicBlock *BB = TheLoop->getHeader();
892 DEBUG(dbgs() << "LV: Found a loop: " << BB->getName() << "\n");
894 // Go over each instruction and look at memory deps.
895 if (!canVectorizeBlock(*BB)) {
896 DEBUG(dbgs() << "LV: Can't vectorize this loop header\n");
900 // ScalarEvolution needs to be able to find the exit count.
901 const SCEV *ExitCount = SE->getExitCount(TheLoop, BB);
902 if (ExitCount == SE->getCouldNotCompute()) {
903 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
907 DEBUG(dbgs() << "LV: We can vectorize this loop!\n");
909 // Okay! We can vectorize. At this point we don't have any other mem analysis
910 // which may limit our maximum vectorization factor, so just return the
911 // maximum SIMD size.
912 return DefaultVectorizationFactor;
915 bool LoopVectorizationLegality::canVectorizeBlock(BasicBlock &BB) {
916 // Holds the read and write pointers that we find.
917 typedef SmallVector<Value*, 10> ValueVector;
921 for (BasicBlock::iterator it = BB.begin(), e = BB.end(); it != e; ++it) {
924 PHINode *Phi = dyn_cast<PHINode>(I);
926 // This should not happen because the loop should be normalized.
927 if (Phi->getNumIncomingValues() != 2) {
928 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
931 // We only look at integer phi nodes.
932 if (!Phi->getType()->isIntegerTy()) {
933 DEBUG(dbgs() << "LV: Found an non-int PHI.\n");
936 if (AddReductionVar(Phi, IntegerAdd)) {
937 DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
940 if (AddReductionVar(Phi, IntegerMult)) {
941 DEBUG(dbgs() << "LV: Found an Mult reduction PHI."<< *Phi <<"\n");
945 DEBUG(dbgs() << "LV: Found too many PHIs.\n");
948 // Found the induction variable.
951 // Check that the PHI is consecutive and starts at zero.
952 const SCEV *PhiScev = SE->getSCEV(Phi);
953 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
955 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
959 const SCEV *Step = AR->getStepRecurrence(*SE);
960 const SCEV *Start = AR->getStart();
962 if (!Step->isOne() || !Start->isZero()) {
963 DEBUG(dbgs() << "LV: PHI does not start at zero or steps by one.\n");
966 }// end of PHI handling
968 // If this is a load, record its pointer. If it is not a load, abort.
969 // Notice that we don't handle function calls that read or write.
970 if (I->mayReadFromMemory()) {
971 LoadInst *Ld = dyn_cast<LoadInst>(I);
972 if (!Ld) return false;
973 if (!Ld->isSimple()) {
974 DEBUG(dbgs() << "LV: Found a non-simple load.\n");
978 Value* Ptr = Ld->getPointerOperand();
979 GetUnderlyingObjects(Ptr, Reads, DL);
982 // Record store pointers. Abort on all other instructions that write to
984 if (I->mayWriteToMemory()) {
985 StoreInst *St = dyn_cast<StoreInst>(I);
986 if (!St) return false;
987 if (!St->isSimple()) {
988 DEBUG(dbgs() << "LV: Found a non-simple store.\n");
992 Value* Ptr = St->getPointerOperand();
993 GetUnderlyingObjects(Ptr, Writes, DL);
996 // We still don't handle functions.
997 CallInst *CI = dyn_cast<CallInst>(I);
999 DEBUG(dbgs() << "LV: Found a call site:"<<
1000 CI->getCalledFunction()->getName() << "\n");
1004 // We do not re-vectorize vectors.
1005 if (!VectorType::isValidElementType(I->getType()) &&
1006 !I->getType()->isVoidTy()) {
1007 DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n");
1011 // Reduction instructions are allowed to have exit users.
1012 // All other instructions must not have external users.
1013 if (!AllowedExit.count(I))
1014 //Check that all of the users of the loop are inside the BB.
1015 for (Value::use_iterator it = I->use_begin(), e = I->use_end();
1017 Instruction *U = cast<Instruction>(*it);
1018 // This user may be a reduction exit value.
1019 BasicBlock *Parent = U->getParent();
1020 if (Parent != &BB) {
1021 DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n");
1028 DEBUG(dbgs() << "LV: Did not find an induction var.\n");
1032 // Check that the underlying objects of the reads and writes are either
1033 // disjoint memory locations, or that they are no-alias arguments.
1034 ValueVector::iterator r, re, w, we;
1035 for (r = Reads.begin(), re = Reads.end(); r != re; ++r) {
1036 if (!isIdentifiedSafeObject(*r)) {
1037 DEBUG(dbgs() << "LV: Found a bad read Ptr: "<< **r << "\n");
1042 for (w = Writes.begin(), we = Writes.end(); w != we; ++w) {
1043 if (!isIdentifiedSafeObject(*w)) {
1044 DEBUG(dbgs() << "LV: Found a bad write Ptr: "<< **w << "\n");
1049 // Check that there are no multiple write locations to the same pointer.
1050 SmallPtrSet<Value*, 8> WritePointerSet;
1051 for (w = Writes.begin(), we = Writes.end(); w != we; ++w) {
1052 if (!WritePointerSet.insert(*w)) {
1053 DEBUG(dbgs() << "LV: Multiple writes to the same index :"<< **w << "\n");
1058 // Check that the reads and the writes are disjoint.
1059 for (r = Reads.begin(), re = Reads.end(); r != re; ++r) {
1060 if (WritePointerSet.count(*r)) {
1061 DEBUG(dbgs() << "Vectorizer: Found a read/write ptr:"<< **r << "\n");
1070 /// Checks if the value is a Global variable or if it is an Arguments
1071 /// marked with the NoAlias attribute.
1072 bool LoopVectorizationLegality::isIdentifiedSafeObject(Value* Val) {
1073 assert(Val && "Invalid value");
1074 if (dyn_cast<GlobalValue>(Val))
1076 if (dyn_cast<AllocaInst>(Val))
1078 Argument *A = dyn_cast<Argument>(Val);
1081 return A->hasNoAliasAttr();
1084 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
1085 ReductionKind Kind) {
1086 if (Phi->getNumIncomingValues() != 2)
1089 // Find the possible incoming reduction variable.
1090 BasicBlock *BB = Phi->getParent();
1091 int SelfEdgeIdx = Phi->getBasicBlockIndex(BB);
1092 int InEdgeBlockIdx = (SelfEdgeIdx ? 0 : 1); // The other entry.
1093 Value *RdxStart = Phi->getIncomingValue(InEdgeBlockIdx);
1095 // We must have a constant that starts the reduction.
1096 if (!isReductionConstant(RdxStart, Kind))
1099 // ExitInstruction is the single value which is used outside the loop.
1100 // We only allow for a single reduction value to be used outside the loop.
1101 // This includes users of the reduction, variables (which form a cycle
1102 // which ends in the phi node).
1103 Instruction *ExitInstruction = 0;
1105 // Iter is our iterator. We start with the PHI node and scan for all of the
1106 // users of this instruction. All users must be instructions which can be
1107 // used as reduction variables (such as ADD). We may have a single
1108 // out-of-block user. They cycle must end with the original PHI.
1109 // Also, we can't have multiple block-local users.
1110 Instruction *Iter = Phi;
1112 // Any reduction instr must be of one of the allowed kinds.
1113 if (!isReductionInstr(Iter, Kind))
1116 // Did we found a user inside this block ?
1117 bool FoundInBlockUser = false;
1118 // Did we reach the initial PHI node ?
1119 bool FoundStartPHI = false;
1120 // For each of the *users* of iter.
1121 for (Value::use_iterator it = Iter->use_begin(), e = Iter->use_end();
1123 Instruction *U = cast<Instruction>(*it);
1124 // We already know that the PHI is a user.
1126 FoundStartPHI = true;
1129 // Check if we found the exit user.
1130 BasicBlock *Parent = U->getParent();
1132 // We must have a single exit instruction.
1133 if (ExitInstruction != 0)
1135 ExitInstruction = Iter;
1137 // We can't have multiple inside users.
1138 if (FoundInBlockUser)
1140 FoundInBlockUser = true;
1144 // We found a reduction var if we have reached the original
1145 // phi node and we only have a single instruction with out-of-loop
1147 if (FoundStartPHI && ExitInstruction) {
1148 // This instruction is allowed to have out-of-loop users.
1149 AllowedExit.insert(ExitInstruction);
1150 // Mark this as a reduction var.
1151 Reductions[Phi] = std::make_pair(ExitInstruction, Kind);
1158 LoopVectorizationLegality::isReductionConstant(Value *V, ReductionKind Kind) {
1159 ConstantInt *CI = dyn_cast<ConstantInt>(V);
1162 if (Kind == IntegerMult && CI->isOne())
1164 if (Kind == IntegerAdd && CI->isZero())
1170 LoopVectorizationLegality::isReductionInstr(Instruction *I,
1171 ReductionKind Kind) {
1172 switch (I->getOpcode()) {
1175 case Instruction::PHI:
1178 case Instruction::Add:
1179 case Instruction::Sub:
1180 return Kind == IntegerAdd;
1181 case Instruction::Mul:
1182 case Instruction::UDiv:
1183 case Instruction::SDiv:
1184 return Kind == IntegerMult;
1190 char LoopVectorize::ID = 0;
1191 static const char lv_name[] = "Loop Vectorization";
1192 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
1193 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
1194 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1195 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
1196 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
1199 Pass *createLoopVectorizePass() {
1200 return new LoopVectorize();