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/IR/Constants.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/DerivedTypes.h"
24 #include "llvm/IR/Function.h"
25 #include "llvm/IR/Instructions.h"
26 #include "llvm/IR/IntrinsicInst.h"
27 #include "llvm/IR/LLVMContext.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/IR/Type.h"
30 #include "llvm/IR/Value.h"
31 #include "llvm/Pass.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/TargetTransformInfo.h"
36 #include "llvm/Transforms/Scalar.h"
37 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
38 #include "llvm/Transforms/Utils/Local.h"
39 #include "llvm/Transforms/Vectorize.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 Attribute::AttrKind FlAttr = Attribute::NoImplicitFloat;
99 unsigned FnIndex = AttributeSet::FunctionIndex;
100 bool OptForSize = F->getAttributes().hasAttribute(FnIndex, SzAttr);
101 bool NoFloat = F->getAttributes().hasAttribute(FnIndex, FlAttr);
104 DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
105 "attribute is used.\n");
109 unsigned VF = CM.selectVectorizationFactor(OptForSize, VectorizationFactor);
112 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
116 DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< VF << ") in "<<
117 F->getParent()->getModuleIdentifier()<<"\n");
119 // If we decided that it is *legal* to vectorizer the loop then do it.
120 InnerLoopVectorizer LB(L, SE, LI, DT, DL, VF);
123 DEBUG(verifyFunction(*L->getHeader()->getParent()));
127 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
128 LoopPass::getAnalysisUsage(AU);
129 AU.addRequiredID(LoopSimplifyID);
130 AU.addRequiredID(LCSSAID);
131 AU.addRequired<LoopInfo>();
132 AU.addRequired<ScalarEvolution>();
133 AU.addRequired<DominatorTree>();
134 AU.addPreserved<LoopInfo>();
135 AU.addPreserved<DominatorTree>();
142 //===----------------------------------------------------------------------===//
143 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
144 // LoopVectorizationCostModel.
145 //===----------------------------------------------------------------------===//
148 LoopVectorizationLegality::RuntimePointerCheck::insert(ScalarEvolution *SE,
149 Loop *Lp, Value *Ptr) {
150 const SCEV *Sc = SE->getSCEV(Ptr);
151 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
152 assert(AR && "Invalid addrec expression");
153 const SCEV *Ex = SE->getExitCount(Lp, Lp->getLoopLatch());
154 const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
155 Pointers.push_back(Ptr);
156 Starts.push_back(AR->getStart());
157 Ends.push_back(ScEnd);
160 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
161 // Save the current insertion location.
162 Instruction *Loc = Builder.GetInsertPoint();
164 // We need to place the broadcast of invariant variables outside the loop.
165 Instruction *Instr = dyn_cast<Instruction>(V);
166 bool NewInstr = (Instr && Instr->getParent() == LoopVectorBody);
167 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
169 // Place the code for broadcasting invariant variables in the new preheader.
171 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
173 // Broadcast the scalar into all locations in the vector.
174 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
176 // Restore the builder insertion point.
178 Builder.SetInsertPoint(Loc);
183 Value *InnerLoopVectorizer::getConsecutiveVector(Value* Val, bool Negate) {
184 assert(Val->getType()->isVectorTy() && "Must be a vector");
185 assert(Val->getType()->getScalarType()->isIntegerTy() &&
186 "Elem must be an integer");
188 Type *ITy = Val->getType()->getScalarType();
189 VectorType *Ty = cast<VectorType>(Val->getType());
190 int VLen = Ty->getNumElements();
191 SmallVector<Constant*, 8> Indices;
193 // Create a vector of consecutive numbers from zero to VF.
194 for (int i = 0; i < VLen; ++i)
195 Indices.push_back(ConstantInt::get(ITy, Negate ? (-i): i ));
197 // Add the consecutive indices to the vector value.
198 Constant *Cv = ConstantVector::get(Indices);
199 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
200 return Builder.CreateAdd(Val, Cv, "induction");
203 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
204 assert(Ptr->getType()->isPointerTy() && "Unexpected non ptr");
206 // If this value is a pointer induction variable we know it is consecutive.
207 PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
208 if (Phi && Inductions.count(Phi)) {
209 InductionInfo II = Inductions[Phi];
210 if (PtrInduction == II.IK)
214 GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
218 unsigned NumOperands = Gep->getNumOperands();
219 Value *LastIndex = Gep->getOperand(NumOperands - 1);
221 // Check that all of the gep indices are uniform except for the last.
222 for (unsigned i = 0; i < NumOperands - 1; ++i)
223 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
226 // We can emit wide load/stores only if the last index is the induction
228 const SCEV *Last = SE->getSCEV(LastIndex);
229 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
230 const SCEV *Step = AR->getStepRecurrence(*SE);
232 // The memory is consecutive because the last index is consecutive
233 // and all other indices are loop invariant.
236 if (Step->isAllOnesValue())
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 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
267 assert(Vec->getType()->isVectorTy() && "Invalid type");
268 SmallVector<Constant*, 8> ShuffleMask;
269 for (unsigned i = 0; i < VF; ++i)
270 ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
272 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
273 ConstantVector::get(ShuffleMask),
277 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr) {
278 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
279 // Holds vector parameters or scalars, in case of uniform vals.
280 SmallVector<Value*, 8> Params;
282 // Find all of the vectorized parameters.
283 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
284 Value *SrcOp = Instr->getOperand(op);
286 // If we are accessing the old induction variable, use the new one.
287 if (SrcOp == OldInduction) {
288 Params.push_back(getVectorValue(SrcOp));
292 // Try using previously calculated values.
293 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
295 // If the src is an instruction that appeared earlier in the basic block
296 // then it should already be vectorized.
297 if (SrcInst && OrigLoop->contains(SrcInst)) {
298 assert(WidenMap.count(SrcInst) && "Source operand is unavailable");
299 // The parameter is a vector value from earlier.
300 Params.push_back(WidenMap[SrcInst]);
302 // The parameter is a scalar from outside the loop. Maybe even a constant.
303 Params.push_back(SrcOp);
307 assert(Params.size() == Instr->getNumOperands() &&
308 "Invalid number of operands");
310 // Does this instruction return a value ?
311 bool IsVoidRetTy = Instr->getType()->isVoidTy();
312 Value *VecResults = 0;
314 // If we have a return value, create an empty vector. We place the scalarized
315 // instructions in this vector.
317 VecResults = UndefValue::get(VectorType::get(Instr->getType(), VF));
319 // For each scalar that we create:
320 for (unsigned i = 0; i < VF; ++i) {
321 Instruction *Cloned = Instr->clone();
323 Cloned->setName(Instr->getName() + ".cloned");
324 // Replace the operands of the cloned instrucions with extracted scalars.
325 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
326 Value *Op = Params[op];
327 // Param is a vector. Need to extract the right lane.
328 if (Op->getType()->isVectorTy())
329 Op = Builder.CreateExtractElement(Op, Builder.getInt32(i));
330 Cloned->setOperand(op, Op);
333 // Place the cloned scalar in the new loop.
334 Builder.Insert(Cloned);
336 // If the original scalar returns a value we need to place it in a vector
337 // so that future users will be able to use it.
339 VecResults = Builder.CreateInsertElement(VecResults, Cloned,
340 Builder.getInt32(i));
344 WidenMap[Instr] = VecResults;
348 InnerLoopVectorizer::addRuntimeCheck(LoopVectorizationLegality *Legal,
350 LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck =
351 Legal->getRuntimePointerCheck();
353 if (!PtrRtCheck->Need)
356 Value *MemoryRuntimeCheck = 0;
357 unsigned NumPointers = PtrRtCheck->Pointers.size();
358 SmallVector<Value* , 2> Starts;
359 SmallVector<Value* , 2> Ends;
361 SCEVExpander Exp(*SE, "induction");
363 // Use this type for pointer arithmetic.
364 Type* PtrArithTy = Type::getInt8PtrTy(Loc->getContext(), 0);
366 for (unsigned i = 0; i < NumPointers; ++i) {
367 Value *Ptr = PtrRtCheck->Pointers[i];
368 const SCEV *Sc = SE->getSCEV(Ptr);
370 if (SE->isLoopInvariant(Sc, OrigLoop)) {
371 DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" <<
373 Starts.push_back(Ptr);
376 DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr <<"\n");
378 Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc);
379 Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
380 Starts.push_back(Start);
385 for (unsigned i = 0; i < NumPointers; ++i) {
386 for (unsigned j = i+1; j < NumPointers; ++j) {
387 Instruction::CastOps Op = Instruction::BitCast;
388 Value *Start0 = CastInst::Create(Op, Starts[i], PtrArithTy, "bc", Loc);
389 Value *Start1 = CastInst::Create(Op, Starts[j], PtrArithTy, "bc", Loc);
390 Value *End0 = CastInst::Create(Op, Ends[i], PtrArithTy, "bc", Loc);
391 Value *End1 = CastInst::Create(Op, Ends[j], PtrArithTy, "bc", Loc);
393 Value *Cmp0 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_ULE,
394 Start0, End1, "bound0", Loc);
395 Value *Cmp1 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_ULE,
396 Start1, End0, "bound1", Loc);
397 Value *IsConflict = BinaryOperator::Create(Instruction::And, Cmp0, Cmp1,
398 "found.conflict", Loc);
399 if (MemoryRuntimeCheck)
400 MemoryRuntimeCheck = BinaryOperator::Create(Instruction::Or,
403 "conflict.rdx", Loc);
405 MemoryRuntimeCheck = IsConflict;
410 return MemoryRuntimeCheck;
414 InnerLoopVectorizer::createEmptyLoop(LoopVectorizationLegality *Legal) {
416 In this function we generate a new loop. The new loop will contain
417 the vectorized instructions while the old loop will continue to run the
420 [ ] <-- vector loop bypass.
423 | [ ] <-- vector pre header.
427 | [ ]_| <-- vector loop.
430 >[ ] <--- middle-block.
433 | [ ] <--- new preheader.
437 | [ ]_| <-- old scalar loop to handle remainder.
444 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
445 BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
446 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
447 assert(ExitBlock && "Must have an exit block");
449 // Some loops have a single integer induction variable, while other loops
450 // don't. One example is c++ iterators that often have multiple pointer
451 // induction variables. In the code below we also support a case where we
452 // don't have a single induction variable.
453 OldInduction = Legal->getInduction();
454 Type *IdxTy = OldInduction ? OldInduction->getType() :
455 DL->getIntPtrType(SE->getContext());
457 // Find the loop boundaries.
458 const SCEV *ExitCount = SE->getExitCount(OrigLoop, OrigLoop->getLoopLatch());
459 assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
461 // Get the total trip count from the count by adding 1.
462 ExitCount = SE->getAddExpr(ExitCount,
463 SE->getConstant(ExitCount->getType(), 1));
465 // Expand the trip count and place the new instructions in the preheader.
466 // Notice that the pre-header does not change, only the loop body.
467 SCEVExpander Exp(*SE, "induction");
469 // Count holds the overall loop count (N).
470 Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
471 BypassBlock->getTerminator());
473 // The loop index does not have to start at Zero. Find the original start
474 // value from the induction PHI node. If we don't have an induction variable
475 // then we know that it starts at zero.
476 Value *StartIdx = OldInduction ?
477 OldInduction->getIncomingValueForBlock(BypassBlock):
478 ConstantInt::get(IdxTy, 0);
480 assert(BypassBlock && "Invalid loop structure");
482 // Generate the code that checks in runtime if arrays overlap.
483 Value *MemoryRuntimeCheck = addRuntimeCheck(Legal,
484 BypassBlock->getTerminator());
486 // Split the single block loop into the two loop structure described above.
487 BasicBlock *VectorPH =
488 BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
489 BasicBlock *VecBody =
490 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
491 BasicBlock *MiddleBlock =
492 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
493 BasicBlock *ScalarPH =
494 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
496 // This is the location in which we add all of the logic for bypassing
497 // the new vector loop.
498 Instruction *Loc = BypassBlock->getTerminator();
500 // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
502 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
504 // Generate the induction variable.
505 Induction = Builder.CreatePHI(IdxTy, 2, "index");
506 Constant *Step = ConstantInt::get(IdxTy, VF);
508 // We may need to extend the index in case there is a type mismatch.
509 // We know that the count starts at zero and does not overflow.
510 if (Count->getType() != IdxTy) {
511 // The exit count can be of pointer type. Convert it to the correct
513 if (ExitCount->getType()->isPointerTy())
514 Count = CastInst::CreatePointerCast(Count, IdxTy, "ptrcnt.to.int", Loc);
516 Count = CastInst::CreateZExtOrBitCast(Count, IdxTy, "zext.cnt", Loc);
519 // Add the start index to the loop count to get the new end index.
520 Value *IdxEnd = BinaryOperator::CreateAdd(Count, StartIdx, "end.idx", Loc);
522 // Now we need to generate the expression for N - (N % VF), which is
523 // the part that the vectorized body will execute.
524 Constant *CIVF = ConstantInt::get(IdxTy, VF);
525 Value *R = BinaryOperator::CreateURem(Count, CIVF, "n.mod.vf", Loc);
526 Value *CountRoundDown = BinaryOperator::CreateSub(Count, R, "n.vec", Loc);
527 Value *IdxEndRoundDown = BinaryOperator::CreateAdd(CountRoundDown, StartIdx,
528 "end.idx.rnd.down", Loc);
530 // Now, compare the new count to zero. If it is zero skip the vector loop and
531 // jump to the scalar loop.
532 Value *Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
537 // If we are using memory runtime checks, include them in.
538 if (MemoryRuntimeCheck)
539 Cmp = BinaryOperator::Create(Instruction::Or, Cmp, MemoryRuntimeCheck,
542 BranchInst::Create(MiddleBlock, VectorPH, Cmp, Loc);
543 // Remove the old terminator.
544 Loc->eraseFromParent();
546 // We are going to resume the execution of the scalar loop.
547 // Go over all of the induction variables that we found and fix the
548 // PHIs that are left in the scalar version of the loop.
549 // The starting values of PHI nodes depend on the counter of the last
550 // iteration in the vectorized loop.
551 // If we come from a bypass edge then we need to start from the original
554 // This variable saves the new starting index for the scalar loop.
555 PHINode *ResumeIndex = 0;
556 LoopVectorizationLegality::InductionList::iterator I, E;
557 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
558 for (I = List->begin(), E = List->end(); I != E; ++I) {
559 PHINode *OrigPhi = I->first;
560 LoopVectorizationLegality::InductionInfo II = I->second;
561 PHINode *ResumeVal = PHINode::Create(OrigPhi->getType(), 2, "resume.val",
562 MiddleBlock->getTerminator());
565 case LoopVectorizationLegality::NoInduction:
566 llvm_unreachable("Unknown induction");
567 case LoopVectorizationLegality::IntInduction: {
568 // Handle the integer induction counter:
569 assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
570 assert(OrigPhi == OldInduction && "Unknown integer PHI");
571 // We know what the end value is.
572 EndValue = IdxEndRoundDown;
573 // We also know which PHI node holds it.
574 ResumeIndex = ResumeVal;
577 case LoopVectorizationLegality::ReverseIntInduction: {
578 // Convert the CountRoundDown variable to the PHI size.
579 unsigned CRDSize = CountRoundDown->getType()->getScalarSizeInBits();
580 unsigned IISize = II.StartValue->getType()->getScalarSizeInBits();
581 Value *CRD = CountRoundDown;
582 if (CRDSize > IISize)
583 CRD = CastInst::Create(Instruction::Trunc, CountRoundDown,
584 II.StartValue->getType(),
585 "tr.crd", BypassBlock->getTerminator());
586 else if (CRDSize < IISize)
587 CRD = CastInst::Create(Instruction::SExt, CountRoundDown,
588 II.StartValue->getType(),
589 "sext.crd", BypassBlock->getTerminator());
590 // Handle reverse integer induction counter:
591 EndValue = BinaryOperator::CreateSub(II.StartValue, CRD, "rev.ind.end",
592 BypassBlock->getTerminator());
595 case LoopVectorizationLegality::PtrInduction: {
596 // For pointer induction variables, calculate the offset using
598 EndValue = GetElementPtrInst::Create(II.StartValue, CountRoundDown,
600 BypassBlock->getTerminator());
605 // The new PHI merges the original incoming value, in case of a bypass,
606 // or the value at the end of the vectorized loop.
607 ResumeVal->addIncoming(II.StartValue, BypassBlock);
608 ResumeVal->addIncoming(EndValue, VecBody);
610 // Fix the scalar body counter (PHI node).
611 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
612 OrigPhi->setIncomingValue(BlockIdx, ResumeVal);
615 // If we are generating a new induction variable then we also need to
616 // generate the code that calculates the exit value. This value is not
617 // simply the end of the counter because we may skip the vectorized body
618 // in case of a runtime check.
620 assert(!ResumeIndex && "Unexpected resume value found");
621 ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
622 MiddleBlock->getTerminator());
623 ResumeIndex->addIncoming(StartIdx, BypassBlock);
624 ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
627 // Make sure that we found the index where scalar loop needs to continue.
628 assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
629 "Invalid resume Index");
631 // Add a check in the middle block to see if we have completed
632 // all of the iterations in the first vector loop.
633 // If (N - N%VF) == N, then we *don't* need to run the remainder.
634 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
635 ResumeIndex, "cmp.n",
636 MiddleBlock->getTerminator());
638 BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
639 // Remove the old terminator.
640 MiddleBlock->getTerminator()->eraseFromParent();
642 // Create i+1 and fill the PHINode.
643 Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
644 Induction->addIncoming(StartIdx, VectorPH);
645 Induction->addIncoming(NextIdx, VecBody);
646 // Create the compare.
647 Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
648 Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
650 // Now we have two terminators. Remove the old one from the block.
651 VecBody->getTerminator()->eraseFromParent();
653 // Get ready to start creating new instructions into the vectorized body.
654 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
656 // Create and register the new vector loop.
657 Loop* Lp = new Loop();
658 Loop *ParentLoop = OrigLoop->getParentLoop();
660 // Insert the new loop into the loop nest and register the new basic blocks.
662 ParentLoop->addChildLoop(Lp);
663 ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
664 ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
665 ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
667 LI->addTopLevelLoop(Lp);
670 Lp->addBasicBlockToLoop(VecBody, LI->getBase());
673 LoopVectorPreHeader = VectorPH;
674 LoopScalarPreHeader = ScalarPH;
675 LoopMiddleBlock = MiddleBlock;
676 LoopExitBlock = ExitBlock;
677 LoopVectorBody = VecBody;
678 LoopScalarBody = OldBasicBlock;
679 LoopBypassBlock = BypassBlock;
682 /// This function returns the identity element (or neutral element) for
685 getReductionIdentity(LoopVectorizationLegality::ReductionKind K) {
687 case LoopVectorizationLegality::IntegerXor:
688 case LoopVectorizationLegality::IntegerAdd:
689 case LoopVectorizationLegality::IntegerOr:
690 // Adding, Xoring, Oring zero to a number does not change it.
692 case LoopVectorizationLegality::IntegerMult:
693 // Multiplying a number by 1 does not change it.
695 case LoopVectorizationLegality::IntegerAnd:
696 // AND-ing a number with an all-1 value does not change it.
699 llvm_unreachable("Unknown reduction kind");
704 isTriviallyVectorizableIntrinsic(Instruction *Inst) {
705 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst);
708 switch (II->getIntrinsicID()) {
709 case Intrinsic::sqrt:
713 case Intrinsic::exp2:
715 case Intrinsic::log10:
716 case Intrinsic::log2:
717 case Intrinsic::fabs:
718 case Intrinsic::floor:
719 case Intrinsic::ceil:
720 case Intrinsic::trunc:
721 case Intrinsic::rint:
722 case Intrinsic::nearbyint:
725 case Intrinsic::fmuladd:
734 InnerLoopVectorizer::vectorizeLoop(LoopVectorizationLegality *Legal) {
735 //===------------------------------------------------===//
737 // Notice: any optimization or new instruction that go
738 // into the code below should be also be implemented in
741 //===------------------------------------------------===//
742 BasicBlock &BB = *OrigLoop->getHeader();
744 ConstantInt::get(IntegerType::getInt32Ty(BB.getContext()), 0);
746 // In order to support reduction variables we need to be able to vectorize
747 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
748 // stages. First, we create a new vector PHI node with no incoming edges.
749 // We use this value when we vectorize all of the instructions that use the
750 // PHI. Next, after all of the instructions in the block are complete we
751 // add the new incoming edges to the PHI. At this point all of the
752 // instructions in the basic block are vectorized, so we can use them to
753 // construct the PHI.
754 PhiVector RdxPHIsToFix;
756 // Scan the loop in a topological order to ensure that defs are vectorized
758 LoopBlocksDFS DFS(OrigLoop);
761 // Vectorize all of the blocks in the original loop.
762 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
763 be = DFS.endRPO(); bb != be; ++bb)
764 vectorizeBlockInLoop(Legal, *bb, &RdxPHIsToFix);
766 // At this point every instruction in the original loop is widened to
767 // a vector form. We are almost done. Now, we need to fix the PHI nodes
768 // that we vectorized. The PHI nodes are currently empty because we did
769 // not want to introduce cycles. Notice that the remaining PHI nodes
770 // that we need to fix are reduction variables.
772 // Create the 'reduced' values for each of the induction vars.
773 // The reduced values are the vector values that we scalarize and combine
774 // after the loop is finished.
775 for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
777 PHINode *RdxPhi = *it;
778 PHINode *VecRdxPhi = dyn_cast<PHINode>(WidenMap[RdxPhi]);
779 assert(RdxPhi && "Unable to recover vectorized PHI");
781 // Find the reduction variable descriptor.
782 assert(Legal->getReductionVars()->count(RdxPhi) &&
783 "Unable to find the reduction variable");
784 LoopVectorizationLegality::ReductionDescriptor RdxDesc =
785 (*Legal->getReductionVars())[RdxPhi];
787 // We need to generate a reduction vector from the incoming scalar.
788 // To do so, we need to generate the 'identity' vector and overide
789 // one of the elements with the incoming scalar reduction. We need
790 // to do it in the vector-loop preheader.
791 Builder.SetInsertPoint(LoopBypassBlock->getTerminator());
793 // This is the vector-clone of the value that leaves the loop.
794 Value *VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
795 Type *VecTy = VectorExit->getType();
797 // Find the reduction identity variable. Zero for addition, or, xor,
798 // one for multiplication, -1 for And.
799 Constant *Identity = getUniformVector(getReductionIdentity(RdxDesc.Kind),
800 VecTy->getScalarType());
802 // This vector is the Identity vector where the first element is the
803 // incoming scalar reduction.
804 Value *VectorStart = Builder.CreateInsertElement(Identity,
805 RdxDesc.StartValue, Zero);
807 // Fix the vector-loop phi.
808 // We created the induction variable so we know that the
809 // preheader is the first entry.
810 BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
812 // Reductions do not have to start at zero. They can start with
813 // any loop invariant values.
814 VecRdxPhi->addIncoming(VectorStart, VecPreheader);
816 getVectorValue(RdxPhi->getIncomingValueForBlock(OrigLoop->getLoopLatch()));
817 VecRdxPhi->addIncoming(Val, LoopVectorBody);
819 // Before each round, move the insertion point right between
820 // the PHIs and the values we are going to write.
821 // This allows us to write both PHINodes and the extractelement
823 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
825 // This PHINode contains the vectorized reduction variable, or
826 // the initial value vector, if we bypass the vector loop.
827 PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
828 NewPhi->addIncoming(VectorStart, LoopBypassBlock);
829 NewPhi->addIncoming(getVectorValue(RdxDesc.LoopExitInstr), LoopVectorBody);
831 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
832 // and vector ops, reducing the set of values being computed by half each
834 assert(isPowerOf2_32(VF) &&
835 "Reduction emission only supported for pow2 vectors!");
836 Value *TmpVec = NewPhi;
837 SmallVector<Constant*, 32> ShuffleMask(VF, 0);
838 for (unsigned i = VF; i != 1; i >>= 1) {
839 // Move the upper half of the vector to the lower half.
840 for (unsigned j = 0; j != i/2; ++j)
841 ShuffleMask[j] = Builder.getInt32(i/2 + j);
843 // Fill the rest of the mask with undef.
844 std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
845 UndefValue::get(Builder.getInt32Ty()));
848 Builder.CreateShuffleVector(TmpVec,
849 UndefValue::get(TmpVec->getType()),
850 ConstantVector::get(ShuffleMask),
853 // Emit the operation on the shuffled value.
854 switch (RdxDesc.Kind) {
855 case LoopVectorizationLegality::IntegerAdd:
856 TmpVec = Builder.CreateAdd(TmpVec, Shuf, "add.rdx");
858 case LoopVectorizationLegality::IntegerMult:
859 TmpVec = Builder.CreateMul(TmpVec, Shuf, "mul.rdx");
861 case LoopVectorizationLegality::IntegerOr:
862 TmpVec = Builder.CreateOr(TmpVec, Shuf, "or.rdx");
864 case LoopVectorizationLegality::IntegerAnd:
865 TmpVec = Builder.CreateAnd(TmpVec, Shuf, "and.rdx");
867 case LoopVectorizationLegality::IntegerXor:
868 TmpVec = Builder.CreateXor(TmpVec, Shuf, "xor.rdx");
871 llvm_unreachable("Unknown reduction operation");
875 // The result is in the first element of the vector.
876 Value *Scalar0 = Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
878 // Now, we need to fix the users of the reduction variable
879 // inside and outside of the scalar remainder loop.
880 // We know that the loop is in LCSSA form. We need to update the
881 // PHI nodes in the exit blocks.
882 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
883 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
884 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
885 if (!LCSSAPhi) continue;
887 // All PHINodes need to have a single entry edge, or two if
888 // we already fixed them.
889 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
891 // We found our reduction value exit-PHI. Update it with the
892 // incoming bypass edge.
893 if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
894 // Add an edge coming from the bypass.
895 LCSSAPhi->addIncoming(Scalar0, LoopMiddleBlock);
898 }// end of the LCSSA phi scan.
900 // Fix the scalar loop reduction variable with the incoming reduction sum
901 // from the vector body and from the backedge value.
902 int IncomingEdgeBlockIdx =
903 (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
904 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
905 // Pick the other block.
906 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
907 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, Scalar0);
908 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
909 }// end of for each redux variable.
911 // The Loop exit block may have single value PHI nodes where the incoming
912 // value is 'undef'. While vectorizing we only handled real values that
913 // were defined inside the loop. Here we handle the 'undef case'.
915 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
916 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
917 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
918 if (!LCSSAPhi) continue;
919 if (LCSSAPhi->getNumIncomingValues() == 1)
920 LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
925 Value *InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
926 assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
929 Value *SrcMask = createBlockInMask(Src);
931 // The terminator has to be a branch inst!
932 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
933 assert(BI && "Unexpected terminator found");
935 Value *EdgeMask = SrcMask;
936 if (BI->isConditional()) {
937 EdgeMask = getVectorValue(BI->getCondition());
938 if (BI->getSuccessor(0) != Dst)
939 EdgeMask = Builder.CreateNot(EdgeMask);
942 return Builder.CreateAnd(EdgeMask, SrcMask);
945 Value *InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
946 assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
948 // Loop incoming mask is all-one.
949 if (OrigLoop->getHeader() == BB) {
950 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
951 return getVectorValue(C);
954 // This is the block mask. We OR all incoming edges, and with zero.
955 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
956 Value *BlockMask = getVectorValue(Zero);
959 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it)
960 BlockMask = Builder.CreateOr(BlockMask, createEdgeMask(*it, BB));
966 InnerLoopVectorizer::vectorizeBlockInLoop(LoopVectorizationLegality *Legal,
967 BasicBlock *BB, PhiVector *PV) {
968 Constant *Zero = Builder.getInt32(0);
970 // For each instruction in the old loop.
971 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
972 switch (it->getOpcode()) {
973 case Instruction::Br:
974 // Nothing to do for PHIs and BR, since we already took care of the
975 // loop control flow instructions.
977 case Instruction::PHI:{
978 PHINode* P = cast<PHINode>(it);
979 // Handle reduction variables:
980 if (Legal->getReductionVars()->count(P)) {
981 // This is phase one of vectorizing PHIs.
982 Type *VecTy = VectorType::get(it->getType(), VF);
984 PHINode::Create(VecTy, 2, "vec.phi",
985 LoopVectorBody->getFirstInsertionPt());
990 // Check for PHI nodes that are lowered to vector selects.
991 if (P->getParent() != OrigLoop->getHeader()) {
992 // We know that all PHIs in non header blocks are converted into
993 // selects, so we don't have to worry about the insertion order and we
994 // can just use the builder.
996 // At this point we generate the predication tree. There may be
997 // duplications since this is a simple recursive scan, but future
998 // optimizations will clean it up.
999 Value *Cond = createEdgeMask(P->getIncomingBlock(0), P->getParent());
1001 Builder.CreateSelect(Cond,
1002 getVectorValue(P->getIncomingValue(0)),
1003 getVectorValue(P->getIncomingValue(1)),
1008 // This PHINode must be an induction variable.
1009 // Make sure that we know about it.
1010 assert(Legal->getInductionVars()->count(P) &&
1011 "Not an induction variable");
1013 LoopVectorizationLegality::InductionInfo II =
1014 Legal->getInductionVars()->lookup(P);
1017 case LoopVectorizationLegality::NoInduction:
1018 llvm_unreachable("Unknown induction");
1019 case LoopVectorizationLegality::IntInduction: {
1020 assert(P == OldInduction && "Unexpected PHI");
1021 Value *Broadcasted = getBroadcastInstrs(Induction);
1022 // After broadcasting the induction variable we need to make the
1023 // vector consecutive by adding 0, 1, 2 ...
1024 Value *ConsecutiveInduction = getConsecutiveVector(Broadcasted);
1025 WidenMap[OldInduction] = ConsecutiveInduction;
1028 case LoopVectorizationLegality::ReverseIntInduction:
1029 case LoopVectorizationLegality::PtrInduction:
1030 // Handle reverse integer and pointer inductions.
1031 Value *StartIdx = 0;
1032 // If we have a single integer induction variable then use it.
1033 // Otherwise, start counting at zero.
1035 LoopVectorizationLegality::InductionInfo OldII =
1036 Legal->getInductionVars()->lookup(OldInduction);
1037 StartIdx = OldII.StartValue;
1039 StartIdx = ConstantInt::get(Induction->getType(), 0);
1041 // This is the normalized GEP that starts counting at zero.
1042 Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
1045 // Handle the reverse integer induction variable case.
1046 if (LoopVectorizationLegality::ReverseIntInduction == II.IK) {
1047 IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType());
1048 Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy,
1050 Value *ReverseInd = Builder.CreateSub(II.StartValue, CNI,
1053 // This is a new value so do not hoist it out.
1054 Value *Broadcasted = getBroadcastInstrs(ReverseInd);
1055 // After broadcasting the induction variable we need to make the
1056 // vector consecutive by adding ... -3, -2, -1, 0.
1057 Value *ConsecutiveInduction = getConsecutiveVector(Broadcasted,
1059 WidenMap[it] = ConsecutiveInduction;
1063 // Handle the pointer induction variable case.
1064 assert(P->getType()->isPointerTy() && "Unexpected type.");
1066 // This is the vector of results. Notice that we don't generate
1067 // vector geps because scalar geps result in better code.
1068 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
1069 for (unsigned int i = 0; i < VF; ++i) {
1070 Constant *Idx = ConstantInt::get(Induction->getType(), i);
1071 Value *GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx,
1073 Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
1075 VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
1076 Builder.getInt32(i),
1080 WidenMap[it] = VecVal;
1086 case Instruction::Add:
1087 case Instruction::FAdd:
1088 case Instruction::Sub:
1089 case Instruction::FSub:
1090 case Instruction::Mul:
1091 case Instruction::FMul:
1092 case Instruction::UDiv:
1093 case Instruction::SDiv:
1094 case Instruction::FDiv:
1095 case Instruction::URem:
1096 case Instruction::SRem:
1097 case Instruction::FRem:
1098 case Instruction::Shl:
1099 case Instruction::LShr:
1100 case Instruction::AShr:
1101 case Instruction::And:
1102 case Instruction::Or:
1103 case Instruction::Xor: {
1104 // Just widen binops.
1105 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
1106 Value *A = getVectorValue(it->getOperand(0));
1107 Value *B = getVectorValue(it->getOperand(1));
1109 // Use this vector value for all users of the original instruction.
1110 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A, B);
1113 // Update the NSW, NUW and Exact flags.
1114 BinaryOperator *VecOp = cast<BinaryOperator>(V);
1115 if (isa<OverflowingBinaryOperator>(BinOp)) {
1116 VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap());
1117 VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap());
1119 if (isa<PossiblyExactOperator>(VecOp))
1120 VecOp->setIsExact(BinOp->isExact());
1123 case Instruction::Select: {
1125 // If the selector is loop invariant we can create a select
1126 // instruction with a scalar condition. Otherwise, use vector-select.
1127 Value *Cond = it->getOperand(0);
1128 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(Cond), OrigLoop);
1130 // The condition can be loop invariant but still defined inside the
1131 // loop. This means that we can't just use the original 'cond' value.
1132 // We have to take the 'vectorized' value and pick the first lane.
1133 // Instcombine will make this a no-op.
1134 Cond = getVectorValue(Cond);
1136 Cond = Builder.CreateExtractElement(Cond, Builder.getInt32(0));
1138 Value *Op0 = getVectorValue(it->getOperand(1));
1139 Value *Op1 = getVectorValue(it->getOperand(2));
1140 WidenMap[it] = Builder.CreateSelect(Cond, Op0, Op1);
1144 case Instruction::ICmp:
1145 case Instruction::FCmp: {
1146 // Widen compares. Generate vector compares.
1147 bool FCmp = (it->getOpcode() == Instruction::FCmp);
1148 CmpInst *Cmp = dyn_cast<CmpInst>(it);
1149 Value *A = getVectorValue(it->getOperand(0));
1150 Value *B = getVectorValue(it->getOperand(1));
1152 WidenMap[it] = Builder.CreateFCmp(Cmp->getPredicate(), A, B);
1154 WidenMap[it] = Builder.CreateICmp(Cmp->getPredicate(), A, B);
1158 case Instruction::Store: {
1159 // Attempt to issue a wide store.
1160 StoreInst *SI = dyn_cast<StoreInst>(it);
1161 Type *StTy = VectorType::get(SI->getValueOperand()->getType(), VF);
1162 Value *Ptr = SI->getPointerOperand();
1163 unsigned Alignment = SI->getAlignment();
1165 assert(!Legal->isUniform(Ptr) &&
1166 "We do not allow storing to uniform addresses");
1169 int Stride = Legal->isConsecutivePtr(Ptr);
1170 bool Reverse = Stride < 0;
1172 scalarizeInstruction(it);
1176 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1178 // The last index does not have to be the induction. It can be
1179 // consecutive and be a function of the index. For example A[I+1];
1180 unsigned NumOperands = Gep->getNumOperands();
1181 Value *LastIndex = getVectorValue(Gep->getOperand(NumOperands - 1));
1182 LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
1184 // Create the new GEP with the new induction variable.
1185 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1186 Gep2->setOperand(NumOperands - 1, LastIndex);
1187 Ptr = Builder.Insert(Gep2);
1189 // Use the induction element ptr.
1190 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1191 Ptr = Builder.CreateExtractElement(getVectorValue(Ptr), Zero);
1194 // If the address is consecutive but reversed, then the
1195 // wide load needs to start at the last vector element.
1197 Ptr = Builder.CreateGEP(Ptr, Builder.getInt32(1 - VF));
1199 Ptr = Builder.CreateBitCast(Ptr, StTy->getPointerTo());
1200 Value *Val = getVectorValue(SI->getValueOperand());
1202 Val = reverseVector(Val);
1203 Builder.CreateStore(Val, Ptr)->setAlignment(Alignment);
1206 case Instruction::Load: {
1207 // Attempt to issue a wide load.
1208 LoadInst *LI = dyn_cast<LoadInst>(it);
1209 Type *RetTy = VectorType::get(LI->getType(), VF);
1210 Value *Ptr = LI->getPointerOperand();
1211 unsigned Alignment = LI->getAlignment();
1213 // If the pointer is loop invariant or if it is non consecutive,
1214 // scalarize the load.
1215 int Stride = Legal->isConsecutivePtr(Ptr);
1216 bool Reverse = Stride < 0;
1217 if (Legal->isUniform(Ptr) || Stride == 0) {
1218 scalarizeInstruction(it);
1222 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1224 // The last index does not have to be the induction. It can be
1225 // consecutive and be a function of the index. For example A[I+1];
1226 unsigned NumOperands = Gep->getNumOperands();
1227 Value *LastIndex = getVectorValue(Gep->getOperand(NumOperands -1));
1228 LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
1230 // Create the new GEP with the new induction variable.
1231 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1232 Gep2->setOperand(NumOperands - 1, LastIndex);
1233 Ptr = Builder.Insert(Gep2);
1235 // Use the induction element ptr.
1236 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1237 Ptr = Builder.CreateExtractElement(getVectorValue(Ptr), Zero);
1239 // If the address is consecutive but reversed, then the
1240 // wide load needs to start at the last vector element.
1242 Ptr = Builder.CreateGEP(Ptr, Builder.getInt32(1 - VF));
1244 Ptr = Builder.CreateBitCast(Ptr, RetTy->getPointerTo());
1245 LI = Builder.CreateLoad(Ptr);
1246 LI->setAlignment(Alignment);
1248 // Use this vector value for all users of the load.
1249 WidenMap[it] = Reverse ? reverseVector(LI) : LI;
1252 case Instruction::ZExt:
1253 case Instruction::SExt:
1254 case Instruction::FPToUI:
1255 case Instruction::FPToSI:
1256 case Instruction::FPExt:
1257 case Instruction::PtrToInt:
1258 case Instruction::IntToPtr:
1259 case Instruction::SIToFP:
1260 case Instruction::UIToFP:
1261 case Instruction::Trunc:
1262 case Instruction::FPTrunc:
1263 case Instruction::BitCast: {
1264 CastInst *CI = dyn_cast<CastInst>(it);
1265 /// Optimize the special case where the source is the induction
1266 /// variable. Notice that we can only optimize the 'trunc' case
1267 /// because: a. FP conversions lose precision, b. sext/zext may wrap,
1268 /// c. other casts depend on pointer size.
1269 if (CI->getOperand(0) == OldInduction &&
1270 it->getOpcode() == Instruction::Trunc) {
1271 Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
1273 Value *Broadcasted = getBroadcastInstrs(ScalarCast);
1274 WidenMap[it] = getConsecutiveVector(Broadcasted);
1277 /// Vectorize casts.
1278 Value *A = getVectorValue(it->getOperand(0));
1279 Type *DestTy = VectorType::get(CI->getType()->getScalarType(), VF);
1280 WidenMap[it] = Builder.CreateCast(CI->getOpcode(), A, DestTy);
1284 case Instruction::Call: {
1285 assert(isTriviallyVectorizableIntrinsic(it));
1286 Module *M = BB->getParent()->getParent();
1287 IntrinsicInst *II = cast<IntrinsicInst>(it);
1288 Intrinsic::ID ID = II->getIntrinsicID();
1289 SmallVector<Value*, 4> Args;
1290 for (unsigned i = 0, ie = II->getNumArgOperands(); i != ie; ++i)
1291 Args.push_back(getVectorValue(II->getArgOperand(i)));
1292 Type *Tys[] = { VectorType::get(II->getType()->getScalarType(), VF) };
1293 Function *F = Intrinsic::getDeclaration(M, ID, Tys);
1294 WidenMap[it] = Builder.CreateCall(F, Args);
1299 // All other instructions are unsupported. Scalarize them.
1300 scalarizeInstruction(it);
1303 }// end of for_each instr.
1306 void InnerLoopVectorizer::updateAnalysis() {
1307 // Forget the original basic block.
1308 SE->forgetLoop(OrigLoop);
1310 // Update the dominator tree information.
1311 assert(DT->properlyDominates(LoopBypassBlock, LoopExitBlock) &&
1312 "Entry does not dominate exit.");
1314 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlock);
1315 DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader);
1316 DT->addNewBlock(LoopMiddleBlock, LoopBypassBlock);
1317 DT->addNewBlock(LoopScalarPreHeader, LoopMiddleBlock);
1318 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
1319 DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
1321 DEBUG(DT->verifyAnalysis());
1324 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
1325 if (!EnableIfConversion)
1328 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
1329 std::vector<BasicBlock*> &LoopBlocks = TheLoop->getBlocksVector();
1331 // Collect the blocks that need predication.
1332 for (unsigned i = 0, e = LoopBlocks.size(); i < e; ++i) {
1333 BasicBlock *BB = LoopBlocks[i];
1335 // We don't support switch statements inside loops.
1336 if (!isa<BranchInst>(BB->getTerminator()))
1339 // We must have at most two predecessors because we need to convert
1340 // all PHIs to selects.
1341 unsigned Preds = std::distance(pred_begin(BB), pred_end(BB));
1345 // We must be able to predicate all blocks that need to be predicated.
1346 if (blockNeedsPredication(BB) && !blockCanBePredicated(BB))
1350 // We can if-convert this loop.
1354 bool LoopVectorizationLegality::canVectorize() {
1355 assert(TheLoop->getLoopPreheader() && "No preheader!!");
1357 // We can only vectorize innermost loops.
1358 if (TheLoop->getSubLoopsVector().size())
1361 // We must have a single backedge.
1362 if (TheLoop->getNumBackEdges() != 1)
1365 // We must have a single exiting block.
1366 if (!TheLoop->getExitingBlock())
1369 unsigned NumBlocks = TheLoop->getNumBlocks();
1371 // Check if we can if-convert non single-bb loops.
1372 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
1373 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
1377 // We need to have a loop header.
1378 BasicBlock *Latch = TheLoop->getLoopLatch();
1379 DEBUG(dbgs() << "LV: Found a loop: " <<
1380 TheLoop->getHeader()->getName() << "\n");
1382 // ScalarEvolution needs to be able to find the exit count.
1383 const SCEV *ExitCount = SE->getExitCount(TheLoop, Latch);
1384 if (ExitCount == SE->getCouldNotCompute()) {
1385 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
1389 // Do not loop-vectorize loops with a tiny trip count.
1390 unsigned TC = SE->getSmallConstantTripCount(TheLoop, Latch);
1391 if (TC > 0u && TC < TinyTripCountThreshold) {
1392 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " <<
1393 "This loop is not worth vectorizing.\n");
1397 // Check if we can vectorize the instructions and CFG in this loop.
1398 if (!canVectorizeInstrs()) {
1399 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
1403 // Go over each instruction and look at memory deps.
1404 if (!canVectorizeMemory()) {
1405 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
1409 // Collect all of the variables that remain uniform after vectorization.
1410 collectLoopUniforms();
1412 DEBUG(dbgs() << "LV: We can vectorize this loop" <<
1413 (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
1416 // Okay! We can vectorize. At this point we don't have any other mem analysis
1417 // which may limit our maximum vectorization factor, so just return true with
1422 bool LoopVectorizationLegality::canVectorizeInstrs() {
1423 BasicBlock *PreHeader = TheLoop->getLoopPreheader();
1424 BasicBlock *Header = TheLoop->getHeader();
1426 // For each block in the loop.
1427 for (Loop::block_iterator bb = TheLoop->block_begin(),
1428 be = TheLoop->block_end(); bb != be; ++bb) {
1430 // Scan the instructions in the block and look for hazards.
1431 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
1434 if (PHINode *Phi = dyn_cast<PHINode>(it)) {
1435 // This should not happen because the loop should be normalized.
1436 if (Phi->getNumIncomingValues() != 2) {
1437 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
1441 // Check that this PHI type is allowed.
1442 if (!Phi->getType()->isIntegerTy() &&
1443 !Phi->getType()->isPointerTy()) {
1444 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
1448 // If this PHINode is not in the header block, then we know that we
1449 // can convert it to select during if-conversion. No need to check if
1450 // the PHIs in this block are induction or reduction variables.
1454 // This is the value coming from the preheader.
1455 Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
1456 // Check if this is an induction variable.
1457 InductionKind IK = isInductionVariable(Phi);
1459 if (NoInduction != IK) {
1460 // Int inductions are special because we only allow one IV.
1461 if (IK == IntInduction) {
1463 DEBUG(dbgs() << "LV: Found too many inductions."<< *Phi <<"\n");
1469 DEBUG(dbgs() << "LV: Found an induction variable.\n");
1470 Inductions[Phi] = InductionInfo(StartValue, IK);
1474 if (AddReductionVar(Phi, IntegerAdd)) {
1475 DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
1478 if (AddReductionVar(Phi, IntegerMult)) {
1479 DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
1482 if (AddReductionVar(Phi, IntegerOr)) {
1483 DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
1486 if (AddReductionVar(Phi, IntegerAnd)) {
1487 DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
1490 if (AddReductionVar(Phi, IntegerXor)) {
1491 DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
1495 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
1497 }// end of PHI handling
1499 // We still don't handle functions.
1500 CallInst *CI = dyn_cast<CallInst>(it);
1501 if (CI && !isTriviallyVectorizableIntrinsic(it)) {
1502 DEBUG(dbgs() << "LV: Found a call site.\n");
1506 // Check that the instruction return type is vectorizable.
1507 if (!VectorType::isValidElementType(it->getType()) &&
1508 !it->getType()->isVoidTy()) {
1509 DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n");
1513 // Check that the stored type is vectorizable.
1514 if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
1515 Type *T = ST->getValueOperand()->getType();
1516 if (!VectorType::isValidElementType(T))
1520 // Reduction instructions are allowed to have exit users.
1521 // All other instructions must not have external users.
1522 if (!AllowedExit.count(it))
1523 //Check that all of the users of the loop are inside the BB.
1524 for (Value::use_iterator I = it->use_begin(), E = it->use_end();
1526 Instruction *U = cast<Instruction>(*I);
1527 // This user may be a reduction exit value.
1528 if (!TheLoop->contains(U)) {
1529 DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n");
1538 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
1539 assert(getInductionVars()->size() && "No induction variables");
1545 void LoopVectorizationLegality::collectLoopUniforms() {
1546 // We now know that the loop is vectorizable!
1547 // Collect variables that will remain uniform after vectorization.
1548 std::vector<Value*> Worklist;
1549 BasicBlock *Latch = TheLoop->getLoopLatch();
1551 // Start with the conditional branch and walk up the block.
1552 Worklist.push_back(Latch->getTerminator()->getOperand(0));
1554 while (Worklist.size()) {
1555 Instruction *I = dyn_cast<Instruction>(Worklist.back());
1556 Worklist.pop_back();
1558 // Look at instructions inside this loop.
1559 // Stop when reaching PHI nodes.
1560 // TODO: we need to follow values all over the loop, not only in this block.
1561 if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
1564 // This is a known uniform.
1567 // Insert all operands.
1568 for (int i = 0, Op = I->getNumOperands(); i < Op; ++i) {
1569 Worklist.push_back(I->getOperand(i));
1574 bool LoopVectorizationLegality::canVectorizeMemory() {
1575 typedef SmallVector<Value*, 16> ValueVector;
1576 typedef SmallPtrSet<Value*, 16> ValueSet;
1577 // Holds the Load and Store *instructions*.
1580 PtrRtCheck.Pointers.clear();
1581 PtrRtCheck.Need = false;
1584 for (Loop::block_iterator bb = TheLoop->block_begin(),
1585 be = TheLoop->block_end(); bb != be; ++bb) {
1587 // Scan the BB and collect legal loads and stores.
1588 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
1591 // If this is a load, save it. If this instruction can read from memory
1592 // but is not a load, then we quit. Notice that we don't handle function
1593 // calls that read or write.
1594 if (it->mayReadFromMemory()) {
1595 LoadInst *Ld = dyn_cast<LoadInst>(it);
1596 if (!Ld) return false;
1597 if (!Ld->isSimple()) {
1598 DEBUG(dbgs() << "LV: Found a non-simple load.\n");
1601 Loads.push_back(Ld);
1605 // Save 'store' instructions. Abort if other instructions write to memory.
1606 if (it->mayWriteToMemory()) {
1607 StoreInst *St = dyn_cast<StoreInst>(it);
1608 if (!St) return false;
1609 if (!St->isSimple()) {
1610 DEBUG(dbgs() << "LV: Found a non-simple store.\n");
1613 Stores.push_back(St);
1618 // Now we have two lists that hold the loads and the stores.
1619 // Next, we find the pointers that they use.
1621 // Check if we see any stores. If there are no stores, then we don't
1622 // care if the pointers are *restrict*.
1623 if (!Stores.size()) {
1624 DEBUG(dbgs() << "LV: Found a read-only loop!\n");
1628 // Holds the read and read-write *pointers* that we find.
1630 ValueVector ReadWrites;
1632 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
1633 // multiple times on the same object. If the ptr is accessed twice, once
1634 // for read and once for write, it will only appear once (on the write
1635 // list). This is okay, since we are going to check for conflicts between
1636 // writes and between reads and writes, but not between reads and reads.
1639 ValueVector::iterator I, IE;
1640 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
1641 StoreInst *ST = cast<StoreInst>(*I);
1642 Value* Ptr = ST->getPointerOperand();
1644 if (isUniform(Ptr)) {
1645 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
1649 // If we did *not* see this pointer before, insert it to
1650 // the read-write list. At this phase it is only a 'write' list.
1651 if (Seen.insert(Ptr))
1652 ReadWrites.push_back(Ptr);
1655 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
1656 LoadInst *LD = cast<LoadInst>(*I);
1657 Value* Ptr = LD->getPointerOperand();
1658 // If we did *not* see this pointer before, insert it to the
1659 // read list. If we *did* see it before, then it is already in
1660 // the read-write list. This allows us to vectorize expressions
1661 // such as A[i] += x; Because the address of A[i] is a read-write
1662 // pointer. This only works if the index of A[i] is consecutive.
1663 // If the address of i is unknown (for example A[B[i]]) then we may
1664 // read a few words, modify, and write a few words, and some of the
1665 // words may be written to the same address.
1666 if (Seen.insert(Ptr) || 0 == isConsecutivePtr(Ptr))
1667 Reads.push_back(Ptr);
1670 // If we write (or read-write) to a single destination and there are no
1671 // other reads in this loop then is it safe to vectorize.
1672 if (ReadWrites.size() == 1 && Reads.size() == 0) {
1673 DEBUG(dbgs() << "LV: Found a write-only loop!\n");
1677 // Find pointers with computable bounds. We are going to use this information
1678 // to place a runtime bound check.
1679 bool CanDoRT = true;
1680 for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I)
1681 if (hasComputableBounds(*I)) {
1682 PtrRtCheck.insert(SE, TheLoop, *I);
1683 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n");
1688 for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I)
1689 if (hasComputableBounds(*I)) {
1690 PtrRtCheck.insert(SE, TheLoop, *I);
1691 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n");
1697 // Check that we did not collect too many pointers or found a
1698 // unsizeable pointer.
1699 if (!CanDoRT || PtrRtCheck.Pointers.size() > RuntimeMemoryCheckThreshold) {
1705 DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
1708 bool NeedRTCheck = false;
1710 // Now that the pointers are in two lists (Reads and ReadWrites), we
1711 // can check that there are no conflicts between each of the writes and
1712 // between the writes to the reads.
1713 ValueSet WriteObjects;
1714 ValueVector TempObjects;
1716 // Check that the read-writes do not conflict with other read-write
1718 bool AllWritesIdentified = true;
1719 for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I) {
1720 GetUnderlyingObjects(*I, TempObjects, DL);
1721 for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
1723 if (!isIdentifiedObject(*it)) {
1724 DEBUG(dbgs() << "LV: Found an unidentified write ptr:"<< **it <<"\n");
1726 AllWritesIdentified = false;
1728 if (!WriteObjects.insert(*it)) {
1729 DEBUG(dbgs() << "LV: Found a possible write-write reorder:"
1734 TempObjects.clear();
1737 /// Check that the reads don't conflict with the read-writes.
1738 for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I) {
1739 GetUnderlyingObjects(*I, TempObjects, DL);
1740 for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
1742 // If all of the writes are identified then we don't care if the read
1743 // pointer is identified or not.
1744 if (!AllWritesIdentified && !isIdentifiedObject(*it)) {
1745 DEBUG(dbgs() << "LV: Found an unidentified read ptr:"<< **it <<"\n");
1748 if (WriteObjects.count(*it)) {
1749 DEBUG(dbgs() << "LV: Found a possible read/write reorder:"
1754 TempObjects.clear();
1757 PtrRtCheck.Need = NeedRTCheck;
1758 if (NeedRTCheck && !CanDoRT) {
1759 DEBUG(dbgs() << "LV: We can't vectorize because we can't find " <<
1760 "the array bounds.\n");
1765 DEBUG(dbgs() << "LV: We "<< (NeedRTCheck ? "" : "don't") <<
1766 " need a runtime memory check.\n");
1770 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
1771 ReductionKind Kind) {
1772 if (Phi->getNumIncomingValues() != 2)
1775 // Reduction variables are only found in the loop header block.
1776 if (Phi->getParent() != TheLoop->getHeader())
1779 // Obtain the reduction start value from the value that comes from the loop
1781 Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
1783 // ExitInstruction is the single value which is used outside the loop.
1784 // We only allow for a single reduction value to be used outside the loop.
1785 // This includes users of the reduction, variables (which form a cycle
1786 // which ends in the phi node).
1787 Instruction *ExitInstruction = 0;
1789 // Iter is our iterator. We start with the PHI node and scan for all of the
1790 // users of this instruction. All users must be instructions that can be
1791 // used as reduction variables (such as ADD). We may have a single
1792 // out-of-block user. The cycle must end with the original PHI.
1793 Instruction *Iter = Phi;
1795 // If the instruction has no users then this is a broken
1796 // chain and can't be a reduction variable.
1797 if (Iter->use_empty())
1800 // Any reduction instr must be of one of the allowed kinds.
1801 if (!isReductionInstr(Iter, Kind))
1804 // Did we find a user inside this loop already ?
1805 bool FoundInBlockUser = false;
1806 // Did we reach the initial PHI node already ?
1807 bool FoundStartPHI = false;
1809 // For each of the *users* of iter.
1810 for (Value::use_iterator it = Iter->use_begin(), e = Iter->use_end();
1812 Instruction *U = cast<Instruction>(*it);
1813 // We already know that the PHI is a user.
1815 FoundStartPHI = true;
1819 // Check if we found the exit user.
1820 BasicBlock *Parent = U->getParent();
1821 if (!TheLoop->contains(Parent)) {
1822 // Exit if you find multiple outside users.
1823 if (ExitInstruction != 0)
1825 ExitInstruction = Iter;
1828 // We allow in-loop PHINodes which are not the original reduction PHI
1829 // node. If this PHI is the only user of Iter (happens in IF w/ no ELSE
1830 // structure) then don't skip this PHI.
1831 if (isa<PHINode>(Iter) && isa<PHINode>(U) &&
1832 U->getParent() != TheLoop->getHeader() &&
1833 TheLoop->contains(U) &&
1834 Iter->getNumUses() > 1)
1837 // We can't have multiple inside users.
1838 if (FoundInBlockUser)
1840 FoundInBlockUser = true;
1844 // We found a reduction var if we have reached the original
1845 // phi node and we only have a single instruction with out-of-loop
1847 if (FoundStartPHI && ExitInstruction) {
1848 // This instruction is allowed to have out-of-loop users.
1849 AllowedExit.insert(ExitInstruction);
1851 // Save the description of this reduction variable.
1852 ReductionDescriptor RD(RdxStart, ExitInstruction, Kind);
1853 Reductions[Phi] = RD;
1857 // If we've reached the start PHI but did not find an outside user then
1858 // this is dead code. Abort.
1865 LoopVectorizationLegality::isReductionInstr(Instruction *I,
1866 ReductionKind Kind) {
1867 switch (I->getOpcode()) {
1870 case Instruction::PHI:
1873 case Instruction::Add:
1874 case Instruction::Sub:
1875 return Kind == IntegerAdd;
1876 case Instruction::Mul:
1877 return Kind == IntegerMult;
1878 case Instruction::And:
1879 return Kind == IntegerAnd;
1880 case Instruction::Or:
1881 return Kind == IntegerOr;
1882 case Instruction::Xor:
1883 return Kind == IntegerXor;
1887 LoopVectorizationLegality::InductionKind
1888 LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
1889 Type *PhiTy = Phi->getType();
1890 // We only handle integer and pointer inductions variables.
1891 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
1894 // Check that the PHI is consecutive and starts at zero.
1895 const SCEV *PhiScev = SE->getSCEV(Phi);
1896 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
1898 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
1901 const SCEV *Step = AR->getStepRecurrence(*SE);
1903 // Integer inductions need to have a stride of one.
1904 if (PhiTy->isIntegerTy()) {
1906 return IntInduction;
1907 if (Step->isAllOnesValue())
1908 return ReverseIntInduction;
1912 // Calculate the pointer stride and check if it is consecutive.
1913 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
1917 assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
1918 uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType());
1919 if (C->getValue()->equalsInt(Size))
1920 return PtrInduction;
1925 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
1926 Value *In0 = const_cast<Value*>(V);
1927 PHINode *PN = dyn_cast_or_null<PHINode>(In0);
1931 return Inductions.count(PN);
1934 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
1935 assert(TheLoop->contains(BB) && "Unknown block used");
1937 // Blocks that do not dominate the latch need predication.
1938 BasicBlock* Latch = TheLoop->getLoopLatch();
1939 return !DT->dominates(BB, Latch);
1942 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB) {
1943 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1944 // We don't predicate loads/stores at the moment.
1945 if (it->mayReadFromMemory() || it->mayWriteToMemory() || it->mayThrow())
1948 // The instructions below can trap.
1949 switch (it->getOpcode()) {
1951 case Instruction::UDiv:
1952 case Instruction::SDiv:
1953 case Instruction::URem:
1954 case Instruction::SRem:
1962 bool LoopVectorizationLegality::hasComputableBounds(Value *Ptr) {
1963 const SCEV *PhiScev = SE->getSCEV(Ptr);
1964 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
1968 return AR->isAffine();
1972 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize,
1974 if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
1975 DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
1979 // Find the trip count.
1980 unsigned TC = SE->getSmallConstantTripCount(TheLoop, TheLoop->getLoopLatch());
1981 DEBUG(dbgs() << "LV: Found trip count:"<<TC<<"\n");
1983 unsigned VF = MaxVectorSize;
1985 // If we optimize the program for size, avoid creating the tail loop.
1987 // If we are unable to calculate the trip count then don't try to vectorize.
1989 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
1993 // Find the maximum SIMD width that can fit within the trip count.
1994 VF = TC % MaxVectorSize;
1999 // If the trip count that we found modulo the vectorization factor is not
2000 // zero then we require a tail.
2002 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
2008 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
2009 DEBUG(dbgs() << "LV: Using user VF "<<UserVF<<".\n");
2015 DEBUG(dbgs() << "LV: No vector target information. Not vectorizing. \n");
2019 float Cost = expectedCost(1);
2021 DEBUG(dbgs() << "LV: Scalar loop costs: "<< (int)Cost << ".\n");
2022 for (unsigned i=2; i <= VF; i*=2) {
2023 // Notice that the vector loop needs to be executed less times, so
2024 // we need to divide the cost of the vector loops by the width of
2025 // the vector elements.
2026 float VectorCost = expectedCost(i) / (float)i;
2027 DEBUG(dbgs() << "LV: Vector loop of width "<< i << " costs: " <<
2028 (int)VectorCost << ".\n");
2029 if (VectorCost < Cost) {
2035 DEBUG(dbgs() << "LV: Selecting VF = : "<< Width << ".\n");
2039 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
2043 for (Loop::block_iterator bb = TheLoop->block_begin(),
2044 be = TheLoop->block_end(); bb != be; ++bb) {
2045 unsigned BlockCost = 0;
2046 BasicBlock *BB = *bb;
2048 // For each instruction in the old loop.
2049 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2050 unsigned C = getInstructionCost(it, VF);
2052 DEBUG(dbgs() << "LV: Found an estimated cost of "<< C <<" for VF " <<
2053 VF << " For instruction: "<< *it << "\n");
2056 // We assume that if-converted blocks have a 50% chance of being executed.
2057 // When the code is scalar then some of the blocks are avoided due to CF.
2058 // When the code is vectorized we execute all code paths.
2059 if (Legal->blockNeedsPredication(*bb) && VF == 1)
2069 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
2070 assert(VTTI && "Invalid vector target transformation info");
2072 // If we know that this instruction will remain uniform, check the cost of
2073 // the scalar version.
2074 if (Legal->isUniformAfterVectorization(I))
2077 Type *RetTy = I->getType();
2078 Type *VectorTy = ToVectorTy(RetTy, VF);
2080 // TODO: We need to estimate the cost of intrinsic calls.
2081 switch (I->getOpcode()) {
2082 case Instruction::GetElementPtr:
2083 // We mark this instruction as zero-cost because scalar GEPs are usually
2084 // lowered to the intruction addressing mode. At the moment we don't
2085 // generate vector geps.
2087 case Instruction::Br: {
2088 return VTTI->getCFInstrCost(I->getOpcode());
2090 case Instruction::PHI:
2091 //TODO: IF-converted IFs become selects.
2093 case Instruction::Add:
2094 case Instruction::FAdd:
2095 case Instruction::Sub:
2096 case Instruction::FSub:
2097 case Instruction::Mul:
2098 case Instruction::FMul:
2099 case Instruction::UDiv:
2100 case Instruction::SDiv:
2101 case Instruction::FDiv:
2102 case Instruction::URem:
2103 case Instruction::SRem:
2104 case Instruction::FRem:
2105 case Instruction::Shl:
2106 case Instruction::LShr:
2107 case Instruction::AShr:
2108 case Instruction::And:
2109 case Instruction::Or:
2110 case Instruction::Xor:
2111 return VTTI->getArithmeticInstrCost(I->getOpcode(), VectorTy);
2112 case Instruction::Select: {
2113 SelectInst *SI = cast<SelectInst>(I);
2114 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
2115 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
2116 Type *CondTy = SI->getCondition()->getType();
2118 CondTy = VectorType::get(CondTy, VF);
2120 return VTTI->getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
2122 case Instruction::ICmp:
2123 case Instruction::FCmp: {
2124 Type *ValTy = I->getOperand(0)->getType();
2125 VectorTy = ToVectorTy(ValTy, VF);
2126 return VTTI->getCmpSelInstrCost(I->getOpcode(), VectorTy);
2128 case Instruction::Store: {
2129 StoreInst *SI = cast<StoreInst>(I);
2130 Type *ValTy = SI->getValueOperand()->getType();
2131 VectorTy = ToVectorTy(ValTy, VF);
2134 return VTTI->getMemoryOpCost(I->getOpcode(), VectorTy,
2136 SI->getPointerAddressSpace());
2138 // Scalarized stores.
2139 int Stride = Legal->isConsecutivePtr(SI->getPointerOperand());
2140 bool Reverse = Stride < 0;
2144 // The cost of extracting from the value vector and pointer vector.
2145 Type *PtrTy = ToVectorTy(I->getOperand(0)->getType(), VF);
2146 for (unsigned i = 0; i < VF; ++i) {
2147 Cost += VTTI->getVectorInstrCost(Instruction::ExtractElement,
2149 Cost += VTTI->getVectorInstrCost(Instruction::ExtractElement,
2153 // The cost of the scalar stores.
2154 Cost += VF * VTTI->getMemoryOpCost(I->getOpcode(),
2155 ValTy->getScalarType(),
2157 SI->getPointerAddressSpace());
2162 unsigned Cost = VTTI->getMemoryOpCost(I->getOpcode(), VectorTy,
2164 SI->getPointerAddressSpace());
2166 Cost += VTTI->getShuffleCost(VectorTargetTransformInfo::Reverse,
2170 case Instruction::Load: {
2171 LoadInst *LI = cast<LoadInst>(I);
2174 return VTTI->getMemoryOpCost(I->getOpcode(), VectorTy,
2176 LI->getPointerAddressSpace());
2178 // Scalarized loads.
2179 int Stride = Legal->isConsecutivePtr(LI->getPointerOperand());
2180 bool Reverse = Stride < 0;
2183 Type *PtrTy = ToVectorTy(I->getOperand(0)->getType(), VF);
2185 // The cost of extracting from the pointer vector.
2186 for (unsigned i = 0; i < VF; ++i)
2187 Cost += VTTI->getVectorInstrCost(Instruction::ExtractElement,
2190 // The cost of inserting data to the result vector.
2191 for (unsigned i = 0; i < VF; ++i)
2192 Cost += VTTI->getVectorInstrCost(Instruction::InsertElement,
2195 // The cost of the scalar stores.
2196 Cost += VF * VTTI->getMemoryOpCost(I->getOpcode(),
2197 RetTy->getScalarType(),
2199 LI->getPointerAddressSpace());
2204 unsigned Cost = VTTI->getMemoryOpCost(I->getOpcode(), VectorTy,
2206 LI->getPointerAddressSpace());
2208 Cost += VTTI->getShuffleCost(VectorTargetTransformInfo::Reverse,
2212 case Instruction::ZExt:
2213 case Instruction::SExt:
2214 case Instruction::FPToUI:
2215 case Instruction::FPToSI:
2216 case Instruction::FPExt:
2217 case Instruction::PtrToInt:
2218 case Instruction::IntToPtr:
2219 case Instruction::SIToFP:
2220 case Instruction::UIToFP:
2221 case Instruction::Trunc:
2222 case Instruction::FPTrunc:
2223 case Instruction::BitCast: {
2224 // We optimize the truncation of induction variable.
2225 // The cost of these is the same as the scalar operation.
2226 if (I->getOpcode() == Instruction::Trunc &&
2227 Legal->isInductionVariable(I->getOperand(0)))
2228 return VTTI->getCastInstrCost(I->getOpcode(), I->getType(),
2229 I->getOperand(0)->getType());
2231 Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
2232 return VTTI->getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
2234 case Instruction::Call: {
2235 assert(isTriviallyVectorizableIntrinsic(I));
2236 IntrinsicInst *II = cast<IntrinsicInst>(I);
2237 Type *RetTy = ToVectorTy(II->getType(), VF);
2238 SmallVector<Type*, 4> Tys;
2239 for (unsigned i = 0, ie = II->getNumArgOperands(); i != ie; ++i)
2240 Tys.push_back(ToVectorTy(II->getArgOperand(i)->getType(), VF));
2241 return VTTI->getIntrinsicInstrCost(II->getIntrinsicID(), RetTy, Tys);
2244 // We are scalarizing the instruction. Return the cost of the scalar
2245 // instruction, plus the cost of insert and extract into vector
2246 // elements, times the vector width.
2249 if (!RetTy->isVoidTy() && VF != 1) {
2250 unsigned InsCost = VTTI->getVectorInstrCost(Instruction::InsertElement,
2252 unsigned ExtCost = VTTI->getVectorInstrCost(Instruction::ExtractElement,
2255 // The cost of inserting the results plus extracting each one of the
2257 Cost += VF * (InsCost + ExtCost * I->getNumOperands());
2260 // The cost of executing VF copies of the scalar instruction. This opcode
2261 // is unknown. Assume that it is the same as 'mul'.
2262 Cost += VF * VTTI->getArithmeticInstrCost(Instruction::Mul, VectorTy);
2268 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
2269 if (Scalar->isVoidTy() || VF == 1)
2271 return VectorType::get(Scalar, VF);
2274 char LoopVectorize::ID = 0;
2275 static const char lv_name[] = "Loop Vectorization";
2276 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
2277 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
2278 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
2279 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
2280 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
2283 Pass *createLoopVectorizePass() {
2284 return new LoopVectorize();