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 //===----------------------------------------------------------------------===//
9 #include "LoopVectorize.h"
10 #include "llvm/ADT/StringExtras.h"
11 #include "llvm/Analysis/AliasAnalysis.h"
12 #include "llvm/Analysis/AliasSetTracker.h"
13 #include "llvm/Analysis/Dominators.h"
14 #include "llvm/Analysis/LoopInfo.h"
15 #include "llvm/Analysis/LoopIterator.h"
16 #include "llvm/Analysis/LoopPass.h"
17 #include "llvm/Analysis/ScalarEvolutionExpander.h"
18 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
19 #include "llvm/Analysis/ValueTracking.h"
20 #include "llvm/Analysis/Verifier.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DataLayout.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Function.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/IntrinsicInst.h"
27 #include "llvm/LLVMContext.h"
28 #include "llvm/Module.h"
29 #include "llvm/Pass.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/TargetTransformInfo.h"
34 #include "llvm/Transforms/Scalar.h"
35 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
36 #include "llvm/Transforms/Utils/Local.h"
37 #include "llvm/Transforms/Vectorize.h"
38 #include "llvm/Type.h"
39 #include "llvm/Value.h"
41 static cl::opt<unsigned>
42 VectorizationFactor("force-vector-width", cl::init(0), cl::Hidden,
43 cl::desc("Sets the SIMD width. Zero is autoselect."));
46 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
47 cl::desc("Enable if-conversion during vectorization."));
51 /// The LoopVectorize Pass.
52 struct LoopVectorize : public LoopPass {
53 /// Pass identification, replacement for typeid
56 explicit LoopVectorize() : LoopPass(ID) {
57 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
63 TargetTransformInfo *TTI;
66 virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
67 // We only vectorize innermost loops.
71 SE = &getAnalysis<ScalarEvolution>();
72 DL = getAnalysisIfAvailable<DataLayout>();
73 LI = &getAnalysis<LoopInfo>();
74 TTI = getAnalysisIfAvailable<TargetTransformInfo>();
75 DT = &getAnalysis<DominatorTree>();
77 DEBUG(dbgs() << "LV: Checking a loop in \"" <<
78 L->getHeader()->getParent()->getName() << "\"\n");
80 // Check if it is legal to vectorize the loop.
81 LoopVectorizationLegality LVL(L, SE, DL, DT);
82 if (!LVL.canVectorize()) {
83 DEBUG(dbgs() << "LV: Not vectorizing.\n");
87 // Select the preffered vectorization factor.
88 const VectorTargetTransformInfo *VTTI = 0;
90 VTTI = TTI->getVectorTargetTransformInfo();
91 // Use the cost model.
92 LoopVectorizationCostModel CM(L, SE, &LVL, VTTI);
94 // Check the function attribues to find out if this function should be
95 // optimized for size.
96 Function *F = L->getHeader()->getParent();
97 Attribute::AttrKind SzAttr= Attribute::OptimizeForSize;
98 bool OptForSize = F->getFnAttributes().hasAttribute(SzAttr);
100 unsigned VF = CM.selectVectorizationFactor(OptForSize, VectorizationFactor);
103 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
107 DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< VF << ") in "<<
108 F->getParent()->getModuleIdentifier()<<"\n");
110 // If we decided that it is *legal* to vectorizer the loop then do it.
111 InnerLoopVectorizer LB(L, SE, LI, DT, DL, VF);
114 DEBUG(verifyFunction(*L->getHeader()->getParent()));
118 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
119 LoopPass::getAnalysisUsage(AU);
120 AU.addRequiredID(LoopSimplifyID);
121 AU.addRequiredID(LCSSAID);
122 AU.addRequired<LoopInfo>();
123 AU.addRequired<ScalarEvolution>();
124 AU.addRequired<DominatorTree>();
125 AU.addPreserved<LoopInfo>();
126 AU.addPreserved<DominatorTree>();
133 //===----------------------------------------------------------------------===//
134 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
135 // LoopVectorizationCostModel.
136 //===----------------------------------------------------------------------===//
139 LoopVectorizationLegality::RuntimePointerCheck::insert(ScalarEvolution *SE,
140 Loop *Lp, Value *Ptr) {
141 const SCEV *Sc = SE->getSCEV(Ptr);
142 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
143 assert(AR && "Invalid addrec expression");
144 const SCEV *Ex = SE->getExitCount(Lp, Lp->getLoopLatch());
145 const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
146 Pointers.push_back(Ptr);
147 Starts.push_back(AR->getStart());
148 Ends.push_back(ScEnd);
151 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
153 LLVMContext &C = V->getContext();
154 Type *VTy = VectorType::get(V->getType(), VF);
155 Type *I32 = IntegerType::getInt32Ty(C);
157 // Save the current insertion location.
158 Instruction *Loc = Builder.GetInsertPoint();
160 // We need to place the broadcast of invariant variables outside the loop.
161 Instruction *Instr = dyn_cast<Instruction>(V);
162 bool NewInstr = (Instr && Instr->getParent() == LoopVectorBody);
163 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
165 // Place the code for broadcasting invariant variables in the new preheader.
167 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
169 Constant *Zero = ConstantInt::get(I32, 0);
170 Value *Zeros = ConstantAggregateZero::get(VectorType::get(I32, VF));
171 Value *UndefVal = UndefValue::get(VTy);
172 // Insert the value into a new vector.
173 Value *SingleElem = Builder.CreateInsertElement(UndefVal, V, Zero);
174 // Broadcast the scalar into all locations in the vector.
175 Value *Shuf = Builder.CreateShuffleVector(SingleElem, UndefVal, Zeros,
178 // Restore the builder insertion point.
180 Builder.SetInsertPoint(Loc);
185 Value *InnerLoopVectorizer::getConsecutiveVector(Value* Val, bool Negate) {
186 assert(Val->getType()->isVectorTy() && "Must be a vector");
187 assert(Val->getType()->getScalarType()->isIntegerTy() &&
188 "Elem must be an integer");
190 Type *ITy = Val->getType()->getScalarType();
191 VectorType *Ty = cast<VectorType>(Val->getType());
192 int VLen = Ty->getNumElements();
193 SmallVector<Constant*, 8> Indices;
195 // Create a vector of consecutive numbers from zero to VF.
196 for (int i = 0; i < VLen; ++i)
197 Indices.push_back(ConstantInt::get(ITy, Negate ? (-i): i ));
199 // Add the consecutive indices to the vector value.
200 Constant *Cv = ConstantVector::get(Indices);
201 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
202 return Builder.CreateAdd(Val, Cv, "induction");
205 bool LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
206 assert(Ptr->getType()->isPointerTy() && "Unexpected non ptr");
208 // If this value is a pointer induction variable we know it is consecutive.
209 PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
210 if (Phi && Inductions.count(Phi)) {
211 InductionInfo II = Inductions[Phi];
212 if (PtrInduction == II.IK)
216 GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
220 unsigned NumOperands = Gep->getNumOperands();
221 Value *LastIndex = Gep->getOperand(NumOperands - 1);
223 // Check that all of the gep indices are uniform except for the last.
224 for (unsigned i = 0; i < NumOperands - 1; ++i)
225 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
228 // We can emit wide load/stores only if the last index is the induction
230 const SCEV *Last = SE->getSCEV(LastIndex);
231 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
232 const SCEV *Step = AR->getStepRecurrence(*SE);
234 // The memory is consecutive because the last index is consecutive
235 // and all other indices are loop invariant.
243 bool LoopVectorizationLegality::isUniform(Value *V) {
244 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
247 Value *InnerLoopVectorizer::getVectorValue(Value *V) {
248 assert(V != Induction && "The new induction variable should not be used.");
249 assert(!V->getType()->isVectorTy() && "Can't widen a vector");
250 // If we saved a vectorized copy of V, use it.
251 Value *&MapEntry = WidenMap[V];
255 // Broadcast V and save the value for future uses.
256 Value *B = getBroadcastInstrs(V);
262 InnerLoopVectorizer::getUniformVector(unsigned Val, Type* ScalarTy) {
263 return ConstantVector::getSplat(VF, ConstantInt::get(ScalarTy, Val, true));
266 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr) {
267 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
268 // Holds vector parameters or scalars, in case of uniform vals.
269 SmallVector<Value*, 8> Params;
271 // Find all of the vectorized parameters.
272 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
273 Value *SrcOp = Instr->getOperand(op);
275 // If we are accessing the old induction variable, use the new one.
276 if (SrcOp == OldInduction) {
277 Params.push_back(getVectorValue(SrcOp));
281 // Try using previously calculated values.
282 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
284 // If the src is an instruction that appeared earlier in the basic block
285 // then it should already be vectorized.
286 if (SrcInst && OrigLoop->contains(SrcInst)) {
287 assert(WidenMap.count(SrcInst) && "Source operand is unavailable");
288 // The parameter is a vector value from earlier.
289 Params.push_back(WidenMap[SrcInst]);
291 // The parameter is a scalar from outside the loop. Maybe even a constant.
292 Params.push_back(SrcOp);
296 assert(Params.size() == Instr->getNumOperands() &&
297 "Invalid number of operands");
299 // Does this instruction return a value ?
300 bool IsVoidRetTy = Instr->getType()->isVoidTy();
301 Value *VecResults = 0;
303 // If we have a return value, create an empty vector. We place the scalarized
304 // instructions in this vector.
306 VecResults = UndefValue::get(VectorType::get(Instr->getType(), VF));
308 // For each scalar that we create:
309 for (unsigned i = 0; i < VF; ++i) {
310 Instruction *Cloned = Instr->clone();
312 Cloned->setName(Instr->getName() + ".cloned");
313 // Replace the operands of the cloned instrucions with extracted scalars.
314 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
315 Value *Op = Params[op];
316 // Param is a vector. Need to extract the right lane.
317 if (Op->getType()->isVectorTy())
318 Op = Builder.CreateExtractElement(Op, Builder.getInt32(i));
319 Cloned->setOperand(op, Op);
322 // Place the cloned scalar in the new loop.
323 Builder.Insert(Cloned);
325 // If the original scalar returns a value we need to place it in a vector
326 // so that future users will be able to use it.
328 VecResults = Builder.CreateInsertElement(VecResults, Cloned,
329 Builder.getInt32(i));
333 WidenMap[Instr] = VecResults;
337 InnerLoopVectorizer::addRuntimeCheck(LoopVectorizationLegality *Legal,
339 LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck =
340 Legal->getRuntimePointerCheck();
342 if (!PtrRtCheck->Need)
345 Value *MemoryRuntimeCheck = 0;
346 unsigned NumPointers = PtrRtCheck->Pointers.size();
347 SmallVector<Value* , 2> Starts;
348 SmallVector<Value* , 2> Ends;
350 SCEVExpander Exp(*SE, "induction");
352 // Use this type for pointer arithmetic.
353 Type* PtrArithTy = Type::getInt8PtrTy(Loc->getContext(), 0);
355 for (unsigned i = 0; i < NumPointers; ++i) {
356 Value *Ptr = PtrRtCheck->Pointers[i];
357 const SCEV *Sc = SE->getSCEV(Ptr);
359 if (SE->isLoopInvariant(Sc, OrigLoop)) {
360 DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" <<
362 Starts.push_back(Ptr);
365 DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr <<"\n");
367 Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc);
368 Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
369 Starts.push_back(Start);
374 for (unsigned i = 0; i < NumPointers; ++i) {
375 for (unsigned j = i+1; j < NumPointers; ++j) {
376 Instruction::CastOps Op = Instruction::BitCast;
377 Value *Start0 = CastInst::Create(Op, Starts[i], PtrArithTy, "bc", Loc);
378 Value *Start1 = CastInst::Create(Op, Starts[j], PtrArithTy, "bc", Loc);
379 Value *End0 = CastInst::Create(Op, Ends[i], PtrArithTy, "bc", Loc);
380 Value *End1 = CastInst::Create(Op, Ends[j], PtrArithTy, "bc", Loc);
382 Value *Cmp0 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_ULE,
383 Start0, End1, "bound0", Loc);
384 Value *Cmp1 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_ULE,
385 Start1, End0, "bound1", Loc);
386 Value *IsConflict = BinaryOperator::Create(Instruction::And, Cmp0, Cmp1,
387 "found.conflict", Loc);
388 if (MemoryRuntimeCheck)
389 MemoryRuntimeCheck = BinaryOperator::Create(Instruction::Or,
392 "conflict.rdx", Loc);
394 MemoryRuntimeCheck = IsConflict;
399 return MemoryRuntimeCheck;
403 InnerLoopVectorizer::createEmptyLoop(LoopVectorizationLegality *Legal) {
405 In this function we generate a new loop. The new loop will contain
406 the vectorized instructions while the old loop will continue to run the
409 [ ] <-- vector loop bypass.
412 | [ ] <-- vector pre header.
416 | [ ]_| <-- vector loop.
419 >[ ] <--- middle-block.
422 | [ ] <--- new preheader.
426 | [ ]_| <-- old scalar loop to handle remainder.
433 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
434 BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
435 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
436 assert(ExitBlock && "Must have an exit block");
438 // Some loops have a single integer induction variable, while other loops
439 // don't. One example is c++ iterators that often have multiple pointer
440 // induction variables. In the code below we also support a case where we
441 // don't have a single induction variable.
442 OldInduction = Legal->getInduction();
443 Type *IdxTy = OldInduction ? OldInduction->getType() :
444 DL->getIntPtrType(SE->getContext());
446 // Find the loop boundaries.
447 const SCEV *ExitCount = SE->getExitCount(OrigLoop, OrigLoop->getLoopLatch());
448 assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
450 // Get the total trip count from the count by adding 1.
451 ExitCount = SE->getAddExpr(ExitCount,
452 SE->getConstant(ExitCount->getType(), 1));
454 // Expand the trip count and place the new instructions in the preheader.
455 // Notice that the pre-header does not change, only the loop body.
456 SCEVExpander Exp(*SE, "induction");
458 // Count holds the overall loop count (N).
459 Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
460 BypassBlock->getTerminator());
462 // The loop index does not have to start at Zero. Find the original start
463 // value from the induction PHI node. If we don't have an induction variable
464 // then we know that it starts at zero.
465 Value *StartIdx = OldInduction ?
466 OldInduction->getIncomingValueForBlock(BypassBlock):
467 ConstantInt::get(IdxTy, 0);
469 assert(BypassBlock && "Invalid loop structure");
471 // Generate the code that checks in runtime if arrays overlap.
472 Value *MemoryRuntimeCheck = addRuntimeCheck(Legal,
473 BypassBlock->getTerminator());
475 // Split the single block loop into the two loop structure described above.
476 BasicBlock *VectorPH =
477 BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
478 BasicBlock *VecBody =
479 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
480 BasicBlock *MiddleBlock =
481 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
482 BasicBlock *ScalarPH =
483 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
485 // This is the location in which we add all of the logic for bypassing
486 // the new vector loop.
487 Instruction *Loc = BypassBlock->getTerminator();
489 // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
491 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
493 // Generate the induction variable.
494 Induction = Builder.CreatePHI(IdxTy, 2, "index");
495 Constant *Step = ConstantInt::get(IdxTy, VF);
497 // We may need to extend the index in case there is a type mismatch.
498 // We know that the count starts at zero and does not overflow.
499 if (Count->getType() != IdxTy) {
500 // The exit count can be of pointer type. Convert it to the correct
502 if (ExitCount->getType()->isPointerTy())
503 Count = CastInst::CreatePointerCast(Count, IdxTy, "ptrcnt.to.int", Loc);
505 Count = CastInst::CreateZExtOrBitCast(Count, IdxTy, "zext.cnt", Loc);
508 // Add the start index to the loop count to get the new end index.
509 Value *IdxEnd = BinaryOperator::CreateAdd(Count, StartIdx, "end.idx", Loc);
511 // Now we need to generate the expression for N - (N % VF), which is
512 // the part that the vectorized body will execute.
513 Constant *CIVF = ConstantInt::get(IdxTy, VF);
514 Value *R = BinaryOperator::CreateURem(Count, CIVF, "n.mod.vf", Loc);
515 Value *CountRoundDown = BinaryOperator::CreateSub(Count, R, "n.vec", Loc);
516 Value *IdxEndRoundDown = BinaryOperator::CreateAdd(CountRoundDown, StartIdx,
517 "end.idx.rnd.down", Loc);
519 // Now, compare the new count to zero. If it is zero skip the vector loop and
520 // jump to the scalar loop.
521 Value *Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
526 // If we are using memory runtime checks, include them in.
527 if (MemoryRuntimeCheck)
528 Cmp = BinaryOperator::Create(Instruction::Or, Cmp, MemoryRuntimeCheck,
531 BranchInst::Create(MiddleBlock, VectorPH, Cmp, Loc);
532 // Remove the old terminator.
533 Loc->eraseFromParent();
535 // We are going to resume the execution of the scalar loop.
536 // Go over all of the induction variables that we found and fix the
537 // PHIs that are left in the scalar version of the loop.
538 // The starting values of PHI nodes depend on the counter of the last
539 // iteration in the vectorized loop.
540 // If we come from a bypass edge then we need to start from the original
543 // This variable saves the new starting index for the scalar loop.
544 PHINode *ResumeIndex = 0;
545 LoopVectorizationLegality::InductionList::iterator I, E;
546 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
547 for (I = List->begin(), E = List->end(); I != E; ++I) {
548 PHINode *OrigPhi = I->first;
549 LoopVectorizationLegality::InductionInfo II = I->second;
550 PHINode *ResumeVal = PHINode::Create(OrigPhi->getType(), 2, "resume.val",
551 MiddleBlock->getTerminator());
554 case LoopVectorizationLegality::NoInduction:
555 llvm_unreachable("Unknown induction");
556 case LoopVectorizationLegality::IntInduction: {
557 // Handle the integer induction counter:
558 assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
559 assert(OrigPhi == OldInduction && "Unknown integer PHI");
560 // We know what the end value is.
561 EndValue = IdxEndRoundDown;
562 // We also know which PHI node holds it.
563 ResumeIndex = ResumeVal;
566 case LoopVectorizationLegality::ReverseIntInduction: {
567 // Convert the CountRoundDown variable to the PHI size.
568 unsigned CRDSize = CountRoundDown->getType()->getScalarSizeInBits();
569 unsigned IISize = II.StartValue->getType()->getScalarSizeInBits();
570 Value *CRD = CountRoundDown;
571 if (CRDSize > IISize)
572 CRD = CastInst::Create(Instruction::Trunc, CountRoundDown,
573 II.StartValue->getType(),
574 "tr.crd", BypassBlock->getTerminator());
575 else if (CRDSize < IISize)
576 CRD = CastInst::Create(Instruction::SExt, CountRoundDown,
577 II.StartValue->getType(),
578 "sext.crd", BypassBlock->getTerminator());
579 // Handle reverse integer induction counter:
580 EndValue = BinaryOperator::CreateSub(II.StartValue, CRD, "rev.ind.end",
581 BypassBlock->getTerminator());
584 case LoopVectorizationLegality::PtrInduction: {
585 // For pointer induction variables, calculate the offset using
587 EndValue = GetElementPtrInst::Create(II.StartValue, CountRoundDown,
589 BypassBlock->getTerminator());
594 // The new PHI merges the original incoming value, in case of a bypass,
595 // or the value at the end of the vectorized loop.
596 ResumeVal->addIncoming(II.StartValue, BypassBlock);
597 ResumeVal->addIncoming(EndValue, VecBody);
599 // Fix the scalar body counter (PHI node).
600 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
601 OrigPhi->setIncomingValue(BlockIdx, ResumeVal);
604 // If we are generating a new induction variable then we also need to
605 // generate the code that calculates the exit value. This value is not
606 // simply the end of the counter because we may skip the vectorized body
607 // in case of a runtime check.
609 assert(!ResumeIndex && "Unexpected resume value found");
610 ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
611 MiddleBlock->getTerminator());
612 ResumeIndex->addIncoming(StartIdx, BypassBlock);
613 ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
616 // Make sure that we found the index where scalar loop needs to continue.
617 assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
618 "Invalid resume Index");
620 // Add a check in the middle block to see if we have completed
621 // all of the iterations in the first vector loop.
622 // If (N - N%VF) == N, then we *don't* need to run the remainder.
623 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
624 ResumeIndex, "cmp.n",
625 MiddleBlock->getTerminator());
627 BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
628 // Remove the old terminator.
629 MiddleBlock->getTerminator()->eraseFromParent();
631 // Create i+1 and fill the PHINode.
632 Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
633 Induction->addIncoming(StartIdx, VectorPH);
634 Induction->addIncoming(NextIdx, VecBody);
635 // Create the compare.
636 Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
637 Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
639 // Now we have two terminators. Remove the old one from the block.
640 VecBody->getTerminator()->eraseFromParent();
642 // Get ready to start creating new instructions into the vectorized body.
643 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
645 // Create and register the new vector loop.
646 Loop* Lp = new Loop();
647 Loop *ParentLoop = OrigLoop->getParentLoop();
649 // Insert the new loop into the loop nest and register the new basic blocks.
651 ParentLoop->addChildLoop(Lp);
652 ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
653 ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
654 ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
656 LI->addTopLevelLoop(Lp);
659 Lp->addBasicBlockToLoop(VecBody, LI->getBase());
662 LoopVectorPreHeader = VectorPH;
663 LoopScalarPreHeader = ScalarPH;
664 LoopMiddleBlock = MiddleBlock;
665 LoopExitBlock = ExitBlock;
666 LoopVectorBody = VecBody;
667 LoopScalarBody = OldBasicBlock;
668 LoopBypassBlock = BypassBlock;
671 /// This function returns the identity element (or neutral element) for
674 getReductionIdentity(LoopVectorizationLegality::ReductionKind K) {
676 case LoopVectorizationLegality::IntegerXor:
677 case LoopVectorizationLegality::IntegerAdd:
678 case LoopVectorizationLegality::IntegerOr:
679 // Adding, Xoring, Oring zero to a number does not change it.
681 case LoopVectorizationLegality::IntegerMult:
682 // Multiplying a number by 1 does not change it.
684 case LoopVectorizationLegality::IntegerAnd:
685 // AND-ing a number with an all-1 value does not change it.
688 llvm_unreachable("Unknown reduction kind");
693 isTriviallyVectorizableIntrinsic(Instruction *Inst) {
694 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst);
697 switch (II->getIntrinsicID()) {
698 case Intrinsic::sqrt:
702 case Intrinsic::exp2:
704 case Intrinsic::log10:
705 case Intrinsic::log2:
706 case Intrinsic::fabs:
707 case Intrinsic::floor:
708 case Intrinsic::ceil:
709 case Intrinsic::trunc:
710 case Intrinsic::rint:
711 case Intrinsic::nearbyint:
722 InnerLoopVectorizer::vectorizeLoop(LoopVectorizationLegality *Legal) {
723 //===------------------------------------------------===//
725 // Notice: any optimization or new instruction that go
726 // into the code below should be also be implemented in
729 //===------------------------------------------------===//
730 BasicBlock &BB = *OrigLoop->getHeader();
732 ConstantInt::get(IntegerType::getInt32Ty(BB.getContext()), 0);
734 // In order to support reduction variables we need to be able to vectorize
735 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
736 // stages. First, we create a new vector PHI node with no incoming edges.
737 // We use this value when we vectorize all of the instructions that use the
738 // PHI. Next, after all of the instructions in the block are complete we
739 // add the new incoming edges to the PHI. At this point all of the
740 // instructions in the basic block are vectorized, so we can use them to
741 // construct the PHI.
742 PhiVector RdxPHIsToFix;
744 // Scan the loop in a topological order to ensure that defs are vectorized
746 LoopBlocksDFS DFS(OrigLoop);
749 // Vectorize all of the blocks in the original loop.
750 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
751 be = DFS.endRPO(); bb != be; ++bb)
752 vectorizeBlockInLoop(Legal, *bb, &RdxPHIsToFix);
754 // At this point every instruction in the original loop is widened to
755 // a vector form. We are almost done. Now, we need to fix the PHI nodes
756 // that we vectorized. The PHI nodes are currently empty because we did
757 // not want to introduce cycles. Notice that the remaining PHI nodes
758 // that we need to fix are reduction variables.
760 // Create the 'reduced' values for each of the induction vars.
761 // The reduced values are the vector values that we scalarize and combine
762 // after the loop is finished.
763 for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
765 PHINode *RdxPhi = *it;
766 PHINode *VecRdxPhi = dyn_cast<PHINode>(WidenMap[RdxPhi]);
767 assert(RdxPhi && "Unable to recover vectorized PHI");
769 // Find the reduction variable descriptor.
770 assert(Legal->getReductionVars()->count(RdxPhi) &&
771 "Unable to find the reduction variable");
772 LoopVectorizationLegality::ReductionDescriptor RdxDesc =
773 (*Legal->getReductionVars())[RdxPhi];
775 // We need to generate a reduction vector from the incoming scalar.
776 // To do so, we need to generate the 'identity' vector and overide
777 // one of the elements with the incoming scalar reduction. We need
778 // to do it in the vector-loop preheader.
779 Builder.SetInsertPoint(LoopBypassBlock->getTerminator());
781 // This is the vector-clone of the value that leaves the loop.
782 Value *VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
783 Type *VecTy = VectorExit->getType();
785 // Find the reduction identity variable. Zero for addition, or, xor,
786 // one for multiplication, -1 for And.
787 Constant *Identity = getUniformVector(getReductionIdentity(RdxDesc.Kind),
788 VecTy->getScalarType());
790 // This vector is the Identity vector where the first element is the
791 // incoming scalar reduction.
792 Value *VectorStart = Builder.CreateInsertElement(Identity,
793 RdxDesc.StartValue, Zero);
795 // Fix the vector-loop phi.
796 // We created the induction variable so we know that the
797 // preheader is the first entry.
798 BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
800 // Reductions do not have to start at zero. They can start with
801 // any loop invariant values.
802 VecRdxPhi->addIncoming(VectorStart, VecPreheader);
804 getVectorValue(RdxPhi->getIncomingValueForBlock(OrigLoop->getLoopLatch()));
805 VecRdxPhi->addIncoming(Val, LoopVectorBody);
807 // Before each round, move the insertion point right between
808 // the PHIs and the values we are going to write.
809 // This allows us to write both PHINodes and the extractelement
811 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
813 // This PHINode contains the vectorized reduction variable, or
814 // the initial value vector, if we bypass the vector loop.
815 PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
816 NewPhi->addIncoming(VectorStart, LoopBypassBlock);
817 NewPhi->addIncoming(getVectorValue(RdxDesc.LoopExitInstr), LoopVectorBody);
819 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
820 // and vector ops, reducing the set of values being computed by half each
822 assert(isPowerOf2_32(VF) &&
823 "Reduction emission only supported for pow2 vectors!");
824 Value *TmpVec = NewPhi;
825 SmallVector<Constant*, 32> ShuffleMask(VF, 0);
826 for (unsigned i = VF; i != 1; i >>= 1) {
827 // Move the upper half of the vector to the lower half.
828 for (unsigned j = 0; j != i/2; ++j)
829 ShuffleMask[j] = Builder.getInt32(i/2 + j);
831 // Fill the rest of the mask with undef.
832 std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
833 UndefValue::get(Builder.getInt32Ty()));
836 Builder.CreateShuffleVector(TmpVec,
837 UndefValue::get(TmpVec->getType()),
838 ConstantVector::get(ShuffleMask),
841 // Emit the operation on the shuffled value.
842 switch (RdxDesc.Kind) {
843 case LoopVectorizationLegality::IntegerAdd:
844 TmpVec = Builder.CreateAdd(TmpVec, Shuf, "add.rdx");
846 case LoopVectorizationLegality::IntegerMult:
847 TmpVec = Builder.CreateMul(TmpVec, Shuf, "mul.rdx");
849 case LoopVectorizationLegality::IntegerOr:
850 TmpVec = Builder.CreateOr(TmpVec, Shuf, "or.rdx");
852 case LoopVectorizationLegality::IntegerAnd:
853 TmpVec = Builder.CreateAnd(TmpVec, Shuf, "and.rdx");
855 case LoopVectorizationLegality::IntegerXor:
856 TmpVec = Builder.CreateXor(TmpVec, Shuf, "xor.rdx");
859 llvm_unreachable("Unknown reduction operation");
863 // The result is in the first element of the vector.
864 Value *Scalar0 = Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
866 // Now, we need to fix the users of the reduction variable
867 // inside and outside of the scalar remainder loop.
868 // We know that the loop is in LCSSA form. We need to update the
869 // PHI nodes in the exit blocks.
870 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
871 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
872 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
873 if (!LCSSAPhi) continue;
875 // All PHINodes need to have a single entry edge, or two if
876 // we already fixed them.
877 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
879 // We found our reduction value exit-PHI. Update it with the
880 // incoming bypass edge.
881 if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
882 // Add an edge coming from the bypass.
883 LCSSAPhi->addIncoming(Scalar0, LoopMiddleBlock);
886 }// end of the LCSSA phi scan.
888 // Fix the scalar loop reduction variable with the incoming reduction sum
889 // from the vector body and from the backedge value.
890 int IncomingEdgeBlockIdx =
891 (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
892 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
893 // Pick the other block.
894 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
895 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, Scalar0);
896 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
897 }// end of for each redux variable.
900 Value *InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
901 assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
904 Value *SrcMask = createBlockInMask(Src);
906 // The terminator has to be a branch inst!
907 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
908 assert(BI && "Unexpected terminator found");
910 Value *EdgeMask = SrcMask;
911 if (BI->isConditional()) {
912 EdgeMask = getVectorValue(BI->getCondition());
913 if (BI->getSuccessor(0) != Dst)
914 EdgeMask = Builder.CreateNot(EdgeMask);
917 return Builder.CreateAnd(EdgeMask, SrcMask);
920 Value *InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
921 assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
923 // Loop incoming mask is all-one.
924 if (OrigLoop->getHeader() == BB) {
925 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
926 return getVectorValue(C);
929 // This is the block mask. We OR all incoming edges, and with zero.
930 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
931 Value *BlockMask = getVectorValue(Zero);
934 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it)
935 BlockMask = Builder.CreateOr(BlockMask, createEdgeMask(*it, BB));
941 InnerLoopVectorizer::vectorizeBlockInLoop(LoopVectorizationLegality *Legal,
942 BasicBlock *BB, PhiVector *PV) {
944 ConstantInt::get(IntegerType::getInt32Ty(BB->getContext()), 0);
946 // For each instruction in the old loop.
947 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
948 switch (it->getOpcode()) {
949 case Instruction::Br:
950 // Nothing to do for PHIs and BR, since we already took care of the
951 // loop control flow instructions.
953 case Instruction::PHI:{
954 PHINode* P = cast<PHINode>(it);
955 // Handle reduction variables:
956 if (Legal->getReductionVars()->count(P)) {
957 // This is phase one of vectorizing PHIs.
958 Type *VecTy = VectorType::get(it->getType(), VF);
960 PHINode::Create(VecTy, 2, "vec.phi",
961 LoopVectorBody->getFirstInsertionPt());
966 // Check for PHI nodes that are lowered to vector selects.
967 if (P->getParent() != OrigLoop->getHeader()) {
968 // We know that all PHIs in non header blocks are converted into
969 // selects, so we don't have to worry about the insertion order and we
970 // can just use the builder.
972 // At this point we generate the predication tree. There may be
973 // duplications since this is a simple recursive scan, but future
974 // optimizations will clean it up.
975 Value *Cond = createEdgeMask(P->getIncomingBlock(0), P->getParent());
977 Builder.CreateSelect(Cond,
978 getVectorValue(P->getIncomingValue(0)),
979 getVectorValue(P->getIncomingValue(1)),
984 // This PHINode must be an induction variable.
985 // Make sure that we know about it.
986 assert(Legal->getInductionVars()->count(P) &&
987 "Not an induction variable");
989 LoopVectorizationLegality::InductionInfo II =
990 Legal->getInductionVars()->lookup(P);
993 case LoopVectorizationLegality::NoInduction:
994 llvm_unreachable("Unknown induction");
995 case LoopVectorizationLegality::IntInduction: {
996 assert(P == OldInduction && "Unexpected PHI");
997 Value *Broadcasted = getBroadcastInstrs(Induction);
998 // After broadcasting the induction variable we need to make the
999 // vector consecutive by adding 0, 1, 2 ...
1000 Value *ConsecutiveInduction = getConsecutiveVector(Broadcasted);
1001 WidenMap[OldInduction] = ConsecutiveInduction;
1004 case LoopVectorizationLegality::ReverseIntInduction:
1005 case LoopVectorizationLegality::PtrInduction:
1006 // Handle reverse integer and pointer inductions.
1007 Value *StartIdx = 0;
1008 // If we have a single integer induction variable then use it.
1009 // Otherwise, start counting at zero.
1011 LoopVectorizationLegality::InductionInfo OldII =
1012 Legal->getInductionVars()->lookup(OldInduction);
1013 StartIdx = OldII.StartValue;
1015 StartIdx = ConstantInt::get(Induction->getType(), 0);
1017 // This is the normalized GEP that starts counting at zero.
1018 Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
1021 // Handle the reverse integer induction variable case.
1022 if (LoopVectorizationLegality::ReverseIntInduction == II.IK) {
1023 IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType());
1024 Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy,
1026 Value *ReverseInd = Builder.CreateSub(II.StartValue, CNI,
1029 // This is a new value so do not hoist it out.
1030 Value *Broadcasted = getBroadcastInstrs(ReverseInd);
1031 // After broadcasting the induction variable we need to make the
1032 // vector consecutive by adding ... -3, -2, -1, 0.
1033 Value *ConsecutiveInduction = getConsecutiveVector(Broadcasted,
1035 WidenMap[it] = ConsecutiveInduction;
1039 // Handle the pointer induction variable case.
1040 assert(P->getType()->isPointerTy() && "Unexpected type.");
1042 // This is the vector of results. Notice that we don't generate
1043 // vector geps because scalar geps result in better code.
1044 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
1045 for (unsigned int i = 0; i < VF; ++i) {
1046 Constant *Idx = ConstantInt::get(Induction->getType(), i);
1047 Value *GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx,
1049 Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
1051 VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
1052 Builder.getInt32(i),
1056 WidenMap[it] = VecVal;
1062 case Instruction::Add:
1063 case Instruction::FAdd:
1064 case Instruction::Sub:
1065 case Instruction::FSub:
1066 case Instruction::Mul:
1067 case Instruction::FMul:
1068 case Instruction::UDiv:
1069 case Instruction::SDiv:
1070 case Instruction::FDiv:
1071 case Instruction::URem:
1072 case Instruction::SRem:
1073 case Instruction::FRem:
1074 case Instruction::Shl:
1075 case Instruction::LShr:
1076 case Instruction::AShr:
1077 case Instruction::And:
1078 case Instruction::Or:
1079 case Instruction::Xor: {
1080 // Just widen binops.
1081 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
1082 Value *A = getVectorValue(it->getOperand(0));
1083 Value *B = getVectorValue(it->getOperand(1));
1085 // Use this vector value for all users of the original instruction.
1086 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A, B);
1089 // Update the NSW, NUW and Exact flags.
1090 BinaryOperator *VecOp = cast<BinaryOperator>(V);
1091 if (isa<OverflowingBinaryOperator>(BinOp)) {
1092 VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap());
1093 VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap());
1095 if (isa<PossiblyExactOperator>(VecOp))
1096 VecOp->setIsExact(BinOp->isExact());
1099 case Instruction::Select: {
1101 // If the selector is loop invariant we can create a select
1102 // instruction with a scalar condition. Otherwise, use vector-select.
1103 Value *Cond = it->getOperand(0);
1104 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(Cond), OrigLoop);
1106 // The condition can be loop invariant but still defined inside the
1107 // loop. This means that we can't just use the original 'cond' value.
1108 // We have to take the 'vectorized' value and pick the first lane.
1109 // Instcombine will make this a no-op.
1110 Cond = getVectorValue(Cond);
1112 Cond = Builder.CreateExtractElement(Cond, Builder.getInt32(0));
1114 Value *Op0 = getVectorValue(it->getOperand(1));
1115 Value *Op1 = getVectorValue(it->getOperand(2));
1116 WidenMap[it] = Builder.CreateSelect(Cond, Op0, Op1);
1120 case Instruction::ICmp:
1121 case Instruction::FCmp: {
1122 // Widen compares. Generate vector compares.
1123 bool FCmp = (it->getOpcode() == Instruction::FCmp);
1124 CmpInst *Cmp = dyn_cast<CmpInst>(it);
1125 Value *A = getVectorValue(it->getOperand(0));
1126 Value *B = getVectorValue(it->getOperand(1));
1128 WidenMap[it] = Builder.CreateFCmp(Cmp->getPredicate(), A, B);
1130 WidenMap[it] = Builder.CreateICmp(Cmp->getPredicate(), A, B);
1134 case Instruction::Store: {
1135 // Attempt to issue a wide store.
1136 StoreInst *SI = dyn_cast<StoreInst>(it);
1137 Type *StTy = VectorType::get(SI->getValueOperand()->getType(), VF);
1138 Value *Ptr = SI->getPointerOperand();
1139 unsigned Alignment = SI->getAlignment();
1141 assert(!Legal->isUniform(Ptr) &&
1142 "We do not allow storing to uniform addresses");
1144 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1146 // This store does not use GEPs.
1147 if (!Legal->isConsecutivePtr(Ptr)) {
1148 scalarizeInstruction(it);
1153 // The last index does not have to be the induction. It can be
1154 // consecutive and be a function of the index. For example A[I+1];
1155 unsigned NumOperands = Gep->getNumOperands();
1156 Value *LastIndex = getVectorValue(Gep->getOperand(NumOperands - 1));
1157 LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
1159 // Create the new GEP with the new induction variable.
1160 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1161 Gep2->setOperand(NumOperands - 1, LastIndex);
1162 Ptr = Builder.Insert(Gep2);
1164 // Use the induction element ptr.
1165 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1166 Ptr = Builder.CreateExtractElement(getVectorValue(Ptr), Zero);
1168 Ptr = Builder.CreateBitCast(Ptr, StTy->getPointerTo());
1169 Value *Val = getVectorValue(SI->getValueOperand());
1170 Builder.CreateStore(Val, Ptr)->setAlignment(Alignment);
1173 case Instruction::Load: {
1174 // Attempt to issue a wide load.
1175 LoadInst *LI = dyn_cast<LoadInst>(it);
1176 Type *RetTy = VectorType::get(LI->getType(), VF);
1177 Value *Ptr = LI->getPointerOperand();
1178 unsigned Alignment = LI->getAlignment();
1179 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1181 // If the pointer is loop invariant or if it is non consecutive,
1182 // scalarize the load.
1183 bool Con = Legal->isConsecutivePtr(Ptr);
1184 if (Legal->isUniform(Ptr) || !Con) {
1185 scalarizeInstruction(it);
1190 // The last index does not have to be the induction. It can be
1191 // consecutive and be a function of the index. For example A[I+1];
1192 unsigned NumOperands = Gep->getNumOperands();
1193 Value *LastIndex = getVectorValue(Gep->getOperand(NumOperands -1));
1194 LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
1196 // Create the new GEP with the new induction variable.
1197 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1198 Gep2->setOperand(NumOperands - 1, LastIndex);
1199 Ptr = Builder.Insert(Gep2);
1201 // Use the induction element ptr.
1202 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1203 Ptr = Builder.CreateExtractElement(getVectorValue(Ptr), Zero);
1206 Ptr = Builder.CreateBitCast(Ptr, RetTy->getPointerTo());
1207 LI = Builder.CreateLoad(Ptr);
1208 LI->setAlignment(Alignment);
1209 // Use this vector value for all users of the load.
1213 case Instruction::ZExt:
1214 case Instruction::SExt:
1215 case Instruction::FPToUI:
1216 case Instruction::FPToSI:
1217 case Instruction::FPExt:
1218 case Instruction::PtrToInt:
1219 case Instruction::IntToPtr:
1220 case Instruction::SIToFP:
1221 case Instruction::UIToFP:
1222 case Instruction::Trunc:
1223 case Instruction::FPTrunc:
1224 case Instruction::BitCast: {
1225 CastInst *CI = dyn_cast<CastInst>(it);
1226 /// Optimize the special case where the source is the induction
1227 /// variable. Notice that we can only optimize the 'trunc' case
1228 /// because: a. FP conversions lose precision, b. sext/zext may wrap,
1229 /// c. other casts depend on pointer size.
1230 if (CI->getOperand(0) == OldInduction &&
1231 it->getOpcode() == Instruction::Trunc) {
1232 Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
1234 Value *Broadcasted = getBroadcastInstrs(ScalarCast);
1235 WidenMap[it] = getConsecutiveVector(Broadcasted);
1238 /// Vectorize casts.
1239 Value *A = getVectorValue(it->getOperand(0));
1240 Type *DestTy = VectorType::get(CI->getType()->getScalarType(), VF);
1241 WidenMap[it] = Builder.CreateCast(CI->getOpcode(), A, DestTy);
1245 case Instruction::Call: {
1246 assert(isTriviallyVectorizableIntrinsic(it));
1247 Module *M = BB->getParent()->getParent();
1248 IntrinsicInst *II = cast<IntrinsicInst>(it);
1249 Intrinsic::ID ID = II->getIntrinsicID();
1250 SmallVector<Value*, 4> Args;
1251 for (unsigned i = 0, ie = II->getNumArgOperands(); i != ie; ++i)
1252 Args.push_back(getVectorValue(II->getArgOperand(i)));
1253 Type *Tys[] = { VectorType::get(II->getType()->getScalarType(), VF) };
1254 Function *F = Intrinsic::getDeclaration(M, ID, Tys);
1255 WidenMap[it] = Builder.CreateCall(F, Args);
1260 // All other instructions are unsupported. Scalarize them.
1261 scalarizeInstruction(it);
1264 }// end of for_each instr.
1267 void InnerLoopVectorizer::updateAnalysis() {
1268 // Forget the original basic block.
1269 SE->forgetLoop(OrigLoop);
1271 // Update the dominator tree information.
1272 assert(DT->properlyDominates(LoopBypassBlock, LoopExitBlock) &&
1273 "Entry does not dominate exit.");
1275 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlock);
1276 DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader);
1277 DT->addNewBlock(LoopMiddleBlock, LoopBypassBlock);
1278 DT->addNewBlock(LoopScalarPreHeader, LoopMiddleBlock);
1279 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
1280 DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
1282 DEBUG(DT->verifyAnalysis());
1285 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
1286 if (!EnableIfConversion)
1289 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
1290 std::vector<BasicBlock*> &LoopBlocks = TheLoop->getBlocksVector();
1292 // Collect the blocks that need predication.
1293 for (unsigned i = 0, e = LoopBlocks.size(); i < e; ++i) {
1294 BasicBlock *BB = LoopBlocks[i];
1296 // We don't support switch statements inside loops.
1297 if (!isa<BranchInst>(BB->getTerminator()))
1300 // We must have at most two predecessors because we need to convert
1301 // all PHIs to selects.
1302 unsigned Preds = std::distance(pred_begin(BB), pred_end(BB));
1306 // We must be able to predicate all blocks that need to be predicated.
1307 if (blockNeedsPredication(BB) && !blockCanBePredicated(BB))
1311 // We can if-convert this loop.
1315 bool LoopVectorizationLegality::canVectorize() {
1316 assert(TheLoop->getLoopPreheader() && "No preheader!!");
1318 // We can only vectorize innermost loops.
1319 if (TheLoop->getSubLoopsVector().size())
1322 // We must have a single backedge.
1323 if (TheLoop->getNumBackEdges() != 1)
1326 // We must have a single exiting block.
1327 if (!TheLoop->getExitingBlock())
1330 unsigned NumBlocks = TheLoop->getNumBlocks();
1332 // Check if we can if-convert non single-bb loops.
1333 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
1334 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
1338 // We need to have a loop header.
1339 BasicBlock *Latch = TheLoop->getLoopLatch();
1340 DEBUG(dbgs() << "LV: Found a loop: " <<
1341 TheLoop->getHeader()->getName() << "\n");
1343 // ScalarEvolution needs to be able to find the exit count.
1344 const SCEV *ExitCount = SE->getExitCount(TheLoop, Latch);
1345 if (ExitCount == SE->getCouldNotCompute()) {
1346 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
1350 // Do not loop-vectorize loops with a tiny trip count.
1351 unsigned TC = SE->getSmallConstantTripCount(TheLoop, Latch);
1352 if (TC > 0u && TC < TinyTripCountThreshold) {
1353 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " <<
1354 "This loop is not worth vectorizing.\n");
1358 // Check if we can vectorize the instructions and CFG in this loop.
1359 if (!canVectorizeInstrs()) {
1360 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
1364 // Go over each instruction and look at memory deps.
1365 if (!canVectorizeMemory()) {
1366 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
1370 // Collect all of the variables that remain uniform after vectorization.
1371 collectLoopUniforms();
1373 DEBUG(dbgs() << "LV: We can vectorize this loop" <<
1374 (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
1377 // Okay! We can vectorize. At this point we don't have any other mem analysis
1378 // which may limit our maximum vectorization factor, so just return true with
1383 bool LoopVectorizationLegality::canVectorizeInstrs() {
1384 BasicBlock *PreHeader = TheLoop->getLoopPreheader();
1385 BasicBlock *Header = TheLoop->getHeader();
1387 // For each block in the loop.
1388 for (Loop::block_iterator bb = TheLoop->block_begin(),
1389 be = TheLoop->block_end(); bb != be; ++bb) {
1391 // Scan the instructions in the block and look for hazards.
1392 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
1395 if (PHINode *Phi = dyn_cast<PHINode>(it)) {
1396 // This should not happen because the loop should be normalized.
1397 if (Phi->getNumIncomingValues() != 2) {
1398 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
1402 // Check that this PHI type is allowed.
1403 if (!Phi->getType()->isIntegerTy() &&
1404 !Phi->getType()->isPointerTy()) {
1405 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
1409 // If this PHINode is not in the header block, then we know that we
1410 // can convert it to select during if-conversion. No need to check if
1411 // the PHIs in this block are induction or reduction variables.
1415 // This is the value coming from the preheader.
1416 Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
1417 // Check if this is an induction variable.
1418 InductionKind IK = isInductionVariable(Phi);
1420 if (NoInduction != IK) {
1421 // Int inductions are special because we only allow one IV.
1422 if (IK == IntInduction) {
1424 DEBUG(dbgs() << "LV: Found too many inductions."<< *Phi <<"\n");
1430 DEBUG(dbgs() << "LV: Found an induction variable.\n");
1431 Inductions[Phi] = InductionInfo(StartValue, IK);
1435 if (AddReductionVar(Phi, IntegerAdd)) {
1436 DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
1439 if (AddReductionVar(Phi, IntegerMult)) {
1440 DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
1443 if (AddReductionVar(Phi, IntegerOr)) {
1444 DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
1447 if (AddReductionVar(Phi, IntegerAnd)) {
1448 DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
1451 if (AddReductionVar(Phi, IntegerXor)) {
1452 DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
1456 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
1458 }// end of PHI handling
1460 // We still don't handle functions.
1461 CallInst *CI = dyn_cast<CallInst>(it);
1462 if (CI && !isTriviallyVectorizableIntrinsic(it)) {
1463 DEBUG(dbgs() << "LV: Found a call site.\n");
1467 // We do not re-vectorize vectors.
1468 if (!VectorType::isValidElementType(it->getType()) &&
1469 !it->getType()->isVoidTy()) {
1470 DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n");
1474 // Reduction instructions are allowed to have exit users.
1475 // All other instructions must not have external users.
1476 if (!AllowedExit.count(it))
1477 //Check that all of the users of the loop are inside the BB.
1478 for (Value::use_iterator I = it->use_begin(), E = it->use_end();
1480 Instruction *U = cast<Instruction>(*I);
1481 // This user may be a reduction exit value.
1482 if (!TheLoop->contains(U)) {
1483 DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n");
1492 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
1493 assert(getInductionVars()->size() && "No induction variables");
1499 void LoopVectorizationLegality::collectLoopUniforms() {
1500 // We now know that the loop is vectorizable!
1501 // Collect variables that will remain uniform after vectorization.
1502 std::vector<Value*> Worklist;
1503 BasicBlock *Latch = TheLoop->getLoopLatch();
1505 // Start with the conditional branch and walk up the block.
1506 Worklist.push_back(Latch->getTerminator()->getOperand(0));
1508 while (Worklist.size()) {
1509 Instruction *I = dyn_cast<Instruction>(Worklist.back());
1510 Worklist.pop_back();
1512 // Look at instructions inside this loop.
1513 // Stop when reaching PHI nodes.
1514 // TODO: we need to follow values all over the loop, not only in this block.
1515 if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
1518 // This is a known uniform.
1521 // Insert all operands.
1522 for (int i = 0, Op = I->getNumOperands(); i < Op; ++i) {
1523 Worklist.push_back(I->getOperand(i));
1528 bool LoopVectorizationLegality::canVectorizeMemory() {
1529 typedef SmallVector<Value*, 16> ValueVector;
1530 typedef SmallPtrSet<Value*, 16> ValueSet;
1531 // Holds the Load and Store *instructions*.
1534 PtrRtCheck.Pointers.clear();
1535 PtrRtCheck.Need = false;
1538 for (Loop::block_iterator bb = TheLoop->block_begin(),
1539 be = TheLoop->block_end(); bb != be; ++bb) {
1541 // Scan the BB and collect legal loads and stores.
1542 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
1545 // If this is a load, save it. If this instruction can read from memory
1546 // but is not a load, then we quit. Notice that we don't handle function
1547 // calls that read or write.
1548 if (it->mayReadFromMemory()) {
1549 LoadInst *Ld = dyn_cast<LoadInst>(it);
1550 if (!Ld) return false;
1551 if (!Ld->isSimple()) {
1552 DEBUG(dbgs() << "LV: Found a non-simple load.\n");
1555 Loads.push_back(Ld);
1559 // Save 'store' instructions. Abort if other instructions write to memory.
1560 if (it->mayWriteToMemory()) {
1561 StoreInst *St = dyn_cast<StoreInst>(it);
1562 if (!St) return false;
1563 if (!St->isSimple()) {
1564 DEBUG(dbgs() << "LV: Found a non-simple store.\n");
1567 Stores.push_back(St);
1572 // Now we have two lists that hold the loads and the stores.
1573 // Next, we find the pointers that they use.
1575 // Check if we see any stores. If there are no stores, then we don't
1576 // care if the pointers are *restrict*.
1577 if (!Stores.size()) {
1578 DEBUG(dbgs() << "LV: Found a read-only loop!\n");
1582 // Holds the read and read-write *pointers* that we find.
1584 ValueVector ReadWrites;
1586 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
1587 // multiple times on the same object. If the ptr is accessed twice, once
1588 // for read and once for write, it will only appear once (on the write
1589 // list). This is okay, since we are going to check for conflicts between
1590 // writes and between reads and writes, but not between reads and reads.
1593 ValueVector::iterator I, IE;
1594 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
1595 StoreInst *ST = cast<StoreInst>(*I);
1596 Value* Ptr = ST->getPointerOperand();
1598 if (isUniform(Ptr)) {
1599 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
1603 // If we did *not* see this pointer before, insert it to
1604 // the read-write list. At this phase it is only a 'write' list.
1605 if (Seen.insert(Ptr))
1606 ReadWrites.push_back(Ptr);
1609 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
1610 LoadInst *LD = cast<LoadInst>(*I);
1611 Value* Ptr = LD->getPointerOperand();
1612 // If we did *not* see this pointer before, insert it to the
1613 // read list. If we *did* see it before, then it is already in
1614 // the read-write list. This allows us to vectorize expressions
1615 // such as A[i] += x; Because the address of A[i] is a read-write
1616 // pointer. This only works if the index of A[i] is consecutive.
1617 // If the address of i is unknown (for example A[B[i]]) then we may
1618 // read a few words, modify, and write a few words, and some of the
1619 // words may be written to the same address.
1620 if (Seen.insert(Ptr) || !isConsecutivePtr(Ptr))
1621 Reads.push_back(Ptr);
1624 // If we write (or read-write) to a single destination and there are no
1625 // other reads in this loop then is it safe to vectorize.
1626 if (ReadWrites.size() == 1 && Reads.size() == 0) {
1627 DEBUG(dbgs() << "LV: Found a write-only loop!\n");
1631 // Find pointers with computable bounds. We are going to use this information
1632 // to place a runtime bound check.
1633 bool CanDoRT = true;
1634 for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I)
1635 if (hasComputableBounds(*I)) {
1636 PtrRtCheck.insert(SE, TheLoop, *I);
1637 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n");
1642 for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I)
1643 if (hasComputableBounds(*I)) {
1644 PtrRtCheck.insert(SE, TheLoop, *I);
1645 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n");
1651 // Check that we did not collect too many pointers or found a
1652 // unsizeable pointer.
1653 if (!CanDoRT || PtrRtCheck.Pointers.size() > RuntimeMemoryCheckThreshold) {
1659 DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
1662 bool NeedRTCheck = false;
1664 // Now that the pointers are in two lists (Reads and ReadWrites), we
1665 // can check that there are no conflicts between each of the writes and
1666 // between the writes to the reads.
1667 ValueSet WriteObjects;
1668 ValueVector TempObjects;
1670 // Check that the read-writes do not conflict with other read-write
1672 for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I) {
1673 GetUnderlyingObjects(*I, TempObjects, DL);
1674 for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
1676 if (!isIdentifiedObject(*it)) {
1677 DEBUG(dbgs() << "LV: Found an unidentified write ptr:"<< **it <<"\n");
1680 if (!WriteObjects.insert(*it)) {
1681 DEBUG(dbgs() << "LV: Found a possible write-write reorder:"
1686 TempObjects.clear();
1689 /// Check that the reads don't conflict with the read-writes.
1690 for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I) {
1691 GetUnderlyingObjects(*I, TempObjects, DL);
1692 for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
1694 if (!isIdentifiedObject(*it)) {
1695 DEBUG(dbgs() << "LV: Found an unidentified read ptr:"<< **it <<"\n");
1698 if (WriteObjects.count(*it)) {
1699 DEBUG(dbgs() << "LV: Found a possible read/write reorder:"
1704 TempObjects.clear();
1707 PtrRtCheck.Need = NeedRTCheck;
1708 if (NeedRTCheck && !CanDoRT) {
1709 DEBUG(dbgs() << "LV: We can't vectorize because we can't find " <<
1710 "the array bounds.\n");
1715 DEBUG(dbgs() << "LV: We "<< (NeedRTCheck ? "" : "don't") <<
1716 " need a runtime memory check.\n");
1720 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
1721 ReductionKind Kind) {
1722 if (Phi->getNumIncomingValues() != 2)
1725 // Reduction variables are only found in the loop header block.
1726 if (Phi->getParent() != TheLoop->getHeader())
1729 // Obtain the reduction start value from the value that comes from the loop
1731 Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
1733 // ExitInstruction is the single value which is used outside the loop.
1734 // We only allow for a single reduction value to be used outside the loop.
1735 // This includes users of the reduction, variables (which form a cycle
1736 // which ends in the phi node).
1737 Instruction *ExitInstruction = 0;
1739 // Iter is our iterator. We start with the PHI node and scan for all of the
1740 // users of this instruction. All users must be instructions which can be
1741 // used as reduction variables (such as ADD). We may have a single
1742 // out-of-block user. They cycle must end with the original PHI.
1743 // Also, we can't have multiple block-local users.
1744 Instruction *Iter = Phi;
1746 // If the instruction has no users then this is a broken
1747 // chain and can't be a reduction variable.
1748 if (Iter->use_empty())
1751 // Any reduction instr must be of one of the allowed kinds.
1752 if (!isReductionInstr(Iter, Kind))
1755 // Did we find a user inside this block ?
1756 bool FoundInBlockUser = false;
1757 // Did we reach the initial PHI node ?
1758 bool FoundStartPHI = false;
1760 // For each of the *users* of iter.
1761 for (Value::use_iterator it = Iter->use_begin(), e = Iter->use_end();
1763 Instruction *U = cast<Instruction>(*it);
1764 // We already know that the PHI is a user.
1766 FoundStartPHI = true;
1770 // Check if we found the exit user.
1771 BasicBlock *Parent = U->getParent();
1772 if (!TheLoop->contains(Parent)) {
1773 // Exit if you find multiple outside users.
1774 if (ExitInstruction != 0)
1776 ExitInstruction = Iter;
1779 // We allow in-loop PHINodes which are not the original reduction PHI
1780 // node. If this PHI is the only user of Iter (happens in IF w/ no ELSE
1781 // structure) then don't skip this PHI.
1782 if (isa<PHINode>(U) && U->getParent() != TheLoop->getHeader() &&
1783 TheLoop->contains(U) && Iter->getNumUses() > 1)
1786 // We can't have multiple inside users.
1787 if (FoundInBlockUser)
1789 FoundInBlockUser = true;
1793 // We found a reduction var if we have reached the original
1794 // phi node and we only have a single instruction with out-of-loop
1796 if (FoundStartPHI && ExitInstruction) {
1797 // This instruction is allowed to have out-of-loop users.
1798 AllowedExit.insert(ExitInstruction);
1800 // Save the description of this reduction variable.
1801 ReductionDescriptor RD(RdxStart, ExitInstruction, Kind);
1802 Reductions[Phi] = RD;
1806 // If we've reached the start PHI but did not find an outside user then
1807 // this is dead code. Abort.
1814 LoopVectorizationLegality::isReductionInstr(Instruction *I,
1815 ReductionKind Kind) {
1816 switch (I->getOpcode()) {
1819 case Instruction::PHI:
1822 case Instruction::Add:
1823 case Instruction::Sub:
1824 return Kind == IntegerAdd;
1825 case Instruction::Mul:
1826 return Kind == IntegerMult;
1827 case Instruction::And:
1828 return Kind == IntegerAnd;
1829 case Instruction::Or:
1830 return Kind == IntegerOr;
1831 case Instruction::Xor:
1832 return Kind == IntegerXor;
1836 LoopVectorizationLegality::InductionKind
1837 LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
1838 Type *PhiTy = Phi->getType();
1839 // We only handle integer and pointer inductions variables.
1840 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
1843 // Check that the PHI is consecutive and starts at zero.
1844 const SCEV *PhiScev = SE->getSCEV(Phi);
1845 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
1847 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
1850 const SCEV *Step = AR->getStepRecurrence(*SE);
1852 // Integer inductions need to have a stride of one.
1853 if (PhiTy->isIntegerTy()) {
1855 return IntInduction;
1856 if (Step->isAllOnesValue())
1857 return ReverseIntInduction;
1861 // Calculate the pointer stride and check if it is consecutive.
1862 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
1866 assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
1867 uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType());
1868 if (C->getValue()->equalsInt(Size))
1869 return PtrInduction;
1874 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
1875 Value *In0 = const_cast<Value*>(V);
1876 PHINode *PN = dyn_cast_or_null<PHINode>(In0);
1880 return Inductions.count(PN);
1883 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
1884 assert(TheLoop->contains(BB) && "Unknown block used");
1886 // Blocks that do not dominate the latch need predication.
1887 BasicBlock* Latch = TheLoop->getLoopLatch();
1888 return !DT->dominates(BB, Latch);
1891 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB) {
1892 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1893 // We don't predicate loads/stores at the moment.
1894 if (it->mayReadFromMemory() || it->mayWriteToMemory() || it->mayThrow())
1897 // The instructions below can trap.
1898 switch (it->getOpcode()) {
1900 case Instruction::UDiv:
1901 case Instruction::SDiv:
1902 case Instruction::URem:
1903 case Instruction::SRem:
1911 bool LoopVectorizationLegality::hasComputableBounds(Value *Ptr) {
1912 const SCEV *PhiScev = SE->getSCEV(Ptr);
1913 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
1917 return AR->isAffine();
1921 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize,
1923 if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
1924 DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
1928 // Find the trip count.
1929 unsigned TC = SE->getSmallConstantTripCount(TheLoop, TheLoop->getLoopLatch());
1930 DEBUG(dbgs() << "LV: Found trip count:"<<TC<<"\n");
1932 unsigned VF = MaxVectorSize;
1934 // If we optimize the program for size, avoid creating the tail loop.
1936 // If we are unable to calculate the trip count then don't try to vectorize.
1938 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
1942 // Find the maximum SIMD width that can fit within the trip count.
1943 VF = TC % MaxVectorSize;
1948 // If the trip count that we found modulo the vectorization factor is not
1949 // zero then we require a tail.
1951 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
1957 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
1958 DEBUG(dbgs() << "LV: Using user VF "<<UserVF<<".\n");
1964 DEBUG(dbgs() << "LV: No vector target information. Not vectorizing. \n");
1968 float Cost = expectedCost(1);
1970 DEBUG(dbgs() << "LV: Scalar loop costs: "<< (int)Cost << ".\n");
1971 for (unsigned i=2; i <= VF; i*=2) {
1972 // Notice that the vector loop needs to be executed less times, so
1973 // we need to divide the cost of the vector loops by the width of
1974 // the vector elements.
1975 float VectorCost = expectedCost(i) / (float)i;
1976 DEBUG(dbgs() << "LV: Vector loop of width "<< i << " costs: " <<
1977 (int)VectorCost << ".\n");
1978 if (VectorCost < Cost) {
1984 DEBUG(dbgs() << "LV: Selecting VF = : "<< Width << ".\n");
1988 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
1992 for (Loop::block_iterator bb = TheLoop->block_begin(),
1993 be = TheLoop->block_end(); bb != be; ++bb) {
1994 unsigned BlockCost = 0;
1995 BasicBlock *BB = *bb;
1997 // For each instruction in the old loop.
1998 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1999 unsigned C = getInstructionCost(it, VF);
2001 DEBUG(dbgs() << "LV: Found an estimated cost of "<< C <<" for VF " <<
2002 VF << " For instruction: "<< *it << "\n");
2005 // We assume that if-converted blocks have a 50% chance of being executed.
2006 // When the code is scalar then some of the blocks are avoided due to CF.
2007 // When the code is vectorized we execute all code paths.
2008 if (Legal->blockNeedsPredication(*bb) && VF == 1)
2018 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
2019 assert(VTTI && "Invalid vector target transformation info");
2021 // If we know that this instruction will remain uniform, check the cost of
2022 // the scalar version.
2023 if (Legal->isUniformAfterVectorization(I))
2026 Type *RetTy = I->getType();
2027 Type *VectorTy = ToVectorTy(RetTy, VF);
2029 // TODO: We need to estimate the cost of intrinsic calls.
2030 switch (I->getOpcode()) {
2031 case Instruction::GetElementPtr:
2032 // We mark this instruction as zero-cost because scalar GEPs are usually
2033 // lowered to the intruction addressing mode. At the moment we don't
2034 // generate vector geps.
2036 case Instruction::Br: {
2037 return VTTI->getCFInstrCost(I->getOpcode());
2039 case Instruction::PHI:
2040 //TODO: IF-converted IFs become selects.
2042 case Instruction::Add:
2043 case Instruction::FAdd:
2044 case Instruction::Sub:
2045 case Instruction::FSub:
2046 case Instruction::Mul:
2047 case Instruction::FMul:
2048 case Instruction::UDiv:
2049 case Instruction::SDiv:
2050 case Instruction::FDiv:
2051 case Instruction::URem:
2052 case Instruction::SRem:
2053 case Instruction::FRem:
2054 case Instruction::Shl:
2055 case Instruction::LShr:
2056 case Instruction::AShr:
2057 case Instruction::And:
2058 case Instruction::Or:
2059 case Instruction::Xor:
2060 return VTTI->getArithmeticInstrCost(I->getOpcode(), VectorTy);
2061 case Instruction::Select: {
2062 SelectInst *SI = cast<SelectInst>(I);
2063 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
2064 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
2065 Type *CondTy = SI->getCondition()->getType();
2067 CondTy = VectorType::get(CondTy, VF);
2069 return VTTI->getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
2071 case Instruction::ICmp:
2072 case Instruction::FCmp: {
2073 Type *ValTy = I->getOperand(0)->getType();
2074 VectorTy = ToVectorTy(ValTy, VF);
2075 return VTTI->getCmpSelInstrCost(I->getOpcode(), VectorTy);
2077 case Instruction::Store: {
2078 StoreInst *SI = cast<StoreInst>(I);
2079 Type *ValTy = SI->getValueOperand()->getType();
2080 VectorTy = ToVectorTy(ValTy, VF);
2083 return VTTI->getMemoryOpCost(I->getOpcode(), VectorTy,
2085 SI->getPointerAddressSpace());
2087 // Scalarized stores.
2088 if (!Legal->isConsecutivePtr(SI->getPointerOperand())) {
2091 // The cost of extracting from the value vector and pointer vector.
2092 Type *PtrTy = ToVectorTy(I->getOperand(0)->getType(), VF);
2093 for (unsigned i = 0; i < VF; ++i) {
2094 Cost += VTTI->getVectorInstrCost(Instruction::ExtractElement,
2096 Cost += VTTI->getVectorInstrCost(Instruction::ExtractElement,
2100 // The cost of the scalar stores.
2101 Cost += VF * VTTI->getMemoryOpCost(I->getOpcode(),
2102 ValTy->getScalarType(),
2104 SI->getPointerAddressSpace());
2109 return VTTI->getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),
2110 SI->getPointerAddressSpace());
2112 case Instruction::Load: {
2113 LoadInst *LI = cast<LoadInst>(I);
2116 return VTTI->getMemoryOpCost(I->getOpcode(), VectorTy,
2118 LI->getPointerAddressSpace());
2120 // Scalarized loads.
2121 if (!Legal->isConsecutivePtr(LI->getPointerOperand())) {
2123 Type *PtrTy = ToVectorTy(I->getOperand(0)->getType(), VF);
2125 // The cost of extracting from the pointer vector.
2126 for (unsigned i = 0; i < VF; ++i)
2127 Cost += VTTI->getVectorInstrCost(Instruction::ExtractElement,
2130 // The cost of inserting data to the result vector.
2131 for (unsigned i = 0; i < VF; ++i)
2132 Cost += VTTI->getVectorInstrCost(Instruction::InsertElement,
2135 // The cost of the scalar stores.
2136 Cost += VF * VTTI->getMemoryOpCost(I->getOpcode(),
2137 RetTy->getScalarType(),
2139 LI->getPointerAddressSpace());
2144 return VTTI->getMemoryOpCost(I->getOpcode(), VectorTy, LI->getAlignment(),
2145 LI->getPointerAddressSpace());
2147 case Instruction::ZExt:
2148 case Instruction::SExt:
2149 case Instruction::FPToUI:
2150 case Instruction::FPToSI:
2151 case Instruction::FPExt:
2152 case Instruction::PtrToInt:
2153 case Instruction::IntToPtr:
2154 case Instruction::SIToFP:
2155 case Instruction::UIToFP:
2156 case Instruction::Trunc:
2157 case Instruction::FPTrunc:
2158 case Instruction::BitCast: {
2159 // We optimize the truncation of induction variable.
2160 // The cost of these is the same as the scalar operation.
2161 if (I->getOpcode() == Instruction::Trunc &&
2162 Legal->isInductionVariable(I->getOperand(0)))
2163 return VTTI->getCastInstrCost(I->getOpcode(), I->getType(),
2164 I->getOperand(0)->getType());
2166 Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
2167 return VTTI->getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
2169 case Instruction::Call: {
2170 assert(isTriviallyVectorizableIntrinsic(I));
2171 IntrinsicInst *II = cast<IntrinsicInst>(I);
2172 Type *RetTy = ToVectorTy(II->getType(), VF);
2173 SmallVector<Type*, 4> Tys;
2174 for (unsigned i = 0, ie = II->getNumArgOperands(); i != ie; ++i)
2175 Tys.push_back(ToVectorTy(II->getArgOperand(i)->getType(), VF));
2176 return VTTI->getIntrinsicInstrCost(II->getIntrinsicID(), RetTy, Tys);
2179 // We are scalarizing the instruction. Return the cost of the scalar
2180 // instruction, plus the cost of insert and extract into vector
2181 // elements, times the vector width.
2184 if (!RetTy->isVoidTy() && VF != 1) {
2185 unsigned InsCost = VTTI->getVectorInstrCost(Instruction::InsertElement,
2187 unsigned ExtCost = VTTI->getVectorInstrCost(Instruction::ExtractElement,
2190 // The cost of inserting the results plus extracting each one of the
2192 Cost += VF * (InsCost + ExtCost * I->getNumOperands());
2195 // The cost of executing VF copies of the scalar instruction. This opcode
2196 // is unknown. Assume that it is the same as 'mul'.
2197 Cost += VF * VTTI->getArithmeticInstrCost(Instruction::Mul, VectorTy);
2203 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
2204 if (Scalar->isVoidTy() || VF == 1)
2206 return VectorType::get(Scalar, VF);
2209 char LoopVectorize::ID = 0;
2210 static const char lv_name[] = "Loop Vectorization";
2211 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
2212 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
2213 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
2214 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
2215 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
2218 Pass *createLoopVectorizePass() {
2219 return new LoopVectorize();