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 DbgLoc(B.getCurrentDebugLocation()) {}
64 Builder.SetCurrentDebugLocation(DbgLoc);
66 Builder.SetInsertPoint(Loc);
71 BuilderLocGuard(const BuilderLocGuard &);
72 BuilderLocGuard &operator=(const BuilderLocGuard &);
74 AssertingVH<Instruction> Loc;
78 /// A helper class for numbering instructions in multiple blocks.
79 /// Numbers start at zero for each basic block.
80 struct BlockNumbering {
82 BlockNumbering(BasicBlock *Bb) : BB(Bb), Valid(false) {}
84 BlockNumbering() : BB(0), Valid(false) {}
86 void numberInstructions() {
90 // Number the instructions in the block.
91 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
93 InstrVec.push_back(it);
94 assert(InstrVec[InstrIdx[it]] == it && "Invalid allocation");
99 int getIndex(Instruction *I) {
100 assert(I->getParent() == BB && "Invalid instruction");
102 numberInstructions();
103 assert(InstrIdx.count(I) && "Unknown instruction");
107 Instruction *getInstruction(unsigned loc) {
109 numberInstructions();
110 assert(InstrVec.size() > loc && "Invalid Index");
111 return InstrVec[loc];
114 void forget() { Valid = false; }
117 /// The block we are numbering.
119 /// Is the block numbered.
121 /// Maps instructions to numbers and back.
122 SmallDenseMap<Instruction *, int> InstrIdx;
123 /// Maps integers to Instructions.
124 SmallVector<Instruction *, 32> InstrVec;
127 /// \returns the parent basic block if all of the instructions in \p VL
128 /// are in the same block or null otherwise.
129 static BasicBlock *getSameBlock(ArrayRef<Value *> VL) {
130 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
133 BasicBlock *BB = I0->getParent();
134 for (int i = 1, e = VL.size(); i < e; i++) {
135 Instruction *I = dyn_cast<Instruction>(VL[i]);
139 if (BB != I->getParent())
145 /// \returns True if all of the values in \p VL are constants.
146 static bool allConstant(ArrayRef<Value *> VL) {
147 for (unsigned i = 0, e = VL.size(); i < e; ++i)
148 if (!isa<Constant>(VL[i]))
153 /// \returns True if all of the values in \p VL are identical.
154 static bool isSplat(ArrayRef<Value *> VL) {
155 for (unsigned i = 1, e = VL.size(); i < e; ++i)
161 /// \returns The opcode if all of the Instructions in \p VL have the same
163 static unsigned getSameOpcode(ArrayRef<Value *> VL) {
164 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
167 unsigned Opcode = I0->getOpcode();
168 for (int i = 1, e = VL.size(); i < e; i++) {
169 Instruction *I = dyn_cast<Instruction>(VL[i]);
170 if (!I || Opcode != I->getOpcode())
176 /// \returns The type that all of the values in \p VL have or null if there
177 /// are different types.
178 static Type* getSameType(ArrayRef<Value *> VL) {
179 Type *Ty = VL[0]->getType();
180 for (int i = 1, e = VL.size(); i < e; i++)
181 if (VL[i]->getType() != Ty)
187 /// \returns True if the ExtractElement instructions in VL can be vectorized
188 /// to use the original vector.
189 static bool CanReuseExtract(ArrayRef<Value *> VL) {
190 assert(Instruction::ExtractElement == getSameOpcode(VL) && "Invalid opcode");
191 // Check if all of the extracts come from the same vector and from the
194 ExtractElementInst *E0 = cast<ExtractElementInst>(VL0);
195 Value *Vec = E0->getOperand(0);
197 // We have to extract from the same vector type.
198 unsigned NElts = Vec->getType()->getVectorNumElements();
200 if (NElts != VL.size())
203 // Check that all of the indices extract from the correct offset.
204 ConstantInt *CI = dyn_cast<ConstantInt>(E0->getOperand(1));
205 if (!CI || CI->getZExtValue())
208 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
209 ExtractElementInst *E = cast<ExtractElementInst>(VL[i]);
210 ConstantInt *CI = dyn_cast<ConstantInt>(E->getOperand(1));
212 if (!CI || CI->getZExtValue() != i || E->getOperand(0) != Vec)
219 /// Bottom Up SLP Vectorizer.
222 typedef SmallVector<Value *, 8> ValueList;
223 typedef SmallVector<Instruction *, 16> InstrList;
224 typedef SmallPtrSet<Value *, 16> ValueSet;
225 typedef SmallVector<StoreInst *, 8> StoreList;
227 BoUpSLP(Function *Func, ScalarEvolution *Se, DataLayout *Dl,
228 TargetTransformInfo *Tti, AliasAnalysis *Aa, LoopInfo *Li,
230 F(Func), SE(Se), DL(Dl), TTI(Tti), AA(Aa), LI(Li), DT(Dt),
231 Builder(Se->getContext()) {
232 // Setup the block numbering utility for all of the blocks in the
234 for (Function::iterator it = F->begin(), e = F->end(); it != e; ++it) {
236 BlocksNumbers[BB] = BlockNumbering(BB);
240 /// \brief Vectorize the tree that starts with the elements in \p VL.
241 void vectorizeTree();
243 /// \returns the vectorization cost of the subtree that starts at \p VL.
244 /// A negative number means that this is profitable.
247 /// Construct a vectorizable tree that starts at \p Roots.
248 void buildTree(ArrayRef<Value *> Roots);
250 /// Clear the internal data structures that are created by 'buildTree'.
252 VectorizableTree.clear();
253 ScalarToTreeEntry.clear();
255 ExternalUses.clear();
256 MemBarrierIgnoreList.clear();
259 /// \returns true if the memory operations A and B are consecutive.
260 bool isConsecutiveAccess(Value *A, Value *B);
262 /// \brief Perform LICM and CSE on the newly generated gather sequences.
263 void optimizeGatherSequence();
267 /// \returns the cost of the vectorizable entry.
268 int getEntryCost(TreeEntry *E);
270 /// This is the recursive part of buildTree.
271 void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth);
273 /// Vectorize a single entry in the tree.
274 Value *vectorizeTree(TreeEntry *E);
276 /// Vectorize a single entry in the tree, starting in \p VL.
277 Value *vectorizeTree(ArrayRef<Value *> VL);
279 /// \returns the pointer to the vectorized value if \p VL is already
280 /// vectorized, or NULL. They may happen in cycles.
281 Value *alreadyVectorized(ArrayRef<Value *> VL);
283 /// \brief Take the pointer operand from the Load/Store instruction.
284 /// \returns NULL if this is not a valid Load/Store instruction.
285 static Value *getPointerOperand(Value *I);
287 /// \brief Take the address space operand from the Load/Store instruction.
288 /// \returns -1 if this is not a valid Load/Store instruction.
289 static unsigned getAddressSpaceOperand(Value *I);
291 /// \returns the scalarization cost for this type. Scalarization in this
292 /// context means the creation of vectors from a group of scalars.
293 int getGatherCost(Type *Ty);
295 /// \returns the scalarization cost for this list of values. Assuming that
296 /// this subtree gets vectorized, we may need to extract the values from the
297 /// roots. This method calculates the cost of extracting the values.
298 int getGatherCost(ArrayRef<Value *> VL);
300 /// \returns the AA location that is being access by the instruction.
301 AliasAnalysis::Location getLocation(Instruction *I);
303 /// \brief Checks if it is possible to sink an instruction from
304 /// \p Src to \p Dst.
305 /// \returns the pointer to the barrier instruction if we can't sink.
306 Value *getSinkBarrier(Instruction *Src, Instruction *Dst);
308 /// \returns the index of the last instrucion in the BB from \p VL.
309 int getLastIndex(ArrayRef<Value *> VL);
311 /// \returns the Instruction in the bundle \p VL.
312 Instruction *getLastInstruction(ArrayRef<Value *> VL);
314 /// \returns a vector from a collection of scalars in \p VL.
315 Value *Gather(ArrayRef<Value *> VL, VectorType *Ty);
318 TreeEntry() : Scalars(), VectorizedValue(0), LastScalarIndex(0),
321 /// \returns true if the scalars in VL are equal to this entry.
322 bool isSame(ArrayRef<Value *> VL) {
323 assert(VL.size() == Scalars.size() && "Invalid size");
324 for (int i = 0, e = VL.size(); i != e; ++i)
325 if (VL[i] != Scalars[i])
330 /// A vector of scalars.
333 /// The Scalars are vectorized into this value. It is initialized to Null.
334 Value *VectorizedValue;
336 /// The index in the basic block of the last scalar.
339 /// Do we need to gather this sequence ?
343 /// Create a new VectorizableTree entry.
344 TreeEntry *newTreeEntry(ArrayRef<Value *> VL, bool Vectorized) {
345 VectorizableTree.push_back(TreeEntry());
346 int idx = VectorizableTree.size() - 1;
347 TreeEntry *Last = &VectorizableTree[idx];
348 Last->Scalars.insert(Last->Scalars.begin(), VL.begin(), VL.end());
349 Last->NeedToGather = !Vectorized;
351 Last->LastScalarIndex = getLastIndex(VL);
352 for (int i = 0, e = VL.size(); i != e; ++i) {
353 assert(!ScalarToTreeEntry.count(VL[i]) && "Scalar already in tree!");
354 ScalarToTreeEntry[VL[i]] = idx;
357 Last->LastScalarIndex = 0;
358 MustGather.insert(VL.begin(), VL.end());
363 /// -- Vectorization State --
364 /// Holds all of the tree entries.
365 std::vector<TreeEntry> VectorizableTree;
367 /// Maps a specific scalar to its tree entry.
368 SmallDenseMap<Value*, int> ScalarToTreeEntry;
370 /// A list of scalars that we found that we need to keep as scalars.
373 /// This POD struct describes one external user in the vectorized tree.
374 struct ExternalUser {
375 ExternalUser (Value *S, llvm::User *U, int L) :
376 Scalar(S), User(U), Lane(L){};
377 // Which scalar in our function.
379 // Which user that uses the scalar.
381 // Which lane does the scalar belong to.
384 typedef SmallVector<ExternalUser, 16> UserList;
386 /// A list of values that need to extracted out of the tree.
387 /// This list holds pairs of (Internal Scalar : External User).
388 UserList ExternalUses;
390 /// A list of instructions to ignore while sinking
391 /// memory instructions. This map must be reset between runs of getCost.
392 ValueSet MemBarrierIgnoreList;
394 /// Holds all of the instructions that we gathered.
395 SetVector<Instruction *> GatherSeq;
397 /// Numbers instructions in different blocks.
398 DenseMap<BasicBlock *, BlockNumbering> BlocksNumbers;
400 // Analysis and block reference.
404 TargetTransformInfo *TTI;
408 /// Instruction builder to construct the vectorized tree.
412 void BoUpSLP::buildTree(ArrayRef<Value *> Roots) {
414 if (!getSameType(Roots))
416 buildTree_rec(Roots, 0);
418 // Collect the values that we need to extract from the tree.
419 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
420 TreeEntry *Entry = &VectorizableTree[EIdx];
423 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
424 Value *Scalar = Entry->Scalars[Lane];
426 // No need to handle users of gathered values.
427 if (Entry->NeedToGather)
430 for (Value::use_iterator User = Scalar->use_begin(),
431 UE = Scalar->use_end(); User != UE; ++User) {
432 DEBUG(dbgs() << "SLP: Checking user:" << **User << ".\n");
434 bool Gathered = MustGather.count(*User);
436 // Skip in-tree scalars that become vectors.
437 if (ScalarToTreeEntry.count(*User) && !Gathered) {
438 DEBUG(dbgs() << "SLP: \tInternal user will be removed:" <<
440 int Idx = ScalarToTreeEntry[*User]; (void) Idx;
441 assert(!VectorizableTree[Idx].NeedToGather && "Bad state");
445 if (!isa<Instruction>(*User))
448 DEBUG(dbgs() << "SLP: Need to extract:" << **User << " from lane " <<
449 Lane << " from " << *Scalar << ".\n");
450 ExternalUses.push_back(ExternalUser(Scalar, *User, Lane));
457 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth) {
458 bool SameTy = getSameType(VL); (void)SameTy;
459 assert(SameTy && "Invalid types!");
461 if (Depth == RecursionMaxDepth) {
462 DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
463 newTreeEntry(VL, false);
467 // Don't handle vectors.
468 if (VL[0]->getType()->isVectorTy()) {
469 DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
470 newTreeEntry(VL, false);
474 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
475 if (SI->getValueOperand()->getType()->isVectorTy()) {
476 DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
477 newTreeEntry(VL, false);
481 // If all of the operands are identical or constant we have a simple solution.
482 if (allConstant(VL) || isSplat(VL) || !getSameBlock(VL) ||
483 !getSameOpcode(VL)) {
484 DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
485 newTreeEntry(VL, false);
489 // We now know that this is a vector of instructions of the same type from
492 // Check if this is a duplicate of another entry.
493 if (ScalarToTreeEntry.count(VL[0])) {
494 int Idx = ScalarToTreeEntry[VL[0]];
495 TreeEntry *E = &VectorizableTree[Idx];
496 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
497 DEBUG(dbgs() << "SLP: \tChecking bundle: " << *VL[i] << ".\n");
498 if (E->Scalars[i] != VL[i]) {
499 DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
500 newTreeEntry(VL, false);
504 DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *VL[0] << ".\n");
508 // Check that none of the instructions in the bundle are already in the tree.
509 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
510 if (ScalarToTreeEntry.count(VL[i])) {
511 DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
512 ") is already in tree.\n");
513 newTreeEntry(VL, false);
518 // If any of the scalars appears in the table OR it is marked as a value that
519 // needs to stat scalar then we need to gather the scalars.
520 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
521 if (ScalarToTreeEntry.count(VL[i]) || MustGather.count(VL[i])) {
522 DEBUG(dbgs() << "SLP: Gathering due to gathered scalar. \n");
523 newTreeEntry(VL, false);
528 // Check that all of the users of the scalars that we want to vectorize are
530 Instruction *VL0 = cast<Instruction>(VL[0]);
531 int MyLastIndex = getLastIndex(VL);
532 BasicBlock *BB = cast<Instruction>(VL0)->getParent();
534 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
535 Instruction *Scalar = cast<Instruction>(VL[i]);
536 DEBUG(dbgs() << "SLP: Checking users of " << *Scalar << ". \n");
537 for (Value::use_iterator U = Scalar->use_begin(), UE = Scalar->use_end();
539 DEBUG(dbgs() << "SLP: \tUser " << **U << ". \n");
540 Instruction *User = dyn_cast<Instruction>(*U);
542 DEBUG(dbgs() << "SLP: Gathering due unknown user. \n");
543 newTreeEntry(VL, false);
547 // We don't care if the user is in a different basic block.
548 BasicBlock *UserBlock = User->getParent();
549 if (UserBlock != BB) {
550 DEBUG(dbgs() << "SLP: User from a different basic block "
555 // If this is a PHINode within this basic block then we can place the
556 // extract wherever we want.
557 if (isa<PHINode>(*User)) {
558 DEBUG(dbgs() << "SLP: \tWe can schedule PHIs:" << *User << ". \n");
562 // Check if this is a safe in-tree user.
563 if (ScalarToTreeEntry.count(User)) {
564 int Idx = ScalarToTreeEntry[User];
565 int VecLocation = VectorizableTree[Idx].LastScalarIndex;
566 if (VecLocation <= MyLastIndex) {
567 DEBUG(dbgs() << "SLP: Gathering due to unschedulable vector. \n");
568 newTreeEntry(VL, false);
571 DEBUG(dbgs() << "SLP: In-tree user (" << *User << ") at #" <<
572 VecLocation << " vector value (" << *Scalar << ") at #"
573 << MyLastIndex << ".\n");
577 // Make sure that we can schedule this unknown user.
578 BlockNumbering &BN = BlocksNumbers[BB];
579 int UserIndex = BN.getIndex(User);
580 if (UserIndex < MyLastIndex) {
582 DEBUG(dbgs() << "SLP: Can't schedule extractelement for "
584 newTreeEntry(VL, false);
590 // Check that every instructions appears once in this bundle.
591 for (unsigned i = 0, e = VL.size(); i < e; ++i)
592 for (unsigned j = i+1; j < e; ++j)
593 if (VL[i] == VL[j]) {
594 DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
595 newTreeEntry(VL, false);
599 // Check that instructions in this bundle don't reference other instructions.
600 // The runtime of this check is O(N * N-1 * uses(N)) and a typical N is 4.
601 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
602 for (Value::use_iterator U = VL[i]->use_begin(), UE = VL[i]->use_end();
604 for (unsigned j = 0; j < e; ++j) {
605 if (i != j && *U == VL[j]) {
606 DEBUG(dbgs() << "SLP: Intra-bundle dependencies!" << **U << ". \n");
607 newTreeEntry(VL, false);
614 DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
616 unsigned Opcode = getSameOpcode(VL);
618 // Check if it is safe to sink the loads or the stores.
619 if (Opcode == Instruction::Load || Opcode == Instruction::Store) {
620 Instruction *Last = getLastInstruction(VL);
622 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
625 Value *Barrier = getSinkBarrier(cast<Instruction>(VL[i]), Last);
627 DEBUG(dbgs() << "SLP: Can't sink " << *VL[i] << "\n down to " << *Last
628 << "\n because of " << *Barrier << ". Gathering.\n");
629 newTreeEntry(VL, false);
636 case Instruction::PHI: {
637 PHINode *PH = dyn_cast<PHINode>(VL0);
638 newTreeEntry(VL, true);
639 DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
641 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
643 // Prepare the operand vector.
644 for (unsigned j = 0; j < VL.size(); ++j)
645 Operands.push_back(cast<PHINode>(VL[j])->getIncomingValue(i));
647 buildTree_rec(Operands, Depth + 1);
651 case Instruction::ExtractElement: {
652 bool Reuse = CanReuseExtract(VL);
654 DEBUG(dbgs() << "SLP: Reusing extract sequence.\n");
656 newTreeEntry(VL, Reuse);
659 case Instruction::Load: {
660 // Check if the loads are consecutive or of we need to swizzle them.
661 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
662 if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
663 newTreeEntry(VL, false);
664 DEBUG(dbgs() << "SLP: Need to swizzle loads.\n");
668 newTreeEntry(VL, true);
669 DEBUG(dbgs() << "SLP: added a vector of loads.\n");
672 case Instruction::ZExt:
673 case Instruction::SExt:
674 case Instruction::FPToUI:
675 case Instruction::FPToSI:
676 case Instruction::FPExt:
677 case Instruction::PtrToInt:
678 case Instruction::IntToPtr:
679 case Instruction::SIToFP:
680 case Instruction::UIToFP:
681 case Instruction::Trunc:
682 case Instruction::FPTrunc:
683 case Instruction::BitCast: {
684 Type *SrcTy = VL0->getOperand(0)->getType();
685 for (unsigned i = 0; i < VL.size(); ++i) {
686 Type *Ty = cast<Instruction>(VL[i])->getOperand(0)->getType();
687 if (Ty != SrcTy || Ty->isAggregateType() || Ty->isVectorTy()) {
688 newTreeEntry(VL, false);
689 DEBUG(dbgs() << "SLP: Gathering casts with different src types.\n");
693 newTreeEntry(VL, true);
694 DEBUG(dbgs() << "SLP: added a vector of casts.\n");
696 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
698 // Prepare the operand vector.
699 for (unsigned j = 0; j < VL.size(); ++j)
700 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
702 buildTree_rec(Operands, Depth+1);
706 case Instruction::ICmp:
707 case Instruction::FCmp: {
708 // Check that all of the compares have the same predicate.
709 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
710 Type *ComparedTy = cast<Instruction>(VL[0])->getOperand(0)->getType();
711 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
712 CmpInst *Cmp = cast<CmpInst>(VL[i]);
713 if (Cmp->getPredicate() != P0 ||
714 Cmp->getOperand(0)->getType() != ComparedTy) {
715 newTreeEntry(VL, false);
716 DEBUG(dbgs() << "SLP: Gathering cmp with different predicate.\n");
721 newTreeEntry(VL, true);
722 DEBUG(dbgs() << "SLP: added a vector of compares.\n");
724 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
726 // Prepare the operand vector.
727 for (unsigned j = 0; j < VL.size(); ++j)
728 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
730 buildTree_rec(Operands, Depth+1);
734 case Instruction::Select:
735 case Instruction::Add:
736 case Instruction::FAdd:
737 case Instruction::Sub:
738 case Instruction::FSub:
739 case Instruction::Mul:
740 case Instruction::FMul:
741 case Instruction::UDiv:
742 case Instruction::SDiv:
743 case Instruction::FDiv:
744 case Instruction::URem:
745 case Instruction::SRem:
746 case Instruction::FRem:
747 case Instruction::Shl:
748 case Instruction::LShr:
749 case Instruction::AShr:
750 case Instruction::And:
751 case Instruction::Or:
752 case Instruction::Xor: {
753 newTreeEntry(VL, true);
754 DEBUG(dbgs() << "SLP: added a vector of bin op.\n");
756 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
758 // Prepare the operand vector.
759 for (unsigned j = 0; j < VL.size(); ++j)
760 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
762 buildTree_rec(Operands, Depth+1);
766 case Instruction::Store: {
767 // Check if the stores are consecutive or of we need to swizzle them.
768 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
769 if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
770 newTreeEntry(VL, false);
771 DEBUG(dbgs() << "SLP: Non consecutive store.\n");
775 newTreeEntry(VL, true);
776 DEBUG(dbgs() << "SLP: added a vector of stores.\n");
779 for (unsigned j = 0; j < VL.size(); ++j)
780 Operands.push_back(cast<Instruction>(VL[j])->getOperand(0));
782 // We can ignore these values because we are sinking them down.
783 MemBarrierIgnoreList.insert(VL.begin(), VL.end());
784 buildTree_rec(Operands, Depth + 1);
788 newTreeEntry(VL, false);
789 DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
794 int BoUpSLP::getEntryCost(TreeEntry *E) {
795 ArrayRef<Value*> VL = E->Scalars;
797 Type *ScalarTy = VL[0]->getType();
798 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
799 ScalarTy = SI->getValueOperand()->getType();
800 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
802 if (E->NeedToGather) {
806 return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
808 return getGatherCost(E->Scalars);
811 assert(getSameOpcode(VL) && getSameType(VL) && getSameBlock(VL) &&
813 Instruction *VL0 = cast<Instruction>(VL[0]);
814 unsigned Opcode = VL0->getOpcode();
816 case Instruction::PHI: {
819 case Instruction::ExtractElement: {
820 if (CanReuseExtract(VL))
822 return getGatherCost(VecTy);
824 case Instruction::ZExt:
825 case Instruction::SExt:
826 case Instruction::FPToUI:
827 case Instruction::FPToSI:
828 case Instruction::FPExt:
829 case Instruction::PtrToInt:
830 case Instruction::IntToPtr:
831 case Instruction::SIToFP:
832 case Instruction::UIToFP:
833 case Instruction::Trunc:
834 case Instruction::FPTrunc:
835 case Instruction::BitCast: {
836 Type *SrcTy = VL0->getOperand(0)->getType();
838 // Calculate the cost of this instruction.
839 int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(),
840 VL0->getType(), SrcTy);
842 VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
843 int VecCost = TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy);
844 return VecCost - ScalarCost;
846 case Instruction::FCmp:
847 case Instruction::ICmp:
848 case Instruction::Select:
849 case Instruction::Add:
850 case Instruction::FAdd:
851 case Instruction::Sub:
852 case Instruction::FSub:
853 case Instruction::Mul:
854 case Instruction::FMul:
855 case Instruction::UDiv:
856 case Instruction::SDiv:
857 case Instruction::FDiv:
858 case Instruction::URem:
859 case Instruction::SRem:
860 case Instruction::FRem:
861 case Instruction::Shl:
862 case Instruction::LShr:
863 case Instruction::AShr:
864 case Instruction::And:
865 case Instruction::Or:
866 case Instruction::Xor: {
867 // Calculate the cost of this instruction.
870 if (Opcode == Instruction::FCmp || Opcode == Instruction::ICmp ||
871 Opcode == Instruction::Select) {
872 VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
873 ScalarCost = VecTy->getNumElements() *
874 TTI->getCmpSelInstrCost(Opcode, ScalarTy, Builder.getInt1Ty());
875 VecCost = TTI->getCmpSelInstrCost(Opcode, VecTy, MaskTy);
877 ScalarCost = VecTy->getNumElements() *
878 TTI->getArithmeticInstrCost(Opcode, ScalarTy);
879 VecCost = TTI->getArithmeticInstrCost(Opcode, VecTy);
881 return VecCost - ScalarCost;
883 case Instruction::Load: {
884 // Cost of wide load - cost of scalar loads.
885 int ScalarLdCost = VecTy->getNumElements() *
886 TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
887 int VecLdCost = TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
888 return VecLdCost - ScalarLdCost;
890 case Instruction::Store: {
891 // We know that we can merge the stores. Calculate the cost.
892 int ScalarStCost = VecTy->getNumElements() *
893 TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
894 int VecStCost = TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
895 return VecStCost - ScalarStCost;
898 llvm_unreachable("Unknown instruction");
902 int BoUpSLP::getTreeCost() {
904 DEBUG(dbgs() << "SLP: Calculating cost for tree of size " <<
905 VectorizableTree.size() << ".\n");
907 // Don't vectorize tiny trees. Small load/store chains or consecutive stores
908 // of constants will be vectoried in SelectionDAG in MergeConsecutiveStores.
909 // The SelectionDAG vectorizer can only handle pairs (trees of height = 2).
910 if (VectorizableTree.size() < 3) {
911 if (!VectorizableTree.size()) {
912 assert(!ExternalUses.size() && "We should not have any external users");
917 unsigned BundleWidth = VectorizableTree[0].Scalars.size();
919 for (unsigned i = 0, e = VectorizableTree.size(); i != e; ++i) {
920 int C = getEntryCost(&VectorizableTree[i]);
921 DEBUG(dbgs() << "SLP: Adding cost " << C << " for bundle that starts with "
922 << *VectorizableTree[i].Scalars[0] << " .\n");
927 for (UserList::iterator I = ExternalUses.begin(), E = ExternalUses.end();
930 VectorType *VecTy = VectorType::get(I->Scalar->getType(), BundleWidth);
931 ExtractCost += TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy,
936 DEBUG(dbgs() << "SLP: Total Cost " << Cost + ExtractCost<< ".\n");
937 return Cost + ExtractCost;
940 int BoUpSLP::getGatherCost(Type *Ty) {
942 for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
943 Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
947 int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) {
948 // Find the type of the operands in VL.
949 Type *ScalarTy = VL[0]->getType();
950 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
951 ScalarTy = SI->getValueOperand()->getType();
952 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
953 // Find the cost of inserting/extracting values from the vector.
954 return getGatherCost(VecTy);
957 AliasAnalysis::Location BoUpSLP::getLocation(Instruction *I) {
958 if (StoreInst *SI = dyn_cast<StoreInst>(I))
959 return AA->getLocation(SI);
960 if (LoadInst *LI = dyn_cast<LoadInst>(I))
961 return AA->getLocation(LI);
962 return AliasAnalysis::Location();
965 Value *BoUpSLP::getPointerOperand(Value *I) {
966 if (LoadInst *LI = dyn_cast<LoadInst>(I))
967 return LI->getPointerOperand();
968 if (StoreInst *SI = dyn_cast<StoreInst>(I))
969 return SI->getPointerOperand();
973 unsigned BoUpSLP::getAddressSpaceOperand(Value *I) {
974 if (LoadInst *L = dyn_cast<LoadInst>(I))
975 return L->getPointerAddressSpace();
976 if (StoreInst *S = dyn_cast<StoreInst>(I))
977 return S->getPointerAddressSpace();
981 bool BoUpSLP::isConsecutiveAccess(Value *A, Value *B) {
982 Value *PtrA = getPointerOperand(A);
983 Value *PtrB = getPointerOperand(B);
984 unsigned ASA = getAddressSpaceOperand(A);
985 unsigned ASB = getAddressSpaceOperand(B);
987 // Check that the address spaces match and that the pointers are valid.
988 if (!PtrA || !PtrB || (ASA != ASB))
991 // Make sure that A and B are different pointers of the same type.
992 if (PtrA == PtrB || PtrA->getType() != PtrB->getType())
995 unsigned PtrBitWidth = DL->getPointerSizeInBits(ASA);
996 Type *Ty = cast<PointerType>(PtrA->getType())->getElementType();
997 APInt Size(PtrBitWidth, DL->getTypeStoreSize(Ty));
999 APInt OffsetA(PtrBitWidth, 0), OffsetB(PtrBitWidth, 0);
1000 PtrA = PtrA->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetA);
1001 PtrB = PtrB->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetB);
1003 APInt OffsetDelta = OffsetB - OffsetA;
1005 // Check if they are based on the same pointer. That makes the offsets
1008 return OffsetDelta == Size;
1010 // Compute the necessary base pointer delta to have the necessary final delta
1011 // equal to the size.
1012 APInt BaseDelta = Size - OffsetDelta;
1014 // Otherwise compute the distance with SCEV between the base pointers.
1015 const SCEV *PtrSCEVA = SE->getSCEV(PtrA);
1016 const SCEV *PtrSCEVB = SE->getSCEV(PtrB);
1017 const SCEV *C = SE->getConstant(BaseDelta);
1018 const SCEV *X = SE->getAddExpr(PtrSCEVA, C);
1019 return X == PtrSCEVB;
1022 Value *BoUpSLP::getSinkBarrier(Instruction *Src, Instruction *Dst) {
1023 assert(Src->getParent() == Dst->getParent() && "Not the same BB");
1024 BasicBlock::iterator I = Src, E = Dst;
1025 /// Scan all of the instruction from SRC to DST and check if
1026 /// the source may alias.
1027 for (++I; I != E; ++I) {
1028 // Ignore store instructions that are marked as 'ignore'.
1029 if (MemBarrierIgnoreList.count(I))
1031 if (Src->mayWriteToMemory()) /* Write */ {
1032 if (!I->mayReadOrWriteMemory())
1035 if (!I->mayWriteToMemory())
1038 AliasAnalysis::Location A = getLocation(&*I);
1039 AliasAnalysis::Location B = getLocation(Src);
1041 if (!A.Ptr || !B.Ptr || AA->alias(A, B))
1047 int BoUpSLP::getLastIndex(ArrayRef<Value *> VL) {
1048 BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
1049 assert(BB == getSameBlock(VL) && BlocksNumbers.count(BB) && "Invalid block");
1050 BlockNumbering &BN = BlocksNumbers[BB];
1052 int MaxIdx = BN.getIndex(BB->getFirstNonPHI());
1053 for (unsigned i = 0, e = VL.size(); i < e; ++i)
1054 MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
1058 Instruction *BoUpSLP::getLastInstruction(ArrayRef<Value *> VL) {
1059 BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
1060 assert(BB == getSameBlock(VL) && BlocksNumbers.count(BB) && "Invalid block");
1061 BlockNumbering &BN = BlocksNumbers[BB];
1063 int MaxIdx = BN.getIndex(cast<Instruction>(VL[0]));
1064 for (unsigned i = 1, e = VL.size(); i < e; ++i)
1065 MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
1066 Instruction *I = BN.getInstruction(MaxIdx);
1067 assert(I && "bad location");
1071 Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
1072 Value *Vec = UndefValue::get(Ty);
1073 // Generate the 'InsertElement' instruction.
1074 for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
1075 Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
1076 if (Instruction *Insrt = dyn_cast<Instruction>(Vec)) {
1077 GatherSeq.insert(Insrt);
1079 // Add to our 'need-to-extract' list.
1080 if (ScalarToTreeEntry.count(VL[i])) {
1081 int Idx = ScalarToTreeEntry[VL[i]];
1082 TreeEntry *E = &VectorizableTree[Idx];
1083 // Find which lane we need to extract.
1085 for (unsigned Lane = 0, LE = VL.size(); Lane != LE; ++Lane) {
1086 // Is this the lane of the scalar that we are looking for ?
1087 if (E->Scalars[Lane] == VL[i]) {
1092 assert(FoundLane >= 0 && "Could not find the correct lane");
1093 ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
1101 Value *BoUpSLP::alreadyVectorized(ArrayRef<Value *> VL) {
1102 if (ScalarToTreeEntry.count(VL[0])) {
1103 int Idx = ScalarToTreeEntry[VL[0]];
1104 TreeEntry *En = &VectorizableTree[Idx];
1105 if (En->isSame(VL) && En->VectorizedValue)
1106 return En->VectorizedValue;
1111 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
1112 if (ScalarToTreeEntry.count(VL[0])) {
1113 int Idx = ScalarToTreeEntry[VL[0]];
1114 TreeEntry *E = &VectorizableTree[Idx];
1116 return vectorizeTree(E);
1119 Type *ScalarTy = VL[0]->getType();
1120 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1121 ScalarTy = SI->getValueOperand()->getType();
1122 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1124 return Gather(VL, VecTy);
1127 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
1128 BuilderLocGuard Guard(Builder);
1130 if (E->VectorizedValue) {
1131 DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
1132 return E->VectorizedValue;
1135 Instruction *VL0 = cast<Instruction>(E->Scalars[0]);
1136 Type *ScalarTy = VL0->getType();
1137 if (StoreInst *SI = dyn_cast<StoreInst>(VL0))
1138 ScalarTy = SI->getValueOperand()->getType();
1139 VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size());
1141 if (E->NeedToGather) {
1142 BasicBlock *BB = VL0->getParent();
1143 BasicBlock::iterator NextInst = getLastInstruction(E->Scalars);
1145 assert(NextInst != BB->end());
1146 Builder.SetInsertPoint(NextInst);
1147 return Gather(E->Scalars, VecTy);
1150 unsigned Opcode = VL0->getOpcode();
1151 assert(Opcode == getSameOpcode(E->Scalars) && "Invalid opcode");
1154 case Instruction::PHI: {
1155 PHINode *PH = dyn_cast<PHINode>(VL0);
1156 Builder.SetInsertPoint(PH->getParent()->getFirstInsertionPt());
1157 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1158 PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
1159 E->VectorizedValue = NewPhi;
1161 // PHINodes may have multiple entries from the same block. We want to
1162 // visit every block once.
1163 SmallSet<BasicBlock*, 4> VisitedBBs;
1165 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1167 BasicBlock *IBB = PH->getIncomingBlock(i);
1169 if (!VisitedBBs.insert(IBB)) {
1170 NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
1174 // Prepare the operand vector.
1175 for (unsigned j = 0; j < E->Scalars.size(); ++j)
1176 Operands.push_back(cast<PHINode>(E->Scalars[j])->
1177 getIncomingValueForBlock(IBB));
1179 Builder.SetInsertPoint(IBB->getTerminator());
1180 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1181 Value *Vec = vectorizeTree(Operands);
1182 NewPhi->addIncoming(Vec, IBB);
1185 assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
1186 "Invalid number of incoming values");
1190 case Instruction::ExtractElement: {
1191 if (CanReuseExtract(E->Scalars)) {
1192 Value *V = VL0->getOperand(0);
1193 E->VectorizedValue = V;
1196 return Gather(E->Scalars, VecTy);
1198 case Instruction::ZExt:
1199 case Instruction::SExt:
1200 case Instruction::FPToUI:
1201 case Instruction::FPToSI:
1202 case Instruction::FPExt:
1203 case Instruction::PtrToInt:
1204 case Instruction::IntToPtr:
1205 case Instruction::SIToFP:
1206 case Instruction::UIToFP:
1207 case Instruction::Trunc:
1208 case Instruction::FPTrunc:
1209 case Instruction::BitCast: {
1211 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1212 INVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1214 Builder.SetInsertPoint(getLastInstruction(E->Scalars));
1215 Builder.SetCurrentDebugLocation(VL0->getDebugLoc());
1217 Value *InVec = vectorizeTree(INVL);
1219 if (Value *V = alreadyVectorized(E->Scalars))
1222 CastInst *CI = dyn_cast<CastInst>(VL0);
1223 Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
1224 E->VectorizedValue = V;
1227 case Instruction::FCmp:
1228 case Instruction::ICmp: {
1229 ValueList LHSV, RHSV;
1230 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1231 LHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1232 RHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1235 Builder.SetInsertPoint(getLastInstruction(E->Scalars));
1236 Builder.SetCurrentDebugLocation(VL0->getDebugLoc());
1238 Value *L = vectorizeTree(LHSV);
1239 Value *R = vectorizeTree(RHSV);
1241 if (Value *V = alreadyVectorized(E->Scalars))
1244 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
1246 if (Opcode == Instruction::FCmp)
1247 V = Builder.CreateFCmp(P0, L, R);
1249 V = Builder.CreateICmp(P0, L, R);
1251 E->VectorizedValue = V;
1254 case Instruction::Select: {
1255 ValueList TrueVec, FalseVec, CondVec;
1256 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1257 CondVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1258 TrueVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1259 FalseVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(2));
1262 Builder.SetInsertPoint(getLastInstruction(E->Scalars));
1263 Builder.SetCurrentDebugLocation(VL0->getDebugLoc());
1265 Value *Cond = vectorizeTree(CondVec);
1266 Value *True = vectorizeTree(TrueVec);
1267 Value *False = vectorizeTree(FalseVec);
1269 if (Value *V = alreadyVectorized(E->Scalars))
1272 Value *V = Builder.CreateSelect(Cond, True, False);
1273 E->VectorizedValue = V;
1276 case Instruction::Add:
1277 case Instruction::FAdd:
1278 case Instruction::Sub:
1279 case Instruction::FSub:
1280 case Instruction::Mul:
1281 case Instruction::FMul:
1282 case Instruction::UDiv:
1283 case Instruction::SDiv:
1284 case Instruction::FDiv:
1285 case Instruction::URem:
1286 case Instruction::SRem:
1287 case Instruction::FRem:
1288 case Instruction::Shl:
1289 case Instruction::LShr:
1290 case Instruction::AShr:
1291 case Instruction::And:
1292 case Instruction::Or:
1293 case Instruction::Xor: {
1294 ValueList LHSVL, RHSVL;
1295 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1296 LHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1297 RHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1300 Builder.SetInsertPoint(getLastInstruction(E->Scalars));
1301 Builder.SetCurrentDebugLocation(VL0->getDebugLoc());
1303 Value *LHS = vectorizeTree(LHSVL);
1304 Value *RHS = vectorizeTree(RHSVL);
1306 if (LHS == RHS && isa<Instruction>(LHS)) {
1307 assert((VL0->getOperand(0) == VL0->getOperand(1)) && "Invalid order");
1310 if (Value *V = alreadyVectorized(E->Scalars))
1313 BinaryOperator *BinOp = cast<BinaryOperator>(VL0);
1314 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), LHS, RHS);
1315 E->VectorizedValue = V;
1318 case Instruction::Load: {
1319 // Loads are inserted at the head of the tree because we don't want to
1320 // sink them all the way down past store instructions.
1321 Builder.SetInsertPoint(getLastInstruction(E->Scalars));
1322 Builder.SetCurrentDebugLocation(VL0->getDebugLoc());
1324 LoadInst *LI = cast<LoadInst>(VL0);
1326 Builder.CreateBitCast(LI->getPointerOperand(), VecTy->getPointerTo());
1327 unsigned Alignment = LI->getAlignment();
1328 LI = Builder.CreateLoad(VecPtr);
1329 LI->setAlignment(Alignment);
1330 E->VectorizedValue = LI;
1333 case Instruction::Store: {
1334 StoreInst *SI = cast<StoreInst>(VL0);
1335 unsigned Alignment = SI->getAlignment();
1338 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1339 ValueOp.push_back(cast<StoreInst>(E->Scalars[i])->getValueOperand());
1341 Builder.SetInsertPoint(getLastInstruction(E->Scalars));
1342 Builder.SetCurrentDebugLocation(VL0->getDebugLoc());
1344 Value *VecValue = vectorizeTree(ValueOp);
1346 Builder.CreateBitCast(SI->getPointerOperand(), VecTy->getPointerTo());
1347 StoreInst *S = Builder.CreateStore(VecValue, VecPtr);
1348 S->setAlignment(Alignment);
1349 E->VectorizedValue = S;
1353 llvm_unreachable("unknown inst");
1358 void BoUpSLP::vectorizeTree() {
1359 Builder.SetInsertPoint(F->getEntryBlock().begin());
1360 vectorizeTree(&VectorizableTree[0]);
1362 DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() << " values .\n");
1364 // Extract all of the elements with the external uses.
1365 for (UserList::iterator it = ExternalUses.begin(), e = ExternalUses.end();
1367 Value *Scalar = it->Scalar;
1368 llvm::User *User = it->User;
1370 // Skip users that we already RAUW. This happens when one instruction
1371 // has multiple uses of the same value.
1372 if (std::find(Scalar->use_begin(), Scalar->use_end(), User) ==
1375 assert(ScalarToTreeEntry.count(Scalar) && "Invalid scalar");
1377 int Idx = ScalarToTreeEntry[Scalar];
1378 TreeEntry *E = &VectorizableTree[Idx];
1379 assert(!E->NeedToGather && "Extracting from a gather list");
1381 Value *Vec = E->VectorizedValue;
1382 assert(Vec && "Can't find vectorizable value");
1384 Value *Lane = Builder.getInt32(it->Lane);
1385 // Generate extracts for out-of-tree users.
1386 // Find the insertion point for the extractelement lane.
1387 if (PHINode *PN = dyn_cast<PHINode>(Vec)) {
1388 Builder.SetInsertPoint(PN->getParent()->getFirstInsertionPt());
1389 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1390 User->replaceUsesOfWith(Scalar, Ex);
1391 } else if (isa<Instruction>(Vec)){
1392 if (PHINode *PH = dyn_cast<PHINode>(User)) {
1393 for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
1394 if (PH->getIncomingValue(i) == Scalar) {
1395 Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
1396 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1397 PH->setOperand(i, Ex);
1401 Builder.SetInsertPoint(cast<Instruction>(User));
1402 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1403 User->replaceUsesOfWith(Scalar, Ex);
1406 Builder.SetInsertPoint(F->getEntryBlock().begin());
1407 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1408 User->replaceUsesOfWith(Scalar, Ex);
1411 DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
1414 // For each vectorized value:
1415 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
1416 TreeEntry *Entry = &VectorizableTree[EIdx];
1419 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
1420 Value *Scalar = Entry->Scalars[Lane];
1422 // No need to handle users of gathered values.
1423 if (Entry->NeedToGather)
1426 assert(Entry->VectorizedValue && "Can't find vectorizable value");
1428 Type *Ty = Scalar->getType();
1429 if (!Ty->isVoidTy()) {
1430 for (Value::use_iterator User = Scalar->use_begin(),
1431 UE = Scalar->use_end(); User != UE; ++User) {
1432 DEBUG(dbgs() << "SLP: \tvalidating user:" << **User << ".\n");
1433 assert(!MustGather.count(*User) &&
1434 "Replacing gathered value with undef");
1435 assert(ScalarToTreeEntry.count(*User) &&
1436 "Replacing out-of-tree value with undef");
1438 Value *Undef = UndefValue::get(Ty);
1439 Scalar->replaceAllUsesWith(Undef);
1441 DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
1442 cast<Instruction>(Scalar)->eraseFromParent();
1446 for (Function::iterator it = F->begin(), e = F->end(); it != e; ++it) {
1447 BlocksNumbers[it].forget();
1449 Builder.ClearInsertionPoint();
1452 void BoUpSLP::optimizeGatherSequence() {
1453 DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
1454 << " gather sequences instructions.\n");
1455 // LICM InsertElementInst sequences.
1456 for (SetVector<Instruction *>::iterator it = GatherSeq.begin(),
1457 e = GatherSeq.end(); it != e; ++it) {
1458 InsertElementInst *Insert = dyn_cast<InsertElementInst>(*it);
1463 // Check if this block is inside a loop.
1464 Loop *L = LI->getLoopFor(Insert->getParent());
1468 // Check if it has a preheader.
1469 BasicBlock *PreHeader = L->getLoopPreheader();
1473 // If the vector or the element that we insert into it are
1474 // instructions that are defined in this basic block then we can't
1475 // hoist this instruction.
1476 Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
1477 Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
1478 if (CurrVec && L->contains(CurrVec))
1480 if (NewElem && L->contains(NewElem))
1483 // We can hoist this instruction. Move it to the pre-header.
1484 Insert->moveBefore(PreHeader->getTerminator());
1487 // Perform O(N^2) search over the gather sequences and merge identical
1488 // instructions. TODO: We can further optimize this scan if we split the
1489 // instructions into different buckets based on the insert lane.
1490 SmallPtrSet<Instruction*, 16> Visited;
1491 SmallVector<Instruction*, 16> ToRemove;
1492 ReversePostOrderTraversal<Function*> RPOT(F);
1493 for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
1494 E = RPOT.end(); I != E; ++I) {
1495 BasicBlock *BB = *I;
1496 // For all instructions in the function:
1497 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1498 Instruction *In = it;
1499 if ((!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In)) ||
1500 !GatherSeq.count(In))
1503 // Check if we can replace this instruction with any of the
1504 // visited instructions.
1505 for (SmallPtrSet<Instruction*, 16>::iterator v = Visited.begin(),
1506 ve = Visited.end(); v != ve; ++v) {
1507 if (In->isIdenticalTo(*v) &&
1508 DT->dominates((*v)->getParent(), In->getParent())) {
1509 In->replaceAllUsesWith(*v);
1510 ToRemove.push_back(In);
1520 // Erase all of the instructions that we RAUWed.
1521 for (SmallVectorImpl<Instruction *>::iterator v = ToRemove.begin(),
1522 ve = ToRemove.end(); v != ve; ++v) {
1523 assert((*v)->getNumUses() == 0 && "Can't remove instructions with uses");
1524 (*v)->eraseFromParent();
1528 /// The SLPVectorizer Pass.
1529 struct SLPVectorizer : public FunctionPass {
1530 typedef SmallVector<StoreInst *, 8> StoreList;
1531 typedef MapVector<Value *, StoreList> StoreListMap;
1533 /// Pass identification, replacement for typeid
1536 explicit SLPVectorizer() : FunctionPass(ID) {
1537 initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
1540 ScalarEvolution *SE;
1542 TargetTransformInfo *TTI;
1547 virtual bool runOnFunction(Function &F) {
1548 SE = &getAnalysis<ScalarEvolution>();
1549 DL = getAnalysisIfAvailable<DataLayout>();
1550 TTI = &getAnalysis<TargetTransformInfo>();
1551 AA = &getAnalysis<AliasAnalysis>();
1552 LI = &getAnalysis<LoopInfo>();
1553 DT = &getAnalysis<DominatorTree>();
1556 bool Changed = false;
1558 // Must have DataLayout. We can't require it because some tests run w/o
1563 // Don't vectorize when the attribute NoImplicitFloat is used.
1564 if (F.hasFnAttribute(Attribute::NoImplicitFloat))
1567 DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
1569 // Use the bollom up slp vectorizer to construct chains that start with
1570 // he store instructions.
1571 BoUpSLP R(&F, SE, DL, TTI, AA, LI, DT);
1573 // Scan the blocks in the function in post order.
1574 for (po_iterator<BasicBlock*> it = po_begin(&F.getEntryBlock()),
1575 e = po_end(&F.getEntryBlock()); it != e; ++it) {
1576 BasicBlock *BB = *it;
1578 // Vectorize trees that end at stores.
1579 if (unsigned count = collectStores(BB, R)) {
1581 DEBUG(dbgs() << "SLP: Found " << count << " stores to vectorize.\n");
1582 Changed |= vectorizeStoreChains(R);
1585 // Vectorize trees that end at reductions.
1586 Changed |= vectorizeChainsInBlock(BB, R);
1590 R.optimizeGatherSequence();
1591 DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
1592 DEBUG(verifyFunction(F));
1597 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1598 FunctionPass::getAnalysisUsage(AU);
1599 AU.addRequired<ScalarEvolution>();
1600 AU.addRequired<AliasAnalysis>();
1601 AU.addRequired<TargetTransformInfo>();
1602 AU.addRequired<LoopInfo>();
1603 AU.addRequired<DominatorTree>();
1604 AU.addPreserved<LoopInfo>();
1605 AU.addPreserved<DominatorTree>();
1606 AU.setPreservesCFG();
1611 /// \brief Collect memory references and sort them according to their base
1612 /// object. We sort the stores to their base objects to reduce the cost of the
1613 /// quadratic search on the stores. TODO: We can further reduce this cost
1614 /// if we flush the chain creation every time we run into a memory barrier.
1615 unsigned collectStores(BasicBlock *BB, BoUpSLP &R);
1617 /// \brief Try to vectorize a chain that starts at two arithmetic instrs.
1618 bool tryToVectorizePair(Value *A, Value *B, BoUpSLP &R);
1620 /// \brief Try to vectorize a list of operands.
1621 /// \returns true if a value was vectorized.
1622 bool tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R);
1624 /// \brief Try to vectorize a chain that may start at the operands of \V;
1625 bool tryToVectorize(BinaryOperator *V, BoUpSLP &R);
1627 /// \brief Vectorize the stores that were collected in StoreRefs.
1628 bool vectorizeStoreChains(BoUpSLP &R);
1630 /// \brief Scan the basic block and look for patterns that are likely to start
1631 /// a vectorization chain.
1632 bool vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R);
1634 bool vectorizeStoreChain(ArrayRef<Value *> Chain, int CostThreshold,
1637 bool vectorizeStores(ArrayRef<StoreInst *> Stores, int costThreshold,
1640 StoreListMap StoreRefs;
1643 bool SLPVectorizer::vectorizeStoreChain(ArrayRef<Value *> Chain,
1644 int CostThreshold, BoUpSLP &R) {
1645 unsigned ChainLen = Chain.size();
1646 DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
1648 Type *StoreTy = cast<StoreInst>(Chain[0])->getValueOperand()->getType();
1649 unsigned Sz = DL->getTypeSizeInBits(StoreTy);
1650 unsigned VF = MinVecRegSize / Sz;
1652 if (!isPowerOf2_32(Sz) || VF < 2)
1655 bool Changed = false;
1656 // Look for profitable vectorizable trees at all offsets, starting at zero.
1657 for (unsigned i = 0, e = ChainLen; i < e; ++i) {
1660 DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
1662 ArrayRef<Value *> Operands = Chain.slice(i, VF);
1664 R.buildTree(Operands);
1666 int Cost = R.getTreeCost();
1668 DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
1669 if (Cost < CostThreshold) {
1670 DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
1673 // Move to the next bundle.
1682 bool SLPVectorizer::vectorizeStores(ArrayRef<StoreInst *> Stores,
1683 int costThreshold, BoUpSLP &R) {
1684 SetVector<Value *> Heads, Tails;
1685 SmallDenseMap<Value *, Value *> ConsecutiveChain;
1687 // We may run into multiple chains that merge into a single chain. We mark the
1688 // stores that we vectorized so that we don't visit the same store twice.
1689 BoUpSLP::ValueSet VectorizedStores;
1690 bool Changed = false;
1692 // Do a quadratic search on all of the given stores and find
1693 // all of the pairs of stores that follow each other.
1694 for (unsigned i = 0, e = Stores.size(); i < e; ++i) {
1695 for (unsigned j = 0; j < e; ++j) {
1699 if (R.isConsecutiveAccess(Stores[i], Stores[j])) {
1700 Tails.insert(Stores[j]);
1701 Heads.insert(Stores[i]);
1702 ConsecutiveChain[Stores[i]] = Stores[j];
1707 // For stores that start but don't end a link in the chain:
1708 for (SetVector<Value *>::iterator it = Heads.begin(), e = Heads.end();
1710 if (Tails.count(*it))
1713 // We found a store instr that starts a chain. Now follow the chain and try
1715 BoUpSLP::ValueList Operands;
1717 // Collect the chain into a list.
1718 while (Tails.count(I) || Heads.count(I)) {
1719 if (VectorizedStores.count(I))
1721 Operands.push_back(I);
1722 // Move to the next value in the chain.
1723 I = ConsecutiveChain[I];
1726 bool Vectorized = vectorizeStoreChain(Operands, costThreshold, R);
1728 // Mark the vectorized stores so that we don't vectorize them again.
1730 VectorizedStores.insert(Operands.begin(), Operands.end());
1731 Changed |= Vectorized;
1738 unsigned SLPVectorizer::collectStores(BasicBlock *BB, BoUpSLP &R) {
1741 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1742 StoreInst *SI = dyn_cast<StoreInst>(it);
1746 // Check that the pointer points to scalars.
1747 Type *Ty = SI->getValueOperand()->getType();
1748 if (Ty->isAggregateType() || Ty->isVectorTy())
1751 // Find the base of the GEP.
1752 Value *Ptr = SI->getPointerOperand();
1753 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
1754 Ptr = GEP->getPointerOperand();
1756 // Save the store locations.
1757 StoreRefs[Ptr].push_back(SI);
1763 bool SLPVectorizer::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
1766 Value *VL[] = { A, B };
1767 return tryToVectorizeList(VL, R);
1770 bool SLPVectorizer::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R) {
1774 DEBUG(dbgs() << "SLP: Vectorizing a list of length = " << VL.size() << ".\n");
1776 // Check that all of the parts are scalar instructions of the same type.
1777 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
1781 unsigned Opcode0 = I0->getOpcode();
1783 for (int i = 0, e = VL.size(); i < e; ++i) {
1784 Type *Ty = VL[i]->getType();
1785 if (Ty->isAggregateType() || Ty->isVectorTy())
1787 Instruction *Inst = dyn_cast<Instruction>(VL[i]);
1788 if (!Inst || Inst->getOpcode() != Opcode0)
1793 int Cost = R.getTreeCost();
1795 if (Cost >= -SLPCostThreshold)
1798 DEBUG(dbgs() << "SLP: Vectorizing pair at cost:" << Cost << ".\n");
1803 bool SLPVectorizer::tryToVectorize(BinaryOperator *V, BoUpSLP &R) {
1807 // Try to vectorize V.
1808 if (tryToVectorizePair(V->getOperand(0), V->getOperand(1), R))
1811 BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0));
1812 BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1));
1814 if (B && B->hasOneUse()) {
1815 BinaryOperator *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
1816 BinaryOperator *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
1817 if (tryToVectorizePair(A, B0, R)) {
1821 if (tryToVectorizePair(A, B1, R)) {
1828 if (A && A->hasOneUse()) {
1829 BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
1830 BinaryOperator *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
1831 if (tryToVectorizePair(A0, B, R)) {
1835 if (tryToVectorizePair(A1, B, R)) {
1843 /// \brief Recognize construction of vectors like
1844 /// %ra = insertelement <4 x float> undef, float %s0, i32 0
1845 /// %rb = insertelement <4 x float> %ra, float %s1, i32 1
1846 /// %rc = insertelement <4 x float> %rb, float %s2, i32 2
1847 /// %rd = insertelement <4 x float> %rc, float %s3, i32 3
1849 /// Returns true if it matches
1851 static bool findBuildVector(InsertElementInst *IE,
1852 SmallVectorImpl<Value *> &Ops) {
1853 if (!isa<UndefValue>(IE->getOperand(0)))
1857 Ops.push_back(IE->getOperand(1));
1859 if (IE->use_empty())
1862 InsertElementInst *NextUse = dyn_cast<InsertElementInst>(IE->use_back());
1866 // If this isn't the final use, make sure the next insertelement is the only
1867 // use. It's OK if the final constructed vector is used multiple times
1868 if (!IE->hasOneUse())
1877 bool SLPVectorizer::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
1878 bool Changed = false;
1879 SmallVector<Value *, 4> Incoming;
1880 SmallSet<Instruction *, 16> VisitedInstrs;
1882 // Collect the incoming values from the PHIs.
1883 for (BasicBlock::iterator instr = BB->begin(), ie = BB->end(); instr != ie;
1885 PHINode *P = dyn_cast<PHINode>(instr);
1890 // We may go through BB multiple times so skip the one we have checked.
1891 if (!VisitedInstrs.insert(instr))
1894 // Stop constructing the list when you reach a different type.
1895 if (Incoming.size() && P->getType() != Incoming[0]->getType()) {
1896 if (tryToVectorizeList(Incoming, R)) {
1897 // We would like to start over since some instructions are deleted
1898 // and the iterator may become invalid value.
1900 instr = BB->begin();
1907 Incoming.push_back(P);
1910 if (Incoming.size() > 1)
1911 Changed |= tryToVectorizeList(Incoming, R);
1913 VisitedInstrs.clear();
1915 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) {
1917 // We may go through BB multiple times so skip the one we have checked.
1918 if (!VisitedInstrs.insert(it))
1921 if (isa<DbgInfoIntrinsic>(it))
1924 // Try to vectorize reductions that use PHINodes.
1925 if (PHINode *P = dyn_cast<PHINode>(it)) {
1926 // Check that the PHI is a reduction PHI.
1927 if (P->getNumIncomingValues() != 2)
1930 (P->getIncomingBlock(0) == BB
1931 ? (P->getIncomingValue(0))
1932 : (P->getIncomingBlock(1) == BB ? P->getIncomingValue(1) : 0));
1933 // Check if this is a Binary Operator.
1934 BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx);
1938 Value *Inst = BI->getOperand(0);
1940 Inst = BI->getOperand(1);
1942 if (tryToVectorize(dyn_cast<BinaryOperator>(Inst), R)) {
1943 // We would like to start over since some instructions are deleted
1944 // and the iterator may become invalid value.
1952 // Try to vectorize trees that start at compare instructions.
1953 if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
1954 if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) {
1956 // We would like to start over since some instructions are deleted
1957 // and the iterator may become invalid value.
1963 for (int i = 0; i < 2; ++i) {
1964 if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i))) {
1965 if (tryToVectorizePair(BI->getOperand(0), BI->getOperand(1), R)) {
1967 // We would like to start over since some instructions are deleted
1968 // and the iterator may become invalid value.
1977 // Try to vectorize trees that start at insertelement instructions.
1978 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(it)) {
1979 SmallVector<Value *, 8> Ops;
1980 if (!findBuildVector(IE, Ops))
1983 if (tryToVectorizeList(Ops, R)) {
1996 bool SLPVectorizer::vectorizeStoreChains(BoUpSLP &R) {
1997 bool Changed = false;
1998 // Attempt to sort and vectorize each of the store-groups.
1999 for (StoreListMap::iterator it = StoreRefs.begin(), e = StoreRefs.end();
2001 if (it->second.size() < 2)
2004 DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
2005 << it->second.size() << ".\n");
2007 // Process the stores in chunks of 16.
2008 for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI+=16) {
2009 unsigned Len = std::min<unsigned>(CE - CI, 16);
2010 ArrayRef<StoreInst *> Chunk(&it->second[CI], Len);
2011 Changed |= vectorizeStores(Chunk, -SLPCostThreshold, R);
2017 } // end anonymous namespace
2019 char SLPVectorizer::ID = 0;
2020 static const char lv_name[] = "SLP Vectorizer";
2021 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
2022 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
2023 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
2024 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
2025 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
2026 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
2029 Pass *createSLPVectorizerPass() { return new SLPVectorizer(); }