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 // This pass has three parts:
14 // 1. The main loop pass that drives the different parts.
15 // 2. LoopVectorizationLegality - A helper class that checks for the legality
16 // of the vectorization.
17 // 3. SingleBlockLoopVectorizer - A helper class that performs the actual
18 // widening of instructions.
20 //===----------------------------------------------------------------------===//
21 #define LV_NAME "loop-vectorize"
22 #define DEBUG_TYPE LV_NAME
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/LLVMContext.h"
27 #include "llvm/Pass.h"
28 #include "llvm/Analysis/LoopPass.h"
29 #include "llvm/Value.h"
30 #include "llvm/Function.h"
31 #include "llvm/Analysis/Verifier.h"
32 #include "llvm/Module.h"
33 #include "llvm/Type.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/ADT/StringExtras.h"
36 #include "llvm/Analysis/AliasAnalysis.h"
37 #include "llvm/Analysis/AliasSetTracker.h"
38 #include "llvm/Transforms/Scalar.h"
39 #include "llvm/Analysis/ScalarEvolution.h"
40 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
41 #include "llvm/Analysis/ScalarEvolutionExpander.h"
42 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
43 #include "llvm/Analysis/ValueTracking.h"
44 #include "llvm/Analysis/LoopInfo.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include "llvm/DataLayout.h"
49 #include "llvm/Transforms/Utils/Local.h"
53 static cl::opt<unsigned>
54 DefaultVectorizationFactor("default-loop-vectorize-width",
55 cl::init(4), cl::Hidden,
56 cl::desc("Set the default loop vectorization width"));
60 /// Vectorize a simple loop. This class performs the widening of simple single
61 /// basic block loops into vectors. It does not perform any
62 /// vectorization-legality checks, and just does it. It widens the vectors
63 /// to a given vectorization factor (VF).
64 class SingleBlockLoopVectorizer {
67 SingleBlockLoopVectorizer(Loop *OrigLoop, ScalarEvolution *Se, LoopInfo *Li,
68 LPPassManager *Lpm, unsigned VecWidth):
69 Orig(OrigLoop), SE(Se), LI(Li), LPM(Lpm), VF(VecWidth),
70 Builder(0), Induction(0), OldInduction(0) { }
72 ~SingleBlockLoopVectorizer() {
76 // Perform the actual loop widening (vectorization).
78 ///Create a new empty loop. Unlink the old loop and connect the new one.
80 /// Widen each instruction in the old loop to a new one in the new loop.
82 // register the new loop.
87 /// Create an empty loop, based on the loop ranges of the old loop.
88 void createEmptyLoop();
89 /// Copy and widen the instructions from the old loop.
91 /// Insert the new loop to the loop hierarchy and pass manager.
94 /// This instruction is un-vectorizable. Implement it as a sequence
96 void scalarizeInstruction(Instruction *Instr);
98 /// Create a broadcast instruction. This method generates a broadcast
99 /// instruction (shuffle) for loop invariant values and for the induction
100 /// value. If this is the induction variable then we extend it to N, N+1, ...
101 /// this is needed because each iteration in the loop corresponds to a SIMD
103 Value *getBroadcastInstrs(Value *V);
105 /// This is a helper function used by getBroadcastInstrs. It adds 0, 1, 2 ..
106 /// for each element in the vector. Starting from zero.
107 Value *getConsecutiveVector(Value* Val);
109 /// Check that the GEP operands are all uniform except for the last index
110 /// which has to be the induction variable.
111 bool isConsecutiveGep(GetElementPtrInst *Gep);
113 /// When we go over instructions in the basic block we rely on previous
114 /// values within the current basic block or on loop invariant values.
115 /// When we widen (vectorize) values we place them in the map. If the values
116 /// are not within the map, they have to be loop invariant, so we simply
117 /// broadcast them into a vector.
118 Value *getVectorValue(Value *V);
120 typedef DenseMap<Value*, Value*> ValueMap;
122 /// The original loop.
124 // Scev analysis to use.
128 // Loop Pass Manager;
130 // The vectorization factor to use.
133 // The builder that we use
134 IRBuilder<> *Builder;
136 // --- Vectorization state ---
138 /// The new Induction variable which was added to the new block.
140 /// The induction variable of the old basic block.
141 PHINode *OldInduction;
142 // Maps scalars to widened vectors.
146 /// Perform the vectorization legality check. This class does not look at the
147 /// profitability of vectorization, only the legality. At the moment the checks
148 /// are very simple and focus on single basic block loops with a constant
149 /// iteration count and no reductions.
150 class LoopVectorizationLegality {
152 LoopVectorizationLegality(Loop *Lp, ScalarEvolution *Se, DataLayout *Dl):
153 TheLoop(Lp), SE(Se), DL(Dl) { }
155 /// Returns the maximum vectorization factor that we *can* use to vectorize
156 /// this loop. This does not mean that it is profitable to vectorize this
157 /// loop, only that it is legal to do so. This may be a large number. We
158 /// can vectorize to any SIMD width below this number.
159 unsigned getLoopMaxVF();
162 /// Check if a single basic block loop is vectorizable.
163 /// At this point we know that this is a loop with a constant trip count
164 /// and we only need to check individual instructions.
165 bool canVectorizeBlock(BasicBlock &BB);
167 // Check if a pointer value is known to be disjoint.
168 // Example: Alloca, Global, NoAlias.
169 bool isIdentifiedSafeObject(Value* Val);
171 /// The loop that we evaluate.
175 /// DataLayout analysis.
179 struct LoopVectorize : public LoopPass {
180 static char ID; // Pass identification, replacement for typeid
182 LoopVectorize() : LoopPass(ID) {
183 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
190 virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
191 // Only vectorize innermost loops.
195 SE = &getAnalysis<ScalarEvolution>();
196 DL = getAnalysisIfAvailable<DataLayout>();
197 LI = &getAnalysis<LoopInfo>();
199 DEBUG(dbgs() << "LV: Checking a loop in \"" <<
200 L->getHeader()->getParent()->getName() << "\"\n");
202 // Check if it is legal to vectorize the loop.
203 LoopVectorizationLegality LVL(L, SE, DL);
204 unsigned MaxVF = LVL.getLoopMaxVF();
206 // Check that we can vectorize using the chosen vectorization width.
207 if (MaxVF < DefaultVectorizationFactor) {
208 DEBUG(dbgs() << "LV: non-vectorizable MaxVF ("<< MaxVF << ").\n");
212 DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< MaxVF << ").\n");
214 // If we decided that is is *legal* to vectorizer the loop. Do it.
215 SingleBlockLoopVectorizer LB(L, SE, LI, &LPM, DefaultVectorizationFactor);
218 DEBUG(verifyFunction(*L->getHeader()->getParent()));
222 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
223 LoopPass::getAnalysisUsage(AU);
224 AU.addRequiredID(LoopSimplifyID);
225 AU.addRequired<LoopInfo>();
226 AU.addRequired<ScalarEvolution>();
231 Value *SingleBlockLoopVectorizer::getBroadcastInstrs(Value *V) {
232 // Instructions that access the old induction variable
233 // actually want to get the new one.
234 if (V == OldInduction)
237 LLVMContext &C = V->getContext();
238 Type *VTy = VectorType::get(V->getType(), VF);
239 Type *I32 = IntegerType::getInt32Ty(C);
240 Constant *Zero = ConstantInt::get(I32, 0);
241 Value *Zeros = ConstantAggregateZero::get(VectorType::get(I32, VF));
242 Value *UndefVal = UndefValue::get(VTy);
243 // Insert the value into a new vector.
244 Value *SingleElem = Builder->CreateInsertElement(UndefVal, V, Zero);
245 // Broadcast the scalar into all locations in the vector.
246 Value *Shuf = Builder->CreateShuffleVector(SingleElem, UndefVal, Zeros,
248 // We are accessing the induction variable. Make sure to promote the
249 // index for each consecutive SIMD lane. This adds 0,1,2 ... to all lanes.
251 return getConsecutiveVector(Shuf);
255 Value *SingleBlockLoopVectorizer::getConsecutiveVector(Value* Val) {
256 assert(Val->getType()->isVectorTy() && "Must be a vector");
257 assert(Val->getType()->getScalarType()->isIntegerTy() &&
258 "Elem must be an integer");
260 Type *ITy = Val->getType()->getScalarType();
261 VectorType *Ty = cast<VectorType>(Val->getType());
262 unsigned VLen = Ty->getNumElements();
263 SmallVector<Constant*, 8> Indices;
265 // Create a vector of consecutive numbers from zero to VF.
266 for (unsigned i = 0; i < VLen; ++i)
267 Indices.push_back(ConstantInt::get(ITy, i));
269 // Add the consecutive indices to the vector value.
270 Constant *Cv = ConstantVector::get(Indices);
271 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
272 return Builder->CreateAdd(Val, Cv, "induction");
276 bool SingleBlockLoopVectorizer::isConsecutiveGep(GetElementPtrInst *Gep) {
280 unsigned NumOperands = Gep->getNumOperands();
281 Value *LastIndex = Gep->getOperand(NumOperands - 1);
283 // Check that all of the gep indices are uniform except for the last.
284 for (unsigned i = 0; i < NumOperands - 1; ++i)
285 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), Orig))
288 // We can emit wide load/stores only of the last index is the induction
290 const SCEV *Last = SE->getSCEV(LastIndex);
291 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
292 const SCEV *Step = AR->getStepRecurrence(*SE);
294 // The memory is consecutive because the last index is consecutive
295 // and all other indices are loop invariant.
303 Value *SingleBlockLoopVectorizer::getVectorValue(Value *V) {
304 // If we saved a vectorized copy of V, use it.
305 ValueMap::iterator it = WidenMap.find(V);
306 if (it != WidenMap.end())
309 // Broadcast V and save the value for future uses.
310 Value *B = getBroadcastInstrs(V);
315 void SingleBlockLoopVectorizer::scalarizeInstruction(Instruction *Instr) {
316 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
317 // Holds vector parameters or scalars, in case of uniform vals.
318 SmallVector<Value*, 8> Params;
320 // Find all of the vectorized parameters.
321 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
322 Value *SrcOp = Instr->getOperand(op);
324 // If we are accessing the old induction variable, use the new one.
325 if (SrcOp == OldInduction) {
326 Params.push_back(getBroadcastInstrs(Induction));
330 // Try using previously calculated values.
331 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
333 // If the src is an instruction that appeared earlier in the basic block
334 // then it should already be vectorized.
335 if (SrcInst && SrcInst->getParent() == Instr->getParent()) {
336 assert(WidenMap.count(SrcInst) && "Source operand is unavailable");
337 // The parameter is a vector value from earlier.
338 Params.push_back(WidenMap[SrcInst]);
340 // The parameter is a scalar from outside the loop. Maybe even a constant.
341 Params.push_back(SrcOp);
345 assert(Params.size() == Instr->getNumOperands() &&
346 "Invalid number of operands");
348 // Does this instruction return a value ?
349 bool IsVoidRetTy = Instr->getType()->isVoidTy();
350 Value *VecResults = 0;
352 // If we have a return value, create an empty vector. We place the scalarized
353 // instructions in this vector.
355 VecResults = UndefValue::get(VectorType::get(Instr->getType(), VF));
357 // For each scalar that we create.
358 for (unsigned i = 0; i < VF; ++i) {
359 Instruction *Cloned = Instr->clone();
361 Cloned->setName(Instr->getName() + ".cloned");
362 // Replace the operands of the cloned instrucions with extracted scalars.
363 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
364 Value *Op = Params[op];
365 // Param is a vector. Need to extract the right lane.
366 if (Op->getType()->isVectorTy())
367 Op = Builder->CreateExtractElement(Op, Builder->getInt32(i));
368 Cloned->setOperand(op, Op);
371 // Place the cloned scalar in the new loop.
372 Builder->Insert(Cloned);
374 // If the original scalar returns a value we need to place it in a vector
375 // so that future users will be able to use it.
377 VecResults = Builder->CreateInsertElement(VecResults, Cloned,
378 Builder->getInt32(i));
382 WidenMap[Instr] = VecResults;
385 void SingleBlockLoopVectorizer::createEmptyLoop() {
387 In this function we generate a new loop. The new loop will contain
388 the vectorized instructions while the old loop will continue to run the
391 [ ] <-- vector loop bypass.
394 | [ ] <-- vector pre header.
398 | [ ]_| <-- vector loop.
401 >[ ] <--- middle-block.
404 | [ ] <--- new preheader.
408 | [ ]_| <-- old scalar loop to handle remainder. ()
415 // This is the original scalar-loop preheader.
416 BasicBlock *BypassBlock = Orig->getLoopPreheader();
417 BasicBlock *ExitBlock = Orig->getExitBlock();
418 assert(ExitBlock && "Must have an exit block");
420 assert(Orig->getNumBlocks() == 1 && "Invalid loop");
421 assert(BypassBlock && "Invalid loop structure");
423 BasicBlock *VectorPH =
424 BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
425 BasicBlock *VecBody = VectorPH->splitBasicBlock(VectorPH->getTerminator(),
428 BasicBlock *MiddleBlock = VecBody->splitBasicBlock(VecBody->getTerminator(),
430 BasicBlock *ScalarPH =
431 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(),
434 // Find the induction variable.
435 BasicBlock *OldBasicBlock = Orig->getHeader();
436 OldInduction = dyn_cast<PHINode>(OldBasicBlock->begin());
437 assert(OldInduction && "We must have a single phi node.");
438 Type *IdxTy = OldInduction->getType();
440 // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
442 Builder = new IRBuilder<>(VecBody);
443 Builder->SetInsertPoint(VecBody->getFirstInsertionPt());
445 // Generate the induction variable.
446 Induction = Builder->CreatePHI(IdxTy, 2, "index");
447 Constant *Zero = ConstantInt::get(IdxTy, 0);
448 Constant *Step = ConstantInt::get(IdxTy, VF);
450 // Find the loop boundaries.
451 const SCEV *ExitCount = SE->getExitCount(Orig, Orig->getHeader());
452 assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
454 // Get the total trip count from the count by adding 1.
455 ExitCount = SE->getAddExpr(ExitCount,
456 SE->getConstant(ExitCount->getType(), 1));
458 // Expand the trip count and place the new instructions in the preheader.
459 // Notice that the pre-header does not change, only the loop body.
460 SCEVExpander Exp(*SE, "induction");
461 Instruction *Loc = BypassBlock->getTerminator();
463 // We may need to extend the index in case there is a type mismatch.
464 // We know that the count starts at zero and does not overflow.
465 // We are using Zext because it should be less expensive.
466 if (ExitCount->getType() != Induction->getType())
467 ExitCount = SE->getZeroExtendExpr(ExitCount, IdxTy);
469 // Count holds the overall loop count (N).
470 Value *Count = Exp.expandCodeFor(ExitCount, Induction->getType(), Loc);
471 // Now we need to generate the expression for N - (N % VF), which is
472 // the part that the vectorized body will execute.
473 Constant *CIVF = ConstantInt::get(IdxTy, VF);
474 Value *R = BinaryOperator::CreateURem(Count, CIVF, "n.mod.vf", Loc);
475 Value *CountRoundDown = BinaryOperator::CreateSub(Count, R, "n.vec", Loc);
477 // Now, compare the new count to zero. If it is zero, jump to the scalar part.
478 Value *Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
479 CountRoundDown, ConstantInt::getNullValue(IdxTy),
481 BranchInst::Create(MiddleBlock, VectorPH, Cmp, Loc);
482 // Remove the old terminator.
483 Loc->eraseFromParent();
485 // Add a check in the middle block to see if we have completed
486 // all of the iterations in the first vector loop.
487 // If (N - N%VF) == N, then we *don't* need to run the remainder.
488 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, Count,
489 CountRoundDown, "cmp.n",
490 MiddleBlock->getTerminator());
492 BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
493 // Remove the old terminator.
494 MiddleBlock->getTerminator()->eraseFromParent();
496 // Create i+1 and fill the PHINode.
497 Value *NextIdx = Builder->CreateAdd(Induction, Step, "index.next");
498 Induction->addIncoming(Zero, VectorPH);
499 Induction->addIncoming(NextIdx, VecBody);
500 // Create the compare.
501 Value *ICmp = Builder->CreateICmpEQ(NextIdx, CountRoundDown);
502 Builder->CreateCondBr(ICmp, MiddleBlock, VecBody);
504 // Now we have two terminators. Remove the old one from the block.
505 VecBody->getTerminator()->eraseFromParent();
507 // Fix the scalar body iteration count.
508 unsigned BlockIdx = OldInduction->getBasicBlockIndex(ScalarPH);
509 OldInduction->setIncomingValue(BlockIdx, CountRoundDown);
511 // Get ready to start creating new instructions into the vectorized body.
512 Builder->SetInsertPoint(VecBody->getFirstInsertionPt());
514 // Register the new loop.
515 Loop* Lp = new Loop();
516 LPM->insertLoop(Lp, Orig->getParentLoop());
518 Lp->addBasicBlockToLoop(VecBody, LI->getBase());
520 Loop *ParentLoop = Orig->getParentLoop();
522 ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
523 ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
524 ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
528 void SingleBlockLoopVectorizer::vectorizeLoop() {
529 BasicBlock &BB = *Orig->getHeader();
531 // For each instruction in the old loop.
532 for (BasicBlock::iterator it = BB.begin(), e = BB.end(); it != e; ++it) {
533 Instruction *Inst = it;
535 switch (Inst->getOpcode()) {
536 case Instruction::PHI:
537 case Instruction::Br:
538 // Nothing to do for PHIs and BR, since we already took care of the
539 // loop control flow instructions.
542 case Instruction::Add:
543 case Instruction::FAdd:
544 case Instruction::Sub:
545 case Instruction::FSub:
546 case Instruction::Mul:
547 case Instruction::FMul:
548 case Instruction::UDiv:
549 case Instruction::SDiv:
550 case Instruction::FDiv:
551 case Instruction::URem:
552 case Instruction::SRem:
553 case Instruction::FRem:
554 case Instruction::Shl:
555 case Instruction::LShr:
556 case Instruction::AShr:
557 case Instruction::And:
558 case Instruction::Or:
559 case Instruction::Xor: {
560 // Just widen binops.
561 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
562 Value *A = getVectorValue(Inst->getOperand(0));
563 Value *B = getVectorValue(Inst->getOperand(1));
564 // Use this vector value for all users of the original instruction.
565 WidenMap[Inst] = Builder->CreateBinOp(BinOp->getOpcode(), A, B);
568 case Instruction::Select: {
570 Value *A = getVectorValue(Inst->getOperand(0));
571 Value *B = getVectorValue(Inst->getOperand(1));
572 Value *C = getVectorValue(Inst->getOperand(2));
573 WidenMap[Inst] = Builder->CreateSelect(A, B, C);
577 case Instruction::ICmp:
578 case Instruction::FCmp: {
579 // Widen compares. Generate vector compares.
580 bool FCmp = (Inst->getOpcode() == Instruction::FCmp);
581 CmpInst *Cmp = dyn_cast<CmpInst>(Inst);
582 Value *A = getVectorValue(Inst->getOperand(0));
583 Value *B = getVectorValue(Inst->getOperand(1));
585 WidenMap[Inst] = Builder->CreateFCmp(Cmp->getPredicate(), A, B);
587 WidenMap[Inst] = Builder->CreateICmp(Cmp->getPredicate(), A, B);
591 case Instruction::Store: {
592 // Attempt to issue a wide store.
593 StoreInst *SI = dyn_cast<StoreInst>(Inst);
594 Type *StTy = VectorType::get(SI->getValueOperand()->getType(), VF);
595 Value *Ptr = SI->getPointerOperand();
596 unsigned Alignment = SI->getAlignment();
597 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
598 // This store does not use GEPs.
599 if (!isConsecutiveGep(Gep)) {
600 scalarizeInstruction(Inst);
604 // Create the new GEP with the new induction variable.
605 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
606 unsigned NumOperands = Gep->getNumOperands();
607 Gep2->setOperand(NumOperands - 1, Induction);
608 Ptr = Builder->Insert(Gep2);
609 Ptr = Builder->CreateBitCast(Ptr, StTy->getPointerTo());
610 Value *Val = getVectorValue(SI->getValueOperand());
611 Builder->CreateStore(Val, Ptr)->setAlignment(Alignment);
614 case Instruction::Load: {
615 // Attempt to issue a wide load.
616 LoadInst *LI = dyn_cast<LoadInst>(Inst);
617 Type *RetTy = VectorType::get(LI->getType(), VF);
618 Value *Ptr = LI->getPointerOperand();
619 unsigned Alignment = LI->getAlignment();
620 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
622 // We don't have a gep. Scalarize the load.
623 if (!isConsecutiveGep(Gep)) {
624 scalarizeInstruction(Inst);
628 // Create the new GEP with the new induction variable.
629 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
630 unsigned NumOperands = Gep->getNumOperands();
631 Gep2->setOperand(NumOperands - 1, Induction);
632 Ptr = Builder->Insert(Gep2);
633 Ptr = Builder->CreateBitCast(Ptr, RetTy->getPointerTo());
634 LI = Builder->CreateLoad(Ptr);
635 LI->setAlignment(Alignment);
636 // Use this vector value for all users of the load.
640 case Instruction::ZExt:
641 case Instruction::SExt:
642 case Instruction::FPToUI:
643 case Instruction::FPToSI:
644 case Instruction::FPExt:
645 case Instruction::PtrToInt:
646 case Instruction::IntToPtr:
647 case Instruction::SIToFP:
648 case Instruction::UIToFP:
649 case Instruction::Trunc:
650 case Instruction::FPTrunc:
651 case Instruction::BitCast: {
652 /// Vectorize bitcasts.
653 CastInst *CI = dyn_cast<CastInst>(Inst);
654 Value *A = getVectorValue(Inst->getOperand(0));
655 Type *DestTy = VectorType::get(CI->getType()->getScalarType(), VF);
656 WidenMap[Inst] = Builder->CreateCast(CI->getOpcode(), A, DestTy);
661 /// All other instructions are unsupported. Scalarize them.
662 scalarizeInstruction(Inst);
665 }// end of for_each instr.
668 void SingleBlockLoopVectorizer::cleanup() {
669 // The original basic block.
670 SE->forgetLoop(Orig);
673 unsigned LoopVectorizationLegality::getLoopMaxVF() {
674 if (!TheLoop->getLoopPreheader()) {
675 assert(false && "No preheader!!");
676 DEBUG(dbgs() << "LV: Loop not normalized." << "\n");
680 // We can only vectorize single basic block loops.
681 unsigned NumBlocks = TheLoop->getNumBlocks();
682 if (NumBlocks != 1) {
683 DEBUG(dbgs() << "LV: Too many blocks:" << NumBlocks << "\n");
687 // We need to have a loop header.
688 BasicBlock *BB = TheLoop->getHeader();
689 DEBUG(dbgs() << "LV: Found a loop: " << BB->getName() << "\n");
691 // Go over each instruction and look at memory deps.
692 if (!canVectorizeBlock(*BB)) {
693 DEBUG(dbgs() << "LV: Can't vectorize this loop header\n");
697 // ScalarEvolution needs to be able to find the exit count.
698 const SCEV *ExitCount = SE->getExitCount(TheLoop, BB);
699 if (ExitCount == SE->getCouldNotCompute()) {
700 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
704 DEBUG(dbgs() << "LV: We can vectorize this loop!\n");
706 // Okay! We can vectorize. At this point we don't have any other mem analysis
707 // which may limit our maximum vectorization factor, so just return the
708 // maximum SIMD size.
709 return DefaultVectorizationFactor;
712 bool LoopVectorizationLegality::canVectorizeBlock(BasicBlock &BB) {
713 // Holds the read and write pointers that we find.
714 typedef SmallVector<Value*, 10> ValueVector;
718 unsigned NumPhis = 0;
719 for (BasicBlock::iterator it = BB.begin(), e = BB.end(); it != e; ++it) {
722 PHINode *Phi = dyn_cast<PHINode>(I);
725 // We only look at integer phi nodes.
726 if (!Phi->getType()->isIntegerTy()) {
727 DEBUG(dbgs() << "LV: Found an non-int PHI.\n");
731 // If we found an induction variable.
733 DEBUG(dbgs() << "LV: Found more than one PHI.\n");
737 // This should not happen because the loop should be normalized.
738 if (Phi->getNumIncomingValues() != 2) {
739 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
743 // Check that the PHI is consecutive and starts at zero.
744 const SCEV *PhiScev = SE->getSCEV(Phi);
745 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
747 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
751 const SCEV *Step = AR->getStepRecurrence(*SE);
752 const SCEV *Start = AR->getStart();
754 if (!Step->isOne() || !Start->isZero()) {
755 DEBUG(dbgs() << "LV: PHI does not start at zero or steps by one.\n");
760 // If this is a load, record its pointer. If it is not a load, abort.
761 // Notice that we don't handle function calls that read or write.
762 if (I->mayReadFromMemory()) {
763 LoadInst *Ld = dyn_cast<LoadInst>(I);
764 if (!Ld) return false;
765 if (!Ld->isSimple()) {
766 DEBUG(dbgs() << "LV: Found a non-simple load.\n");
769 GetUnderlyingObjects(Ld->getPointerOperand(), Reads, DL);
772 // Record store pointers. Abort on all other instructions that write to
774 if (I->mayWriteToMemory()) {
775 StoreInst *St = dyn_cast<StoreInst>(I);
776 if (!St) return false;
777 if (!St->isSimple()) {
778 DEBUG(dbgs() << "LV: Found a non-simple store.\n");
781 GetUnderlyingObjects(St->getPointerOperand(), Writes, DL);
784 // We still don't handle functions.
785 CallInst *CI = dyn_cast<CallInst>(I);
787 DEBUG(dbgs() << "LV: Found a call site:"<<
788 CI->getCalledFunction()->getName() << "\n");
792 // We do not re-vectorize vectors.
793 if (!VectorType::isValidElementType(I->getType()) &&
794 !I->getType()->isVoidTy()) {
795 DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n");
798 //Check that all of the users of the loop are inside the BB.
799 for (Value::use_iterator it = I->use_begin(), e = I->use_end();
801 Instruction *U = cast<Instruction>(*it);
802 BasicBlock *Parent = U->getParent();
804 DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n");
811 DEBUG(dbgs() << "LV: Did not find a Phi node.\n");
815 // Check that the underlying objects of the reads and writes are either
816 // disjoint memory locations, or that they are no-alias arguments.
817 ValueVector::iterator r, re, w, we;
818 for (r = Reads.begin(), re = Reads.end(); r != re; ++r) {
819 if (!isIdentifiedSafeObject(*r)) {
820 DEBUG(dbgs() << "LV: Found a bad read Ptr: "<< **r << "\n");
825 for (w = Writes.begin(), we = Writes.end(); w != we; ++w) {
826 if (!isIdentifiedSafeObject(*w)) {
827 DEBUG(dbgs() << "LV: Found a bad write Ptr: "<< **w << "\n");
832 // Check that there are no multiple write locations to the same pointer.
833 SmallPtrSet<Value*, 8> WritePointerSet;
834 for (w = Writes.begin(), we = Writes.end(); w != we; ++w) {
835 if (!WritePointerSet.insert(*w)) {
836 DEBUG(dbgs() << "LV: Multiple writes to the same index :"<< **w << "\n");
841 // Check that the reads and the writes are disjoint.
842 for (r = Reads.begin(), re = Reads.end(); r != re; ++r) {
843 if (WritePointerSet.count(*r)) {
844 DEBUG(dbgs() << "Vectorizer: Found a read/write ptr:"<< **r << "\n");
853 /// Checks if the value is a Global variable or if it is an Arguments
854 /// marked with the NoAlias attribute.
855 bool LoopVectorizationLegality::isIdentifiedSafeObject(Value* Val) {
856 assert(Val && "Invalid value");
857 if (dyn_cast<GlobalValue>(Val))
859 if (dyn_cast<AllocaInst>(Val))
861 Argument *A = dyn_cast<Argument>(Val);
864 return A->hasNoAliasAttr();
869 char LoopVectorize::ID = 0;
870 static const char lv_name[] = "Loop Vectorization";
871 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
872 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
873 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
874 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
875 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
878 Pass *createLoopVectorizePass() {
879 return new LoopVectorize();