1 //===- SLPVectorizer.cpp - A bottom up SLP 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 // This pass implements the Bottom Up SLP vectorizer. It detects consecutive
10 // stores that can be put together into vector-stores. Next, it attempts to
11 // construct vectorizable tree using the use-def chains. If a profitable tree
12 // was found, the SLP vectorizer performs vectorization on the tree.
14 // The pass is inspired by the work described in the paper:
15 // "Loop-Aware SLP in GCC" by Ira Rosen, Dorit Nuzman, Ayal Zaks.
17 //===----------------------------------------------------------------------===//
18 #define SV_NAME "slp-vectorizer"
19 #define DEBUG_TYPE "SLP"
21 #include "llvm/Transforms/Vectorize.h"
22 #include "llvm/ADT/MapVector.h"
23 #include "llvm/ADT/PostOrderIterator.h"
24 #include "llvm/ADT/SetVector.h"
25 #include "llvm/Analysis/AliasAnalysis.h"
26 #include "llvm/Analysis/ScalarEvolution.h"
27 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
28 #include "llvm/Analysis/AliasAnalysis.h"
29 #include "llvm/Analysis/TargetTransformInfo.h"
30 #include "llvm/Analysis/Verifier.h"
31 #include "llvm/Analysis/LoopInfo.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/Instructions.h"
34 #include "llvm/IR/IntrinsicInst.h"
35 #include "llvm/IR/IRBuilder.h"
36 #include "llvm/IR/Module.h"
37 #include "llvm/IR/Type.h"
38 #include "llvm/IR/Value.h"
39 #include "llvm/Pass.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/raw_ostream.h"
49 SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
50 cl::desc("Only vectorize if you gain more than this "
54 static const unsigned MinVecRegSize = 128;
56 static const unsigned RecursionMaxDepth = 12;
58 /// RAII pattern to save the insertion point of the IR builder.
59 class BuilderLocGuard {
61 BuilderLocGuard(IRBuilder<> &B) : Builder(B), Loc(B.GetInsertPoint()) {}
62 ~BuilderLocGuard() { if (Loc) Builder.SetInsertPoint(Loc); }
66 BuilderLocGuard(const BuilderLocGuard &);
67 BuilderLocGuard &operator=(const BuilderLocGuard &);
69 AssertingVH<Instruction> Loc;
72 /// A helper class for numbering instructions in multible blocks.
73 /// Numbers starts at zero for each basic block.
74 struct BlockNumbering {
76 BlockNumbering(BasicBlock *Bb) : BB(Bb), Valid(false) {}
78 BlockNumbering() : BB(0), Valid(false) {}
80 void numberInstructions() {
84 // Number the instructions in the block.
85 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
87 InstrVec.push_back(it);
88 assert(InstrVec[InstrIdx[it]] == it && "Invalid allocation");
93 int getIndex(Instruction *I) {
94 assert(I->getParent() == BB && "Invalid instruction");
97 assert(InstrIdx.count(I) && "Unknown instruction");
101 Instruction *getInstruction(unsigned loc) {
103 numberInstructions();
104 assert(InstrVec.size() > loc && "Invalid Index");
105 return InstrVec[loc];
108 void forget() { Valid = false; }
111 /// The block we are numbering.
113 /// Is the block numbered.
115 /// Maps instructions to numbers and back.
116 SmallDenseMap<Instruction *, int> InstrIdx;
117 /// Maps integers to Instructions.
118 std::vector<Instruction *> InstrVec;
121 /// \returns the parent basic block if all of the instructions in \p VL
122 /// are in the same block or null otherwise.
123 static BasicBlock *getSameBlock(ArrayRef<Value *> VL) {
124 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
127 BasicBlock *BB = I0->getParent();
128 for (int i = 1, e = VL.size(); i < e; i++) {
129 Instruction *I = dyn_cast<Instruction>(VL[i]);
133 if (BB != I->getParent())
139 /// \returns True if all of the values in \p VL are constants.
140 static bool allConstant(ArrayRef<Value *> VL) {
141 for (unsigned i = 0, e = VL.size(); i < e; ++i)
142 if (!isa<Constant>(VL[i]))
147 /// \returns True if all of the values in \p VL are identical.
148 static bool isSplat(ArrayRef<Value *> VL) {
149 for (unsigned i = 1, e = VL.size(); i < e; ++i)
155 /// \returns The opcode if all of the Instructions in \p VL have the same
157 static unsigned getSameOpcode(ArrayRef<Value *> VL) {
158 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
161 unsigned Opcode = I0->getOpcode();
162 for (int i = 1, e = VL.size(); i < e; i++) {
163 Instruction *I = dyn_cast<Instruction>(VL[i]);
164 if (!I || Opcode != I->getOpcode())
170 /// \returns The type that all of the values in \p VL have or null if there
171 /// are different types.
172 static Type* getSameType(ArrayRef<Value *> VL) {
173 Type *Ty = VL[0]->getType();
174 for (int i = 1, e = VL.size(); i < e; i++)
175 if (VL[i]->getType() != Ty)
181 /// \returns True if the ExtractElement instructions in VL can be vectorized
182 /// to use the original vector.
183 static bool CanReuseExtract(ArrayRef<Value *> VL) {
184 assert(Instruction::ExtractElement == getSameOpcode(VL) && "Invalid opcode");
185 // Check if all of the extracts come from the same vector and from the
188 ExtractElementInst *E0 = cast<ExtractElementInst>(VL0);
189 Value *Vec = E0->getOperand(0);
191 // We have to extract from the same vector type.
192 unsigned NElts = Vec->getType()->getVectorNumElements();
194 if (NElts != VL.size())
197 // Check that all of the indices extract from the correct offset.
198 ConstantInt *CI = dyn_cast<ConstantInt>(E0->getOperand(1));
199 if (!CI || CI->getZExtValue())
202 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
203 ExtractElementInst *E = cast<ExtractElementInst>(VL[i]);
204 ConstantInt *CI = dyn_cast<ConstantInt>(E->getOperand(1));
206 if (!CI || CI->getZExtValue() != i || E->getOperand(0) != Vec)
213 /// Bottom Up SLP Vectorizer.
216 typedef SmallVector<Value *, 8> ValueList;
217 typedef SmallVector<Instruction *, 16> InstrList;
218 typedef SmallPtrSet<Value *, 16> ValueSet;
219 typedef SmallVector<StoreInst *, 8> StoreList;
221 BoUpSLP(Function *Func, ScalarEvolution *Se, DataLayout *Dl,
222 TargetTransformInfo *Tti, AliasAnalysis *Aa, LoopInfo *Li,
224 F(Func), SE(Se), DL(Dl), TTI(Tti), AA(Aa), LI(Li), DT(Dt),
225 Builder(Se->getContext()) {
226 // Setup the block numbering utility for all of the blocks in the
228 for (Function::iterator it = F->begin(), e = F->end(); it != e; ++it) {
230 BlocksNumbers[BB] = BlockNumbering(BB);
234 /// \brief Vectorize the tree that starts with the elements in \p VL.
235 void vectorizeTree();
237 /// \returns the vectorization cost of the subtree that starts at \p VL.
238 /// A negative number means that this is profitable.
241 /// Construct a vectorizable tree that starts at \p Roots.
242 void buildTree(ArrayRef<Value *> Roots);
244 /// Clear the internal data structures that are created by 'buildTree'.
246 VectorizableTree.clear();
247 ScalarToTreeEntry.clear();
249 MemBarrierIgnoreList.clear();
252 /// \returns the scalarization cost for this list of values. Assuming that
253 /// this subtree gets vectorized, we may need to extract the values from the
254 /// roots. This method calculates the cost of extracting the values.
255 int getGatherCost(ArrayRef<Value *> VL);
257 /// \returns true if the memory operations A and B are consecutive.
258 bool isConsecutiveAccess(Value *A, Value *B);
260 /// \brief Perform LICM and CSE on the newly generated gather sequences.
261 void optimizeGatherSequence();
265 /// \returns the cost of the vectorizable entry.
266 int getEntryCost(TreeEntry *E);
268 /// This is the recursive part of buildTree.
269 void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth);
271 /// Vectorizer a single entry in the tree.
272 Value *vectorizeTree(TreeEntry *E);
274 /// Vectorizer a single entry in the tree, starting in \p VL.
275 Value *vectorizeTree(ArrayRef<Value *> VL);
277 /// \brief Take the pointer operand from the Load/Store instruction.
278 /// \returns NULL if this is not a valid Load/Store instruction.
279 static Value *getPointerOperand(Value *I);
281 /// \brief Take the address space operand from the Load/Store instruction.
282 /// \returns -1 if this is not a valid Load/Store instruction.
283 static unsigned getAddressSpaceOperand(Value *I);
285 /// \returns the scalarization cost for this type. Scalarization in this
286 /// context means the creation of vectors from a group of scalars.
287 int getGatherCost(Type *Ty);
289 /// \returns the AA location that is being access by the instruction.
290 AliasAnalysis::Location getLocation(Instruction *I);
292 /// \brief Checks if it is possible to sink an instruction from
293 /// \p Src to \p Dst.
294 /// \returns the pointer to the barrier instruction if we can't sink.
295 Value *getSinkBarrier(Instruction *Src, Instruction *Dst);
297 /// \returns the index of the last instrucion in the BB from \p VL.
298 int getLastIndex(ArrayRef<Value *> VL);
300 /// \returns the Instrucion in the bundle \p VL.
301 Instruction *getLastInstruction(ArrayRef<Value *> VL);
303 /// \returns the Instruction at index \p Index which is in Block \p BB.
304 Instruction *getInstructionForIndex(unsigned Index, BasicBlock *BB);
306 /// \returns the index of the first User of \p VL.
307 int getFirstUserIndex(ArrayRef<Value *> VL);
309 /// \returns a vector from a collection of scalars in \p VL.
310 Value *Gather(ArrayRef<Value *> VL, VectorType *Ty);
313 TreeEntry() : Scalars(), VectorizedValue(0), LastScalarIndex(0),
316 /// \returns true if the scalars in VL are equal to this entry.
317 bool isSame(ArrayRef<Value *> VL) {
318 assert(VL.size() == Scalars.size() && "Invalid size");
319 for (int i = 0, e = VL.size(); i != e; ++i)
320 if (VL[i] != Scalars[i])
325 /// A vector of scalars.
328 /// The Scalars are vectorized into this value. It is initialized to Null.
329 Value *VectorizedValue;
331 /// The index in the basic block of the last scalar.
334 /// Do we need to gather this sequence ?
338 /// Create a new VectorizableTree entry.
339 TreeEntry *newTreeEntry(ArrayRef<Value *> VL, bool Vectorized) {
340 VectorizableTree.push_back(TreeEntry());
341 int idx = VectorizableTree.size() - 1;
342 TreeEntry *Last = &VectorizableTree[idx];
343 Last->Scalars.insert(Last->Scalars.begin(), VL.begin(), VL.end());
344 Last->NeedToGather = !Vectorized;
346 Last->LastScalarIndex = getLastIndex(VL);
347 for (int i = 0, e = VL.size(); i != e; ++i) {
348 assert(!ScalarToTreeEntry.count(VL[i]) && "Scalar already in tree!");
349 ScalarToTreeEntry[VL[i]] = idx;
352 Last->LastScalarIndex = 0;
353 MustGather.insert(VL.begin(), VL.end());
358 /// -- Vectorization State --
359 /// Holds all of the tree entries.
360 std::vector<TreeEntry> VectorizableTree;
362 /// Maps a specific scalar to its tree entry.
363 SmallDenseMap<Value*, int> ScalarToTreeEntry;
365 /// A list of scalars that we found that we need to keep as scalars.
368 /// A list of instructions to ignore while sinking
369 /// memory instructions. This map must be reset between runs of getCost.
370 ValueSet MemBarrierIgnoreList;
372 /// Holds all of the instructions that we gathered.
373 SetVector<Instruction *> GatherSeq;
375 /// Numbers instructions in different blocks.
376 std::map<BasicBlock *, BlockNumbering> BlocksNumbers;
378 // Analysis and block reference.
382 TargetTransformInfo *TTI;
386 /// Instruction builder to construct the vectorized tree.
390 void BoUpSLP::buildTree(ArrayRef<Value *> Roots) {
392 if (!getSameType(Roots))
394 buildTree_rec(Roots, 0);
398 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth) {
399 bool SameTy = getSameType(VL); (void)SameTy;
400 assert(SameTy && "Invalid types!");
402 if (Depth == RecursionMaxDepth) {
403 DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
404 newTreeEntry(VL, false);
408 // Don't handle vectors.
409 if (VL[0]->getType()->isVectorTy()) {
410 DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
411 newTreeEntry(VL, false);
415 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
416 if (SI->getValueOperand()->getType()->isVectorTy()) {
417 DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
418 newTreeEntry(VL, false);
422 // If all of the operands are identical or constant we have a simple solution.
423 if (allConstant(VL) || isSplat(VL) || !getSameBlock(VL) ||
424 !getSameOpcode(VL)) {
425 DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
426 newTreeEntry(VL, false);
430 // We now know that this is a vector of instructions of the same type from
433 // Check if this is a duplicate of another entry.
434 if (ScalarToTreeEntry.count(VL[0])) {
435 int Idx = ScalarToTreeEntry[VL[0]];
436 TreeEntry *E = &VectorizableTree[Idx];
437 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
438 DEBUG(dbgs() << "SLP: \tChecking bundle: " << *VL[i] << ".\n");
439 if (E->Scalars[i] != VL[i]) {
440 DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
441 newTreeEntry(VL, false);
445 DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *VL[0] << ".\n");
449 // Check that none of the instructions in the bundle are already in the tree.
450 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
451 if (ScalarToTreeEntry.count(VL[i])) {
452 DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
453 ") is already in tree.\n");
454 newTreeEntry(VL, false);
459 // If any of the scalars appears in the table OR it is marked as a value that
460 // needs to stat scalar then we need to gather the scalars.
461 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
462 if (ScalarToTreeEntry.count(VL[i]) || MustGather.count(VL[i])) {
463 DEBUG(dbgs() << "SLP: Gathering due to gathered scalar. \n");
464 newTreeEntry(VL, false);
469 // Check that all of the users of the scalars that we want to vectorize are
471 Instruction *VL0 = cast<Instruction>(VL[0]);
472 int MyLastIndex = getLastIndex(VL);
473 BasicBlock *BB = cast<Instruction>(VL0)->getParent();
475 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
476 Instruction *Scalar = cast<Instruction>(VL[i]);
477 DEBUG(dbgs() << "SLP: Checking users of " << *Scalar << ". \n");
478 for (Value::use_iterator U = Scalar->use_begin(), UE = Scalar->use_end();
480 DEBUG(dbgs() << "SLP: \tUser " << **U << ". \n");
481 Instruction *User = dyn_cast<Instruction>(*U);
483 DEBUG(dbgs() << "SLP: Gathering due unknown user. \n");
484 newTreeEntry(VL, false);
488 // We don't care if the user is in a different basic block.
489 BasicBlock *UserBlock = User->getParent();
490 if (UserBlock != BB) {
491 DEBUG(dbgs() << "SLP: User from a different basic block "
496 // If this is a PHINode within this basic block then we can place the
497 // extract wherever we want.
498 if (isa<PHINode>(*User)) {
499 DEBUG(dbgs() << "SLP: \tWe can schedule PHIs:" << *User << ". \n");
503 // Check if this is a safe in-tree user.
504 if (ScalarToTreeEntry.count(User)) {
505 int Idx = ScalarToTreeEntry[User];
506 int VecLocation = VectorizableTree[Idx].LastScalarIndex;
507 if (VecLocation <= MyLastIndex) {
508 DEBUG(dbgs() << "SLP: Gathering due to unschedulable vector. \n");
509 newTreeEntry(VL, false);
512 DEBUG(dbgs() << "SLP: In-tree user (" << *User << ") at #" <<
513 VecLocation << " vector value (" << *Scalar << ") at #"
514 << MyLastIndex << ".\n");
518 // Make sure that we can schedule this unknown user.
519 BlockNumbering &BN = BlocksNumbers[BB];
520 int UserIndex = BN.getIndex(User);
521 if (UserIndex < MyLastIndex) {
523 DEBUG(dbgs() << "SLP: Can't schedule extractelement for "
525 newTreeEntry(VL, false);
531 // Check that every instructions appears once in this bundle.
532 for (unsigned i = 0, e = VL.size(); i < e; ++i)
533 for (unsigned j = i+1; j < e; ++j)
534 if (VL[i] == VL[j]) {
535 DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
536 newTreeEntry(VL, false);
540 // Check that instructions in this bundle don't reference other instructions.
541 // The runtime of this check is O(N * N-1 * uses(N)) and a typical N is 4.
542 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
543 for (Value::use_iterator U = VL[i]->use_begin(), UE = VL[i]->use_end();
545 for (unsigned j = 0; j < e; ++j) {
546 if (i != j && *U == VL[j]) {
547 DEBUG(dbgs() << "SLP: Intra-bundle dependencies!" << **U << ". \n");
548 newTreeEntry(VL, false);
555 DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
557 unsigned Opcode = getSameOpcode(VL);
559 // Check if it is safe to sink the loads or the stores.
560 if (Opcode == Instruction::Load || Opcode == Instruction::Store) {
561 Instruction *Last = getLastInstruction(VL);
563 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
566 Value *Barrier = getSinkBarrier(cast<Instruction>(VL[i]), Last);
568 DEBUG(dbgs() << "SLP: Can't sink " << *VL[i] << "\n down to " << *Last
569 << "\n because of " << *Barrier << ". Gathering.\n");
570 newTreeEntry(VL, false);
577 case Instruction::PHI: {
578 PHINode *PH = dyn_cast<PHINode>(VL0);
579 newTreeEntry(VL, true);
580 DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
582 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
584 // Prepare the operand vector.
585 for (unsigned j = 0; j < VL.size(); ++j)
586 Operands.push_back(cast<PHINode>(VL[j])->getIncomingValue(i));
588 buildTree_rec(Operands, Depth + 1);
592 case Instruction::ExtractElement: {
593 bool Reuse = CanReuseExtract(VL);
595 DEBUG(dbgs() << "SLP: Reusing extract sequence.\n");
597 newTreeEntry(VL, Reuse);
600 case Instruction::Load: {
601 // Check if the loads are consecutive or of we need to swizzle them.
602 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
603 if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
604 newTreeEntry(VL, false);
605 DEBUG(dbgs() << "SLP: Need to swizzle loads.\n");
609 newTreeEntry(VL, true);
610 DEBUG(dbgs() << "SLP: added a vector of loads.\n");
613 case Instruction::ZExt:
614 case Instruction::SExt:
615 case Instruction::FPToUI:
616 case Instruction::FPToSI:
617 case Instruction::FPExt:
618 case Instruction::PtrToInt:
619 case Instruction::IntToPtr:
620 case Instruction::SIToFP:
621 case Instruction::UIToFP:
622 case Instruction::Trunc:
623 case Instruction::FPTrunc:
624 case Instruction::BitCast: {
625 Type *SrcTy = VL0->getOperand(0)->getType();
626 for (unsigned i = 0; i < VL.size(); ++i) {
627 Type *Ty = cast<Instruction>(VL[i])->getOperand(0)->getType();
628 if (Ty != SrcTy || Ty->isAggregateType() || Ty->isVectorTy()) {
629 newTreeEntry(VL, false);
630 DEBUG(dbgs() << "SLP: Gathering casts with different src types.\n");
634 newTreeEntry(VL, true);
635 DEBUG(dbgs() << "SLP: added a vector of casts.\n");
637 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
639 // Prepare the operand vector.
640 for (unsigned j = 0; j < VL.size(); ++j)
641 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
643 buildTree_rec(Operands, Depth+1);
647 case Instruction::ICmp:
648 case Instruction::FCmp: {
649 // Check that all of the compares have the same predicate.
650 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
651 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
652 CmpInst *Cmp = cast<CmpInst>(VL[i]);
653 if (Cmp->getPredicate() != P0) {
654 newTreeEntry(VL, false);
655 DEBUG(dbgs() << "SLP: Gathering cmp with different predicate.\n");
660 newTreeEntry(VL, true);
661 DEBUG(dbgs() << "SLP: added a vector of compares.\n");
663 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
665 // Prepare the operand vector.
666 for (unsigned j = 0; j < VL.size(); ++j)
667 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
669 buildTree_rec(Operands, Depth+1);
673 case Instruction::Select:
674 case Instruction::Add:
675 case Instruction::FAdd:
676 case Instruction::Sub:
677 case Instruction::FSub:
678 case Instruction::Mul:
679 case Instruction::FMul:
680 case Instruction::UDiv:
681 case Instruction::SDiv:
682 case Instruction::FDiv:
683 case Instruction::URem:
684 case Instruction::SRem:
685 case Instruction::FRem:
686 case Instruction::Shl:
687 case Instruction::LShr:
688 case Instruction::AShr:
689 case Instruction::And:
690 case Instruction::Or:
691 case Instruction::Xor: {
692 newTreeEntry(VL, true);
693 DEBUG(dbgs() << "SLP: added a vector of bin op.\n");
695 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
697 // Prepare the operand vector.
698 for (unsigned j = 0; j < VL.size(); ++j)
699 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
701 buildTree_rec(Operands, Depth+1);
705 case Instruction::Store: {
706 // Check if the stores are consecutive or of we need to swizzle them.
707 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
708 if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
709 newTreeEntry(VL, false);
710 DEBUG(dbgs() << "SLP: Non consecutive store.\n");
714 newTreeEntry(VL, true);
715 DEBUG(dbgs() << "SLP: added a vector of stores.\n");
718 for (unsigned j = 0; j < VL.size(); ++j)
719 Operands.push_back(cast<Instruction>(VL[j])->getOperand(0));
721 // We can ignore these values because we are sinking them down.
722 MemBarrierIgnoreList.insert(VL.begin(), VL.end());
723 buildTree_rec(Operands, Depth + 1);
727 newTreeEntry(VL, false);
728 DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
733 int BoUpSLP::getEntryCost(TreeEntry *E) {
734 ArrayRef<Value*> VL = E->Scalars;
736 Type *ScalarTy = VL[0]->getType();
737 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
738 ScalarTy = SI->getValueOperand()->getType();
739 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
741 if (E->NeedToGather) {
745 return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
747 return getGatherCost(E->Scalars);
750 assert(getSameOpcode(VL) && getSameType(VL) && getSameBlock(VL) &&
752 Instruction *VL0 = cast<Instruction>(VL[0]);
753 unsigned Opcode = VL0->getOpcode();
755 case Instruction::PHI: {
758 case Instruction::ExtractElement: {
759 if (CanReuseExtract(VL))
761 return getGatherCost(VecTy);
763 case Instruction::ZExt:
764 case Instruction::SExt:
765 case Instruction::FPToUI:
766 case Instruction::FPToSI:
767 case Instruction::FPExt:
768 case Instruction::PtrToInt:
769 case Instruction::IntToPtr:
770 case Instruction::SIToFP:
771 case Instruction::UIToFP:
772 case Instruction::Trunc:
773 case Instruction::FPTrunc:
774 case Instruction::BitCast: {
775 Type *SrcTy = VL0->getOperand(0)->getType();
777 // Calculate the cost of this instruction.
778 int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(),
779 VL0->getType(), SrcTy);
781 VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
782 int VecCost = TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy);
783 return VecCost - ScalarCost;
785 case Instruction::FCmp:
786 case Instruction::ICmp:
787 case Instruction::Select:
788 case Instruction::Add:
789 case Instruction::FAdd:
790 case Instruction::Sub:
791 case Instruction::FSub:
792 case Instruction::Mul:
793 case Instruction::FMul:
794 case Instruction::UDiv:
795 case Instruction::SDiv:
796 case Instruction::FDiv:
797 case Instruction::URem:
798 case Instruction::SRem:
799 case Instruction::FRem:
800 case Instruction::Shl:
801 case Instruction::LShr:
802 case Instruction::AShr:
803 case Instruction::And:
804 case Instruction::Or:
805 case Instruction::Xor: {
806 // Calculate the cost of this instruction.
809 if (Opcode == Instruction::FCmp || Opcode == Instruction::ICmp ||
810 Opcode == Instruction::Select) {
811 VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
812 ScalarCost = VecTy->getNumElements() *
813 TTI->getCmpSelInstrCost(Opcode, ScalarTy, Builder.getInt1Ty());
814 VecCost = TTI->getCmpSelInstrCost(Opcode, VecTy, MaskTy);
816 ScalarCost = VecTy->getNumElements() *
817 TTI->getArithmeticInstrCost(Opcode, ScalarTy);
818 VecCost = TTI->getArithmeticInstrCost(Opcode, VecTy);
820 return VecCost - ScalarCost;
822 case Instruction::Load: {
823 // Cost of wide load - cost of scalar loads.
824 int ScalarLdCost = VecTy->getNumElements() *
825 TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
826 int VecLdCost = TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
827 return VecLdCost - ScalarLdCost;
829 case Instruction::Store: {
830 // We know that we can merge the stores. Calculate the cost.
831 int ScalarStCost = VecTy->getNumElements() *
832 TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
833 int VecStCost = TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
834 return VecStCost - ScalarStCost;
837 llvm_unreachable("Unknown instruction");
841 int BoUpSLP::getTreeCost() {
843 DEBUG(dbgs() << "SLP: Calculating cost for tree of size " <<
844 VectorizableTree.size() << ".\n");
846 for (unsigned i = 0, e = VectorizableTree.size(); i != e; ++i) {
847 int C = getEntryCost(&VectorizableTree[i]);
848 DEBUG(dbgs() << "SLP: Adding cost " << C << " for bundle that starts with "
849 << *VectorizableTree[i].Scalars[0] << " .\n");
852 DEBUG(dbgs() << "SLP: Total Cost " << Cost << ".\n");
856 int BoUpSLP::getGatherCost(Type *Ty) {
858 for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
859 Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
863 int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) {
864 // Find the type of the operands in VL.
865 Type *ScalarTy = VL[0]->getType();
866 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
867 ScalarTy = SI->getValueOperand()->getType();
868 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
869 // Find the cost of inserting/extracting values from the vector.
870 return getGatherCost(VecTy);
873 AliasAnalysis::Location BoUpSLP::getLocation(Instruction *I) {
874 if (StoreInst *SI = dyn_cast<StoreInst>(I))
875 return AA->getLocation(SI);
876 if (LoadInst *LI = dyn_cast<LoadInst>(I))
877 return AA->getLocation(LI);
878 return AliasAnalysis::Location();
881 Value *BoUpSLP::getPointerOperand(Value *I) {
882 if (LoadInst *LI = dyn_cast<LoadInst>(I))
883 return LI->getPointerOperand();
884 if (StoreInst *SI = dyn_cast<StoreInst>(I))
885 return SI->getPointerOperand();
889 unsigned BoUpSLP::getAddressSpaceOperand(Value *I) {
890 if (LoadInst *L = dyn_cast<LoadInst>(I))
891 return L->getPointerAddressSpace();
892 if (StoreInst *S = dyn_cast<StoreInst>(I))
893 return S->getPointerAddressSpace();
897 bool BoUpSLP::isConsecutiveAccess(Value *A, Value *B) {
898 Value *PtrA = getPointerOperand(A);
899 Value *PtrB = getPointerOperand(B);
900 unsigned ASA = getAddressSpaceOperand(A);
901 unsigned ASB = getAddressSpaceOperand(B);
903 // Check that the address spaces match and that the pointers are valid.
904 if (!PtrA || !PtrB || (ASA != ASB))
907 // Check that A and B are of the same type.
908 if (PtrA->getType() != PtrB->getType())
911 // Calculate the distance.
912 const SCEV *PtrSCEVA = SE->getSCEV(PtrA);
913 const SCEV *PtrSCEVB = SE->getSCEV(PtrB);
914 const SCEV *OffsetSCEV = SE->getMinusSCEV(PtrSCEVA, PtrSCEVB);
915 const SCEVConstant *ConstOffSCEV = dyn_cast<SCEVConstant>(OffsetSCEV);
917 // Non constant distance.
921 int64_t Offset = ConstOffSCEV->getValue()->getSExtValue();
922 Type *Ty = cast<PointerType>(PtrA->getType())->getElementType();
923 // The Instructions are connsecutive if the size of the first load/store is
924 // the same as the offset.
925 int64_t Sz = DL->getTypeStoreSize(Ty);
926 return ((-Offset) == Sz);
929 Value *BoUpSLP::getSinkBarrier(Instruction *Src, Instruction *Dst) {
930 assert(Src->getParent() == Dst->getParent() && "Not the same BB");
931 BasicBlock::iterator I = Src, E = Dst;
932 /// Scan all of the instruction from SRC to DST and check if
933 /// the source may alias.
934 for (++I; I != E; ++I) {
935 // Ignore store instructions that are marked as 'ignore'.
936 if (MemBarrierIgnoreList.count(I))
938 if (Src->mayWriteToMemory()) /* Write */ {
939 if (!I->mayReadOrWriteMemory())
942 if (!I->mayWriteToMemory())
945 AliasAnalysis::Location A = getLocation(&*I);
946 AliasAnalysis::Location B = getLocation(Src);
948 if (!A.Ptr || !B.Ptr || AA->alias(A, B))
954 int BoUpSLP::getLastIndex(ArrayRef<Value *> VL) {
955 BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
956 assert(BB == getSameBlock(VL) && BlocksNumbers.count(BB) && "Invalid block");
957 BlockNumbering &BN = BlocksNumbers[BB];
959 int MaxIdx = BN.getIndex(BB->getFirstNonPHI());
960 for (unsigned i = 0, e = VL.size(); i < e; ++i)
961 MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
965 Instruction *BoUpSLP::getLastInstruction(ArrayRef<Value *> VL) {
966 BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
967 assert(BB == getSameBlock(VL) && BlocksNumbers.count(BB) && "Invalid block");
968 BlockNumbering &BN = BlocksNumbers[BB];
970 int MaxIdx = BN.getIndex(cast<Instruction>(VL[0]));
971 for (unsigned i = 1, e = VL.size(); i < e; ++i)
972 MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
973 Instruction *I = BN.getInstruction(MaxIdx);
974 assert(I && "bad location");
978 Instruction *BoUpSLP::getInstructionForIndex(unsigned Index, BasicBlock *BB) {
979 BlockNumbering &BN = BlocksNumbers[BB];
980 return BN.getInstruction(Index);
983 int BoUpSLP::getFirstUserIndex(ArrayRef<Value *> VL) {
984 BasicBlock *BB = getSameBlock(VL);
985 assert(BB && "All instructions must come from the same block");
986 BlockNumbering &BN = BlocksNumbers[BB];
988 // Find the first user of the values.
989 int FirstUser = BN.getIndex(BB->getTerminator());
990 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
991 for (Value::use_iterator U = VL[i]->use_begin(), UE = VL[i]->use_end();
993 Instruction *Instr = dyn_cast<Instruction>(*U);
995 if (!Instr || Instr->getParent() != BB)
998 FirstUser = std::min(FirstUser, BN.getIndex(Instr));
1004 Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
1005 Value *Vec = UndefValue::get(Ty);
1006 // Generate the 'InsertElement' instruction.
1007 for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
1008 Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
1009 if (Instruction *I = dyn_cast<Instruction>(Vec))
1010 GatherSeq.insert(I);
1016 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
1017 if (ScalarToTreeEntry.count(VL[0])) {
1018 int Idx = ScalarToTreeEntry[VL[0]];
1019 TreeEntry *E = &VectorizableTree[Idx];
1021 return vectorizeTree(E);
1024 Type *ScalarTy = VL[0]->getType();
1025 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1026 ScalarTy = SI->getValueOperand()->getType();
1027 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1029 return Gather(VL, VecTy);
1032 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
1033 BuilderLocGuard Guard(Builder);
1035 if (E->VectorizedValue) {
1036 DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
1037 return E->VectorizedValue;
1040 Type *ScalarTy = E->Scalars[0]->getType();
1041 if (StoreInst *SI = dyn_cast<StoreInst>(E->Scalars[0]))
1042 ScalarTy = SI->getValueOperand()->getType();
1043 VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size());
1045 if (E->NeedToGather) {
1046 return Gather(E->Scalars, VecTy);
1049 Instruction *VL0 = cast<Instruction>(E->Scalars[0]);
1050 unsigned Opcode = VL0->getOpcode();
1051 assert(Opcode == getSameOpcode(E->Scalars) && "Invalid opcode");
1054 case Instruction::PHI: {
1055 PHINode *PH = dyn_cast<PHINode>(VL0);
1056 Builder.SetInsertPoint(PH->getParent()->getFirstInsertionPt());
1057 PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
1058 E->VectorizedValue = NewPhi;
1060 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1062 BasicBlock *IBB = PH->getIncomingBlock(i);
1064 // Prepare the operand vector.
1065 for (unsigned j = 0; j < E->Scalars.size(); ++j)
1066 Operands.push_back(cast<PHINode>(E->Scalars[j])->
1067 getIncomingValueForBlock(IBB));
1069 Builder.SetInsertPoint(IBB->getTerminator());
1070 Value *Vec = vectorizeTree(Operands);
1071 NewPhi->addIncoming(Vec, IBB);
1074 assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
1075 "Invalid number of incoming values");
1079 case Instruction::ExtractElement: {
1080 if (CanReuseExtract(E->Scalars)) {
1081 Value *V = VL0->getOperand(0);
1082 E->VectorizedValue = V;
1085 return Gather(E->Scalars, VecTy);
1087 case Instruction::ZExt:
1088 case Instruction::SExt:
1089 case Instruction::FPToUI:
1090 case Instruction::FPToSI:
1091 case Instruction::FPExt:
1092 case Instruction::PtrToInt:
1093 case Instruction::IntToPtr:
1094 case Instruction::SIToFP:
1095 case Instruction::UIToFP:
1096 case Instruction::Trunc:
1097 case Instruction::FPTrunc:
1098 case Instruction::BitCast: {
1100 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1101 INVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1103 Builder.SetInsertPoint(getLastInstruction(E->Scalars));
1104 Value *InVec = vectorizeTree(INVL);
1105 CastInst *CI = dyn_cast<CastInst>(VL0);
1106 Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
1107 E->VectorizedValue = V;
1110 case Instruction::FCmp:
1111 case Instruction::ICmp: {
1112 ValueList LHSV, RHSV;
1113 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1114 LHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1115 RHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1118 Builder.SetInsertPoint(getLastInstruction(E->Scalars));
1119 Value *L = vectorizeTree(LHSV);
1120 Value *R = vectorizeTree(RHSV);
1123 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
1124 if (Opcode == Instruction::FCmp)
1125 V = Builder.CreateFCmp(P0, L, R);
1127 V = Builder.CreateICmp(P0, L, R);
1129 E->VectorizedValue = V;
1132 case Instruction::Select: {
1133 ValueList TrueVec, FalseVec, CondVec;
1134 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1135 CondVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1136 TrueVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1137 FalseVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(2));
1140 Builder.SetInsertPoint(getLastInstruction(E->Scalars));
1141 Value *Cond = vectorizeTree(CondVec);
1142 Value *True = vectorizeTree(TrueVec);
1143 Value *False = vectorizeTree(FalseVec);
1144 Value *V = Builder.CreateSelect(Cond, True, False);
1145 E->VectorizedValue = V;
1148 case Instruction::Add:
1149 case Instruction::FAdd:
1150 case Instruction::Sub:
1151 case Instruction::FSub:
1152 case Instruction::Mul:
1153 case Instruction::FMul:
1154 case Instruction::UDiv:
1155 case Instruction::SDiv:
1156 case Instruction::FDiv:
1157 case Instruction::URem:
1158 case Instruction::SRem:
1159 case Instruction::FRem:
1160 case Instruction::Shl:
1161 case Instruction::LShr:
1162 case Instruction::AShr:
1163 case Instruction::And:
1164 case Instruction::Or:
1165 case Instruction::Xor: {
1166 ValueList LHSVL, RHSVL;
1167 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1168 LHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1169 RHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1172 Builder.SetInsertPoint(getLastInstruction(E->Scalars));
1173 Value *LHS = vectorizeTree(LHSVL);
1174 Value *RHS = vectorizeTree(RHSVL);
1176 if (LHS == RHS && isa<Instruction>(LHS)) {
1177 assert((VL0->getOperand(0) == VL0->getOperand(1)) && "Invalid order");
1180 BinaryOperator *BinOp = cast<BinaryOperator>(VL0);
1181 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), LHS, RHS);
1182 E->VectorizedValue = V;
1185 case Instruction::Load: {
1186 // Loads are inserted at the head of the tree because we don't want to
1187 // sink them all the way down past store instructions.
1188 Builder.SetInsertPoint(getLastInstruction(E->Scalars));
1189 LoadInst *LI = cast<LoadInst>(VL0);
1191 Builder.CreateBitCast(LI->getPointerOperand(), VecTy->getPointerTo());
1192 unsigned Alignment = LI->getAlignment();
1193 LI = Builder.CreateLoad(VecPtr);
1194 LI->setAlignment(Alignment);
1195 E->VectorizedValue = LI;
1198 case Instruction::Store: {
1199 StoreInst *SI = cast<StoreInst>(VL0);
1200 unsigned Alignment = SI->getAlignment();
1203 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1204 ValueOp.push_back(cast<StoreInst>(E->Scalars[i])->getValueOperand());
1206 Builder.SetInsertPoint(getLastInstruction(E->Scalars));
1207 Value *VecValue = vectorizeTree(ValueOp);
1209 Builder.CreateBitCast(SI->getPointerOperand(), VecTy->getPointerTo());
1210 StoreInst *S = Builder.CreateStore(VecValue, VecPtr);
1211 S->setAlignment(Alignment);
1212 E->VectorizedValue = S;
1216 llvm_unreachable("unknown inst");
1221 void BoUpSLP::vectorizeTree() {
1222 Builder.SetInsertPoint(F->getEntryBlock().begin());
1223 vectorizeTree(&VectorizableTree[0]);
1225 // For each vectorized value:
1226 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
1227 TreeEntry *Entry = &VectorizableTree[EIdx];
1230 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
1231 Value *Scalar = Entry->Scalars[Lane];
1233 // No need to handle users of gathered values.
1234 if (Entry->NeedToGather)
1237 Value *Vec = Entry->VectorizedValue;
1238 assert(Vec && "Can't find vectorizable value");
1240 SmallVector<User*, 16> Users(Scalar->use_begin(), Scalar->use_end());
1242 for (SmallVector<User*, 16>::iterator User = Users.begin(),
1243 UE = Users.end(); User != UE; ++User) {
1244 DEBUG(dbgs() << "SLP: \tupdating user " << **User << ".\n");
1246 bool Gathered = MustGather.count(*User);
1248 // Skip in-tree scalars that become vectors.
1249 if (ScalarToTreeEntry.count(*User) && !Gathered) {
1250 DEBUG(dbgs() << "SLP: \tUser will be removed soon:" <<
1252 int Idx = ScalarToTreeEntry[*User]; (void) Idx;
1253 assert(!VectorizableTree[Idx].NeedToGather && "bad state ?");
1257 if (!isa<Instruction>(*User))
1260 // Generate extracts for out-of-tree users.
1261 // Find the insertion point for the extractelement lane.
1262 Instruction *Loc = 0;
1263 if (PHINode *PN = dyn_cast<PHINode>(Vec)) {
1264 Loc = PN->getParent()->getFirstInsertionPt();
1265 } else if (Instruction *Iv = dyn_cast<Instruction>(Vec)){
1266 Loc = ++((BasicBlock::iterator)*Iv);
1268 Loc = F->getEntryBlock().begin();
1271 Builder.SetInsertPoint(Loc);
1272 Value *Ex = Builder.CreateExtractElement(Vec, Builder.getInt32(Lane));
1273 (*User)->replaceUsesOfWith(Scalar, Ex);
1274 DEBUG(dbgs() << "SLP: \tupdated user:" << **User << ".\n");
1277 Type *Ty = Scalar->getType();
1278 if (!Ty->isVoidTy()) {
1279 for (Value::use_iterator User = Scalar->use_begin(), UE = Scalar->use_end();
1280 User != UE; ++User) {
1281 DEBUG(dbgs() << "SLP: \tvalidating user:" << **User << ".\n");
1282 assert(!MustGather.count(*User) &&
1283 "Replacing gathered value with undef");
1284 assert(ScalarToTreeEntry.count(*User) &&
1285 "Replacing out-of-tree value with undef");
1287 Value *Undef = UndefValue::get(Ty);
1288 Scalar->replaceAllUsesWith(Undef);
1290 DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
1291 cast<Instruction>(Scalar)->eraseFromParent();
1295 for (Function::iterator it = F->begin(), e = F->end(); it != e; ++it) {
1296 BlocksNumbers[it].forget();
1298 Builder.ClearInsertionPoint();
1301 void BoUpSLP::optimizeGatherSequence() {
1302 DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
1303 << " gather sequences instructions.\n");
1304 // LICM InsertElementInst sequences.
1305 for (SetVector<Instruction *>::iterator it = GatherSeq.begin(),
1306 e = GatherSeq.end(); it != e; ++it) {
1307 InsertElementInst *Insert = dyn_cast<InsertElementInst>(*it);
1312 // Check if this block is inside a loop.
1313 Loop *L = LI->getLoopFor(Insert->getParent());
1317 // Check if it has a preheader.
1318 BasicBlock *PreHeader = L->getLoopPreheader();
1322 // If the vector or the element that we insert into it are
1323 // instructions that are defined in this basic block then we can't
1324 // hoist this instruction.
1325 Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
1326 Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
1327 if (CurrVec && L->contains(CurrVec))
1329 if (NewElem && L->contains(NewElem))
1332 // We can hoist this instruction. Move it to the pre-header.
1333 Insert->moveBefore(PreHeader->getTerminator());
1336 // Perform O(N^2) search over the gather sequences and merge identical
1337 // instructions. TODO: We can further optimize this scan if we split the
1338 // instructions into different buckets based on the insert lane.
1339 SmallPtrSet<Instruction*, 16> Visited;
1340 SmallVector<Instruction*, 16> ToRemove;
1341 ReversePostOrderTraversal<Function*> RPOT(F);
1342 for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
1343 E = RPOT.end(); I != E; ++I) {
1344 BasicBlock *BB = *I;
1345 // For all instructions in the function:
1346 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1347 InsertElementInst *Insert = dyn_cast<InsertElementInst>(it);
1348 if (!Insert || !GatherSeq.count(Insert))
1351 // Check if we can replace this instruction with any of the
1352 // visited instructions.
1353 for (SmallPtrSet<Instruction*, 16>::iterator v = Visited.begin(),
1354 ve = Visited.end(); v != ve; ++v) {
1355 if (Insert->isIdenticalTo(*v) &&
1356 DT->dominates((*v)->getParent(), Insert->getParent())) {
1357 Insert->replaceAllUsesWith(*v);
1358 ToRemove.push_back(Insert);
1364 Visited.insert(Insert);
1368 // Erase all of the instructions that we RAUWed.
1369 for (SmallVectorImpl<Instruction *>::iterator v = ToRemove.begin(),
1370 ve = ToRemove.end(); v != ve; ++v) {
1371 assert((*v)->getNumUses() == 0 && "Can't remove instructions with uses");
1372 (*v)->eraseFromParent();
1376 /// The SLPVectorizer Pass.
1377 struct SLPVectorizer : public FunctionPass {
1378 typedef SmallVector<StoreInst *, 8> StoreList;
1379 typedef MapVector<Value *, StoreList> StoreListMap;
1381 /// Pass identification, replacement for typeid
1384 explicit SLPVectorizer() : FunctionPass(ID) {
1385 initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
1388 ScalarEvolution *SE;
1390 TargetTransformInfo *TTI;
1395 virtual bool runOnFunction(Function &F) {
1396 SE = &getAnalysis<ScalarEvolution>();
1397 DL = getAnalysisIfAvailable<DataLayout>();
1398 TTI = &getAnalysis<TargetTransformInfo>();
1399 AA = &getAnalysis<AliasAnalysis>();
1400 LI = &getAnalysis<LoopInfo>();
1401 DT = &getAnalysis<DominatorTree>();
1404 bool Changed = false;
1406 // Must have DataLayout. We can't require it because some tests run w/o
1411 DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
1413 // Use the bollom up slp vectorizer to construct chains that start with
1414 // he store instructions.
1415 BoUpSLP R(&F, SE, DL, TTI, AA, LI, DT);
1417 // Scan the blocks in the function in post order.
1418 for (po_iterator<BasicBlock*> it = po_begin(&F.getEntryBlock()),
1419 e = po_end(&F.getEntryBlock()); it != e; ++it) {
1420 BasicBlock *BB = *it;
1422 // Vectorize trees that end at reductions.
1423 Changed |= vectorizeChainsInBlock(BB, R);
1425 // Vectorize trees that end at stores.
1426 if (unsigned count = collectStores(BB, R)) {
1428 DEBUG(dbgs() << "SLP: Found " << count << " stores to vectorize.\n");
1429 Changed |= vectorizeStoreChains(R);
1434 R.optimizeGatherSequence();
1435 DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
1436 DEBUG(verifyFunction(F));
1441 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1442 FunctionPass::getAnalysisUsage(AU);
1443 AU.addRequired<ScalarEvolution>();
1444 AU.addRequired<AliasAnalysis>();
1445 AU.addRequired<TargetTransformInfo>();
1446 AU.addRequired<LoopInfo>();
1447 AU.addRequired<DominatorTree>();
1448 AU.addPreserved<LoopInfo>();
1449 AU.addPreserved<DominatorTree>();
1450 AU.setPreservesCFG();
1455 /// \brief Collect memory references and sort them according to their base
1456 /// object. We sort the stores to their base objects to reduce the cost of the
1457 /// quadratic search on the stores. TODO: We can further reduce this cost
1458 /// if we flush the chain creation every time we run into a memory barrier.
1459 unsigned collectStores(BasicBlock *BB, BoUpSLP &R);
1461 /// \brief Try to vectorize a chain that starts at two arithmetic instrs.
1462 bool tryToVectorizePair(Value *A, Value *B, BoUpSLP &R);
1464 /// \brief Try to vectorize a list of operands. If \p NeedExtracts is true
1465 /// then we calculate the cost of extracting the scalars from the vector.
1466 /// \returns true if a value was vectorized.
1467 bool tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R, bool NeedExtracts);
1469 /// \brief Try to vectorize a chain that may start at the operands of \V;
1470 bool tryToVectorize(BinaryOperator *V, BoUpSLP &R);
1472 /// \brief Vectorize the stores that were collected in StoreRefs.
1473 bool vectorizeStoreChains(BoUpSLP &R);
1475 /// \brief Scan the basic block and look for patterns that are likely to start
1476 /// a vectorization chain.
1477 bool vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R);
1479 bool vectorizeStoreChain(ArrayRef<Value *> Chain, int CostThreshold,
1482 bool vectorizeStores(ArrayRef<StoreInst *> Stores, int costThreshold,
1485 StoreListMap StoreRefs;
1488 bool SLPVectorizer::vectorizeStoreChain(ArrayRef<Value *> Chain,
1489 int CostThreshold, BoUpSLP &R) {
1490 unsigned ChainLen = Chain.size();
1491 DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
1493 Type *StoreTy = cast<StoreInst>(Chain[0])->getValueOperand()->getType();
1494 unsigned Sz = DL->getTypeSizeInBits(StoreTy);
1495 unsigned VF = MinVecRegSize / Sz;
1497 if (!isPowerOf2_32(Sz) || VF < 2)
1500 bool Changed = false;
1501 // Look for profitable vectorizable trees at all offsets, starting at zero.
1502 for (unsigned i = 0, e = ChainLen; i < e; ++i) {
1505 DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
1507 ArrayRef<Value *> Operands = Chain.slice(i, VF);
1509 R.buildTree(Operands);
1511 int Cost = R.getTreeCost();
1513 DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
1514 if (Cost < CostThreshold) {
1515 DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
1518 // Move to the next bundle.
1524 if (Changed || ChainLen > VF)
1527 // Handle short chains. This helps us catch types such as <3 x float> that
1528 // are smaller than vector size.
1531 int Cost = R.getTreeCost();
1533 if (Cost < CostThreshold) {
1534 DEBUG(dbgs() << "SLP: Found store chain cost = " << Cost
1535 << " for size = " << ChainLen << "\n");
1543 bool SLPVectorizer::vectorizeStores(ArrayRef<StoreInst *> Stores,
1544 int costThreshold, BoUpSLP &R) {
1545 SetVector<Value *> Heads, Tails;
1546 SmallDenseMap<Value *, Value *> ConsecutiveChain;
1548 // We may run into multiple chains that merge into a single chain. We mark the
1549 // stores that we vectorized so that we don't visit the same store twice.
1550 BoUpSLP::ValueSet VectorizedStores;
1551 bool Changed = false;
1553 // Do a quadratic search on all of the given stores and find
1554 // all of the pairs of loads that follow each other.
1555 for (unsigned i = 0, e = Stores.size(); i < e; ++i)
1556 for (unsigned j = 0; j < e; ++j) {
1560 if (R.isConsecutiveAccess(Stores[i], Stores[j])) {
1561 Tails.insert(Stores[j]);
1562 Heads.insert(Stores[i]);
1563 ConsecutiveChain[Stores[i]] = Stores[j];
1567 // For stores that start but don't end a link in the chain:
1568 for (SetVector<Value *>::iterator it = Heads.begin(), e = Heads.end();
1570 if (Tails.count(*it))
1573 // We found a store instr that starts a chain. Now follow the chain and try
1575 BoUpSLP::ValueList Operands;
1577 // Collect the chain into a list.
1578 while (Tails.count(I) || Heads.count(I)) {
1579 if (VectorizedStores.count(I))
1581 Operands.push_back(I);
1582 // Move to the next value in the chain.
1583 I = ConsecutiveChain[I];
1586 bool Vectorized = vectorizeStoreChain(Operands, costThreshold, R);
1588 // Mark the vectorized stores so that we don't vectorize them again.
1590 VectorizedStores.insert(Operands.begin(), Operands.end());
1591 Changed |= Vectorized;
1598 unsigned SLPVectorizer::collectStores(BasicBlock *BB, BoUpSLP &R) {
1601 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1602 StoreInst *SI = dyn_cast<StoreInst>(it);
1606 // Check that the pointer points to scalars.
1607 Type *Ty = SI->getValueOperand()->getType();
1608 if (Ty->isAggregateType() || Ty->isVectorTy())
1611 // Find the base of the GEP.
1612 Value *Ptr = SI->getPointerOperand();
1613 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
1614 Ptr = GEP->getPointerOperand();
1616 // Save the store locations.
1617 StoreRefs[Ptr].push_back(SI);
1623 bool SLPVectorizer::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
1626 Value *VL[] = { A, B };
1627 return tryToVectorizeList(VL, R, true);
1630 bool SLPVectorizer::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
1631 bool NeedExtracts) {
1635 DEBUG(dbgs() << "SLP: Vectorizing a list of length = " << VL.size() << ".\n");
1637 // Check that all of the parts are scalar instructions of the same type.
1638 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
1642 unsigned Opcode0 = I0->getOpcode();
1644 for (int i = 0, e = VL.size(); i < e; ++i) {
1645 Type *Ty = VL[i]->getType();
1646 if (Ty->isAggregateType() || Ty->isVectorTy())
1648 Instruction *Inst = dyn_cast<Instruction>(VL[i]);
1649 if (!Inst || Inst->getOpcode() != Opcode0)
1654 int Cost = R.getTreeCost();
1656 int ExtrCost = NeedExtracts ? R.getGatherCost(VL) : 0;
1657 DEBUG(dbgs() << "SLP: Cost of pair:" << Cost
1658 << " Cost of extract:" << ExtrCost << ".\n");
1659 if ((Cost + ExtrCost) >= -SLPCostThreshold)
1661 DEBUG(dbgs() << "SLP: Vectorizing pair.\n");
1666 bool SLPVectorizer::tryToVectorize(BinaryOperator *V, BoUpSLP &R) {
1670 // Try to vectorize V.
1671 if (tryToVectorizePair(V->getOperand(0), V->getOperand(1), R))
1674 BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0));
1675 BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1));
1677 if (B && B->hasOneUse()) {
1678 BinaryOperator *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
1679 BinaryOperator *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
1680 if (tryToVectorizePair(A, B0, R)) {
1684 if (tryToVectorizePair(A, B1, R)) {
1691 if (A && A->hasOneUse()) {
1692 BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
1693 BinaryOperator *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
1694 if (tryToVectorizePair(A0, B, R)) {
1698 if (tryToVectorizePair(A1, B, R)) {
1706 bool SLPVectorizer::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
1707 bool Changed = false;
1708 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1709 if (isa<DbgInfoIntrinsic>(it))
1712 // Try to vectorize reductions that use PHINodes.
1713 if (PHINode *P = dyn_cast<PHINode>(it)) {
1714 // Check that the PHI is a reduction PHI.
1715 if (P->getNumIncomingValues() != 2)
1718 (P->getIncomingBlock(0) == BB
1719 ? (P->getIncomingValue(0))
1720 : (P->getIncomingBlock(1) == BB ? P->getIncomingValue(1) : 0));
1721 // Check if this is a Binary Operator.
1722 BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx);
1726 Value *Inst = BI->getOperand(0);
1728 Inst = BI->getOperand(1);
1730 Changed |= tryToVectorize(dyn_cast<BinaryOperator>(Inst), R);
1734 // Try to vectorize trees that start at compare instructions.
1735 if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
1736 if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) {
1740 for (int i = 0; i < 2; ++i)
1741 if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i)))
1743 tryToVectorizePair(BI->getOperand(0), BI->getOperand(1), R);
1748 // Scan the PHINodes in our successors in search for pairing hints.
1749 for (succ_iterator it = succ_begin(BB), e = succ_end(BB); it != e; ++it) {
1750 BasicBlock *Succ = *it;
1751 SmallVector<Value *, 4> Incoming;
1753 // Collect the incoming values from the PHIs.
1754 for (BasicBlock::iterator instr = Succ->begin(), ie = Succ->end();
1755 instr != ie; ++instr) {
1756 PHINode *P = dyn_cast<PHINode>(instr);
1761 Value *V = P->getIncomingValueForBlock(BB);
1762 if (Instruction *I = dyn_cast<Instruction>(V))
1763 if (I->getParent() == BB)
1764 Incoming.push_back(I);
1767 if (Incoming.size() > 1)
1768 Changed |= tryToVectorizeList(Incoming, R, true);
1774 bool SLPVectorizer::vectorizeStoreChains(BoUpSLP &R) {
1775 bool Changed = false;
1776 // Attempt to sort and vectorize each of the store-groups.
1777 for (StoreListMap::iterator it = StoreRefs.begin(), e = StoreRefs.end();
1779 if (it->second.size() < 2)
1782 DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
1783 << it->second.size() << ".\n");
1785 Changed |= vectorizeStores(it->second, -SLPCostThreshold, R);
1790 } // end anonymous namespace
1792 char SLPVectorizer::ID = 0;
1793 static const char lv_name[] = "SLP Vectorizer";
1794 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
1795 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
1796 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
1797 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1798 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
1799 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
1802 Pass *createSLPVectorizerPass() { return new SLPVectorizer(); }