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/ScalarEvolutionExpander.h"
19 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
20 #include "llvm/Analysis/ValueTracking.h"
21 #include "llvm/Analysis/Verifier.h"
22 #include "llvm/Constants.h"
23 #include "llvm/DataLayout.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Function.h"
26 #include "llvm/Instructions.h"
27 #include "llvm/IntrinsicInst.h"
28 #include "llvm/LLVMContext.h"
29 #include "llvm/Module.h"
30 #include "llvm/Pass.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/TargetTransformInfo.h"
35 #include "llvm/Transforms/Scalar.h"
36 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
37 #include "llvm/Transforms/Utils/Local.h"
38 #include "llvm/Transforms/Vectorize.h"
39 #include "llvm/Type.h"
40 #include "llvm/Value.h"
42 static cl::opt<unsigned>
43 VectorizationFactor("force-vector-width", cl::init(0), cl::Hidden,
44 cl::desc("Sets the SIMD width. Zero is autoselect."));
47 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
48 cl::desc("Enable if-conversion during vectorization."));
52 /// The LoopVectorize Pass.
53 struct LoopVectorize : public LoopPass {
54 /// Pass identification, replacement for typeid
57 explicit LoopVectorize() : LoopPass(ID) {
58 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
64 TargetTransformInfo *TTI;
67 virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
68 // We only vectorize innermost loops.
72 SE = &getAnalysis<ScalarEvolution>();
73 DL = getAnalysisIfAvailable<DataLayout>();
74 LI = &getAnalysis<LoopInfo>();
75 TTI = getAnalysisIfAvailable<TargetTransformInfo>();
76 DT = &getAnalysis<DominatorTree>();
78 DEBUG(dbgs() << "LV: Checking a loop in \"" <<
79 L->getHeader()->getParent()->getName() << "\"\n");
81 // Check if it is legal to vectorize the loop.
82 LoopVectorizationLegality LVL(L, SE, DL, DT);
83 if (!LVL.canVectorize()) {
84 DEBUG(dbgs() << "LV: Not vectorizing.\n");
88 // Select the preffered vectorization factor.
89 const VectorTargetTransformInfo *VTTI = 0;
91 VTTI = TTI->getVectorTargetTransformInfo();
92 // Use the cost model.
93 LoopVectorizationCostModel CM(L, SE, &LVL, VTTI);
95 // Check the function attribues to find out if this function should be
96 // optimized for size.
97 Function *F = L->getHeader()->getParent();
99 F->getFnAttributes().hasAttribute(Attributes::OptimizeForSize);
101 unsigned VF = CM.selectVectorizationFactor(OptForSize,
102 VectorizationFactor);
105 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
109 DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< VF << ") in "<<
110 L->getHeader()->getParent()->getParent()->getModuleIdentifier()<<
113 // If we decided that it is *legal* to vectorizer the loop then do it.
114 InnerLoopVectorizer LB(L, SE, LI, DT, DL, VF);
117 DEBUG(verifyFunction(*L->getHeader()->getParent()));
121 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
122 LoopPass::getAnalysisUsage(AU);
123 AU.addRequiredID(LoopSimplifyID);
124 AU.addRequiredID(LCSSAID);
125 AU.addRequired<LoopInfo>();
126 AU.addRequired<ScalarEvolution>();
127 AU.addRequired<DominatorTree>();
128 AU.addPreserved<LoopInfo>();
129 AU.addPreserved<DominatorTree>();
136 //===----------------------------------------------------------------------===//
137 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
138 // LoopVectorizationCostModel.
139 //===----------------------------------------------------------------------===//
142 LoopVectorizationLegality::RuntimePointerCheck::insert(ScalarEvolution *SE,
143 Loop *Lp, Value *Ptr) {
144 const SCEV *Sc = SE->getSCEV(Ptr);
145 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
146 assert(AR && "Invalid addrec expression");
147 const SCEV *Ex = SE->getExitCount(Lp, Lp->getLoopLatch());
148 const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
149 Pointers.push_back(Ptr);
150 Starts.push_back(AR->getStart());
151 Ends.push_back(ScEnd);
154 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
156 LLVMContext &C = V->getContext();
157 Type *VTy = VectorType::get(V->getType(), VF);
158 Type *I32 = IntegerType::getInt32Ty(C);
160 // Save the current insertion location.
161 Instruction *Loc = Builder.GetInsertPoint();
163 // We need to place the broadcast of invariant variables outside the loop.
164 Instruction *Instr = dyn_cast<Instruction>(V);
165 bool NewInstr = (Instr && Instr->getParent() == LoopVectorBody);
166 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
168 // Place the code for broadcasting invariant variables in the new preheader.
170 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
172 Constant *Zero = ConstantInt::get(I32, 0);
173 Value *Zeros = ConstantAggregateZero::get(VectorType::get(I32, VF));
174 Value *UndefVal = UndefValue::get(VTy);
175 // Insert the value into a new vector.
176 Value *SingleElem = Builder.CreateInsertElement(UndefVal, V, Zero);
177 // Broadcast the scalar into all locations in the vector.
178 Value *Shuf = Builder.CreateShuffleVector(SingleElem, UndefVal, Zeros,
181 // Restore the builder insertion point.
183 Builder.SetInsertPoint(Loc);
188 Value *InnerLoopVectorizer::getConsecutiveVector(Value* Val, bool Negate) {
189 assert(Val->getType()->isVectorTy() && "Must be a vector");
190 assert(Val->getType()->getScalarType()->isIntegerTy() &&
191 "Elem must be an integer");
193 Type *ITy = Val->getType()->getScalarType();
194 VectorType *Ty = cast<VectorType>(Val->getType());
195 int VLen = Ty->getNumElements();
196 SmallVector<Constant*, 8> Indices;
198 // Create a vector of consecutive numbers from zero to VF.
199 for (int i = 0; i < VLen; ++i)
200 Indices.push_back(ConstantInt::get(ITy, Negate ? (-i): i ));
202 // Add the consecutive indices to the vector value.
203 Constant *Cv = ConstantVector::get(Indices);
204 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
205 return Builder.CreateAdd(Val, Cv, "induction");
208 bool LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
209 assert(Ptr->getType()->isPointerTy() && "Unexpected non ptr");
211 // If this value is a pointer induction variable we know it is consecutive.
212 PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
213 if (Phi && Inductions.count(Phi)) {
214 InductionInfo II = Inductions[Phi];
215 if (PtrInduction == II.IK)
219 GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
223 unsigned NumOperands = Gep->getNumOperands();
224 Value *LastIndex = Gep->getOperand(NumOperands - 1);
226 // Check that all of the gep indices are uniform except for the last.
227 for (unsigned i = 0; i < NumOperands - 1; ++i)
228 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
231 // We can emit wide load/stores only if the last index is the induction
233 const SCEV *Last = SE->getSCEV(LastIndex);
234 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
235 const SCEV *Step = AR->getStepRecurrence(*SE);
237 // The memory is consecutive because the last index is consecutive
238 // and all other indices are loop invariant.
246 bool LoopVectorizationLegality::isUniform(Value *V) {
247 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
250 Value *InnerLoopVectorizer::getVectorValue(Value *V) {
251 assert(V != Induction && "The new induction variable should not be used.");
252 assert(!V->getType()->isVectorTy() && "Can't widen a vector");
253 // If we saved a vectorized copy of V, use it.
254 Value *&MapEntry = WidenMap[V];
258 // Broadcast V and save the value for future uses.
259 Value *B = getBroadcastInstrs(V);
265 InnerLoopVectorizer::getUniformVector(unsigned Val, Type* ScalarTy) {
266 return ConstantVector::getSplat(VF, ConstantInt::get(ScalarTy, Val, true));
269 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr) {
270 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
271 // Holds vector parameters or scalars, in case of uniform vals.
272 SmallVector<Value*, 8> Params;
274 // Find all of the vectorized parameters.
275 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
276 Value *SrcOp = Instr->getOperand(op);
278 // If we are accessing the old induction variable, use the new one.
279 if (SrcOp == OldInduction) {
280 Params.push_back(getVectorValue(SrcOp));
284 // Try using previously calculated values.
285 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
287 // If the src is an instruction that appeared earlier in the basic block
288 // then it should already be vectorized.
289 if (SrcInst && SrcInst->getParent() == Instr->getParent()) {
290 assert(WidenMap.count(SrcInst) && "Source operand is unavailable");
291 // The parameter is a vector value from earlier.
292 Params.push_back(WidenMap[SrcInst]);
294 // The parameter is a scalar from outside the loop. Maybe even a constant.
295 Params.push_back(SrcOp);
299 assert(Params.size() == Instr->getNumOperands() &&
300 "Invalid number of operands");
302 // Does this instruction return a value ?
303 bool IsVoidRetTy = Instr->getType()->isVoidTy();
304 Value *VecResults = 0;
306 // If we have a return value, create an empty vector. We place the scalarized
307 // instructions in this vector.
309 VecResults = UndefValue::get(VectorType::get(Instr->getType(), VF));
311 // For each scalar that we create:
312 for (unsigned i = 0; i < VF; ++i) {
313 Instruction *Cloned = Instr->clone();
315 Cloned->setName(Instr->getName() + ".cloned");
316 // Replace the operands of the cloned instrucions with extracted scalars.
317 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
318 Value *Op = Params[op];
319 // Param is a vector. Need to extract the right lane.
320 if (Op->getType()->isVectorTy())
321 Op = Builder.CreateExtractElement(Op, Builder.getInt32(i));
322 Cloned->setOperand(op, Op);
325 // Place the cloned scalar in the new loop.
326 Builder.Insert(Cloned);
328 // If the original scalar returns a value we need to place it in a vector
329 // so that future users will be able to use it.
331 VecResults = Builder.CreateInsertElement(VecResults, Cloned,
332 Builder.getInt32(i));
336 WidenMap[Instr] = VecResults;
340 InnerLoopVectorizer::addRuntimeCheck(LoopVectorizationLegality *Legal,
342 LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck =
343 Legal->getRuntimePointerCheck();
345 if (!PtrRtCheck->Need)
348 Value *MemoryRuntimeCheck = 0;
349 unsigned NumPointers = PtrRtCheck->Pointers.size();
350 SmallVector<Value* , 2> Starts;
351 SmallVector<Value* , 2> Ends;
353 SCEVExpander Exp(*SE, "induction");
355 // Use this type for pointer arithmetic.
356 Type* PtrArithTy = Type::getInt8PtrTy(Loc->getContext(), 0);
358 for (unsigned i = 0; i < NumPointers; ++i) {
359 Value *Ptr = PtrRtCheck->Pointers[i];
360 const SCEV *Sc = SE->getSCEV(Ptr);
362 if (SE->isLoopInvariant(Sc, OrigLoop)) {
363 DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" <<
365 Starts.push_back(Ptr);
368 DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr <<"\n");
370 Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc);
371 Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
372 Starts.push_back(Start);
377 for (unsigned i = 0; i < NumPointers; ++i) {
378 for (unsigned j = i+1; j < NumPointers; ++j) {
379 Instruction::CastOps Op = Instruction::BitCast;
380 Value *Start0 = CastInst::Create(Op, Starts[i], PtrArithTy, "bc", Loc);
381 Value *Start1 = CastInst::Create(Op, Starts[j], PtrArithTy, "bc", Loc);
382 Value *End0 = CastInst::Create(Op, Ends[i], PtrArithTy, "bc", Loc);
383 Value *End1 = CastInst::Create(Op, Ends[j], PtrArithTy, "bc", Loc);
385 Value *Cmp0 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_ULE,
386 Start0, End1, "bound0", Loc);
387 Value *Cmp1 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_ULE,
388 Start1, End0, "bound1", Loc);
389 Value *IsConflict = BinaryOperator::Create(Instruction::And, Cmp0, Cmp1,
390 "found.conflict", Loc);
391 if (MemoryRuntimeCheck)
392 MemoryRuntimeCheck = BinaryOperator::Create(Instruction::Or,
395 "conflict.rdx", Loc);
397 MemoryRuntimeCheck = IsConflict;
402 return MemoryRuntimeCheck;
406 InnerLoopVectorizer::createEmptyLoop(LoopVectorizationLegality *Legal) {
408 In this function we generate a new loop. The new loop will contain
409 the vectorized instructions while the old loop will continue to run the
412 [ ] <-- vector loop bypass.
415 | [ ] <-- vector pre header.
419 | [ ]_| <-- vector loop.
422 >[ ] <--- middle-block.
425 | [ ] <--- new preheader.
429 | [ ]_| <-- old scalar loop to handle remainder.
436 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
437 BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
438 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
439 assert(ExitBlock && "Must have an exit block");
441 // Some loops have a single integer induction variable, while other loops
442 // don't. One example is c++ iterators that often have multiple pointer
443 // induction variables. In the code below we also support a case where we
444 // don't have a single induction variable.
445 OldInduction = Legal->getInduction();
446 Type *IdxTy = OldInduction ? OldInduction->getType() :
447 DL->getIntPtrType(SE->getContext());
449 // Find the loop boundaries.
450 const SCEV *ExitCount = SE->getExitCount(OrigLoop, OrigLoop->getLoopLatch());
451 assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
453 // Get the total trip count from the count by adding 1.
454 ExitCount = SE->getAddExpr(ExitCount,
455 SE->getConstant(ExitCount->getType(), 1));
457 // Expand the trip count and place the new instructions in the preheader.
458 // Notice that the pre-header does not change, only the loop body.
459 SCEVExpander Exp(*SE, "induction");
461 // Count holds the overall loop count (N).
462 Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
463 BypassBlock->getTerminator());
465 // The loop index does not have to start at Zero. Find the original start
466 // value from the induction PHI node. If we don't have an induction variable
467 // then we know that it starts at zero.
468 Value *StartIdx = OldInduction ?
469 OldInduction->getIncomingValueForBlock(BypassBlock):
470 ConstantInt::get(IdxTy, 0);
472 assert(BypassBlock && "Invalid loop structure");
474 // Generate the code that checks in runtime if arrays overlap.
475 Value *MemoryRuntimeCheck = addRuntimeCheck(Legal,
476 BypassBlock->getTerminator());
478 // Split the single block loop into the two loop structure described above.
479 BasicBlock *VectorPH =
480 BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
481 BasicBlock *VecBody =
482 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
483 BasicBlock *MiddleBlock =
484 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
485 BasicBlock *ScalarPH =
486 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
488 // This is the location in which we add all of the logic for bypassing
489 // the new vector loop.
490 Instruction *Loc = BypassBlock->getTerminator();
492 // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
494 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
496 // Generate the induction variable.
497 Induction = Builder.CreatePHI(IdxTy, 2, "index");
498 Constant *Step = ConstantInt::get(IdxTy, VF);
500 // We may need to extend the index in case there is a type mismatch.
501 // We know that the count starts at zero and does not overflow.
502 if (Count->getType() != IdxTy) {
503 // The exit count can be of pointer type. Convert it to the correct
505 if (ExitCount->getType()->isPointerTy())
506 Count = CastInst::CreatePointerCast(Count, IdxTy, "ptrcnt.to.int", Loc);
508 Count = CastInst::CreateZExtOrBitCast(Count, IdxTy, "zext.cnt", Loc);
511 // Add the start index to the loop count to get the new end index.
512 Value *IdxEnd = BinaryOperator::CreateAdd(Count, StartIdx, "end.idx", Loc);
514 // Now we need to generate the expression for N - (N % VF), which is
515 // the part that the vectorized body will execute.
516 Constant *CIVF = ConstantInt::get(IdxTy, VF);
517 Value *R = BinaryOperator::CreateURem(Count, CIVF, "n.mod.vf", Loc);
518 Value *CountRoundDown = BinaryOperator::CreateSub(Count, R, "n.vec", Loc);
519 Value *IdxEndRoundDown = BinaryOperator::CreateAdd(CountRoundDown, StartIdx,
520 "end.idx.rnd.down", Loc);
522 // Now, compare the new count to zero. If it is zero skip the vector loop and
523 // jump to the scalar loop.
524 Value *Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
529 // If we are using memory runtime checks, include them in.
530 if (MemoryRuntimeCheck)
531 Cmp = BinaryOperator::Create(Instruction::Or, Cmp, MemoryRuntimeCheck,
534 BranchInst::Create(MiddleBlock, VectorPH, Cmp, Loc);
535 // Remove the old terminator.
536 Loc->eraseFromParent();
538 // We are going to resume the execution of the scalar loop.
539 // Go over all of the induction variables that we found and fix the
540 // PHIs that are left in the scalar version of the loop.
541 // The starting values of PHI nodes depend on the counter of the last
542 // iteration in the vectorized loop.
543 // If we come from a bypass edge then we need to start from the original
546 // This variable saves the new starting index for the scalar loop.
547 PHINode *ResumeIndex = 0;
548 LoopVectorizationLegality::InductionList::iterator I, E;
549 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
550 for (I = List->begin(), E = List->end(); I != E; ++I) {
551 PHINode *OrigPhi = I->first;
552 LoopVectorizationLegality::InductionInfo II = I->second;
553 PHINode *ResumeVal = PHINode::Create(OrigPhi->getType(), 2, "resume.val",
554 MiddleBlock->getTerminator());
557 case LoopVectorizationLegality::NoInduction:
558 llvm_unreachable("Unknown induction");
559 case LoopVectorizationLegality::IntInduction: {
560 // Handle the integer induction counter:
561 assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
562 assert(OrigPhi == OldInduction && "Unknown integer PHI");
563 // We know what the end value is.
564 EndValue = IdxEndRoundDown;
565 // We also know which PHI node holds it.
566 ResumeIndex = ResumeVal;
569 case LoopVectorizationLegality::ReverseIntInduction: {
570 // Convert the CountRoundDown variable to the PHI size.
571 unsigned CRDSize = CountRoundDown->getType()->getScalarSizeInBits();
572 unsigned IISize = II.StartValue->getType()->getScalarSizeInBits();
573 Value *CRD = CountRoundDown;
574 if (CRDSize > IISize)
575 CRD = CastInst::Create(Instruction::Trunc, CountRoundDown,
576 II.StartValue->getType(),
577 "tr.crd", BypassBlock->getTerminator());
578 else if (CRDSize < IISize)
579 CRD = CastInst::Create(Instruction::SExt, CountRoundDown,
580 II.StartValue->getType(),
581 "sext.crd", BypassBlock->getTerminator());
582 // Handle reverse integer induction counter:
583 EndValue = BinaryOperator::CreateSub(II.StartValue, CRD, "rev.ind.end",
584 BypassBlock->getTerminator());
587 case LoopVectorizationLegality::PtrInduction: {
588 // For pointer induction variables, calculate the offset using
590 EndValue = GetElementPtrInst::Create(II.StartValue, CountRoundDown,
592 BypassBlock->getTerminator());
597 // The new PHI merges the original incoming value, in case of a bypass,
598 // or the value at the end of the vectorized loop.
599 ResumeVal->addIncoming(II.StartValue, BypassBlock);
600 ResumeVal->addIncoming(EndValue, VecBody);
602 // Fix the scalar body counter (PHI node).
603 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
604 OrigPhi->setIncomingValue(BlockIdx, ResumeVal);
607 // If we are generating a new induction variable then we also need to
608 // generate the code that calculates the exit value. This value is not
609 // simply the end of the counter because we may skip the vectorized body
610 // in case of a runtime check.
612 assert(!ResumeIndex && "Unexpected resume value found");
613 ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
614 MiddleBlock->getTerminator());
615 ResumeIndex->addIncoming(StartIdx, BypassBlock);
616 ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
619 // Make sure that we found the index where scalar loop needs to continue.
620 assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
621 "Invalid resume Index");
623 // Add a check in the middle block to see if we have completed
624 // all of the iterations in the first vector loop.
625 // If (N - N%VF) == N, then we *don't* need to run the remainder.
626 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
627 ResumeIndex, "cmp.n",
628 MiddleBlock->getTerminator());
630 BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
631 // Remove the old terminator.
632 MiddleBlock->getTerminator()->eraseFromParent();
634 // Create i+1 and fill the PHINode.
635 Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
636 Induction->addIncoming(StartIdx, VectorPH);
637 Induction->addIncoming(NextIdx, VecBody);
638 // Create the compare.
639 Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
640 Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
642 // Now we have two terminators. Remove the old one from the block.
643 VecBody->getTerminator()->eraseFromParent();
645 // Get ready to start creating new instructions into the vectorized body.
646 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
648 // Create and register the new vector loop.
649 Loop* Lp = new Loop();
650 Loop *ParentLoop = OrigLoop->getParentLoop();
652 // Insert the new loop into the loop nest and register the new basic blocks.
654 ParentLoop->addChildLoop(Lp);
655 ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
656 ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
657 ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
659 LI->addTopLevelLoop(Lp);
662 Lp->addBasicBlockToLoop(VecBody, LI->getBase());
665 LoopVectorPreHeader = VectorPH;
666 LoopScalarPreHeader = ScalarPH;
667 LoopMiddleBlock = MiddleBlock;
668 LoopExitBlock = ExitBlock;
669 LoopVectorBody = VecBody;
670 LoopScalarBody = OldBasicBlock;
671 LoopBypassBlock = BypassBlock;
674 /// This function returns the identity element (or neutral element) for
677 getReductionIdentity(LoopVectorizationLegality::ReductionKind K) {
679 case LoopVectorizationLegality::IntegerXor:
680 case LoopVectorizationLegality::IntegerAdd:
681 case LoopVectorizationLegality::IntegerOr:
682 // Adding, Xoring, Oring zero to a number does not change it.
684 case LoopVectorizationLegality::IntegerMult:
685 // Multiplying a number by 1 does not change it.
687 case LoopVectorizationLegality::IntegerAnd:
688 // AND-ing a number with an all-1 value does not change it.
691 llvm_unreachable("Unknown reduction kind");
696 isTriviallyVectorizableIntrinsic(Instruction *Inst) {
697 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst);
700 switch (II->getIntrinsicID()) {
701 case Intrinsic::sqrt:
705 case Intrinsic::exp2:
707 case Intrinsic::log10:
708 case Intrinsic::log2:
709 case Intrinsic::fabs:
710 case Intrinsic::floor:
711 case Intrinsic::ceil:
712 case Intrinsic::trunc:
713 case Intrinsic::rint:
714 case Intrinsic::nearbyint:
725 InnerLoopVectorizer::vectorizeLoop(LoopVectorizationLegality *Legal) {
726 //===------------------------------------------------===//
728 // Notice: any optimization or new instruction that go
729 // into the code below should be also be implemented in
732 //===------------------------------------------------===//
733 BasicBlock &BB = *OrigLoop->getHeader();
735 ConstantInt::get(IntegerType::getInt32Ty(BB.getContext()), 0);
737 // In order to support reduction variables we need to be able to vectorize
738 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
739 // stages. First, we create a new vector PHI node with no incoming edges.
740 // We use this value when we vectorize all of the instructions that use the
741 // PHI. Next, after all of the instructions in the block are complete we
742 // add the new incoming edges to the PHI. At this point all of the
743 // instructions in the basic block are vectorized, so we can use them to
744 // construct the PHI.
745 PhiVector RdxPHIsToFix;
747 // Scan the loop in a topological order to ensure that defs are vectorized
749 LoopBlocksDFS DFS(OrigLoop);
752 // Vectorize all of the blocks in the original loop.
753 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
754 be = DFS.endRPO(); bb != be; ++bb)
755 vectorizeBlockInLoop(Legal, *bb, &RdxPHIsToFix);
757 // At this point every instruction in the original loop is widened to
758 // a vector form. We are almost done. Now, we need to fix the PHI nodes
759 // that we vectorized. The PHI nodes are currently empty because we did
760 // not want to introduce cycles. Notice that the remaining PHI nodes
761 // that we need to fix are reduction variables.
763 // Create the 'reduced' values for each of the induction vars.
764 // The reduced values are the vector values that we scalarize and combine
765 // after the loop is finished.
766 for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
768 PHINode *RdxPhi = *it;
769 PHINode *VecRdxPhi = dyn_cast<PHINode>(WidenMap[RdxPhi]);
770 assert(RdxPhi && "Unable to recover vectorized PHI");
772 // Find the reduction variable descriptor.
773 assert(Legal->getReductionVars()->count(RdxPhi) &&
774 "Unable to find the reduction variable");
775 LoopVectorizationLegality::ReductionDescriptor RdxDesc =
776 (*Legal->getReductionVars())[RdxPhi];
778 // We need to generate a reduction vector from the incoming scalar.
779 // To do so, we need to generate the 'identity' vector and overide
780 // one of the elements with the incoming scalar reduction. We need
781 // to do it in the vector-loop preheader.
782 Builder.SetInsertPoint(LoopBypassBlock->getTerminator());
784 // This is the vector-clone of the value that leaves the loop.
785 Value *VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
786 Type *VecTy = VectorExit->getType();
788 // Find the reduction identity variable. Zero for addition, or, xor,
789 // one for multiplication, -1 for And.
790 Constant *Identity = getUniformVector(getReductionIdentity(RdxDesc.Kind),
791 VecTy->getScalarType());
793 // This vector is the Identity vector where the first element is the
794 // incoming scalar reduction.
795 Value *VectorStart = Builder.CreateInsertElement(Identity,
796 RdxDesc.StartValue, Zero);
798 // Fix the vector-loop phi.
799 // We created the induction variable so we know that the
800 // preheader is the first entry.
801 BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
803 // Reductions do not have to start at zero. They can start with
804 // any loop invariant values.
805 VecRdxPhi->addIncoming(VectorStart, VecPreheader);
807 getVectorValue(RdxPhi->getIncomingValueForBlock(OrigLoop->getLoopLatch()));
808 VecRdxPhi->addIncoming(Val, LoopVectorBody);
810 // Before each round, move the insertion point right between
811 // the PHIs and the values we are going to write.
812 // This allows us to write both PHINodes and the extractelement
814 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
816 // This PHINode contains the vectorized reduction variable, or
817 // the initial value vector, if we bypass the vector loop.
818 PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
819 NewPhi->addIncoming(VectorStart, LoopBypassBlock);
820 NewPhi->addIncoming(getVectorValue(RdxDesc.LoopExitInstr), LoopVectorBody);
822 // Extract the first scalar.
824 Builder.CreateExtractElement(NewPhi, Builder.getInt32(0));
825 // Extract and reduce the remaining vector elements.
826 for (unsigned i=1; i < VF; ++i) {
828 Builder.CreateExtractElement(NewPhi, Builder.getInt32(i));
829 switch (RdxDesc.Kind) {
830 case LoopVectorizationLegality::IntegerAdd:
831 Scalar0 = Builder.CreateAdd(Scalar0, Scalar1, "add.rdx");
833 case LoopVectorizationLegality::IntegerMult:
834 Scalar0 = Builder.CreateMul(Scalar0, Scalar1, "mul.rdx");
836 case LoopVectorizationLegality::IntegerOr:
837 Scalar0 = Builder.CreateOr(Scalar0, Scalar1, "or.rdx");
839 case LoopVectorizationLegality::IntegerAnd:
840 Scalar0 = Builder.CreateAnd(Scalar0, Scalar1, "and.rdx");
842 case LoopVectorizationLegality::IntegerXor:
843 Scalar0 = Builder.CreateXor(Scalar0, Scalar1, "xor.rdx");
846 llvm_unreachable("Unknown reduction operation");
850 // Now, we need to fix the users of the reduction variable
851 // inside and outside of the scalar remainder loop.
852 // We know that the loop is in LCSSA form. We need to update the
853 // PHI nodes in the exit blocks.
854 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
855 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
856 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
857 if (!LCSSAPhi) continue;
859 // All PHINodes need to have a single entry edge, or two if
860 // we already fixed them.
861 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
863 // We found our reduction value exit-PHI. Update it with the
864 // incoming bypass edge.
865 if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
866 // Add an edge coming from the bypass.
867 LCSSAPhi->addIncoming(Scalar0, LoopMiddleBlock);
870 }// end of the LCSSA phi scan.
872 // Fix the scalar loop reduction variable with the incoming reduction sum
873 // from the vector body and from the backedge value.
874 int IncomingEdgeBlockIdx =
875 (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
876 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
877 // Pick the other block.
878 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
879 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, Scalar0);
880 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
881 }// end of for each redux variable.
884 Value *InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
885 assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
888 Value *SrcMask = createBlockInMask(Src);
890 // The terminator has to be a branch inst!
891 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
892 assert(BI && "Unexpected terminator found");
894 Value *EdgeMask = SrcMask;
895 if (BI->isConditional()) {
896 EdgeMask = getVectorValue(BI->getCondition());
897 if (BI->getSuccessor(0) != Dst)
898 EdgeMask = Builder.CreateNot(EdgeMask);
901 return Builder.CreateAnd(EdgeMask, SrcMask);
904 Value *InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
905 assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
907 // Loop incoming mask is all-one.
908 if (OrigLoop->getHeader() == BB) {
909 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
910 return getVectorValue(C);
913 // This is the block mask. We OR all incoming edges, and with zero.
914 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
915 Value *BlockMask = getVectorValue(Zero);
918 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it)
919 BlockMask = Builder.CreateOr(BlockMask, createEdgeMask(*it, BB));
925 InnerLoopVectorizer::vectorizeBlockInLoop(LoopVectorizationLegality *Legal,
926 BasicBlock *BB, PhiVector *PV) {
928 ConstantInt::get(IntegerType::getInt32Ty(BB->getContext()), 0);
930 // For each instruction in the old loop.
931 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
932 switch (it->getOpcode()) {
933 case Instruction::Br:
934 // Nothing to do for PHIs and BR, since we already took care of the
935 // loop control flow instructions.
937 case Instruction::PHI:{
938 PHINode* P = cast<PHINode>(it);
939 // Handle reduction variables:
940 if (Legal->getReductionVars()->count(P)) {
941 // This is phase one of vectorizing PHIs.
942 Type *VecTy = VectorType::get(it->getType(), VF);
944 PHINode::Create(VecTy, 2, "vec.phi",
945 LoopVectorBody->getFirstInsertionPt());
950 // Check for PHI nodes that are lowered to vector selects.
951 if (P->getParent() != OrigLoop->getHeader()) {
952 // We know that all PHIs in non header blocks are converted into
953 // selects, so we don't have to worry about the insertion order and we
954 // can just use the builder.
956 // At this point we generate the predication tree. There may be
957 // duplications since this is a simple recursive scan, but future
958 // optimizations will clean it up.
959 Value *Cond = createEdgeMask(P->getIncomingBlock(0), P->getParent());
961 Builder.CreateSelect(Cond,
962 getVectorValue(P->getIncomingValue(0)),
963 getVectorValue(P->getIncomingValue(1)),
968 // This PHINode must be an induction variable.
969 // Make sure that we know about it.
970 assert(Legal->getInductionVars()->count(P) &&
971 "Not an induction variable");
973 LoopVectorizationLegality::InductionInfo II =
974 Legal->getInductionVars()->lookup(P);
977 case LoopVectorizationLegality::NoInduction:
978 llvm_unreachable("Unknown induction");
979 case LoopVectorizationLegality::IntInduction: {
980 assert(P == OldInduction && "Unexpected PHI");
981 Value *Broadcasted = getBroadcastInstrs(Induction);
982 // After broadcasting the induction variable we need to make the
983 // vector consecutive by adding 0, 1, 2 ...
984 Value *ConsecutiveInduction = getConsecutiveVector(Broadcasted);
985 WidenMap[OldInduction] = ConsecutiveInduction;
988 case LoopVectorizationLegality::ReverseIntInduction:
989 case LoopVectorizationLegality::PtrInduction:
990 // Handle reverse integer and pointer inductions.
992 // If we have a single integer induction variable then use it.
993 // Otherwise, start counting at zero.
995 LoopVectorizationLegality::InductionInfo OldII =
996 Legal->getInductionVars()->lookup(OldInduction);
997 StartIdx = OldII.StartValue;
999 StartIdx = ConstantInt::get(Induction->getType(), 0);
1001 // This is the normalized GEP that starts counting at zero.
1002 Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
1005 // Handle the reverse integer induction variable case.
1006 if (LoopVectorizationLegality::ReverseIntInduction == II.IK) {
1007 IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType());
1008 Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy,
1010 Value *ReverseInd = Builder.CreateSub(II.StartValue, CNI,
1013 // This is a new value so do not hoist it out.
1014 Value *Broadcasted = getBroadcastInstrs(ReverseInd);
1015 // After broadcasting the induction variable we need to make the
1016 // vector consecutive by adding ... -3, -2, -1, 0.
1017 Value *ConsecutiveInduction = getConsecutiveVector(Broadcasted,
1019 WidenMap[it] = ConsecutiveInduction;
1023 // Handle the pointer induction variable case.
1024 assert(P->getType()->isPointerTy() && "Unexpected type.");
1026 // This is the vector of results. Notice that we don't generate
1027 // vector geps because scalar geps result in better code.
1028 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
1029 for (unsigned int i = 0; i < VF; ++i) {
1030 Constant *Idx = ConstantInt::get(Induction->getType(), i);
1031 Value *GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx,
1033 Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
1035 VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
1036 Builder.getInt32(i),
1040 WidenMap[it] = VecVal;
1046 case Instruction::Add:
1047 case Instruction::FAdd:
1048 case Instruction::Sub:
1049 case Instruction::FSub:
1050 case Instruction::Mul:
1051 case Instruction::FMul:
1052 case Instruction::UDiv:
1053 case Instruction::SDiv:
1054 case Instruction::FDiv:
1055 case Instruction::URem:
1056 case Instruction::SRem:
1057 case Instruction::FRem:
1058 case Instruction::Shl:
1059 case Instruction::LShr:
1060 case Instruction::AShr:
1061 case Instruction::And:
1062 case Instruction::Or:
1063 case Instruction::Xor: {
1064 // Just widen binops.
1065 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
1066 Value *A = getVectorValue(it->getOperand(0));
1067 Value *B = getVectorValue(it->getOperand(1));
1069 // Use this vector value for all users of the original instruction.
1070 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A, B);
1073 // Update the NSW, NUW and Exact flags.
1074 BinaryOperator *VecOp = cast<BinaryOperator>(V);
1075 if (isa<OverflowingBinaryOperator>(BinOp)) {
1076 VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap());
1077 VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap());
1079 if (isa<PossiblyExactOperator>(VecOp))
1080 VecOp->setIsExact(BinOp->isExact());
1083 case Instruction::Select: {
1085 // If the selector is loop invariant we can create a select
1086 // instruction with a scalar condition. Otherwise, use vector-select.
1087 Value *Cond = it->getOperand(0);
1088 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(Cond), OrigLoop);
1090 // The condition can be loop invariant but still defined inside the
1091 // loop. This means that we can't just use the original 'cond' value.
1092 // We have to take the 'vectorized' value and pick the first lane.
1093 // Instcombine will make this a no-op.
1094 Cond = getVectorValue(Cond);
1096 Cond = Builder.CreateExtractElement(Cond, Builder.getInt32(0));
1098 Value *Op0 = getVectorValue(it->getOperand(1));
1099 Value *Op1 = getVectorValue(it->getOperand(2));
1100 WidenMap[it] = Builder.CreateSelect(Cond, Op0, Op1);
1104 case Instruction::ICmp:
1105 case Instruction::FCmp: {
1106 // Widen compares. Generate vector compares.
1107 bool FCmp = (it->getOpcode() == Instruction::FCmp);
1108 CmpInst *Cmp = dyn_cast<CmpInst>(it);
1109 Value *A = getVectorValue(it->getOperand(0));
1110 Value *B = getVectorValue(it->getOperand(1));
1112 WidenMap[it] = Builder.CreateFCmp(Cmp->getPredicate(), A, B);
1114 WidenMap[it] = Builder.CreateICmp(Cmp->getPredicate(), A, B);
1118 case Instruction::Store: {
1119 // Attempt to issue a wide store.
1120 StoreInst *SI = dyn_cast<StoreInst>(it);
1121 Type *StTy = VectorType::get(SI->getValueOperand()->getType(), VF);
1122 Value *Ptr = SI->getPointerOperand();
1123 unsigned Alignment = SI->getAlignment();
1125 assert(!Legal->isUniform(Ptr) &&
1126 "We do not allow storing to uniform addresses");
1128 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1130 // This store does not use GEPs.
1131 if (!Legal->isConsecutivePtr(Ptr)) {
1132 scalarizeInstruction(it);
1137 // The last index does not have to be the induction. It can be
1138 // consecutive and be a function of the index. For example A[I+1];
1139 unsigned NumOperands = Gep->getNumOperands();
1140 Value *LastIndex = getVectorValue(Gep->getOperand(NumOperands - 1));
1141 LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
1143 // Create the new GEP with the new induction variable.
1144 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1145 Gep2->setOperand(NumOperands - 1, LastIndex);
1146 Ptr = Builder.Insert(Gep2);
1148 // Use the induction element ptr.
1149 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1150 Ptr = Builder.CreateExtractElement(getVectorValue(Ptr), Zero);
1152 Ptr = Builder.CreateBitCast(Ptr, StTy->getPointerTo());
1153 Value *Val = getVectorValue(SI->getValueOperand());
1154 Builder.CreateStore(Val, Ptr)->setAlignment(Alignment);
1157 case Instruction::Load: {
1158 // Attempt to issue a wide load.
1159 LoadInst *LI = dyn_cast<LoadInst>(it);
1160 Type *RetTy = VectorType::get(LI->getType(), VF);
1161 Value *Ptr = LI->getPointerOperand();
1162 unsigned Alignment = LI->getAlignment();
1163 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1165 // If the pointer is loop invariant or if it is non consecutive,
1166 // scalarize the load.
1167 bool Con = Legal->isConsecutivePtr(Ptr);
1168 if (Legal->isUniform(Ptr) || !Con) {
1169 scalarizeInstruction(it);
1174 // The last index does not have to be the induction. It can be
1175 // consecutive and be a function of the index. For example A[I+1];
1176 unsigned NumOperands = Gep->getNumOperands();
1177 Value *LastIndex = getVectorValue(Gep->getOperand(NumOperands -1));
1178 LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
1180 // Create the new GEP with the new induction variable.
1181 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1182 Gep2->setOperand(NumOperands - 1, LastIndex);
1183 Ptr = Builder.Insert(Gep2);
1185 // Use the induction element ptr.
1186 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1187 Ptr = Builder.CreateExtractElement(getVectorValue(Ptr), Zero);
1190 Ptr = Builder.CreateBitCast(Ptr, RetTy->getPointerTo());
1191 LI = Builder.CreateLoad(Ptr);
1192 LI->setAlignment(Alignment);
1193 // Use this vector value for all users of the load.
1197 case Instruction::ZExt:
1198 case Instruction::SExt:
1199 case Instruction::FPToUI:
1200 case Instruction::FPToSI:
1201 case Instruction::FPExt:
1202 case Instruction::PtrToInt:
1203 case Instruction::IntToPtr:
1204 case Instruction::SIToFP:
1205 case Instruction::UIToFP:
1206 case Instruction::Trunc:
1207 case Instruction::FPTrunc:
1208 case Instruction::BitCast: {
1209 CastInst *CI = dyn_cast<CastInst>(it);
1210 /// Optimize the special case where the source is the induction
1211 /// variable. Notice that we can only optimize the 'trunc' case
1212 /// because: a. FP conversions lose precision, b. sext/zext may wrap,
1213 /// c. other casts depend on pointer size.
1214 if (CI->getOperand(0) == OldInduction &&
1215 it->getOpcode() == Instruction::Trunc) {
1216 Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
1218 Value *Broadcasted = getBroadcastInstrs(ScalarCast);
1219 WidenMap[it] = getConsecutiveVector(Broadcasted);
1222 /// Vectorize casts.
1223 Value *A = getVectorValue(it->getOperand(0));
1224 Type *DestTy = VectorType::get(CI->getType()->getScalarType(), VF);
1225 WidenMap[it] = Builder.CreateCast(CI->getOpcode(), A, DestTy);
1229 case Instruction::Call: {
1230 assert(isTriviallyVectorizableIntrinsic(it));
1231 Module *M = BB->getParent()->getParent();
1232 IntrinsicInst *II = cast<IntrinsicInst>(it);
1233 Intrinsic::ID ID = II->getIntrinsicID();
1234 SmallVector<Value*, 4> Args;
1235 for (unsigned i = 0, ie = II->getNumArgOperands(); i != ie; ++i)
1236 Args.push_back(getVectorValue(II->getArgOperand(i)));
1237 Type *Tys[] = { VectorType::get(II->getType()->getScalarType(), VF) };
1238 Function *F = Intrinsic::getDeclaration(M, ID, Tys);
1239 WidenMap[it] = Builder.CreateCall(F, Args);
1244 // All other instructions are unsupported. Scalarize them.
1245 scalarizeInstruction(it);
1248 }// end of for_each instr.
1251 void InnerLoopVectorizer::updateAnalysis() {
1252 // Forget the original basic block.
1253 SE->forgetLoop(OrigLoop);
1255 // Update the dominator tree information.
1256 assert(DT->properlyDominates(LoopBypassBlock, LoopExitBlock) &&
1257 "Entry does not dominate exit.");
1259 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlock);
1260 DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader);
1261 DT->addNewBlock(LoopMiddleBlock, LoopBypassBlock);
1262 DT->addNewBlock(LoopScalarPreHeader, LoopMiddleBlock);
1263 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
1264 DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
1266 DEBUG(DT->verifyAnalysis());
1269 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
1270 if (!EnableIfConversion)
1273 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
1274 std::vector<BasicBlock*> &LoopBlocks = TheLoop->getBlocksVector();
1276 // Collect the blocks that need predication.
1277 for (unsigned i = 0, e = LoopBlocks.size(); i < e; ++i) {
1278 BasicBlock *BB = LoopBlocks[i];
1280 // We don't support switch statements inside loops.
1281 if (!isa<BranchInst>(BB->getTerminator()))
1284 // We must have at most two predecessors because we need to convert
1285 // all PHIs to selects.
1286 unsigned Preds = std::distance(pred_begin(BB), pred_end(BB));
1290 // We must be able to predicate all blocks that need to be predicated.
1291 if (blockNeedsPredication(BB) && !blockCanBePredicated(BB))
1295 // We can if-convert this loop.
1299 bool LoopVectorizationLegality::canVectorize() {
1300 assert(TheLoop->getLoopPreheader() && "No preheader!!");
1302 // We can only vectorize innermost loops.
1303 if (TheLoop->getSubLoopsVector().size())
1306 // We must have a single backedge.
1307 if (TheLoop->getNumBackEdges() != 1)
1310 // We must have a single exiting block.
1311 if (!TheLoop->getExitingBlock())
1314 unsigned NumBlocks = TheLoop->getNumBlocks();
1316 // Check if we can if-convert non single-bb loops.
1317 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
1318 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
1322 // We need to have a loop header.
1323 BasicBlock *Latch = TheLoop->getLoopLatch();
1324 DEBUG(dbgs() << "LV: Found a loop: " <<
1325 TheLoop->getHeader()->getName() << "\n");
1327 // ScalarEvolution needs to be able to find the exit count.
1328 const SCEV *ExitCount = SE->getExitCount(TheLoop, Latch);
1329 if (ExitCount == SE->getCouldNotCompute()) {
1330 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
1334 // Do not loop-vectorize loops with a tiny trip count.
1335 unsigned TC = SE->getSmallConstantTripCount(TheLoop, Latch);
1336 if (TC > 0u && TC < TinyTripCountThreshold) {
1337 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " <<
1338 "This loop is not worth vectorizing.\n");
1342 // Check if we can vectorize the instructions and CFG in this loop.
1343 if (!canVectorizeInstrs()) {
1344 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
1348 // Go over each instruction and look at memory deps.
1349 if (!canVectorizeMemory()) {
1350 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
1354 // Collect all of the variables that remain uniform after vectorization.
1355 collectLoopUniforms();
1357 DEBUG(dbgs() << "LV: We can vectorize this loop" <<
1358 (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
1361 // Okay! We can vectorize. At this point we don't have any other mem analysis
1362 // which may limit our maximum vectorization factor, so just return true with
1367 bool LoopVectorizationLegality::canVectorizeInstrs() {
1368 BasicBlock *PreHeader = TheLoop->getLoopPreheader();
1369 BasicBlock *Header = TheLoop->getHeader();
1371 // For each block in the loop.
1372 for (Loop::block_iterator bb = TheLoop->block_begin(),
1373 be = TheLoop->block_end(); bb != be; ++bb) {
1375 // Scan the instructions in the block and look for hazards.
1376 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
1379 if (PHINode *Phi = dyn_cast<PHINode>(it)) {
1380 // This should not happen because the loop should be normalized.
1381 if (Phi->getNumIncomingValues() != 2) {
1382 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
1386 // Check that this PHI type is allowed.
1387 if (!Phi->getType()->isIntegerTy() &&
1388 !Phi->getType()->isPointerTy()) {
1389 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
1393 // If this PHINode is not in the header block, then we know that we
1394 // can convert it to select during if-conversion. No need to check if
1395 // the PHIs in this block are induction or reduction variables.
1399 // This is the value coming from the preheader.
1400 Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
1401 // Check if this is an induction variable.
1402 InductionKind IK = isInductionVariable(Phi);
1404 if (NoInduction != IK) {
1405 // Int inductions are special because we only allow one IV.
1406 if (IK == IntInduction) {
1408 DEBUG(dbgs() << "LV: Found too many inductions."<< *Phi <<"\n");
1414 DEBUG(dbgs() << "LV: Found an induction variable.\n");
1415 Inductions[Phi] = InductionInfo(StartValue, IK);
1419 if (AddReductionVar(Phi, IntegerAdd)) {
1420 DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
1423 if (AddReductionVar(Phi, IntegerMult)) {
1424 DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
1427 if (AddReductionVar(Phi, IntegerOr)) {
1428 DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
1431 if (AddReductionVar(Phi, IntegerAnd)) {
1432 DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
1435 if (AddReductionVar(Phi, IntegerXor)) {
1436 DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
1440 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
1442 }// end of PHI handling
1444 // We still don't handle functions.
1445 CallInst *CI = dyn_cast<CallInst>(it);
1446 if (CI && !isTriviallyVectorizableIntrinsic(it)) {
1447 DEBUG(dbgs() << "LV: Found a call site.\n");
1451 // We do not re-vectorize vectors.
1452 if (!VectorType::isValidElementType(it->getType()) &&
1453 !it->getType()->isVoidTy()) {
1454 DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n");
1458 // Reduction instructions are allowed to have exit users.
1459 // All other instructions must not have external users.
1460 if (!AllowedExit.count(it))
1461 //Check that all of the users of the loop are inside the BB.
1462 for (Value::use_iterator I = it->use_begin(), E = it->use_end();
1464 Instruction *U = cast<Instruction>(*I);
1465 // This user may be a reduction exit value.
1466 if (!TheLoop->contains(U)) {
1467 DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n");
1476 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
1477 assert(getInductionVars()->size() && "No induction variables");
1483 void LoopVectorizationLegality::collectLoopUniforms() {
1484 // We now know that the loop is vectorizable!
1485 // Collect variables that will remain uniform after vectorization.
1486 std::vector<Value*> Worklist;
1487 BasicBlock *Latch = TheLoop->getLoopLatch();
1489 // Start with the conditional branch and walk up the block.
1490 Worklist.push_back(Latch->getTerminator()->getOperand(0));
1492 while (Worklist.size()) {
1493 Instruction *I = dyn_cast<Instruction>(Worklist.back());
1494 Worklist.pop_back();
1496 // Look at instructions inside this loop.
1497 // Stop when reaching PHI nodes.
1498 // TODO: we need to follow values all over the loop, not only in this block.
1499 if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
1502 // This is a known uniform.
1505 // Insert all operands.
1506 for (int i = 0, Op = I->getNumOperands(); i < Op; ++i) {
1507 Worklist.push_back(I->getOperand(i));
1512 bool LoopVectorizationLegality::canVectorizeMemory() {
1513 typedef SmallVector<Value*, 16> ValueVector;
1514 typedef SmallPtrSet<Value*, 16> ValueSet;
1515 // Holds the Load and Store *instructions*.
1518 PtrRtCheck.Pointers.clear();
1519 PtrRtCheck.Need = false;
1522 for (Loop::block_iterator bb = TheLoop->block_begin(),
1523 be = TheLoop->block_end(); bb != be; ++bb) {
1525 // Scan the BB and collect legal loads and stores.
1526 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
1529 // If this is a load, save it. If this instruction can read from memory
1530 // but is not a load, then we quit. Notice that we don't handle function
1531 // calls that read or write.
1532 if (it->mayReadFromMemory()) {
1533 LoadInst *Ld = dyn_cast<LoadInst>(it);
1534 if (!Ld) return false;
1535 if (!Ld->isSimple()) {
1536 DEBUG(dbgs() << "LV: Found a non-simple load.\n");
1539 Loads.push_back(Ld);
1543 // Save 'store' instructions. Abort if other instructions write to memory.
1544 if (it->mayWriteToMemory()) {
1545 StoreInst *St = dyn_cast<StoreInst>(it);
1546 if (!St) return false;
1547 if (!St->isSimple()) {
1548 DEBUG(dbgs() << "LV: Found a non-simple store.\n");
1551 Stores.push_back(St);
1556 // Now we have two lists that hold the loads and the stores.
1557 // Next, we find the pointers that they use.
1559 // Check if we see any stores. If there are no stores, then we don't
1560 // care if the pointers are *restrict*.
1561 if (!Stores.size()) {
1562 DEBUG(dbgs() << "LV: Found a read-only loop!\n");
1566 // Holds the read and read-write *pointers* that we find.
1568 ValueVector ReadWrites;
1570 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
1571 // multiple times on the same object. If the ptr is accessed twice, once
1572 // for read and once for write, it will only appear once (on the write
1573 // list). This is okay, since we are going to check for conflicts between
1574 // writes and between reads and writes, but not between reads and reads.
1577 ValueVector::iterator I, IE;
1578 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
1579 StoreInst *ST = dyn_cast<StoreInst>(*I);
1580 assert(ST && "Bad StoreInst");
1581 Value* Ptr = ST->getPointerOperand();
1583 if (isUniform(Ptr)) {
1584 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
1588 // If we did *not* see this pointer before, insert it to
1589 // the read-write list. At this phase it is only a 'write' list.
1590 if (Seen.insert(Ptr))
1591 ReadWrites.push_back(Ptr);
1594 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
1595 LoadInst *LD = dyn_cast<LoadInst>(*I);
1596 assert(LD && "Bad LoadInst");
1597 Value* Ptr = LD->getPointerOperand();
1598 // If we did *not* see this pointer before, insert it to the
1599 // read list. If we *did* see it before, then it is already in
1600 // the read-write list. This allows us to vectorize expressions
1601 // such as A[i] += x; Because the address of A[i] is a read-write
1602 // pointer. This only works if the index of A[i] is consecutive.
1603 // If the address of i is unknown (for example A[B[i]]) then we may
1604 // read a few words, modify, and write a few words, and some of the
1605 // words may be written to the same address.
1606 if (Seen.insert(Ptr) || !isConsecutivePtr(Ptr))
1607 Reads.push_back(Ptr);
1610 // If we write (or read-write) to a single destination and there are no
1611 // other reads in this loop then is it safe to vectorize.
1612 if (ReadWrites.size() == 1 && Reads.size() == 0) {
1613 DEBUG(dbgs() << "LV: Found a write-only loop!\n");
1617 // Find pointers with computable bounds. We are going to use this information
1618 // to place a runtime bound check.
1620 for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I)
1621 if (hasComputableBounds(*I)) {
1622 PtrRtCheck.insert(SE, TheLoop, *I);
1623 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n");
1628 for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I)
1629 if (hasComputableBounds(*I)) {
1630 PtrRtCheck.insert(SE, TheLoop, *I);
1631 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n");
1637 // Check that we did not collect too many pointers or found a
1638 // unsizeable pointer.
1639 if (!RT || PtrRtCheck.Pointers.size() > RuntimeMemoryCheckThreshold) {
1644 PtrRtCheck.Need = RT;
1647 DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
1650 // Now that the pointers are in two lists (Reads and ReadWrites), we
1651 // can check that there are no conflicts between each of the writes and
1652 // between the writes to the reads.
1653 ValueSet WriteObjects;
1654 ValueVector TempObjects;
1656 // Check that the read-writes do not conflict with other read-write
1658 for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I) {
1659 GetUnderlyingObjects(*I, TempObjects, DL);
1660 for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
1662 if (!isIdentifiedObject(*it)) {
1663 DEBUG(dbgs() << "LV: Found an unidentified write ptr:"<< **it <<"\n");
1666 if (!WriteObjects.insert(*it)) {
1667 DEBUG(dbgs() << "LV: Found a possible write-write reorder:"
1672 TempObjects.clear();
1675 /// Check that the reads don't conflict with the read-writes.
1676 for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I) {
1677 GetUnderlyingObjects(*I, TempObjects, DL);
1678 for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
1680 if (!isIdentifiedObject(*it)) {
1681 DEBUG(dbgs() << "LV: Found an unidentified read ptr:"<< **it <<"\n");
1684 if (WriteObjects.count(*it)) {
1685 DEBUG(dbgs() << "LV: Found a possible read/write reorder:"
1690 TempObjects.clear();
1693 // It is safe to vectorize and we don't need any runtime checks.
1694 DEBUG(dbgs() << "LV: We don't need a runtime memory check.\n");
1699 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
1700 ReductionKind Kind) {
1701 if (Phi->getNumIncomingValues() != 2)
1704 // Reduction variables are only found in the loop header block.
1705 if (Phi->getParent() != TheLoop->getHeader())
1708 // Obtain the reduction start value from the value that comes from the loop
1710 Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
1712 // ExitInstruction is the single value which is used outside the loop.
1713 // We only allow for a single reduction value to be used outside the loop.
1714 // This includes users of the reduction, variables (which form a cycle
1715 // which ends in the phi node).
1716 Instruction *ExitInstruction = 0;
1718 // Iter is our iterator. We start with the PHI node and scan for all of the
1719 // users of this instruction. All users must be instructions which can be
1720 // used as reduction variables (such as ADD). We may have a single
1721 // out-of-block user. They cycle must end with the original PHI.
1722 // Also, we can't have multiple block-local users.
1723 Instruction *Iter = Phi;
1725 // If the instruction has no users then this is a broken
1726 // chain and can't be a reduction variable.
1727 if (Iter->use_empty())
1730 // Any reduction instr must be of one of the allowed kinds.
1731 if (!isReductionInstr(Iter, Kind))
1734 // Did we find a user inside this block ?
1735 bool FoundInBlockUser = false;
1736 // Did we reach the initial PHI node ?
1737 bool FoundStartPHI = false;
1739 // For each of the *users* of iter.
1740 for (Value::use_iterator it = Iter->use_begin(), e = Iter->use_end();
1742 Instruction *U = cast<Instruction>(*it);
1743 // We already know that the PHI is a user.
1745 FoundStartPHI = true;
1749 // Check if we found the exit user.
1750 BasicBlock *Parent = U->getParent();
1751 if (!TheLoop->contains(Parent)) {
1752 // Exit if you find multiple outside users.
1753 if (ExitInstruction != 0)
1755 ExitInstruction = Iter;
1758 // We allow in-loop PHINodes which are not the original reduction PHI
1759 // node. If this PHI is the only user of Iter (happens in IF w/ no ELSE
1760 // structure) then don't skip this PHI.
1761 if (isa<PHINode>(U) && U->getParent() != TheLoop->getHeader() &&
1762 TheLoop->contains(U) && Iter->getNumUses() > 1)
1765 // We can't have multiple inside users.
1766 if (FoundInBlockUser)
1768 FoundInBlockUser = true;
1772 // We found a reduction var if we have reached the original
1773 // phi node and we only have a single instruction with out-of-loop
1775 if (FoundStartPHI && ExitInstruction) {
1776 // This instruction is allowed to have out-of-loop users.
1777 AllowedExit.insert(ExitInstruction);
1779 // Save the description of this reduction variable.
1780 ReductionDescriptor RD(RdxStart, ExitInstruction, Kind);
1781 Reductions[Phi] = RD;
1785 // If we've reached the start PHI but did not find an outside user then
1786 // this is dead code. Abort.
1793 LoopVectorizationLegality::isReductionInstr(Instruction *I,
1794 ReductionKind Kind) {
1795 switch (I->getOpcode()) {
1798 case Instruction::PHI:
1801 case Instruction::Add:
1802 case Instruction::Sub:
1803 return Kind == IntegerAdd;
1804 case Instruction::Mul:
1805 return Kind == IntegerMult;
1806 case Instruction::And:
1807 return Kind == IntegerAnd;
1808 case Instruction::Or:
1809 return Kind == IntegerOr;
1810 case Instruction::Xor:
1811 return Kind == IntegerXor;
1815 LoopVectorizationLegality::InductionKind
1816 LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
1817 Type *PhiTy = Phi->getType();
1818 // We only handle integer and pointer inductions variables.
1819 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
1822 // Check that the PHI is consecutive and starts at zero.
1823 const SCEV *PhiScev = SE->getSCEV(Phi);
1824 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
1826 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
1829 const SCEV *Step = AR->getStepRecurrence(*SE);
1831 // Integer inductions need to have a stride of one.
1832 if (PhiTy->isIntegerTy()) {
1834 return IntInduction;
1835 if (Step->isAllOnesValue())
1836 return ReverseIntInduction;
1840 // Calculate the pointer stride and check if it is consecutive.
1841 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
1845 assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
1846 uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType());
1847 if (C->getValue()->equalsInt(Size))
1848 return PtrInduction;
1853 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
1854 assert(TheLoop->contains(BB) && "Unknown block used");
1856 // Blocks that do not dominate the latch need predication.
1857 BasicBlock* Latch = TheLoop->getLoopLatch();
1858 return !DT->dominates(BB, Latch);
1861 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB) {
1862 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1863 // We don't predicate loads/stores at the moment.
1864 if (it->mayReadFromMemory() || it->mayWriteToMemory() || it->mayThrow())
1867 // The instructions below can trap.
1868 switch (it->getOpcode()) {
1870 case Instruction::UDiv:
1871 case Instruction::SDiv:
1872 case Instruction::URem:
1873 case Instruction::SRem:
1881 bool LoopVectorizationLegality::hasComputableBounds(Value *Ptr) {
1882 const SCEV *PhiScev = SE->getSCEV(Ptr);
1883 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
1887 return AR->isAffine();
1891 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize,
1893 if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
1894 DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
1898 // Find the trip count.
1899 unsigned TC = SE->getSmallConstantTripCount(TheLoop, TheLoop->getLoopLatch());
1900 DEBUG(dbgs() << "LV: Found trip count:"<<TC<<"\n");
1902 unsigned VF = MaxVectorSize;
1904 // If we optimize the program for size, avoid creating the tail loop.
1906 // If we are unable to calculate the trip count then don't try to vectorize.
1908 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
1912 // Find the maximum SIMD width that can fit within the trip count.
1913 VF = TC % MaxVectorSize;
1918 // If the trip count that we found modulo the vectorization factor is not
1919 // zero then we require a tail.
1921 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
1927 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
1928 DEBUG(dbgs() << "LV: Using user VF "<<UserVF<<".\n");
1934 DEBUG(dbgs() << "LV: No vector target information. Not vectorizing. \n");
1938 float Cost = expectedCost(1);
1940 DEBUG(dbgs() << "LV: Scalar loop costs: "<< (int)Cost << ".\n");
1941 for (unsigned i=2; i <= VF; i*=2) {
1942 // Notice that the vector loop needs to be executed less times, so
1943 // we need to divide the cost of the vector loops by the width of
1944 // the vector elements.
1945 float VectorCost = expectedCost(i) / (float)i;
1946 DEBUG(dbgs() << "LV: Vector loop of width "<< i << " costs: " <<
1947 (int)VectorCost << ".\n");
1948 if (VectorCost < Cost) {
1954 DEBUG(dbgs() << "LV: Selecting VF = : "<< Width << ".\n");
1958 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
1962 for (Loop::block_iterator bb = TheLoop->block_begin(),
1963 be = TheLoop->block_end(); bb != be; ++bb) {
1964 unsigned BlockCost = 0;
1965 BasicBlock *BB = *bb;
1967 // For each instruction in the old loop.
1968 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1969 unsigned C = getInstructionCost(it, VF);
1971 DEBUG(dbgs() << "LV: Found an estimated cost of "<< C <<" for VF " <<
1972 VF << " For instruction: "<< *it << "\n");
1975 // We assume that if-converted blocks have a 50% chance of being executed.
1976 // When the code is scalar then some of the blocks are avoided due to CF.
1977 // When the code is vectorized we execute all code paths.
1978 if (Legal->blockNeedsPredication(*bb) && VF == 1)
1988 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
1989 assert(VTTI && "Invalid vector target transformation info");
1991 // If we know that this instruction will remain uniform, check the cost of
1992 // the scalar version.
1993 if (Legal->isUniformAfterVectorization(I))
1996 Type *RetTy = I->getType();
1997 Type *VectorTy = ToVectorTy(RetTy, VF);
1999 // TODO: We need to estimate the cost of intrinsic calls.
2000 switch (I->getOpcode()) {
2001 case Instruction::GetElementPtr:
2002 // We mark this instruction as zero-cost because scalar GEPs are usually
2003 // lowered to the intruction addressing mode. At the moment we don't
2004 // generate vector geps.
2006 case Instruction::Br: {
2007 return VTTI->getCFInstrCost(I->getOpcode());
2009 case Instruction::PHI:
2010 //TODO: IF-converted IFs become selects.
2012 case Instruction::Add:
2013 case Instruction::FAdd:
2014 case Instruction::Sub:
2015 case Instruction::FSub:
2016 case Instruction::Mul:
2017 case Instruction::FMul:
2018 case Instruction::UDiv:
2019 case Instruction::SDiv:
2020 case Instruction::FDiv:
2021 case Instruction::URem:
2022 case Instruction::SRem:
2023 case Instruction::FRem:
2024 case Instruction::Shl:
2025 case Instruction::LShr:
2026 case Instruction::AShr:
2027 case Instruction::And:
2028 case Instruction::Or:
2029 case Instruction::Xor:
2030 return VTTI->getArithmeticInstrCost(I->getOpcode(), VectorTy);
2031 case Instruction::Select: {
2032 SelectInst *SI = cast<SelectInst>(I);
2033 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
2034 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
2035 Type *CondTy = SI->getCondition()->getType();
2037 CondTy = VectorType::get(CondTy, VF);
2039 return VTTI->getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
2041 case Instruction::ICmp:
2042 case Instruction::FCmp: {
2043 Type *ValTy = I->getOperand(0)->getType();
2044 VectorTy = ToVectorTy(ValTy, VF);
2045 return VTTI->getCmpSelInstrCost(I->getOpcode(), VectorTy);
2047 case Instruction::Store: {
2048 StoreInst *SI = cast<StoreInst>(I);
2049 Type *ValTy = SI->getValueOperand()->getType();
2050 VectorTy = ToVectorTy(ValTy, VF);
2053 return VTTI->getMemoryOpCost(I->getOpcode(), ValTy,
2055 SI->getPointerAddressSpace());
2057 // Scalarized stores.
2058 if (!Legal->isConsecutivePtr(SI->getPointerOperand())) {
2060 unsigned ExtCost = VTTI->getInstrCost(Instruction::ExtractElement,
2062 // The cost of extracting from the value vector.
2063 Cost += VF * (ExtCost);
2064 // The cost of the scalar stores.
2065 Cost += VF * VTTI->getMemoryOpCost(I->getOpcode(),
2066 ValTy->getScalarType(),
2068 SI->getPointerAddressSpace());
2073 return VTTI->getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),
2074 SI->getPointerAddressSpace());
2076 case Instruction::Load: {
2077 LoadInst *LI = cast<LoadInst>(I);
2080 return VTTI->getMemoryOpCost(I->getOpcode(), RetTy,
2082 LI->getPointerAddressSpace());
2084 // Scalarized loads.
2085 if (!Legal->isConsecutivePtr(LI->getPointerOperand())) {
2087 unsigned InCost = VTTI->getInstrCost(Instruction::InsertElement, RetTy);
2088 // The cost of inserting the loaded value into the result vector.
2089 Cost += VF * (InCost);
2090 // The cost of the scalar stores.
2091 Cost += VF * VTTI->getMemoryOpCost(I->getOpcode(),
2092 RetTy->getScalarType(),
2094 LI->getPointerAddressSpace());
2099 return VTTI->getMemoryOpCost(I->getOpcode(), VectorTy, LI->getAlignment(),
2100 LI->getPointerAddressSpace());
2102 case Instruction::ZExt:
2103 case Instruction::SExt:
2104 case Instruction::FPToUI:
2105 case Instruction::FPToSI:
2106 case Instruction::FPExt:
2107 case Instruction::PtrToInt:
2108 case Instruction::IntToPtr:
2109 case Instruction::SIToFP:
2110 case Instruction::UIToFP:
2111 case Instruction::Trunc:
2112 case Instruction::FPTrunc:
2113 case Instruction::BitCast: {
2114 Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
2115 return VTTI->getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
2117 case Instruction::Call: {
2118 assert(isTriviallyVectorizableIntrinsic(I));
2119 IntrinsicInst *II = cast<IntrinsicInst>(I);
2120 Type *RetTy = ToVectorTy(II->getType(), VF);
2121 SmallVector<Type*, 4> Tys;
2122 for (unsigned i = 0, ie = II->getNumArgOperands(); i != ie; ++i)
2123 Tys.push_back(ToVectorTy(II->getArgOperand(i)->getType(), VF));
2124 return VTTI->getIntrinsicInstrCost(II->getIntrinsicID(), RetTy, Tys);
2127 // We are scalarizing the instruction. Return the cost of the scalar
2128 // instruction, plus the cost of insert and extract into vector
2129 // elements, times the vector width.
2132 bool IsVoid = RetTy->isVoidTy();
2134 unsigned InsCost = (IsVoid ? 0 :
2135 VTTI->getInstrCost(Instruction::InsertElement,
2138 unsigned ExtCost = VTTI->getInstrCost(Instruction::ExtractElement,
2141 // The cost of inserting the results plus extracting each one of the
2143 Cost += VF * (InsCost + ExtCost * I->getNumOperands());
2145 // The cost of executing VF copies of the scalar instruction.
2146 Cost += VF * VTTI->getInstrCost(I->getOpcode(), RetTy);
2152 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
2153 if (Scalar->isVoidTy() || VF == 1)
2155 return VectorType::get(Scalar, VF);
2158 char LoopVectorize::ID = 0;
2159 static const char lv_name[] = "Loop Vectorization";
2160 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
2161 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
2162 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
2163 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
2164 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
2167 Pass *createLoopVectorizePass() {
2168 return new LoopVectorize();