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 SmallVector<Instruction *, 32> 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 ExternalUses.clear();
250 MemBarrierIgnoreList.clear();
253 /// \returns true if the memory operations A and B are consecutive.
254 bool isConsecutiveAccess(Value *A, Value *B);
256 /// \brief Perform LICM and CSE on the newly generated gather sequences.
257 void optimizeGatherSequence();
261 /// \returns the cost of the vectorizable entry.
262 int getEntryCost(TreeEntry *E);
264 /// This is the recursive part of buildTree.
265 void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth);
267 /// Vectorize a single entry in the tree.
268 Value *vectorizeTree(TreeEntry *E);
270 /// Vectorize a single entry in the tree, starting in \p VL.
271 Value *vectorizeTree(ArrayRef<Value *> VL);
273 /// \returns the pointer to the vectorized value if \p VL is already
274 /// vectorized, or NULL. They may happen in cycles.
275 Value *alreadyVectorized(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 scalarization cost for this list of values. Assuming that
290 /// this subtree gets vectorized, we may need to extract the values from the
291 /// roots. This method calculates the cost of extracting the values.
292 int getGatherCost(ArrayRef<Value *> VL);
294 /// \returns the AA location that is being access by the instruction.
295 AliasAnalysis::Location getLocation(Instruction *I);
297 /// \brief Checks if it is possible to sink an instruction from
298 /// \p Src to \p Dst.
299 /// \returns the pointer to the barrier instruction if we can't sink.
300 Value *getSinkBarrier(Instruction *Src, Instruction *Dst);
302 /// \returns the index of the last instrucion in the BB from \p VL.
303 int getLastIndex(ArrayRef<Value *> VL);
305 /// \returns the Instrucion in the bundle \p VL.
306 Instruction *getLastInstruction(ArrayRef<Value *> VL);
308 /// \returns a vector from a collection of scalars in \p VL.
309 Value *Gather(ArrayRef<Value *> VL, VectorType *Ty);
312 TreeEntry() : Scalars(), VectorizedValue(0), LastScalarIndex(0),
315 /// \returns true if the scalars in VL are equal to this entry.
316 bool isSame(ArrayRef<Value *> VL) {
317 assert(VL.size() == Scalars.size() && "Invalid size");
318 for (int i = 0, e = VL.size(); i != e; ++i)
319 if (VL[i] != Scalars[i])
324 /// A vector of scalars.
327 /// The Scalars are vectorized into this value. It is initialized to Null.
328 Value *VectorizedValue;
330 /// The index in the basic block of the last scalar.
333 /// Do we need to gather this sequence ?
337 /// Create a new VectorizableTree entry.
338 TreeEntry *newTreeEntry(ArrayRef<Value *> VL, bool Vectorized) {
339 VectorizableTree.push_back(TreeEntry());
340 int idx = VectorizableTree.size() - 1;
341 TreeEntry *Last = &VectorizableTree[idx];
342 Last->Scalars.insert(Last->Scalars.begin(), VL.begin(), VL.end());
343 Last->NeedToGather = !Vectorized;
345 Last->LastScalarIndex = getLastIndex(VL);
346 for (int i = 0, e = VL.size(); i != e; ++i) {
347 assert(!ScalarToTreeEntry.count(VL[i]) && "Scalar already in tree!");
348 ScalarToTreeEntry[VL[i]] = idx;
351 Last->LastScalarIndex = 0;
352 MustGather.insert(VL.begin(), VL.end());
357 /// -- Vectorization State --
358 /// Holds all of the tree entries.
359 std::vector<TreeEntry> VectorizableTree;
361 /// Maps a specific scalar to its tree entry.
362 SmallDenseMap<Value*, int> ScalarToTreeEntry;
364 /// A list of scalars that we found that we need to keep as scalars.
367 /// This POD struct describes one external user in the vectorized tree.
368 struct ExternalUser {
369 ExternalUser (Value *S, llvm::User *U, int L) :
370 Scalar(S), User(U), Lane(L){};
371 // Which scalar in our function.
373 // Which user that uses the scalar.
375 // Which lane does the scalar belong to.
378 typedef SmallVector<ExternalUser, 16> UserList;
380 /// A list of values that need to extracted out of the tree.
381 /// This list holds pairs of (Internal Scalar : External User).
382 UserList ExternalUses;
384 /// A list of instructions to ignore while sinking
385 /// memory instructions. This map must be reset between runs of getCost.
386 ValueSet MemBarrierIgnoreList;
388 /// Holds all of the instructions that we gathered.
389 SetVector<Instruction *> GatherSeq;
391 /// Numbers instructions in different blocks.
392 DenseMap<BasicBlock *, BlockNumbering> BlocksNumbers;
394 // Analysis and block reference.
398 TargetTransformInfo *TTI;
402 /// Instruction builder to construct the vectorized tree.
406 void BoUpSLP::buildTree(ArrayRef<Value *> Roots) {
408 if (!getSameType(Roots))
410 buildTree_rec(Roots, 0);
412 // Collect the values that we need to extract from the tree.
413 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
414 TreeEntry *Entry = &VectorizableTree[EIdx];
417 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
418 Value *Scalar = Entry->Scalars[Lane];
420 // No need to handle users of gathered values.
421 if (Entry->NeedToGather)
424 for (Value::use_iterator User = Scalar->use_begin(),
425 UE = Scalar->use_end(); User != UE; ++User) {
426 DEBUG(dbgs() << "SLP: Checking user:" << **User << ".\n");
428 bool Gathered = MustGather.count(*User);
430 // Skip in-tree scalars that become vectors.
431 if (ScalarToTreeEntry.count(*User) && !Gathered) {
432 DEBUG(dbgs() << "SLP: \tInternal user will be removed:" <<
434 int Idx = ScalarToTreeEntry[*User]; (void) Idx;
435 assert(!VectorizableTree[Idx].NeedToGather && "Bad state");
439 if (!isa<Instruction>(*User))
442 DEBUG(dbgs() << "SLP: Need to extract:" << **User << " from lane " <<
443 Lane << " from " << *Scalar << ".\n");
444 ExternalUses.push_back(ExternalUser(Scalar, *User, Lane));
451 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth) {
452 bool SameTy = getSameType(VL); (void)SameTy;
453 assert(SameTy && "Invalid types!");
455 if (Depth == RecursionMaxDepth) {
456 DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
457 newTreeEntry(VL, false);
461 // Don't handle vectors.
462 if (VL[0]->getType()->isVectorTy()) {
463 DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
464 newTreeEntry(VL, false);
468 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
469 if (SI->getValueOperand()->getType()->isVectorTy()) {
470 DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
471 newTreeEntry(VL, false);
475 // If all of the operands are identical or constant we have a simple solution.
476 if (allConstant(VL) || isSplat(VL) || !getSameBlock(VL) ||
477 !getSameOpcode(VL)) {
478 DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
479 newTreeEntry(VL, false);
483 // We now know that this is a vector of instructions of the same type from
486 // Check if this is a duplicate of another entry.
487 if (ScalarToTreeEntry.count(VL[0])) {
488 int Idx = ScalarToTreeEntry[VL[0]];
489 TreeEntry *E = &VectorizableTree[Idx];
490 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
491 DEBUG(dbgs() << "SLP: \tChecking bundle: " << *VL[i] << ".\n");
492 if (E->Scalars[i] != VL[i]) {
493 DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
494 newTreeEntry(VL, false);
498 DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *VL[0] << ".\n");
502 // Check that none of the instructions in the bundle are already in the tree.
503 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
504 if (ScalarToTreeEntry.count(VL[i])) {
505 DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
506 ") is already in tree.\n");
507 newTreeEntry(VL, false);
512 // If any of the scalars appears in the table OR it is marked as a value that
513 // needs to stat scalar then we need to gather the scalars.
514 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
515 if (ScalarToTreeEntry.count(VL[i]) || MustGather.count(VL[i])) {
516 DEBUG(dbgs() << "SLP: Gathering due to gathered scalar. \n");
517 newTreeEntry(VL, false);
522 // Check that all of the users of the scalars that we want to vectorize are
524 Instruction *VL0 = cast<Instruction>(VL[0]);
525 int MyLastIndex = getLastIndex(VL);
526 BasicBlock *BB = cast<Instruction>(VL0)->getParent();
528 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
529 Instruction *Scalar = cast<Instruction>(VL[i]);
530 DEBUG(dbgs() << "SLP: Checking users of " << *Scalar << ". \n");
531 for (Value::use_iterator U = Scalar->use_begin(), UE = Scalar->use_end();
533 DEBUG(dbgs() << "SLP: \tUser " << **U << ". \n");
534 Instruction *User = dyn_cast<Instruction>(*U);
536 DEBUG(dbgs() << "SLP: Gathering due unknown user. \n");
537 newTreeEntry(VL, false);
541 // We don't care if the user is in a different basic block.
542 BasicBlock *UserBlock = User->getParent();
543 if (UserBlock != BB) {
544 DEBUG(dbgs() << "SLP: User from a different basic block "
549 // If this is a PHINode within this basic block then we can place the
550 // extract wherever we want.
551 if (isa<PHINode>(*User)) {
552 DEBUG(dbgs() << "SLP: \tWe can schedule PHIs:" << *User << ". \n");
556 // Check if this is a safe in-tree user.
557 if (ScalarToTreeEntry.count(User)) {
558 int Idx = ScalarToTreeEntry[User];
559 int VecLocation = VectorizableTree[Idx].LastScalarIndex;
560 if (VecLocation <= MyLastIndex) {
561 DEBUG(dbgs() << "SLP: Gathering due to unschedulable vector. \n");
562 newTreeEntry(VL, false);
565 DEBUG(dbgs() << "SLP: In-tree user (" << *User << ") at #" <<
566 VecLocation << " vector value (" << *Scalar << ") at #"
567 << MyLastIndex << ".\n");
571 // Make sure that we can schedule this unknown user.
572 BlockNumbering &BN = BlocksNumbers[BB];
573 int UserIndex = BN.getIndex(User);
574 if (UserIndex < MyLastIndex) {
576 DEBUG(dbgs() << "SLP: Can't schedule extractelement for "
578 newTreeEntry(VL, false);
584 // Check that every instructions appears once in this bundle.
585 for (unsigned i = 0, e = VL.size(); i < e; ++i)
586 for (unsigned j = i+1; j < e; ++j)
587 if (VL[i] == VL[j]) {
588 DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
589 newTreeEntry(VL, false);
593 // Check that instructions in this bundle don't reference other instructions.
594 // The runtime of this check is O(N * N-1 * uses(N)) and a typical N is 4.
595 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
596 for (Value::use_iterator U = VL[i]->use_begin(), UE = VL[i]->use_end();
598 for (unsigned j = 0; j < e; ++j) {
599 if (i != j && *U == VL[j]) {
600 DEBUG(dbgs() << "SLP: Intra-bundle dependencies!" << **U << ". \n");
601 newTreeEntry(VL, false);
608 DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
610 unsigned Opcode = getSameOpcode(VL);
612 // Check if it is safe to sink the loads or the stores.
613 if (Opcode == Instruction::Load || Opcode == Instruction::Store) {
614 Instruction *Last = getLastInstruction(VL);
616 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
619 Value *Barrier = getSinkBarrier(cast<Instruction>(VL[i]), Last);
621 DEBUG(dbgs() << "SLP: Can't sink " << *VL[i] << "\n down to " << *Last
622 << "\n because of " << *Barrier << ". Gathering.\n");
623 newTreeEntry(VL, false);
630 case Instruction::PHI: {
631 PHINode *PH = dyn_cast<PHINode>(VL0);
632 newTreeEntry(VL, true);
633 DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
635 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
637 // Prepare the operand vector.
638 for (unsigned j = 0; j < VL.size(); ++j)
639 Operands.push_back(cast<PHINode>(VL[j])->getIncomingValue(i));
641 buildTree_rec(Operands, Depth + 1);
645 case Instruction::ExtractElement: {
646 bool Reuse = CanReuseExtract(VL);
648 DEBUG(dbgs() << "SLP: Reusing extract sequence.\n");
650 newTreeEntry(VL, Reuse);
653 case Instruction::Load: {
654 // Check if the loads are consecutive or of we need to swizzle them.
655 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
656 if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
657 newTreeEntry(VL, false);
658 DEBUG(dbgs() << "SLP: Need to swizzle loads.\n");
662 newTreeEntry(VL, true);
663 DEBUG(dbgs() << "SLP: added a vector of loads.\n");
666 case Instruction::ZExt:
667 case Instruction::SExt:
668 case Instruction::FPToUI:
669 case Instruction::FPToSI:
670 case Instruction::FPExt:
671 case Instruction::PtrToInt:
672 case Instruction::IntToPtr:
673 case Instruction::SIToFP:
674 case Instruction::UIToFP:
675 case Instruction::Trunc:
676 case Instruction::FPTrunc:
677 case Instruction::BitCast: {
678 Type *SrcTy = VL0->getOperand(0)->getType();
679 for (unsigned i = 0; i < VL.size(); ++i) {
680 Type *Ty = cast<Instruction>(VL[i])->getOperand(0)->getType();
681 if (Ty != SrcTy || Ty->isAggregateType() || Ty->isVectorTy()) {
682 newTreeEntry(VL, false);
683 DEBUG(dbgs() << "SLP: Gathering casts with different src types.\n");
687 newTreeEntry(VL, true);
688 DEBUG(dbgs() << "SLP: added a vector of casts.\n");
690 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
692 // Prepare the operand vector.
693 for (unsigned j = 0; j < VL.size(); ++j)
694 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
696 buildTree_rec(Operands, Depth+1);
700 case Instruction::ICmp:
701 case Instruction::FCmp: {
702 // Check that all of the compares have the same predicate.
703 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
704 Type *ComparedTy = cast<Instruction>(VL[0])->getOperand(0)->getType();
705 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
706 CmpInst *Cmp = cast<CmpInst>(VL[i]);
707 if (Cmp->getPredicate() != P0 ||
708 Cmp->getOperand(0)->getType() != ComparedTy) {
709 newTreeEntry(VL, false);
710 DEBUG(dbgs() << "SLP: Gathering cmp with different predicate.\n");
715 newTreeEntry(VL, true);
716 DEBUG(dbgs() << "SLP: added a vector of compares.\n");
718 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
720 // Prepare the operand vector.
721 for (unsigned j = 0; j < VL.size(); ++j)
722 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
724 buildTree_rec(Operands, Depth+1);
728 case Instruction::Select:
729 case Instruction::Add:
730 case Instruction::FAdd:
731 case Instruction::Sub:
732 case Instruction::FSub:
733 case Instruction::Mul:
734 case Instruction::FMul:
735 case Instruction::UDiv:
736 case Instruction::SDiv:
737 case Instruction::FDiv:
738 case Instruction::URem:
739 case Instruction::SRem:
740 case Instruction::FRem:
741 case Instruction::Shl:
742 case Instruction::LShr:
743 case Instruction::AShr:
744 case Instruction::And:
745 case Instruction::Or:
746 case Instruction::Xor: {
747 newTreeEntry(VL, true);
748 DEBUG(dbgs() << "SLP: added a vector of bin op.\n");
750 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
752 // Prepare the operand vector.
753 for (unsigned j = 0; j < VL.size(); ++j)
754 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
756 buildTree_rec(Operands, Depth+1);
760 case Instruction::Store: {
761 // Check if the stores are consecutive or of we need to swizzle them.
762 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
763 if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
764 newTreeEntry(VL, false);
765 DEBUG(dbgs() << "SLP: Non consecutive store.\n");
769 newTreeEntry(VL, true);
770 DEBUG(dbgs() << "SLP: added a vector of stores.\n");
773 for (unsigned j = 0; j < VL.size(); ++j)
774 Operands.push_back(cast<Instruction>(VL[j])->getOperand(0));
776 // We can ignore these values because we are sinking them down.
777 MemBarrierIgnoreList.insert(VL.begin(), VL.end());
778 buildTree_rec(Operands, Depth + 1);
782 newTreeEntry(VL, false);
783 DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
788 int BoUpSLP::getEntryCost(TreeEntry *E) {
789 ArrayRef<Value*> VL = E->Scalars;
791 Type *ScalarTy = VL[0]->getType();
792 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
793 ScalarTy = SI->getValueOperand()->getType();
794 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
796 if (E->NeedToGather) {
800 return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
802 return getGatherCost(E->Scalars);
805 assert(getSameOpcode(VL) && getSameType(VL) && getSameBlock(VL) &&
807 Instruction *VL0 = cast<Instruction>(VL[0]);
808 unsigned Opcode = VL0->getOpcode();
810 case Instruction::PHI: {
813 case Instruction::ExtractElement: {
814 if (CanReuseExtract(VL))
816 return getGatherCost(VecTy);
818 case Instruction::ZExt:
819 case Instruction::SExt:
820 case Instruction::FPToUI:
821 case Instruction::FPToSI:
822 case Instruction::FPExt:
823 case Instruction::PtrToInt:
824 case Instruction::IntToPtr:
825 case Instruction::SIToFP:
826 case Instruction::UIToFP:
827 case Instruction::Trunc:
828 case Instruction::FPTrunc:
829 case Instruction::BitCast: {
830 Type *SrcTy = VL0->getOperand(0)->getType();
832 // Calculate the cost of this instruction.
833 int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(),
834 VL0->getType(), SrcTy);
836 VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
837 int VecCost = TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy);
838 return VecCost - ScalarCost;
840 case Instruction::FCmp:
841 case Instruction::ICmp:
842 case Instruction::Select:
843 case Instruction::Add:
844 case Instruction::FAdd:
845 case Instruction::Sub:
846 case Instruction::FSub:
847 case Instruction::Mul:
848 case Instruction::FMul:
849 case Instruction::UDiv:
850 case Instruction::SDiv:
851 case Instruction::FDiv:
852 case Instruction::URem:
853 case Instruction::SRem:
854 case Instruction::FRem:
855 case Instruction::Shl:
856 case Instruction::LShr:
857 case Instruction::AShr:
858 case Instruction::And:
859 case Instruction::Or:
860 case Instruction::Xor: {
861 // Calculate the cost of this instruction.
864 if (Opcode == Instruction::FCmp || Opcode == Instruction::ICmp ||
865 Opcode == Instruction::Select) {
866 VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
867 ScalarCost = VecTy->getNumElements() *
868 TTI->getCmpSelInstrCost(Opcode, ScalarTy, Builder.getInt1Ty());
869 VecCost = TTI->getCmpSelInstrCost(Opcode, VecTy, MaskTy);
871 ScalarCost = VecTy->getNumElements() *
872 TTI->getArithmeticInstrCost(Opcode, ScalarTy);
873 VecCost = TTI->getArithmeticInstrCost(Opcode, VecTy);
875 return VecCost - ScalarCost;
877 case Instruction::Load: {
878 // Cost of wide load - cost of scalar loads.
879 int ScalarLdCost = VecTy->getNumElements() *
880 TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
881 int VecLdCost = TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
882 return VecLdCost - ScalarLdCost;
884 case Instruction::Store: {
885 // We know that we can merge the stores. Calculate the cost.
886 int ScalarStCost = VecTy->getNumElements() *
887 TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
888 int VecStCost = TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
889 return VecStCost - ScalarStCost;
892 llvm_unreachable("Unknown instruction");
896 int BoUpSLP::getTreeCost() {
898 DEBUG(dbgs() << "SLP: Calculating cost for tree of size " <<
899 VectorizableTree.size() << ".\n");
901 // Don't vectorize tiny trees. Small load/store chains or consecutive stores
902 // of constants will be vectoried in SelectionDAG in MergeConsecutiveStores.
903 // The SelectionDAG vectorizer can only handle pairs (trees of height = 2).
904 if (VectorizableTree.size() < 3) {
905 if (!VectorizableTree.size()) {
906 assert(!ExternalUses.size() && "We should not have any external users");
911 unsigned BundleWidth = VectorizableTree[0].Scalars.size();
913 for (unsigned i = 0, e = VectorizableTree.size(); i != e; ++i) {
914 int C = getEntryCost(&VectorizableTree[i]);
915 DEBUG(dbgs() << "SLP: Adding cost " << C << " for bundle that starts with "
916 << *VectorizableTree[i].Scalars[0] << " .\n");
921 for (UserList::iterator I = ExternalUses.begin(), E = ExternalUses.end();
924 VectorType *VecTy = VectorType::get(I->Scalar->getType(), BundleWidth);
925 ExtractCost += TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy,
930 DEBUG(dbgs() << "SLP: Total Cost " << Cost + ExtractCost<< ".\n");
931 return Cost + ExtractCost;
934 int BoUpSLP::getGatherCost(Type *Ty) {
936 for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
937 Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
941 int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) {
942 // Find the type of the operands in VL.
943 Type *ScalarTy = VL[0]->getType();
944 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
945 ScalarTy = SI->getValueOperand()->getType();
946 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
947 // Find the cost of inserting/extracting values from the vector.
948 return getGatherCost(VecTy);
951 AliasAnalysis::Location BoUpSLP::getLocation(Instruction *I) {
952 if (StoreInst *SI = dyn_cast<StoreInst>(I))
953 return AA->getLocation(SI);
954 if (LoadInst *LI = dyn_cast<LoadInst>(I))
955 return AA->getLocation(LI);
956 return AliasAnalysis::Location();
959 Value *BoUpSLP::getPointerOperand(Value *I) {
960 if (LoadInst *LI = dyn_cast<LoadInst>(I))
961 return LI->getPointerOperand();
962 if (StoreInst *SI = dyn_cast<StoreInst>(I))
963 return SI->getPointerOperand();
967 unsigned BoUpSLP::getAddressSpaceOperand(Value *I) {
968 if (LoadInst *L = dyn_cast<LoadInst>(I))
969 return L->getPointerAddressSpace();
970 if (StoreInst *S = dyn_cast<StoreInst>(I))
971 return S->getPointerAddressSpace();
975 bool BoUpSLP::isConsecutiveAccess(Value *A, Value *B) {
976 Value *PtrA = getPointerOperand(A);
977 Value *PtrB = getPointerOperand(B);
978 unsigned ASA = getAddressSpaceOperand(A);
979 unsigned ASB = getAddressSpaceOperand(B);
981 // Check that the address spaces match and that the pointers are valid.
982 if (!PtrA || !PtrB || (ASA != ASB))
985 // Make sure that A and B are different pointers of the same type.
986 if (PtrA == PtrB || PtrA->getType() != PtrB->getType())
989 // Calculate a constant offset from the base pointer without using SCEV
990 // in the supported cases.
991 // TODO: Add support for the case where one of the pointers is a GEP that
992 // uses the other pointer.
993 GetElementPtrInst *GepA = dyn_cast<GetElementPtrInst>(PtrA);
994 GetElementPtrInst *GepB = dyn_cast<GetElementPtrInst>(PtrB);
996 unsigned BW = DL->getPointerSizeInBits(ASA);
997 Type *Ty = cast<PointerType>(PtrA->getType())->getElementType();
998 int64_t Sz = DL->getTypeStoreSize(Ty);
1000 // Check if PtrA is the base and PtrB is a constant offset.
1001 if (GepB && GepB->getPointerOperand() == PtrA) {
1002 APInt Offset(BW, 0);
1003 if (GepB->accumulateConstantOffset(*DL, Offset))
1004 return Offset.getSExtValue() == Sz;
1008 // Check if PtrB is the base and PtrA is a constant offset.
1009 if (GepA && GepA->getPointerOperand() == PtrB) {
1010 APInt Offset(BW, 0);
1011 if (GepA->accumulateConstantOffset(*DL, Offset))
1012 return Offset.getSExtValue() == -Sz;
1016 // If both pointers are GEPs:
1018 // Check that they have the same base pointer and number of indices.
1019 if (GepA->getPointerOperand() != GepB->getPointerOperand() ||
1020 GepA->getNumIndices() != GepB->getNumIndices())
1023 // Try to strip the geps. This makes SCEV faster.
1024 // Make sure that all of the indices except for the last are identical.
1025 int LastIdx = GepA->getNumIndices();
1026 for (int i = 0; i < LastIdx - 1; i++) {
1027 if (GepA->getOperand(i+1) != GepB->getOperand(i+1))
1031 PtrA = GepA->getOperand(LastIdx);
1032 PtrB = GepB->getOperand(LastIdx);
1036 ConstantInt *CA = dyn_cast<ConstantInt>(PtrA);
1037 ConstantInt *CB = dyn_cast<ConstantInt>(PtrB);
1039 return (CA->getSExtValue() + Sz == CB->getSExtValue());
1042 // Calculate the distance.
1043 const SCEV *PtrSCEVA = SE->getSCEV(PtrA);
1044 const SCEV *PtrSCEVB = SE->getSCEV(PtrB);
1045 const SCEV *C = SE->getConstant(PtrSCEVA->getType(), Sz);
1046 const SCEV *X = SE->getAddExpr(PtrSCEVA, C);
1047 return X == PtrSCEVB;
1050 Value *BoUpSLP::getSinkBarrier(Instruction *Src, Instruction *Dst) {
1051 assert(Src->getParent() == Dst->getParent() && "Not the same BB");
1052 BasicBlock::iterator I = Src, E = Dst;
1053 /// Scan all of the instruction from SRC to DST and check if
1054 /// the source may alias.
1055 for (++I; I != E; ++I) {
1056 // Ignore store instructions that are marked as 'ignore'.
1057 if (MemBarrierIgnoreList.count(I))
1059 if (Src->mayWriteToMemory()) /* Write */ {
1060 if (!I->mayReadOrWriteMemory())
1063 if (!I->mayWriteToMemory())
1066 AliasAnalysis::Location A = getLocation(&*I);
1067 AliasAnalysis::Location B = getLocation(Src);
1069 if (!A.Ptr || !B.Ptr || AA->alias(A, B))
1075 int BoUpSLP::getLastIndex(ArrayRef<Value *> VL) {
1076 BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
1077 assert(BB == getSameBlock(VL) && BlocksNumbers.count(BB) && "Invalid block");
1078 BlockNumbering &BN = BlocksNumbers[BB];
1080 int MaxIdx = BN.getIndex(BB->getFirstNonPHI());
1081 for (unsigned i = 0, e = VL.size(); i < e; ++i)
1082 MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
1086 Instruction *BoUpSLP::getLastInstruction(ArrayRef<Value *> VL) {
1087 BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
1088 assert(BB == getSameBlock(VL) && BlocksNumbers.count(BB) && "Invalid block");
1089 BlockNumbering &BN = BlocksNumbers[BB];
1091 int MaxIdx = BN.getIndex(cast<Instruction>(VL[0]));
1092 for (unsigned i = 1, e = VL.size(); i < e; ++i)
1093 MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
1094 Instruction *I = BN.getInstruction(MaxIdx);
1095 assert(I && "bad location");
1099 Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
1100 Value *Vec = UndefValue::get(Ty);
1101 // Generate the 'InsertElement' instruction.
1102 for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
1103 Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
1104 if (Instruction *Insrt = dyn_cast<Instruction>(Vec)) {
1105 GatherSeq.insert(Insrt);
1107 // Add to our 'need-to-extract' list.
1108 if (ScalarToTreeEntry.count(VL[i])) {
1109 int Idx = ScalarToTreeEntry[VL[i]];
1110 TreeEntry *E = &VectorizableTree[Idx];
1111 // Find which lane we need to extract.
1113 for (unsigned Lane = 0, LE = VL.size(); Lane != LE; ++Lane) {
1114 // Is this the lane of the scalar that we are looking for ?
1115 if (E->Scalars[Lane] == VL[i]) {
1120 assert(FoundLane >= 0 && "Could not find the correct lane");
1121 ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
1129 Value *BoUpSLP::alreadyVectorized(ArrayRef<Value *> VL) {
1130 if (ScalarToTreeEntry.count(VL[0])) {
1131 int Idx = ScalarToTreeEntry[VL[0]];
1132 TreeEntry *En = &VectorizableTree[Idx];
1133 if (En->isSame(VL) && En->VectorizedValue)
1134 return En->VectorizedValue;
1139 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
1140 if (ScalarToTreeEntry.count(VL[0])) {
1141 int Idx = ScalarToTreeEntry[VL[0]];
1142 TreeEntry *E = &VectorizableTree[Idx];
1144 return vectorizeTree(E);
1147 Type *ScalarTy = VL[0]->getType();
1148 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1149 ScalarTy = SI->getValueOperand()->getType();
1150 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1152 return Gather(VL, VecTy);
1155 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
1156 BuilderLocGuard Guard(Builder);
1158 if (E->VectorizedValue) {
1159 DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
1160 return E->VectorizedValue;
1163 Type *ScalarTy = E->Scalars[0]->getType();
1164 if (StoreInst *SI = dyn_cast<StoreInst>(E->Scalars[0]))
1165 ScalarTy = SI->getValueOperand()->getType();
1166 VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size());
1168 if (E->NeedToGather) {
1169 return Gather(E->Scalars, VecTy);
1172 Instruction *VL0 = cast<Instruction>(E->Scalars[0]);
1173 unsigned Opcode = VL0->getOpcode();
1174 assert(Opcode == getSameOpcode(E->Scalars) && "Invalid opcode");
1177 case Instruction::PHI: {
1178 PHINode *PH = dyn_cast<PHINode>(VL0);
1179 Builder.SetInsertPoint(PH->getParent()->getFirstInsertionPt());
1180 PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
1181 E->VectorizedValue = NewPhi;
1183 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1185 BasicBlock *IBB = PH->getIncomingBlock(i);
1187 // Prepare the operand vector.
1188 for (unsigned j = 0; j < E->Scalars.size(); ++j)
1189 Operands.push_back(cast<PHINode>(E->Scalars[j])->
1190 getIncomingValueForBlock(IBB));
1192 Builder.SetInsertPoint(IBB->getTerminator());
1193 Value *Vec = vectorizeTree(Operands);
1194 NewPhi->addIncoming(Vec, IBB);
1197 assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
1198 "Invalid number of incoming values");
1202 case Instruction::ExtractElement: {
1203 if (CanReuseExtract(E->Scalars)) {
1204 Value *V = VL0->getOperand(0);
1205 E->VectorizedValue = V;
1208 return Gather(E->Scalars, VecTy);
1210 case Instruction::ZExt:
1211 case Instruction::SExt:
1212 case Instruction::FPToUI:
1213 case Instruction::FPToSI:
1214 case Instruction::FPExt:
1215 case Instruction::PtrToInt:
1216 case Instruction::IntToPtr:
1217 case Instruction::SIToFP:
1218 case Instruction::UIToFP:
1219 case Instruction::Trunc:
1220 case Instruction::FPTrunc:
1221 case Instruction::BitCast: {
1223 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1224 INVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1226 Builder.SetInsertPoint(getLastInstruction(E->Scalars));
1227 Value *InVec = vectorizeTree(INVL);
1229 if (Value *V = alreadyVectorized(E->Scalars))
1232 CastInst *CI = dyn_cast<CastInst>(VL0);
1233 Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
1234 E->VectorizedValue = V;
1237 case Instruction::FCmp:
1238 case Instruction::ICmp: {
1239 ValueList LHSV, RHSV;
1240 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1241 LHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1242 RHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1245 Builder.SetInsertPoint(getLastInstruction(E->Scalars));
1246 Value *L = vectorizeTree(LHSV);
1247 Value *R = vectorizeTree(RHSV);
1249 if (Value *V = alreadyVectorized(E->Scalars))
1252 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
1254 if (Opcode == Instruction::FCmp)
1255 V = Builder.CreateFCmp(P0, L, R);
1257 V = Builder.CreateICmp(P0, L, R);
1259 E->VectorizedValue = V;
1262 case Instruction::Select: {
1263 ValueList TrueVec, FalseVec, CondVec;
1264 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1265 CondVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1266 TrueVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1267 FalseVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(2));
1270 Builder.SetInsertPoint(getLastInstruction(E->Scalars));
1271 Value *Cond = vectorizeTree(CondVec);
1272 Value *True = vectorizeTree(TrueVec);
1273 Value *False = vectorizeTree(FalseVec);
1275 if (Value *V = alreadyVectorized(E->Scalars))
1278 Value *V = Builder.CreateSelect(Cond, True, False);
1279 E->VectorizedValue = V;
1282 case Instruction::Add:
1283 case Instruction::FAdd:
1284 case Instruction::Sub:
1285 case Instruction::FSub:
1286 case Instruction::Mul:
1287 case Instruction::FMul:
1288 case Instruction::UDiv:
1289 case Instruction::SDiv:
1290 case Instruction::FDiv:
1291 case Instruction::URem:
1292 case Instruction::SRem:
1293 case Instruction::FRem:
1294 case Instruction::Shl:
1295 case Instruction::LShr:
1296 case Instruction::AShr:
1297 case Instruction::And:
1298 case Instruction::Or:
1299 case Instruction::Xor: {
1300 ValueList LHSVL, RHSVL;
1301 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1302 LHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1303 RHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1306 Builder.SetInsertPoint(getLastInstruction(E->Scalars));
1307 Value *LHS = vectorizeTree(LHSVL);
1308 Value *RHS = vectorizeTree(RHSVL);
1310 if (LHS == RHS && isa<Instruction>(LHS)) {
1311 assert((VL0->getOperand(0) == VL0->getOperand(1)) && "Invalid order");
1314 if (Value *V = alreadyVectorized(E->Scalars))
1317 BinaryOperator *BinOp = cast<BinaryOperator>(VL0);
1318 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), LHS, RHS);
1319 E->VectorizedValue = V;
1322 case Instruction::Load: {
1323 // Loads are inserted at the head of the tree because we don't want to
1324 // sink them all the way down past store instructions.
1325 Builder.SetInsertPoint(getLastInstruction(E->Scalars));
1326 LoadInst *LI = cast<LoadInst>(VL0);
1328 Builder.CreateBitCast(LI->getPointerOperand(), VecTy->getPointerTo());
1329 unsigned Alignment = LI->getAlignment();
1330 LI = Builder.CreateLoad(VecPtr);
1331 LI->setAlignment(Alignment);
1332 E->VectorizedValue = LI;
1335 case Instruction::Store: {
1336 StoreInst *SI = cast<StoreInst>(VL0);
1337 unsigned Alignment = SI->getAlignment();
1340 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1341 ValueOp.push_back(cast<StoreInst>(E->Scalars[i])->getValueOperand());
1343 Builder.SetInsertPoint(getLastInstruction(E->Scalars));
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 // Generate extracts for out-of-tree users.
1385 // Find the insertion point for the extractelement lane.
1386 Instruction *Loc = 0;
1387 if (PHINode *PN = dyn_cast<PHINode>(Vec)) {
1388 Loc = PN->getParent()->getFirstInsertionPt();
1389 } else if (isa<Instruction>(Vec)){
1390 if (PHINode *PH = dyn_cast<PHINode>(User)) {
1391 for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
1392 if (PH->getIncomingValue(i) == Scalar) {
1393 Loc = PH->getIncomingBlock(i)->getTerminator();
1397 assert(Loc && "Unable to find incoming value for the PHI");
1399 Loc = cast<Instruction>(User);
1402 Loc = F->getEntryBlock().begin();
1405 Builder.SetInsertPoint(Loc);
1406 Value *Ex = Builder.CreateExtractElement(Vec, Builder.getInt32(it->Lane));
1407 User->replaceUsesOfWith(Scalar, Ex);
1408 DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
1411 // For each vectorized value:
1412 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
1413 TreeEntry *Entry = &VectorizableTree[EIdx];
1416 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
1417 Value *Scalar = Entry->Scalars[Lane];
1419 // No need to handle users of gathered values.
1420 if (Entry->NeedToGather)
1423 assert(Entry->VectorizedValue && "Can't find vectorizable value");
1425 Type *Ty = Scalar->getType();
1426 if (!Ty->isVoidTy()) {
1427 for (Value::use_iterator User = Scalar->use_begin(),
1428 UE = Scalar->use_end(); User != UE; ++User) {
1429 DEBUG(dbgs() << "SLP: \tvalidating user:" << **User << ".\n");
1430 assert(!MustGather.count(*User) &&
1431 "Replacing gathered value with undef");
1432 assert(ScalarToTreeEntry.count(*User) &&
1433 "Replacing out-of-tree value with undef");
1435 Value *Undef = UndefValue::get(Ty);
1436 Scalar->replaceAllUsesWith(Undef);
1438 DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
1439 cast<Instruction>(Scalar)->eraseFromParent();
1443 for (Function::iterator it = F->begin(), e = F->end(); it != e; ++it) {
1444 BlocksNumbers[it].forget();
1446 Builder.ClearInsertionPoint();
1449 void BoUpSLP::optimizeGatherSequence() {
1450 DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
1451 << " gather sequences instructions.\n");
1452 // LICM InsertElementInst sequences.
1453 for (SetVector<Instruction *>::iterator it = GatherSeq.begin(),
1454 e = GatherSeq.end(); it != e; ++it) {
1455 InsertElementInst *Insert = dyn_cast<InsertElementInst>(*it);
1460 // Check if this block is inside a loop.
1461 Loop *L = LI->getLoopFor(Insert->getParent());
1465 // Check if it has a preheader.
1466 BasicBlock *PreHeader = L->getLoopPreheader();
1470 // If the vector or the element that we insert into it are
1471 // instructions that are defined in this basic block then we can't
1472 // hoist this instruction.
1473 Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
1474 Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
1475 if (CurrVec && L->contains(CurrVec))
1477 if (NewElem && L->contains(NewElem))
1480 // We can hoist this instruction. Move it to the pre-header.
1481 Insert->moveBefore(PreHeader->getTerminator());
1484 // Perform O(N^2) search over the gather sequences and merge identical
1485 // instructions. TODO: We can further optimize this scan if we split the
1486 // instructions into different buckets based on the insert lane.
1487 SmallPtrSet<Instruction*, 16> Visited;
1488 SmallVector<Instruction*, 16> ToRemove;
1489 ReversePostOrderTraversal<Function*> RPOT(F);
1490 for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
1491 E = RPOT.end(); I != E; ++I) {
1492 BasicBlock *BB = *I;
1493 // For all instructions in the function:
1494 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1495 Instruction *In = it;
1496 if ((!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In)) ||
1497 !GatherSeq.count(In))
1500 // Check if we can replace this instruction with any of the
1501 // visited instructions.
1502 for (SmallPtrSet<Instruction*, 16>::iterator v = Visited.begin(),
1503 ve = Visited.end(); v != ve; ++v) {
1504 if (In->isIdenticalTo(*v) &&
1505 DT->dominates((*v)->getParent(), In->getParent())) {
1506 In->replaceAllUsesWith(*v);
1507 ToRemove.push_back(In);
1517 // Erase all of the instructions that we RAUWed.
1518 for (SmallVectorImpl<Instruction *>::iterator v = ToRemove.begin(),
1519 ve = ToRemove.end(); v != ve; ++v) {
1520 assert((*v)->getNumUses() == 0 && "Can't remove instructions with uses");
1521 (*v)->eraseFromParent();
1525 /// The SLPVectorizer Pass.
1526 struct SLPVectorizer : public FunctionPass {
1527 typedef SmallVector<StoreInst *, 8> StoreList;
1528 typedef MapVector<Value *, StoreList> StoreListMap;
1530 /// Pass identification, replacement for typeid
1533 explicit SLPVectorizer() : FunctionPass(ID) {
1534 initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
1537 ScalarEvolution *SE;
1539 TargetTransformInfo *TTI;
1544 virtual bool runOnFunction(Function &F) {
1545 SE = &getAnalysis<ScalarEvolution>();
1546 DL = getAnalysisIfAvailable<DataLayout>();
1547 TTI = &getAnalysis<TargetTransformInfo>();
1548 AA = &getAnalysis<AliasAnalysis>();
1549 LI = &getAnalysis<LoopInfo>();
1550 DT = &getAnalysis<DominatorTree>();
1553 bool Changed = false;
1555 // Must have DataLayout. We can't require it because some tests run w/o
1560 // Don't vectorize when the attribute NoImplicitFloat is used.
1561 if (F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1562 Attribute::NoImplicitFloat))
1565 DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
1567 // Use the bollom up slp vectorizer to construct chains that start with
1568 // he store instructions.
1569 BoUpSLP R(&F, SE, DL, TTI, AA, LI, DT);
1571 // Scan the blocks in the function in post order.
1572 for (po_iterator<BasicBlock*> it = po_begin(&F.getEntryBlock()),
1573 e = po_end(&F.getEntryBlock()); it != e; ++it) {
1574 BasicBlock *BB = *it;
1576 // Vectorize trees that end at stores.
1577 if (unsigned count = collectStores(BB, R)) {
1579 DEBUG(dbgs() << "SLP: Found " << count << " stores to vectorize.\n");
1580 Changed |= vectorizeStoreChains(R);
1583 // Vectorize trees that end at reductions.
1584 Changed |= vectorizeChainsInBlock(BB, R);
1588 R.optimizeGatherSequence();
1589 DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
1590 DEBUG(verifyFunction(F));
1595 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1596 FunctionPass::getAnalysisUsage(AU);
1597 AU.addRequired<ScalarEvolution>();
1598 AU.addRequired<AliasAnalysis>();
1599 AU.addRequired<TargetTransformInfo>();
1600 AU.addRequired<LoopInfo>();
1601 AU.addRequired<DominatorTree>();
1602 AU.addPreserved<LoopInfo>();
1603 AU.addPreserved<DominatorTree>();
1604 AU.setPreservesCFG();
1609 /// \brief Collect memory references and sort them according to their base
1610 /// object. We sort the stores to their base objects to reduce the cost of the
1611 /// quadratic search on the stores. TODO: We can further reduce this cost
1612 /// if we flush the chain creation every time we run into a memory barrier.
1613 unsigned collectStores(BasicBlock *BB, BoUpSLP &R);
1615 /// \brief Try to vectorize a chain that starts at two arithmetic instrs.
1616 bool tryToVectorizePair(Value *A, Value *B, BoUpSLP &R);
1618 /// \brief Try to vectorize a list of operands.
1619 /// \returns true if a value was vectorized.
1620 bool tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R);
1622 /// \brief Try to vectorize a chain that may start at the operands of \V;
1623 bool tryToVectorize(BinaryOperator *V, BoUpSLP &R);
1625 /// \brief Vectorize the stores that were collected in StoreRefs.
1626 bool vectorizeStoreChains(BoUpSLP &R);
1628 /// \brief Scan the basic block and look for patterns that are likely to start
1629 /// a vectorization chain.
1630 bool vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R);
1632 bool vectorizeStoreChain(ArrayRef<Value *> Chain, int CostThreshold,
1635 bool vectorizeStores(ArrayRef<StoreInst *> Stores, int costThreshold,
1638 StoreListMap StoreRefs;
1641 bool SLPVectorizer::vectorizeStoreChain(ArrayRef<Value *> Chain,
1642 int CostThreshold, BoUpSLP &R) {
1643 unsigned ChainLen = Chain.size();
1644 DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
1646 Type *StoreTy = cast<StoreInst>(Chain[0])->getValueOperand()->getType();
1647 unsigned Sz = DL->getTypeSizeInBits(StoreTy);
1648 unsigned VF = MinVecRegSize / Sz;
1650 if (!isPowerOf2_32(Sz) || VF < 2)
1653 bool Changed = false;
1654 // Look for profitable vectorizable trees at all offsets, starting at zero.
1655 for (unsigned i = 0, e = ChainLen; i < e; ++i) {
1658 DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
1660 ArrayRef<Value *> Operands = Chain.slice(i, VF);
1662 R.buildTree(Operands);
1664 int Cost = R.getTreeCost();
1666 DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
1667 if (Cost < CostThreshold) {
1668 DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
1671 // Move to the next bundle.
1680 bool SLPVectorizer::vectorizeStores(ArrayRef<StoreInst *> Stores,
1681 int costThreshold, BoUpSLP &R) {
1682 SetVector<Value *> Heads, Tails;
1683 SmallDenseMap<Value *, Value *> ConsecutiveChain;
1685 // We may run into multiple chains that merge into a single chain. We mark the
1686 // stores that we vectorized so that we don't visit the same store twice.
1687 BoUpSLP::ValueSet VectorizedStores;
1688 bool Changed = false;
1690 // Do a quadratic search on all of the given stores and find
1691 // all of the pairs of stores that follow each other.
1692 for (unsigned i = 0, e = Stores.size(); i < e; ++i) {
1693 for (unsigned j = 0; j < e; ++j) {
1697 if (R.isConsecutiveAccess(Stores[i], Stores[j])) {
1698 Tails.insert(Stores[j]);
1699 Heads.insert(Stores[i]);
1700 ConsecutiveChain[Stores[i]] = Stores[j];
1705 // For stores that start but don't end a link in the chain:
1706 for (SetVector<Value *>::iterator it = Heads.begin(), e = Heads.end();
1708 if (Tails.count(*it))
1711 // We found a store instr that starts a chain. Now follow the chain and try
1713 BoUpSLP::ValueList Operands;
1715 // Collect the chain into a list.
1716 while (Tails.count(I) || Heads.count(I)) {
1717 if (VectorizedStores.count(I))
1719 Operands.push_back(I);
1720 // Move to the next value in the chain.
1721 I = ConsecutiveChain[I];
1724 bool Vectorized = vectorizeStoreChain(Operands, costThreshold, R);
1726 // Mark the vectorized stores so that we don't vectorize them again.
1728 VectorizedStores.insert(Operands.begin(), Operands.end());
1729 Changed |= Vectorized;
1736 unsigned SLPVectorizer::collectStores(BasicBlock *BB, BoUpSLP &R) {
1739 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1740 StoreInst *SI = dyn_cast<StoreInst>(it);
1744 // Check that the pointer points to scalars.
1745 Type *Ty = SI->getValueOperand()->getType();
1746 if (Ty->isAggregateType() || Ty->isVectorTy())
1749 // Find the base of the GEP.
1750 Value *Ptr = SI->getPointerOperand();
1751 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
1752 Ptr = GEP->getPointerOperand();
1754 // Save the store locations.
1755 StoreRefs[Ptr].push_back(SI);
1761 bool SLPVectorizer::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
1764 Value *VL[] = { A, B };
1765 return tryToVectorizeList(VL, R);
1768 bool SLPVectorizer::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R) {
1772 DEBUG(dbgs() << "SLP: Vectorizing a list of length = " << VL.size() << ".\n");
1774 // Check that all of the parts are scalar instructions of the same type.
1775 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
1779 unsigned Opcode0 = I0->getOpcode();
1781 for (int i = 0, e = VL.size(); i < e; ++i) {
1782 Type *Ty = VL[i]->getType();
1783 if (Ty->isAggregateType() || Ty->isVectorTy())
1785 Instruction *Inst = dyn_cast<Instruction>(VL[i]);
1786 if (!Inst || Inst->getOpcode() != Opcode0)
1791 int Cost = R.getTreeCost();
1793 if (Cost >= -SLPCostThreshold)
1796 DEBUG(dbgs() << "SLP: Vectorizing pair at cost:" << Cost << ".\n");
1801 bool SLPVectorizer::tryToVectorize(BinaryOperator *V, BoUpSLP &R) {
1805 // Try to vectorize V.
1806 if (tryToVectorizePair(V->getOperand(0), V->getOperand(1), R))
1809 BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0));
1810 BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1));
1812 if (B && B->hasOneUse()) {
1813 BinaryOperator *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
1814 BinaryOperator *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
1815 if (tryToVectorizePair(A, B0, R)) {
1819 if (tryToVectorizePair(A, B1, R)) {
1826 if (A && A->hasOneUse()) {
1827 BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
1828 BinaryOperator *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
1829 if (tryToVectorizePair(A0, B, R)) {
1833 if (tryToVectorizePair(A1, B, R)) {
1841 bool SLPVectorizer::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
1842 bool Changed = false;
1843 SmallVector<Value *, 4> Incoming;
1844 // Collect the incoming values from the PHIs.
1845 for (BasicBlock::iterator instr = BB->begin(), ie = BB->end(); instr != ie;
1847 PHINode *P = dyn_cast<PHINode>(instr);
1852 // Stop constructing the list when you reach a different type.
1853 if (Incoming.size() && P->getType() != Incoming[0]->getType()) {
1854 Changed |= tryToVectorizeList(Incoming, R);
1858 Incoming.push_back(P);
1861 if (Incoming.size() > 1)
1862 Changed |= tryToVectorizeList(Incoming, R);
1864 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1865 if (isa<DbgInfoIntrinsic>(it))
1868 // Try to vectorize reductions that use PHINodes.
1869 if (PHINode *P = dyn_cast<PHINode>(it)) {
1870 // Check that the PHI is a reduction PHI.
1871 if (P->getNumIncomingValues() != 2)
1874 (P->getIncomingBlock(0) == BB
1875 ? (P->getIncomingValue(0))
1876 : (P->getIncomingBlock(1) == BB ? P->getIncomingValue(1) : 0));
1877 // Check if this is a Binary Operator.
1878 BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx);
1882 Value *Inst = BI->getOperand(0);
1884 Inst = BI->getOperand(1);
1886 Changed |= tryToVectorize(dyn_cast<BinaryOperator>(Inst), R);
1890 // Try to vectorize trees that start at compare instructions.
1891 if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
1892 if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) {
1896 for (int i = 0; i < 2; ++i)
1897 if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i)))
1899 tryToVectorizePair(BI->getOperand(0), BI->getOperand(1), R);
1907 bool SLPVectorizer::vectorizeStoreChains(BoUpSLP &R) {
1908 bool Changed = false;
1909 // Attempt to sort and vectorize each of the store-groups.
1910 for (StoreListMap::iterator it = StoreRefs.begin(), e = StoreRefs.end();
1912 if (it->second.size() < 2)
1915 DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
1916 << it->second.size() << ".\n");
1918 // Process the stores in chunks of 16.
1919 for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI+=16) {
1920 unsigned Len = std::min<unsigned>(CE - CI, 16);
1921 ArrayRef<StoreInst *> Chunk(&it->second[CI], Len);
1922 Changed |= vectorizeStores(Chunk, -SLPCostThreshold, R);
1928 } // end anonymous namespace
1930 char SLPVectorizer::ID = 0;
1931 static const char lv_name[] = "SLP Vectorizer";
1932 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
1933 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
1934 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
1935 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1936 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
1937 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
1940 Pass *createSLPVectorizerPass() { return new SLPVectorizer(); }