1 //===- LoopVectorize.cpp - A Loop Vectorizer ------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This is a simple loop vectorizer. We currently only support single block
11 // loops. We have a very simple and restrictive legality check: we need to read
12 // and write from disjoint memory locations. We still don't have a cost model.
13 // This pass has three parts:
14 // 1. The main loop pass that drives the different parts.
15 // 2. LoopVectorizationLegality - A helper class that checks for the legality
16 // of the vectorization.
17 // 3. SingleBlockLoopVectorizer - A helper class that performs the actual
18 // widening of instructions.
20 //===----------------------------------------------------------------------===//
21 #define LV_NAME "loop-vectorize"
22 #define DEBUG_TYPE LV_NAME
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/LLVMContext.h"
27 #include "llvm/Pass.h"
28 #include "llvm/Analysis/LoopPass.h"
29 #include "llvm/Value.h"
30 #include "llvm/Function.h"
31 #include "llvm/Module.h"
32 #include "llvm/Type.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/StringExtras.h"
35 #include "llvm/Analysis/AliasAnalysis.h"
36 #include "llvm/Analysis/AliasSetTracker.h"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/Analysis/ScalarEvolution.h"
39 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
40 #include "llvm/Analysis/ScalarEvolutionExpander.h"
41 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
42 #include "llvm/Analysis/ValueTracking.h"
43 #include "llvm/Analysis/LoopInfo.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/Debug.h"
46 #include "llvm/Support/raw_ostream.h"
47 #include "llvm/DataLayout.h"
48 #include "llvm/Transforms/Utils/Local.h"
52 static cl::opt<unsigned>
53 DefaultVectorizationFactor("default-loop-vectorize-width",
54 cl::init(4), cl::Hidden,
55 cl::desc("Set the default loop vectorization width"));
59 /// Vectorize a simple loop. This class performs the widening of simple single
60 /// basic block loops into vectors. It does not perform any
61 /// vectorization-legality checks, and just does it. It widens the vectors
62 /// to a given vectorization factor (VF).
63 class SingleBlockLoopVectorizer {
67 SingleBlockLoopVectorizer(Loop *OrigLoop, ScalarEvolution *Se, LoopInfo *Li,
69 Orig(OrigLoop), SE(Se), LI(Li), VF(VecWidth),
70 Builder(0), Induction(0), OldInduction(0) { }
72 ~SingleBlockLoopVectorizer() {
76 // Perform the actual loop widening (vectorization).
78 ///Create a new empty loop. Unlink the old loop and connect the new one.
80 /// Widen each instruction in the old loop to a new one in the new loop.
82 // Delete the old loop.
87 /// Create an empty loop, based on the loop ranges of the old loop.
89 /// Copy and widen the instructions from the old loop.
91 /// Delete the old loop.
94 /// This instruction is un-vectorizable. Implement it as a sequence
96 void scalarizeInstruction(Instruction *Instr);
98 /// Create a broadcast instruction. This method generates a broadcast
99 /// instruction (shuffle) for loop invariant values and for the induction
100 /// value. If this is the induction variable then we extend it to N, N+1, ...
101 /// this is needed because each iteration in the loop corresponds to a SIMD
103 Value *getBroadcastInstrs(Value *V);
105 /// This is a helper function used by getBroadcastInstrs. It adds 0, 1, 2 ..
106 /// for each element in the vector. Starting from zero.
107 Value *getConsecutiveVector(Value* Val);
109 /// Check that the GEP operands are all uniform except for the last index
110 /// which has to be the induction variable.
111 bool isConsecutiveGep(GetElementPtrInst *Gep);
113 /// When we go over instructions in the basic block we rely on previous
114 /// values within the current basic block or on loop invariant values.
115 /// When we widen (vectorize) values we place them in the map. If the values
116 /// are not within the map, they have to be loop invariant, so we simply
117 /// broadcast them into a vector.
118 Value *getVectorValue(Value *V);
120 /// The original loop.
122 // Scev analysis to use.
126 // The vectorization factor to use.
129 // The builder that we use
130 IRBuilder<> *Builder;
132 // --- Vectorization state ---
134 /// The new Induction variable which was added to the new block.
135 Instruction *Induction;
136 /// The induction variable of the old basic block.
137 Instruction *OldInduction;
138 // Maps scalars to widened vectors.
139 DenseMap<Value*, Value*> WidenMap;
143 /// Perform the vectorization legality check. This class does not look at the
144 /// profitability of vectorization, only the legality. At the moment the checks
145 /// are very simple and focus on single basic block loops with a constant
146 /// iteration count and no reductions.
147 class LoopVectorizationLegality {
149 LoopVectorizationLegality(Loop *Lp, ScalarEvolution *Se, DataLayout *Dl):
150 TheLoop(Lp), SE(Se), DL(Dl) { }
152 /// Returns the maximum vectorization factor that we *can* use to vectorize
153 /// this loop. This does not mean that it is profitable to vectorize this
154 /// loop, only that it is legal to do so. This may be a large number. We
155 /// can vectorize to any SIMD width below this number.
156 unsigned getLoopMaxVF();
159 /// Check if a single basic block loop is vectorizable.
160 /// At this point we know that this is a loop with a constant trip count
161 /// and we only need to check individual instructions.
162 bool canVectorizeBlock(BasicBlock &BB);
164 // Check if a pointer value is known to be disjoint.
165 // Example: Alloca, Global, NoAlias.
166 bool isKnownDisjoint(Value* Val);
168 /// The loop that we evaluate.
172 /// DataLayout analysis.
176 struct LoopVectorize : public LoopPass {
177 static char ID; // Pass identification, replacement for typeid
179 LoopVectorize() : LoopPass(ID) {
180 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
188 virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
189 // Only vectorize innermost loops.
193 AA = &getAnalysis<AliasAnalysis>();
194 SE = &getAnalysis<ScalarEvolution>();
195 DL = getAnalysisIfAvailable<DataLayout>();
196 LI = &getAnalysis<LoopInfo>();
198 DEBUG(dbgs() << "LV: Checking a loop in \"" <<
199 L->getHeader()->getParent()->getName() << "\"\n");
201 // Check if it is legal to vectorize the loop.
202 LoopVectorizationLegality LVL(L, SE, DL);
203 unsigned MaxVF = LVL.getLoopMaxVF();
205 // Check that we can vectorize using the chosen vectorization width.
206 if ((MaxVF < DefaultVectorizationFactor) ||
207 (MaxVF % DefaultVectorizationFactor)) {
208 DEBUG(dbgs() << "LV: non-vectorizable MaxVF ("<< MaxVF << ").\n");
212 DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< MaxVF << ").\n");
214 // If we decided that is is *legal* to vectorizer the loop. Do it.
215 SingleBlockLoopVectorizer LB(L, SE, LI, DefaultVectorizationFactor);
218 // The loop is now vectorized. Remove it from LMP.
219 LPM.deleteLoopFromQueue(L);
223 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
224 LoopPass::getAnalysisUsage(AU);
225 AU.addRequiredID(LoopSimplifyID);
226 AU.addRequired<AliasAnalysis>();
227 AU.addRequired<LoopInfo>();
228 AU.addRequired<ScalarEvolution>();
233 Value *SingleBlockLoopVectorizer::getBroadcastInstrs(Value *V) {
234 // Instructions that access the old induction variable
235 // actually want to get the new one.
236 if (V == OldInduction)
239 LLVMContext &C = V->getContext();
240 Type *VTy = VectorType::get(V->getType(), VF);
241 Type *I32 = IntegerType::getInt32Ty(C);
242 Constant *Zero = ConstantInt::get(I32, 0);
243 Value *Zeros = ConstantAggregateZero::get(VectorType::get(I32, VF));
244 Value *UndefVal = UndefValue::get(VTy);
245 // Insert the value into a new vector.
246 Value *SingleElem = Builder->CreateInsertElement(UndefVal, V, Zero);
247 // Broadcast the scalar into all locations in the vector.
248 Value *Shuf = Builder->CreateShuffleVector(SingleElem, UndefVal, Zeros,
250 // We are accessing the induction variable. Make sure to promote the
251 // index for each consecutive SIMD lane. This adds 0,1,2 ... to all lanes.
253 return getConsecutiveVector(Shuf);
257 Value *SingleBlockLoopVectorizer::getConsecutiveVector(Value* Val) {
258 assert(Val->getType()->isVectorTy() && "Must be a vector");
259 assert(Val->getType()->getScalarType()->isIntegerTy() &&
260 "Elem must be an integer");
262 Type *ITy = Val->getType()->getScalarType();
263 VectorType *Ty = cast<VectorType>(Val->getType());
264 unsigned VLen = Ty->getNumElements();
265 SmallVector<Constant*, 8> Indices;
267 // Create a vector of consecutive numbers from zero to VF.
268 for (unsigned i = 0; i < VLen; ++i)
269 Indices.push_back(ConstantInt::get(ITy, i));
271 // Add the consecutive indices to the vector value.
272 Constant *Cv = ConstantVector::get(Indices);
273 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
274 return Builder->CreateAdd(Val, Cv, "induction");
278 bool SingleBlockLoopVectorizer::isConsecutiveGep(GetElementPtrInst *Gep) {
282 unsigned NumOperands = Gep->getNumOperands();
283 Value *LastIndex = Gep->getOperand(NumOperands - 1);
285 // Check that all of the gep indices are uniform except for the last.
286 for (unsigned i = 0; i < NumOperands - 1; ++i)
287 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), Orig))
290 // The last operand has to be the induction in order to emit
291 // a wide load/store.
292 const SCEV *Last = SE->getSCEV(LastIndex);
293 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
294 const SCEV *Step = AR->getStepRecurrence(*SE);
296 // The memory is consecutive because the last index is consecutive
297 // and all other indices are loop invariant.
305 Value *SingleBlockLoopVectorizer::getVectorValue(Value *V) {
306 if (WidenMap.count(V))
308 return getBroadcastInstrs(V);
311 void SingleBlockLoopVectorizer::scalarizeInstruction(Instruction *Instr) {
312 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
313 // Holds vector parameters or scalars, in case of uniform vals.
314 SmallVector<Value*, 8> Params;
316 // Find all of the vectorized parameters.
317 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
318 Value *SrcOp = Instr->getOperand(op);
320 // If we are accessing the old induction variable, use the new one.
321 if (SrcOp == OldInduction) {
322 Params.push_back(getBroadcastInstrs(Induction));
326 // Try using previously calculated values.
327 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
329 // If the src is an instruction that appeared earlier in the basic block
330 // then it should already be vectorized.
331 if (SrcInst && SrcInst->getParent() == Instr->getParent()) {
332 assert(WidenMap.count(SrcInst) && "Source operand is unavailable");
333 // The parameter is a vector value from earlier.
334 Params.push_back(WidenMap[SrcInst]);
336 // The parameter is a scalar from outside the loop. Maybe even a constant.
337 Params.push_back(SrcOp);
341 assert(Params.size() == Instr->getNumOperands() &&
342 "Invalid number of operands");
344 // Does this instruction return a value ?
345 bool IsVoidRetTy = Instr->getType()->isVoidTy();
346 Value *VecResults = 0;
348 // If we have a return value, create an empty vector. We place the scalarized
349 // instructions in this vector.
351 VecResults = UndefValue::get(VectorType::get(Instr->getType(), VF));
353 // For each scalar that we create.
354 for (unsigned i = 0; i < VF; ++i) {
355 Instruction *Cloned = Instr->clone();
357 Cloned->setName(Instr->getName() + ".cloned");
358 // Replace the operands of the cloned instrucions with extracted scalars.
359 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
360 Value *Op = Params[op];
361 // Param is a vector. Need to extract the right lane.
362 if (Op->getType()->isVectorTy())
363 Op = Builder->CreateExtractElement(Op, Builder->getInt32(i));
364 Cloned->setOperand(op, Op);
367 // Place the cloned scalar in the new loop.
368 Builder->Insert(Cloned);
370 // If the original scalar returns a value we need to place it in a vector
371 // so that future users will be able to use it.
373 VecResults = Builder->CreateInsertElement(VecResults, Cloned,
374 Builder->getInt32(i));
378 WidenMap[Instr] = VecResults;
381 void SingleBlockLoopVectorizer::copyEmptyLoop() {
382 assert(Orig->getNumBlocks() == 1 && "Invalid loop");
383 BasicBlock *PH = Orig->getLoopPreheader();
384 BasicBlock *ExitBlock = Orig->getExitBlock();
385 assert(ExitBlock && "Invalid loop exit");
387 // Create a new single-basic block loop.
388 BasicBlock *BB = BasicBlock::Create(PH->getContext(), "vectorizedloop",
389 PH->getParent(), ExitBlock);
391 // Find the induction variable.
392 BasicBlock *OldBasicBlock = Orig->getHeader();
393 PHINode *OldInd = dyn_cast<PHINode>(OldBasicBlock->begin());
394 assert(OldInd && "We must have a single phi node.");
395 Type *IdxTy = OldInd->getType();
397 // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
399 Builder = new IRBuilder<>(BB);
401 // Generate the induction variable.
402 PHINode *Phi = Builder->CreatePHI(IdxTy, 2, "index");
403 Constant *Zero = ConstantInt::get(IdxTy, 0);
404 Constant *Step = ConstantInt::get(IdxTy, VF);
406 // Find the loop boundaries.
407 const SCEV *ExitCount = SE->getExitCount(Orig, Orig->getHeader());
408 assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
410 // Get the trip count from the count by adding 1.
411 ExitCount = SE->getAddExpr(ExitCount,
412 SE->getConstant(ExitCount->getType(), 1));
414 // Expand the trip count and place the new instructions in the preheader.
415 // Notice that the pre-header does not change, only the loop body.
416 SCEVExpander Exp(*SE, "induction");
417 Instruction *Loc = Orig->getLoopPreheader()->getTerminator();
418 if (ExitCount->getType() != Phi->getType())
419 ExitCount = SE->getSignExtendExpr(ExitCount, Phi->getType());
420 Value *Count = Exp.expandCodeFor(ExitCount, Phi->getType(), Loc);
422 // Create i+1 and fill the PHINode.
423 Value *Next = Builder->CreateAdd(Phi, Step, "index.next");
424 Phi->addIncoming(Zero, PH);
425 Phi->addIncoming(Next, BB);
426 // Create the compare.
427 Value *ICmp = Builder->CreateICmpEQ(Next, Count);
428 Builder->CreateCondBr(ICmp, ExitBlock, BB);
430 PH->getTerminator()->setSuccessor(0, BB);
431 Builder->SetInsertPoint(BB->getFirstInsertionPt());
433 // Save the induction variables.
435 OldInduction = OldInd;
438 void SingleBlockLoopVectorizer::vectorizeLoop() {
439 BasicBlock &BB = *Orig->getHeader();
441 // For each instruction in the old loop.
442 for (BasicBlock::iterator it = BB.begin(), e = BB.end(); it != e; ++it) {
443 Instruction *Inst = it;
445 switch (Inst->getOpcode()) {
446 case Instruction::PHI:
447 case Instruction::Br:
448 // Nothing to do for PHIs and BR, since we already took care of the
449 // loop control flow instructions.
452 case Instruction::Add:
453 case Instruction::FAdd:
454 case Instruction::Sub:
455 case Instruction::FSub:
456 case Instruction::Mul:
457 case Instruction::FMul:
458 case Instruction::UDiv:
459 case Instruction::SDiv:
460 case Instruction::FDiv:
461 case Instruction::URem:
462 case Instruction::SRem:
463 case Instruction::FRem:
464 case Instruction::Shl:
465 case Instruction::LShr:
466 case Instruction::AShr:
467 case Instruction::And:
468 case Instruction::Or:
469 case Instruction::Xor: {
470 // Just widen binops.
471 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
472 Value *A = getVectorValue(Inst->getOperand(0));
473 Value *B = getVectorValue(Inst->getOperand(1));
474 // Use this vector value for all users of the original instruction.
475 WidenMap[Inst] = Builder->CreateBinOp(BinOp->getOpcode(), A, B);
478 case Instruction::Select: {
480 Value *A = getVectorValue(Inst->getOperand(0));
481 Value *B = getVectorValue(Inst->getOperand(1));
482 Value *C = getVectorValue(Inst->getOperand(2));
483 WidenMap[Inst] = Builder->CreateSelect(A, B, C);
487 case Instruction::ICmp:
488 case Instruction::FCmp: {
489 // Widen compares. Generate vector compares.
490 bool FCmp = (Inst->getOpcode() == Instruction::FCmp);
491 CmpInst *Cmp = dyn_cast<CmpInst>(Inst);
492 Value *A = getVectorValue(Inst->getOperand(0));
493 Value *B = getVectorValue(Inst->getOperand(1));
495 WidenMap[Inst] = Builder->CreateFCmp(Cmp->getPredicate(), A, B);
497 WidenMap[Inst] = Builder->CreateICmp(Cmp->getPredicate(), A, B);
501 case Instruction::Store: {
502 // Attempt to issue a wide store.
503 StoreInst *SI = dyn_cast<StoreInst>(Inst);
504 Type *StTy = VectorType::get(SI->getValueOperand()->getType(), VF);
505 Value *Ptr = SI->getPointerOperand();
506 unsigned Alignment = SI->getAlignment();
507 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
508 // This store does not use GEPs.
509 if (!isConsecutiveGep(Gep)) {
510 scalarizeInstruction(Inst);
514 // Create the new GEP with the new induction variable.
515 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
516 unsigned NumOperands = Gep->getNumOperands();
517 Gep2->setOperand(NumOperands - 1, Induction);
518 Ptr = Builder->Insert(Gep2);
519 Ptr = Builder->CreateBitCast(Ptr, StTy->getPointerTo());
520 Value *Val = getVectorValue(SI->getValueOperand());
521 Builder->CreateStore(Val, Ptr)->setAlignment(Alignment);
524 case Instruction::Load: {
525 // Attempt to issue a wide load.
526 LoadInst *LI = dyn_cast<LoadInst>(Inst);
527 Type *RetTy = VectorType::get(LI->getType(), VF);
528 Value *Ptr = LI->getPointerOperand();
529 unsigned Alignment = LI->getAlignment();
530 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
532 // We don't have a gep. Scalarize the load.
533 if (!isConsecutiveGep(Gep)) {
534 scalarizeInstruction(Inst);
538 // Create the new GEP with the new induction variable.
539 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
540 unsigned NumOperands = Gep->getNumOperands();
541 Gep2->setOperand(NumOperands - 1, Induction);
542 Ptr = Builder->Insert(Gep2);
543 Ptr = Builder->CreateBitCast(Ptr, RetTy->getPointerTo());
544 LI = Builder->CreateLoad(Ptr);
545 LI->setAlignment(Alignment);
546 // Use this vector value for all users of the load.
550 case Instruction::ZExt:
551 case Instruction::SExt:
552 case Instruction::FPToUI:
553 case Instruction::FPToSI:
554 case Instruction::FPExt:
555 case Instruction::PtrToInt:
556 case Instruction::IntToPtr:
557 case Instruction::SIToFP:
558 case Instruction::UIToFP:
559 case Instruction::Trunc:
560 case Instruction::FPTrunc:
561 case Instruction::BitCast: {
562 /// Vectorize bitcasts.
563 CastInst *CI = dyn_cast<CastInst>(Inst);
564 Value *A = getVectorValue(Inst->getOperand(0));
565 Type *DestTy = VectorType::get(CI->getType()->getScalarType(), VF);
566 WidenMap[Inst] = Builder->CreateCast(CI->getOpcode(), A, DestTy);
571 /// All other instructions are unsupported. Scalarize them.
572 scalarizeInstruction(Inst);
575 }// end of for_each instr.
578 void SingleBlockLoopVectorizer::deleteOldLoop() {
579 // The original basic block.
580 BasicBlock *BB = Orig->getHeader();
581 SE->forgetLoop(Orig);
584 Orig->addBasicBlockToLoop(Induction->getParent(), LI->getBase());
586 // Remove the old loop block.
590 unsigned LoopVectorizationLegality::getLoopMaxVF() {
591 if (!TheLoop->getLoopPreheader()) {
592 assert(false && "No preheader!!");
593 DEBUG(dbgs() << "LV: Loop not normalized." << "\n");
597 // We can only vectorize single basic block loops.
598 unsigned NumBlocks = TheLoop->getNumBlocks();
599 if (NumBlocks != 1) {
600 DEBUG(dbgs() << "LV: Too many blocks:" << NumBlocks << "\n");
604 // We need to have a loop header.
605 BasicBlock *BB = TheLoop->getHeader();
606 DEBUG(dbgs() << "LV: Found a loop: " << BB->getName() << "\n");
608 // Find the max vectorization factor.
609 unsigned MaxVF = SE->getSmallConstantTripMultiple(TheLoop, BB);
612 // Perform an early check. Do not scan the block if we did not find a loop.
614 DEBUG(dbgs() << "LV: Can't find a vectorizable loop structure\n");
618 // Go over each instruction and look at memory deps.
619 if (!canVectorizeBlock(*BB)) {
620 DEBUG(dbgs() << "LV: Can't vectorize this loop header\n");
624 DEBUG(dbgs() << "LV: We can vectorize this loop! VF="<<MaxVF<<"\n");
626 // Okay! We can vectorize. Return the max trip multiple.
630 bool LoopVectorizationLegality::canVectorizeBlock(BasicBlock &BB) {
631 // Holds the read and write pointers that we find.
632 typedef SmallVector<Value*, 10> ValueVector;
636 unsigned NumPhis = 0;
637 for (BasicBlock::iterator it = BB.begin(), e = BB.end(); it != e; ++it) {
640 PHINode *Phi = dyn_cast<PHINode>(I);
643 // We only look at integer phi nodes.
644 if (!Phi->getType()->isIntegerTy()) {
645 DEBUG(dbgs() << "LV: Found an non-int PHI.\n");
649 // If we found an induction variable.
651 DEBUG(dbgs() << "LV: Found more than one PHI.\n");
655 // This should not happen because the loop should be normalized.
656 if (Phi->getNumIncomingValues() != 2) {
657 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
661 // Check that the PHI is consecutive and starts at zero.
662 const SCEV *PhiScev = SE->getSCEV(Phi);
663 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
665 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
669 const SCEV *Step = AR->getStepRecurrence(*SE);
670 const SCEV *Start = AR->getStart();
672 if (!Step->isOne() || !Start->isZero()) {
673 DEBUG(dbgs() << "LV: PHI does not start at zero or steps by one.\n");
678 // If this is a load, record its pointer. If it is not a load, abort.
679 // Notice that we don't handle function calls that read or write.
680 if (I->mayReadFromMemory()) {
681 LoadInst *Ld = dyn_cast<LoadInst>(I);
682 if (!Ld) return false;
683 if (!Ld->isSimple()) {
684 DEBUG(dbgs() << "LV: Found a non-simple load.\n");
687 GetUnderlyingObjects(Ld->getPointerOperand(), Reads, DL);
690 // Record store pointers. Abort on all other instructions that write to
692 if (I->mayWriteToMemory()) {
693 StoreInst *St = dyn_cast<StoreInst>(I);
694 if (!St) return false;
695 if (!St->isSimple()) {
696 DEBUG(dbgs() << "LV: Found a non-simple store.\n");
699 GetUnderlyingObjects(St->getPointerOperand(), Writes, DL);
702 // We still don't handle functions.
703 CallInst *CI = dyn_cast<CallInst>(I);
705 DEBUG(dbgs() << "LV: Found a call site:"<<
706 CI->getCalledFunction()->getName() << "\n");
710 // We do not re-vectorize vectors.
711 if (!VectorType::isValidElementType(I->getType()) &&
712 !I->getType()->isVoidTy()) {
713 DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n");
716 //Check that all of the users of the loop are inside the BB.
717 for (Value::use_iterator it = I->use_begin(), e = I->use_end();
719 Instruction *U = cast<Instruction>(*it);
720 BasicBlock *Parent = U->getParent();
722 DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n");
728 // Check that the underlying objects of the reads and writes are either
729 // disjoint memory locations, or that they are no-alias arguments.
730 ValueVector::iterator r, re, w, we;
731 for (r = Reads.begin(), re = Reads.end(); r != re; ++r) {
732 if (!isKnownDisjoint(*r)) {
733 DEBUG(dbgs() << "LV: Found a bad read Ptr: "<< **r << "\n");
738 for (w = Writes.begin(), we = Writes.end(); w != we; ++w) {
739 if (!isKnownDisjoint(*w)) {
740 DEBUG(dbgs() << "LV: Found a bad write Ptr: "<< **w << "\n");
745 // Check that there are no multiple write locations to the same pointer.
746 SmallPtrSet<Value*, 8> BasePointers;
747 for (w = Writes.begin(), we = Writes.end(); w != we; ++w) {
748 if (BasePointers.count(*w)) {
749 DEBUG(dbgs() << "LV: Multiple writes to the same index :"<< **w << "\n");
752 BasePointers.insert(*w);
755 // Sort the writes vector so that we can use a binary search.
756 std::sort(Writes.begin(), Writes.end());
757 // Check that the reads and the writes are disjoint.
758 for (r = Reads.begin(), re = Reads.end(); r != re; ++r) {
759 if (std::binary_search(Writes.begin(), Writes.end(), *r)) {
760 DEBUG(dbgs() << "Vectorizer: Found a read/write ptr:"<< **r << "\n");
769 /// Checks if the value is a Global variable or if it is an Arguments
770 /// marked with the NoAlias attribute.
771 bool LoopVectorizationLegality::isKnownDisjoint(Value* Val) {
772 assert(Val && "Invalid value");
773 if (dyn_cast<GlobalValue>(Val))
775 if (dyn_cast<AllocaInst>(Val))
777 Argument *A = dyn_cast<Argument>(Val);
780 return A->hasNoAliasAttr();
785 char LoopVectorize::ID = 0;
786 static const char lv_name[] = "Loop Vectorization";
787 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
788 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
789 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
790 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
791 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
794 Pass *createLoopVectorizePass() {
795 return new LoopVectorize();