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/TargetTransformInfo.h"
29 #include "llvm/Analysis/ValueTracking.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 ShouldVectorizeHor("slp-vectorize-hor", cl::init(false), cl::Hidden,
55 cl::desc("Attempt to vectorize horizontal reductions"));
57 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
58 "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
60 "Attempt to vectorize horizontal reductions feeding into a store"));
64 static const unsigned MinVecRegSize = 128;
66 static const unsigned RecursionMaxDepth = 12;
68 /// A helper class for numbering instructions in multiple blocks.
69 /// Numbers start at zero for each basic block.
70 struct BlockNumbering {
72 BlockNumbering(BasicBlock *Bb) : BB(Bb), Valid(false) {}
74 BlockNumbering() : BB(0), Valid(false) {}
76 void numberInstructions() {
80 // Number the instructions in the block.
81 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
83 InstrVec.push_back(it);
84 assert(InstrVec[InstrIdx[it]] == it && "Invalid allocation");
89 int getIndex(Instruction *I) {
90 assert(I->getParent() == BB && "Invalid instruction");
93 assert(InstrIdx.count(I) && "Unknown instruction");
97 Instruction *getInstruction(unsigned loc) {
100 assert(InstrVec.size() > loc && "Invalid Index");
101 return InstrVec[loc];
104 void forget() { Valid = false; }
107 /// The block we are numbering.
109 /// Is the block numbered.
111 /// Maps instructions to numbers and back.
112 SmallDenseMap<Instruction *, int> InstrIdx;
113 /// Maps integers to Instructions.
114 SmallVector<Instruction *, 32> InstrVec;
117 /// \returns the parent basic block if all of the instructions in \p VL
118 /// are in the same block or null otherwise.
119 static BasicBlock *getSameBlock(ArrayRef<Value *> VL) {
120 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
123 BasicBlock *BB = I0->getParent();
124 for (int i = 1, e = VL.size(); i < e; i++) {
125 Instruction *I = dyn_cast<Instruction>(VL[i]);
129 if (BB != I->getParent())
135 /// \returns True if all of the values in \p VL are constants.
136 static bool allConstant(ArrayRef<Value *> VL) {
137 for (unsigned i = 0, e = VL.size(); i < e; ++i)
138 if (!isa<Constant>(VL[i]))
143 /// \returns True if all of the values in \p VL are identical.
144 static bool isSplat(ArrayRef<Value *> VL) {
145 for (unsigned i = 1, e = VL.size(); i < e; ++i)
151 /// \returns The opcode if all of the Instructions in \p VL have the same
153 static unsigned getSameOpcode(ArrayRef<Value *> VL) {
154 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
157 unsigned Opcode = I0->getOpcode();
158 for (int i = 1, e = VL.size(); i < e; i++) {
159 Instruction *I = dyn_cast<Instruction>(VL[i]);
160 if (!I || Opcode != I->getOpcode())
166 /// \returns The type that all of the values in \p VL have or null if there
167 /// are different types.
168 static Type* getSameType(ArrayRef<Value *> VL) {
169 Type *Ty = VL[0]->getType();
170 for (int i = 1, e = VL.size(); i < e; i++)
171 if (VL[i]->getType() != Ty)
177 /// \returns True if the ExtractElement instructions in VL can be vectorized
178 /// to use the original vector.
179 static bool CanReuseExtract(ArrayRef<Value *> VL) {
180 assert(Instruction::ExtractElement == getSameOpcode(VL) && "Invalid opcode");
181 // Check if all of the extracts come from the same vector and from the
184 ExtractElementInst *E0 = cast<ExtractElementInst>(VL0);
185 Value *Vec = E0->getOperand(0);
187 // We have to extract from the same vector type.
188 unsigned NElts = Vec->getType()->getVectorNumElements();
190 if (NElts != VL.size())
193 // Check that all of the indices extract from the correct offset.
194 ConstantInt *CI = dyn_cast<ConstantInt>(E0->getOperand(1));
195 if (!CI || CI->getZExtValue())
198 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
199 ExtractElementInst *E = cast<ExtractElementInst>(VL[i]);
200 ConstantInt *CI = dyn_cast<ConstantInt>(E->getOperand(1));
202 if (!CI || CI->getZExtValue() != i || E->getOperand(0) != Vec)
209 /// Bottom Up SLP Vectorizer.
212 typedef SmallVector<Value *, 8> ValueList;
213 typedef SmallVector<Instruction *, 16> InstrList;
214 typedef SmallPtrSet<Value *, 16> ValueSet;
215 typedef SmallVector<StoreInst *, 8> StoreList;
217 BoUpSLP(Function *Func, ScalarEvolution *Se, DataLayout *Dl,
218 TargetTransformInfo *Tti, AliasAnalysis *Aa, LoopInfo *Li,
220 F(Func), SE(Se), DL(Dl), TTI(Tti), AA(Aa), LI(Li), DT(Dt),
221 Builder(Se->getContext()) {
222 // Setup the block numbering utility for all of the blocks in the
224 for (Function::iterator it = F->begin(), e = F->end(); it != e; ++it) {
226 BlocksNumbers[BB] = BlockNumbering(BB);
230 /// \brief Vectorize the tree that starts with the elements in \p VL.
231 /// Returns the vectorized root.
232 Value *vectorizeTree();
234 /// \returns the vectorization cost of the subtree that starts at \p VL.
235 /// A negative number means that this is profitable.
238 /// Construct a vectorizable tree that starts at \p Roots and is possibly
239 /// used by a reduction of \p RdxOps.
240 void buildTree(ArrayRef<Value *> Roots, ValueSet *RdxOps = 0);
242 /// Clear the internal data structures that are created by 'buildTree'.
245 VectorizableTree.clear();
246 ScalarToTreeEntry.clear();
248 ExternalUses.clear();
249 MemBarrierIgnoreList.clear();
252 /// \returns true if the memory operations A and B are consecutive.
253 bool isConsecutiveAccess(Value *A, Value *B);
255 /// \brief Perform LICM and CSE on the newly generated gather sequences.
256 void optimizeGatherSequence();
260 /// \returns the cost of the vectorizable entry.
261 int getEntryCost(TreeEntry *E);
263 /// This is the recursive part of buildTree.
264 void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth);
266 /// Vectorize a single entry in the tree.
267 Value *vectorizeTree(TreeEntry *E);
269 /// Vectorize a single entry in the tree, starting in \p VL.
270 Value *vectorizeTree(ArrayRef<Value *> VL);
272 /// \returns the pointer to the vectorized value if \p VL is already
273 /// vectorized, or NULL. They may happen in cycles.
274 Value *alreadyVectorized(ArrayRef<Value *> VL) const;
276 /// \brief Take the pointer operand from the Load/Store instruction.
277 /// \returns NULL if this is not a valid Load/Store instruction.
278 static Value *getPointerOperand(Value *I);
280 /// \brief Take the address space operand from the Load/Store instruction.
281 /// \returns -1 if this is not a valid Load/Store instruction.
282 static unsigned getAddressSpaceOperand(Value *I);
284 /// \returns the scalarization cost for this type. Scalarization in this
285 /// context means the creation of vectors from a group of scalars.
286 int getGatherCost(Type *Ty);
288 /// \returns the scalarization cost for this list of values. Assuming that
289 /// this subtree gets vectorized, we may need to extract the values from the
290 /// roots. This method calculates the cost of extracting the values.
291 int getGatherCost(ArrayRef<Value *> VL);
293 /// \returns the AA location that is being access by the instruction.
294 AliasAnalysis::Location getLocation(Instruction *I);
296 /// \brief Checks if it is possible to sink an instruction from
297 /// \p Src to \p Dst.
298 /// \returns the pointer to the barrier instruction if we can't sink.
299 Value *getSinkBarrier(Instruction *Src, Instruction *Dst);
301 /// \returns the index of the last instruction in the BB from \p VL.
302 int getLastIndex(ArrayRef<Value *> VL);
304 /// \returns the Instruction in the bundle \p VL.
305 Instruction *getLastInstruction(ArrayRef<Value *> VL);
307 /// \brief Set the Builder insert point to one after the last instruction in
309 void setInsertPointAfterBundle(ArrayRef<Value *> VL);
311 /// \returns a vector from a collection of scalars in \p VL.
312 Value *Gather(ArrayRef<Value *> VL, VectorType *Ty);
314 /// \returns whether the VectorizableTree is fully vectoriable and will
315 /// be beneficial even the tree height is tiny.
316 bool isFullyVectorizableTinyTree();
319 TreeEntry() : Scalars(), VectorizedValue(0), LastScalarIndex(0),
322 /// \returns true if the scalars in VL are equal to this entry.
323 bool isSame(ArrayRef<Value *> VL) const {
324 assert(VL.size() == Scalars.size() && "Invalid size");
325 return std::equal(VL.begin(), VL.end(), Scalars.begin());
328 /// A vector of scalars.
331 /// The Scalars are vectorized into this value. It is initialized to Null.
332 Value *VectorizedValue;
334 /// The index in the basic block of the last scalar.
337 /// Do we need to gather this sequence ?
341 /// Create a new VectorizableTree entry.
342 TreeEntry *newTreeEntry(ArrayRef<Value *> VL, bool Vectorized) {
343 VectorizableTree.push_back(TreeEntry());
344 int idx = VectorizableTree.size() - 1;
345 TreeEntry *Last = &VectorizableTree[idx];
346 Last->Scalars.insert(Last->Scalars.begin(), VL.begin(), VL.end());
347 Last->NeedToGather = !Vectorized;
349 Last->LastScalarIndex = getLastIndex(VL);
350 for (int i = 0, e = VL.size(); i != e; ++i) {
351 assert(!ScalarToTreeEntry.count(VL[i]) && "Scalar already in tree!");
352 ScalarToTreeEntry[VL[i]] = idx;
355 Last->LastScalarIndex = 0;
356 MustGather.insert(VL.begin(), VL.end());
361 /// -- Vectorization State --
362 /// Holds all of the tree entries.
363 std::vector<TreeEntry> VectorizableTree;
365 /// Maps a specific scalar to its tree entry.
366 SmallDenseMap<Value*, int> ScalarToTreeEntry;
368 /// A list of scalars that we found that we need to keep as scalars.
371 /// This POD struct describes one external user in the vectorized tree.
372 struct ExternalUser {
373 ExternalUser (Value *S, llvm::User *U, int L) :
374 Scalar(S), User(U), Lane(L){};
375 // Which scalar in our function.
377 // Which user that uses the scalar.
379 // Which lane does the scalar belong to.
382 typedef SmallVector<ExternalUser, 16> UserList;
384 /// A list of values that need to extracted out of the tree.
385 /// This list holds pairs of (Internal Scalar : External User).
386 UserList ExternalUses;
388 /// A list of instructions to ignore while sinking
389 /// memory instructions. This map must be reset between runs of getCost.
390 ValueSet MemBarrierIgnoreList;
392 /// Holds all of the instructions that we gathered.
393 SetVector<Instruction *> GatherSeq;
395 /// Numbers instructions in different blocks.
396 DenseMap<BasicBlock *, BlockNumbering> BlocksNumbers;
398 /// Reduction operators.
401 // Analysis and block reference.
405 TargetTransformInfo *TTI;
409 /// Instruction builder to construct the vectorized tree.
413 void BoUpSLP::buildTree(ArrayRef<Value *> Roots, ValueSet *Rdx) {
416 if (!getSameType(Roots))
418 buildTree_rec(Roots, 0);
420 // Collect the values that we need to extract from the tree.
421 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
422 TreeEntry *Entry = &VectorizableTree[EIdx];
425 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
426 Value *Scalar = Entry->Scalars[Lane];
428 // No need to handle users of gathered values.
429 if (Entry->NeedToGather)
432 for (Value::use_iterator User = Scalar->use_begin(),
433 UE = Scalar->use_end(); User != UE; ++User) {
434 DEBUG(dbgs() << "SLP: Checking user:" << **User << ".\n");
436 bool Gathered = MustGather.count(*User);
438 // Skip in-tree scalars that become vectors.
439 if (ScalarToTreeEntry.count(*User) && !Gathered) {
440 DEBUG(dbgs() << "SLP: \tInternal user will be removed:" <<
442 int Idx = ScalarToTreeEntry[*User]; (void) Idx;
443 assert(!VectorizableTree[Idx].NeedToGather && "Bad state");
446 Instruction *UserInst = dyn_cast<Instruction>(*User);
450 // Ignore uses that are part of the reduction.
451 if (Rdx && std::find(Rdx->begin(), Rdx->end(), UserInst) != Rdx->end())
454 DEBUG(dbgs() << "SLP: Need to extract:" << **User << " from lane " <<
455 Lane << " from " << *Scalar << ".\n");
456 ExternalUses.push_back(ExternalUser(Scalar, *User, Lane));
463 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth) {
464 bool SameTy = getSameType(VL); (void)SameTy;
465 assert(SameTy && "Invalid types!");
467 if (Depth == RecursionMaxDepth) {
468 DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
469 newTreeEntry(VL, false);
473 // Don't handle vectors.
474 if (VL[0]->getType()->isVectorTy()) {
475 DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
476 newTreeEntry(VL, false);
480 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
481 if (SI->getValueOperand()->getType()->isVectorTy()) {
482 DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
483 newTreeEntry(VL, false);
487 // If all of the operands are identical or constant we have a simple solution.
488 if (allConstant(VL) || isSplat(VL) || !getSameBlock(VL) ||
489 !getSameOpcode(VL)) {
490 DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
491 newTreeEntry(VL, false);
495 // We now know that this is a vector of instructions of the same type from
498 // Check if this is a duplicate of another entry.
499 if (ScalarToTreeEntry.count(VL[0])) {
500 int Idx = ScalarToTreeEntry[VL[0]];
501 TreeEntry *E = &VectorizableTree[Idx];
502 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
503 DEBUG(dbgs() << "SLP: \tChecking bundle: " << *VL[i] << ".\n");
504 if (E->Scalars[i] != VL[i]) {
505 DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
506 newTreeEntry(VL, false);
510 DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *VL[0] << ".\n");
514 // Check that none of the instructions in the bundle are already in the tree.
515 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
516 if (ScalarToTreeEntry.count(VL[i])) {
517 DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
518 ") is already in tree.\n");
519 newTreeEntry(VL, false);
524 // If any of the scalars appears in the table OR it is marked as a value that
525 // needs to stat scalar then we need to gather the scalars.
526 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
527 if (ScalarToTreeEntry.count(VL[i]) || MustGather.count(VL[i])) {
528 DEBUG(dbgs() << "SLP: Gathering due to gathered scalar. \n");
529 newTreeEntry(VL, false);
534 // Check that all of the users of the scalars that we want to vectorize are
536 Instruction *VL0 = cast<Instruction>(VL[0]);
537 int MyLastIndex = getLastIndex(VL);
538 BasicBlock *BB = cast<Instruction>(VL0)->getParent();
540 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
541 Instruction *Scalar = cast<Instruction>(VL[i]);
542 DEBUG(dbgs() << "SLP: Checking users of " << *Scalar << ". \n");
543 for (Value::use_iterator U = Scalar->use_begin(), UE = Scalar->use_end();
545 DEBUG(dbgs() << "SLP: \tUser " << **U << ". \n");
546 Instruction *User = dyn_cast<Instruction>(*U);
548 DEBUG(dbgs() << "SLP: Gathering due unknown user. \n");
549 newTreeEntry(VL, false);
553 // We don't care if the user is in a different basic block.
554 BasicBlock *UserBlock = User->getParent();
555 if (UserBlock != BB) {
556 DEBUG(dbgs() << "SLP: User from a different basic block "
561 // If this is a PHINode within this basic block then we can place the
562 // extract wherever we want.
563 if (isa<PHINode>(*User)) {
564 DEBUG(dbgs() << "SLP: \tWe can schedule PHIs:" << *User << ". \n");
568 // Check if this is a safe in-tree user.
569 if (ScalarToTreeEntry.count(User)) {
570 int Idx = ScalarToTreeEntry[User];
571 int VecLocation = VectorizableTree[Idx].LastScalarIndex;
572 if (VecLocation <= MyLastIndex) {
573 DEBUG(dbgs() << "SLP: Gathering due to unschedulable vector. \n");
574 newTreeEntry(VL, false);
577 DEBUG(dbgs() << "SLP: In-tree user (" << *User << ") at #" <<
578 VecLocation << " vector value (" << *Scalar << ") at #"
579 << MyLastIndex << ".\n");
583 // This user is part of the reduction.
584 if (RdxOps && RdxOps->count(User))
587 // Make sure that we can schedule this unknown user.
588 BlockNumbering &BN = BlocksNumbers[BB];
589 int UserIndex = BN.getIndex(User);
590 if (UserIndex < MyLastIndex) {
592 DEBUG(dbgs() << "SLP: Can't schedule extractelement for "
594 newTreeEntry(VL, false);
600 // Check that every instructions appears once in this bundle.
601 for (unsigned i = 0, e = VL.size(); i < e; ++i)
602 for (unsigned j = i+1; j < e; ++j)
603 if (VL[i] == VL[j]) {
604 DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
605 newTreeEntry(VL, false);
609 // Check that instructions in this bundle don't reference other instructions.
610 // The runtime of this check is O(N * N-1 * uses(N)) and a typical N is 4.
611 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
612 for (Value::use_iterator U = VL[i]->use_begin(), UE = VL[i]->use_end();
614 for (unsigned j = 0; j < e; ++j) {
615 if (i != j && *U == VL[j]) {
616 DEBUG(dbgs() << "SLP: Intra-bundle dependencies!" << **U << ". \n");
617 newTreeEntry(VL, false);
624 DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
626 unsigned Opcode = getSameOpcode(VL);
628 // Check if it is safe to sink the loads or the stores.
629 if (Opcode == Instruction::Load || Opcode == Instruction::Store) {
630 Instruction *Last = getLastInstruction(VL);
632 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
635 Value *Barrier = getSinkBarrier(cast<Instruction>(VL[i]), Last);
637 DEBUG(dbgs() << "SLP: Can't sink " << *VL[i] << "\n down to " << *Last
638 << "\n because of " << *Barrier << ". Gathering.\n");
639 newTreeEntry(VL, false);
646 case Instruction::PHI: {
647 PHINode *PH = dyn_cast<PHINode>(VL0);
649 // Check for terminator values (e.g. invoke).
650 for (unsigned j = 0; j < VL.size(); ++j)
651 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
652 TerminatorInst *Term = dyn_cast<TerminatorInst>(cast<PHINode>(VL[j])->getIncomingValue(i));
654 DEBUG(dbgs() << "SLP: Need to swizzle PHINodes (TerminatorInst use).\n");
655 newTreeEntry(VL, false);
660 newTreeEntry(VL, true);
661 DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
663 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
665 // Prepare the operand vector.
666 for (unsigned j = 0; j < VL.size(); ++j)
667 Operands.push_back(cast<PHINode>(VL[j])->getIncomingValue(i));
669 buildTree_rec(Operands, Depth + 1);
673 case Instruction::ExtractElement: {
674 bool Reuse = CanReuseExtract(VL);
676 DEBUG(dbgs() << "SLP: Reusing extract sequence.\n");
678 newTreeEntry(VL, Reuse);
681 case Instruction::Load: {
682 // Check if the loads are consecutive or of we need to swizzle them.
683 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
684 if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
685 newTreeEntry(VL, false);
686 DEBUG(dbgs() << "SLP: Need to swizzle loads.\n");
690 newTreeEntry(VL, true);
691 DEBUG(dbgs() << "SLP: added a vector of loads.\n");
694 case Instruction::ZExt:
695 case Instruction::SExt:
696 case Instruction::FPToUI:
697 case Instruction::FPToSI:
698 case Instruction::FPExt:
699 case Instruction::PtrToInt:
700 case Instruction::IntToPtr:
701 case Instruction::SIToFP:
702 case Instruction::UIToFP:
703 case Instruction::Trunc:
704 case Instruction::FPTrunc:
705 case Instruction::BitCast: {
706 Type *SrcTy = VL0->getOperand(0)->getType();
707 for (unsigned i = 0; i < VL.size(); ++i) {
708 Type *Ty = cast<Instruction>(VL[i])->getOperand(0)->getType();
709 if (Ty != SrcTy || Ty->isAggregateType() || Ty->isVectorTy()) {
710 newTreeEntry(VL, false);
711 DEBUG(dbgs() << "SLP: Gathering casts with different src types.\n");
715 newTreeEntry(VL, true);
716 DEBUG(dbgs() << "SLP: added a vector of casts.\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::ICmp:
729 case Instruction::FCmp: {
730 // Check that all of the compares have the same predicate.
731 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
732 Type *ComparedTy = cast<Instruction>(VL[0])->getOperand(0)->getType();
733 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
734 CmpInst *Cmp = cast<CmpInst>(VL[i]);
735 if (Cmp->getPredicate() != P0 ||
736 Cmp->getOperand(0)->getType() != ComparedTy) {
737 newTreeEntry(VL, false);
738 DEBUG(dbgs() << "SLP: Gathering cmp with different predicate.\n");
743 newTreeEntry(VL, true);
744 DEBUG(dbgs() << "SLP: added a vector of compares.\n");
746 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
748 // Prepare the operand vector.
749 for (unsigned j = 0; j < VL.size(); ++j)
750 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
752 buildTree_rec(Operands, Depth+1);
756 case Instruction::Select:
757 case Instruction::Add:
758 case Instruction::FAdd:
759 case Instruction::Sub:
760 case Instruction::FSub:
761 case Instruction::Mul:
762 case Instruction::FMul:
763 case Instruction::UDiv:
764 case Instruction::SDiv:
765 case Instruction::FDiv:
766 case Instruction::URem:
767 case Instruction::SRem:
768 case Instruction::FRem:
769 case Instruction::Shl:
770 case Instruction::LShr:
771 case Instruction::AShr:
772 case Instruction::And:
773 case Instruction::Or:
774 case Instruction::Xor: {
775 newTreeEntry(VL, true);
776 DEBUG(dbgs() << "SLP: added a vector of bin op.\n");
778 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
780 // Prepare the operand vector.
781 for (unsigned j = 0; j < VL.size(); ++j)
782 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
784 buildTree_rec(Operands, Depth+1);
788 case Instruction::Store: {
789 // Check if the stores are consecutive or of we need to swizzle them.
790 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
791 if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
792 newTreeEntry(VL, false);
793 DEBUG(dbgs() << "SLP: Non consecutive store.\n");
797 newTreeEntry(VL, true);
798 DEBUG(dbgs() << "SLP: added a vector of stores.\n");
801 for (unsigned j = 0; j < VL.size(); ++j)
802 Operands.push_back(cast<Instruction>(VL[j])->getOperand(0));
804 // We can ignore these values because we are sinking them down.
805 MemBarrierIgnoreList.insert(VL.begin(), VL.end());
806 buildTree_rec(Operands, Depth + 1);
810 newTreeEntry(VL, false);
811 DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
816 int BoUpSLP::getEntryCost(TreeEntry *E) {
817 ArrayRef<Value*> VL = E->Scalars;
819 Type *ScalarTy = VL[0]->getType();
820 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
821 ScalarTy = SI->getValueOperand()->getType();
822 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
824 if (E->NeedToGather) {
828 return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
830 return getGatherCost(E->Scalars);
833 assert(getSameOpcode(VL) && getSameType(VL) && getSameBlock(VL) &&
835 Instruction *VL0 = cast<Instruction>(VL[0]);
836 unsigned Opcode = VL0->getOpcode();
838 case Instruction::PHI: {
841 case Instruction::ExtractElement: {
842 if (CanReuseExtract(VL))
844 return getGatherCost(VecTy);
846 case Instruction::ZExt:
847 case Instruction::SExt:
848 case Instruction::FPToUI:
849 case Instruction::FPToSI:
850 case Instruction::FPExt:
851 case Instruction::PtrToInt:
852 case Instruction::IntToPtr:
853 case Instruction::SIToFP:
854 case Instruction::UIToFP:
855 case Instruction::Trunc:
856 case Instruction::FPTrunc:
857 case Instruction::BitCast: {
858 Type *SrcTy = VL0->getOperand(0)->getType();
860 // Calculate the cost of this instruction.
861 int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(),
862 VL0->getType(), SrcTy);
864 VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
865 int VecCost = TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy);
866 return VecCost - ScalarCost;
868 case Instruction::FCmp:
869 case Instruction::ICmp:
870 case Instruction::Select:
871 case Instruction::Add:
872 case Instruction::FAdd:
873 case Instruction::Sub:
874 case Instruction::FSub:
875 case Instruction::Mul:
876 case Instruction::FMul:
877 case Instruction::UDiv:
878 case Instruction::SDiv:
879 case Instruction::FDiv:
880 case Instruction::URem:
881 case Instruction::SRem:
882 case Instruction::FRem:
883 case Instruction::Shl:
884 case Instruction::LShr:
885 case Instruction::AShr:
886 case Instruction::And:
887 case Instruction::Or:
888 case Instruction::Xor: {
889 // Calculate the cost of this instruction.
892 if (Opcode == Instruction::FCmp || Opcode == Instruction::ICmp ||
893 Opcode == Instruction::Select) {
894 VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
895 ScalarCost = VecTy->getNumElements() *
896 TTI->getCmpSelInstrCost(Opcode, ScalarTy, Builder.getInt1Ty());
897 VecCost = TTI->getCmpSelInstrCost(Opcode, VecTy, MaskTy);
899 ScalarCost = VecTy->getNumElements() *
900 TTI->getArithmeticInstrCost(Opcode, ScalarTy);
901 VecCost = TTI->getArithmeticInstrCost(Opcode, VecTy);
903 return VecCost - ScalarCost;
905 case Instruction::Load: {
906 // Cost of wide load - cost of scalar loads.
907 int ScalarLdCost = VecTy->getNumElements() *
908 TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
909 int VecLdCost = TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
910 return VecLdCost - ScalarLdCost;
912 case Instruction::Store: {
913 // We know that we can merge the stores. Calculate the cost.
914 int ScalarStCost = VecTy->getNumElements() *
915 TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
916 int VecStCost = TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
917 return VecStCost - ScalarStCost;
920 llvm_unreachable("Unknown instruction");
924 bool BoUpSLP::isFullyVectorizableTinyTree() {
925 DEBUG(dbgs() << "SLP: Check whether the tree with height " <<
926 VectorizableTree.size() << " is fully vectorizable .\n");
928 // We only handle trees of height 2.
929 if (VectorizableTree.size() != 2)
932 // Gathering cost would be too much for tiny trees.
933 if (VectorizableTree[0].NeedToGather || VectorizableTree[1].NeedToGather)
939 int BoUpSLP::getTreeCost() {
941 DEBUG(dbgs() << "SLP: Calculating cost for tree of size " <<
942 VectorizableTree.size() << ".\n");
944 // We only vectorize tiny trees if it is fully vectorizable.
945 if (VectorizableTree.size() < 3 && !isFullyVectorizableTinyTree()) {
946 if (!VectorizableTree.size()) {
947 assert(!ExternalUses.size() && "We should not have any external users");
952 unsigned BundleWidth = VectorizableTree[0].Scalars.size();
954 for (unsigned i = 0, e = VectorizableTree.size(); i != e; ++i) {
955 int C = getEntryCost(&VectorizableTree[i]);
956 DEBUG(dbgs() << "SLP: Adding cost " << C << " for bundle that starts with "
957 << *VectorizableTree[i].Scalars[0] << " .\n");
962 for (UserList::iterator I = ExternalUses.begin(), E = ExternalUses.end();
965 VectorType *VecTy = VectorType::get(I->Scalar->getType(), BundleWidth);
966 ExtractCost += TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy,
971 DEBUG(dbgs() << "SLP: Total Cost " << Cost + ExtractCost<< ".\n");
972 return Cost + ExtractCost;
975 int BoUpSLP::getGatherCost(Type *Ty) {
977 for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
978 Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
982 int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) {
983 // Find the type of the operands in VL.
984 Type *ScalarTy = VL[0]->getType();
985 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
986 ScalarTy = SI->getValueOperand()->getType();
987 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
988 // Find the cost of inserting/extracting values from the vector.
989 return getGatherCost(VecTy);
992 AliasAnalysis::Location BoUpSLP::getLocation(Instruction *I) {
993 if (StoreInst *SI = dyn_cast<StoreInst>(I))
994 return AA->getLocation(SI);
995 if (LoadInst *LI = dyn_cast<LoadInst>(I))
996 return AA->getLocation(LI);
997 return AliasAnalysis::Location();
1000 Value *BoUpSLP::getPointerOperand(Value *I) {
1001 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1002 return LI->getPointerOperand();
1003 if (StoreInst *SI = dyn_cast<StoreInst>(I))
1004 return SI->getPointerOperand();
1008 unsigned BoUpSLP::getAddressSpaceOperand(Value *I) {
1009 if (LoadInst *L = dyn_cast<LoadInst>(I))
1010 return L->getPointerAddressSpace();
1011 if (StoreInst *S = dyn_cast<StoreInst>(I))
1012 return S->getPointerAddressSpace();
1016 bool BoUpSLP::isConsecutiveAccess(Value *A, Value *B) {
1017 Value *PtrA = getPointerOperand(A);
1018 Value *PtrB = getPointerOperand(B);
1019 unsigned ASA = getAddressSpaceOperand(A);
1020 unsigned ASB = getAddressSpaceOperand(B);
1022 // Check that the address spaces match and that the pointers are valid.
1023 if (!PtrA || !PtrB || (ASA != ASB))
1026 // Make sure that A and B are different pointers of the same type.
1027 if (PtrA == PtrB || PtrA->getType() != PtrB->getType())
1030 unsigned PtrBitWidth = DL->getPointerSizeInBits(ASA);
1031 Type *Ty = cast<PointerType>(PtrA->getType())->getElementType();
1032 APInt Size(PtrBitWidth, DL->getTypeStoreSize(Ty));
1034 APInt OffsetA(PtrBitWidth, 0), OffsetB(PtrBitWidth, 0);
1035 PtrA = PtrA->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetA);
1036 PtrB = PtrB->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetB);
1038 APInt OffsetDelta = OffsetB - OffsetA;
1040 // Check if they are based on the same pointer. That makes the offsets
1043 return OffsetDelta == Size;
1045 // Compute the necessary base pointer delta to have the necessary final delta
1046 // equal to the size.
1047 APInt BaseDelta = Size - OffsetDelta;
1049 // Otherwise compute the distance with SCEV between the base pointers.
1050 const SCEV *PtrSCEVA = SE->getSCEV(PtrA);
1051 const SCEV *PtrSCEVB = SE->getSCEV(PtrB);
1052 const SCEV *C = SE->getConstant(BaseDelta);
1053 const SCEV *X = SE->getAddExpr(PtrSCEVA, C);
1054 return X == PtrSCEVB;
1057 Value *BoUpSLP::getSinkBarrier(Instruction *Src, Instruction *Dst) {
1058 assert(Src->getParent() == Dst->getParent() && "Not the same BB");
1059 BasicBlock::iterator I = Src, E = Dst;
1060 /// Scan all of the instruction from SRC to DST and check if
1061 /// the source may alias.
1062 for (++I; I != E; ++I) {
1063 // Ignore store instructions that are marked as 'ignore'.
1064 if (MemBarrierIgnoreList.count(I))
1066 if (Src->mayWriteToMemory()) /* Write */ {
1067 if (!I->mayReadOrWriteMemory())
1070 if (!I->mayWriteToMemory())
1073 AliasAnalysis::Location A = getLocation(&*I);
1074 AliasAnalysis::Location B = getLocation(Src);
1076 if (!A.Ptr || !B.Ptr || AA->alias(A, B))
1082 int BoUpSLP::getLastIndex(ArrayRef<Value *> VL) {
1083 BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
1084 assert(BB == getSameBlock(VL) && BlocksNumbers.count(BB) && "Invalid block");
1085 BlockNumbering &BN = BlocksNumbers[BB];
1087 int MaxIdx = BN.getIndex(BB->getFirstNonPHI());
1088 for (unsigned i = 0, e = VL.size(); i < e; ++i)
1089 MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
1093 Instruction *BoUpSLP::getLastInstruction(ArrayRef<Value *> VL) {
1094 BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
1095 assert(BB == getSameBlock(VL) && BlocksNumbers.count(BB) && "Invalid block");
1096 BlockNumbering &BN = BlocksNumbers[BB];
1098 int MaxIdx = BN.getIndex(cast<Instruction>(VL[0]));
1099 for (unsigned i = 1, e = VL.size(); i < e; ++i)
1100 MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
1101 Instruction *I = BN.getInstruction(MaxIdx);
1102 assert(I && "bad location");
1106 void BoUpSLP::setInsertPointAfterBundle(ArrayRef<Value *> VL) {
1107 Instruction *VL0 = cast<Instruction>(VL[0]);
1108 Instruction *LastInst = getLastInstruction(VL);
1109 BasicBlock::iterator NextInst = LastInst;
1111 Builder.SetInsertPoint(VL0->getParent(), NextInst);
1112 Builder.SetCurrentDebugLocation(VL0->getDebugLoc());
1115 Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
1116 Value *Vec = UndefValue::get(Ty);
1117 // Generate the 'InsertElement' instruction.
1118 for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
1119 Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
1120 if (Instruction *Insrt = dyn_cast<Instruction>(Vec)) {
1121 GatherSeq.insert(Insrt);
1123 // Add to our 'need-to-extract' list.
1124 if (ScalarToTreeEntry.count(VL[i])) {
1125 int Idx = ScalarToTreeEntry[VL[i]];
1126 TreeEntry *E = &VectorizableTree[Idx];
1127 // Find which lane we need to extract.
1129 for (unsigned Lane = 0, LE = VL.size(); Lane != LE; ++Lane) {
1130 // Is this the lane of the scalar that we are looking for ?
1131 if (E->Scalars[Lane] == VL[i]) {
1136 assert(FoundLane >= 0 && "Could not find the correct lane");
1137 ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
1145 Value *BoUpSLP::alreadyVectorized(ArrayRef<Value *> VL) const {
1146 SmallDenseMap<Value*, int>::const_iterator Entry
1147 = ScalarToTreeEntry.find(VL[0]);
1148 if (Entry != ScalarToTreeEntry.end()) {
1149 int Idx = Entry->second;
1150 const TreeEntry *En = &VectorizableTree[Idx];
1151 if (En->isSame(VL) && En->VectorizedValue)
1152 return En->VectorizedValue;
1157 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
1158 if (ScalarToTreeEntry.count(VL[0])) {
1159 int Idx = ScalarToTreeEntry[VL[0]];
1160 TreeEntry *E = &VectorizableTree[Idx];
1162 return vectorizeTree(E);
1165 Type *ScalarTy = VL[0]->getType();
1166 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1167 ScalarTy = SI->getValueOperand()->getType();
1168 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1170 return Gather(VL, VecTy);
1173 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
1174 IRBuilder<>::InsertPointGuard Guard(Builder);
1176 if (E->VectorizedValue) {
1177 DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
1178 return E->VectorizedValue;
1181 Instruction *VL0 = cast<Instruction>(E->Scalars[0]);
1182 Type *ScalarTy = VL0->getType();
1183 if (StoreInst *SI = dyn_cast<StoreInst>(VL0))
1184 ScalarTy = SI->getValueOperand()->getType();
1185 VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size());
1187 if (E->NeedToGather) {
1188 setInsertPointAfterBundle(E->Scalars);
1189 return Gather(E->Scalars, VecTy);
1192 unsigned Opcode = VL0->getOpcode();
1193 assert(Opcode == getSameOpcode(E->Scalars) && "Invalid opcode");
1196 case Instruction::PHI: {
1197 PHINode *PH = dyn_cast<PHINode>(VL0);
1198 Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
1199 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1200 PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
1201 E->VectorizedValue = NewPhi;
1203 // PHINodes may have multiple entries from the same block. We want to
1204 // visit every block once.
1205 SmallSet<BasicBlock*, 4> VisitedBBs;
1207 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1209 BasicBlock *IBB = PH->getIncomingBlock(i);
1211 if (!VisitedBBs.insert(IBB)) {
1212 NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
1216 // Prepare the operand vector.
1217 for (unsigned j = 0; j < E->Scalars.size(); ++j)
1218 Operands.push_back(cast<PHINode>(E->Scalars[j])->
1219 getIncomingValueForBlock(IBB));
1221 Builder.SetInsertPoint(IBB->getTerminator());
1222 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1223 Value *Vec = vectorizeTree(Operands);
1224 NewPhi->addIncoming(Vec, IBB);
1227 assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
1228 "Invalid number of incoming values");
1232 case Instruction::ExtractElement: {
1233 if (CanReuseExtract(E->Scalars)) {
1234 Value *V = VL0->getOperand(0);
1235 E->VectorizedValue = V;
1238 return Gather(E->Scalars, VecTy);
1240 case Instruction::ZExt:
1241 case Instruction::SExt:
1242 case Instruction::FPToUI:
1243 case Instruction::FPToSI:
1244 case Instruction::FPExt:
1245 case Instruction::PtrToInt:
1246 case Instruction::IntToPtr:
1247 case Instruction::SIToFP:
1248 case Instruction::UIToFP:
1249 case Instruction::Trunc:
1250 case Instruction::FPTrunc:
1251 case Instruction::BitCast: {
1253 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1254 INVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1256 setInsertPointAfterBundle(E->Scalars);
1258 Value *InVec = vectorizeTree(INVL);
1260 if (Value *V = alreadyVectorized(E->Scalars))
1263 CastInst *CI = dyn_cast<CastInst>(VL0);
1264 Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
1265 E->VectorizedValue = V;
1268 case Instruction::FCmp:
1269 case Instruction::ICmp: {
1270 ValueList LHSV, RHSV;
1271 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1272 LHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1273 RHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1276 setInsertPointAfterBundle(E->Scalars);
1278 Value *L = vectorizeTree(LHSV);
1279 Value *R = vectorizeTree(RHSV);
1281 if (Value *V = alreadyVectorized(E->Scalars))
1284 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
1286 if (Opcode == Instruction::FCmp)
1287 V = Builder.CreateFCmp(P0, L, R);
1289 V = Builder.CreateICmp(P0, L, R);
1291 E->VectorizedValue = V;
1294 case Instruction::Select: {
1295 ValueList TrueVec, FalseVec, CondVec;
1296 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1297 CondVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1298 TrueVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1299 FalseVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(2));
1302 setInsertPointAfterBundle(E->Scalars);
1304 Value *Cond = vectorizeTree(CondVec);
1305 Value *True = vectorizeTree(TrueVec);
1306 Value *False = vectorizeTree(FalseVec);
1308 if (Value *V = alreadyVectorized(E->Scalars))
1311 Value *V = Builder.CreateSelect(Cond, True, False);
1312 E->VectorizedValue = V;
1315 case Instruction::Add:
1316 case Instruction::FAdd:
1317 case Instruction::Sub:
1318 case Instruction::FSub:
1319 case Instruction::Mul:
1320 case Instruction::FMul:
1321 case Instruction::UDiv:
1322 case Instruction::SDiv:
1323 case Instruction::FDiv:
1324 case Instruction::URem:
1325 case Instruction::SRem:
1326 case Instruction::FRem:
1327 case Instruction::Shl:
1328 case Instruction::LShr:
1329 case Instruction::AShr:
1330 case Instruction::And:
1331 case Instruction::Or:
1332 case Instruction::Xor: {
1333 ValueList LHSVL, RHSVL;
1334 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1335 LHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1336 RHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1339 setInsertPointAfterBundle(E->Scalars);
1341 Value *LHS = vectorizeTree(LHSVL);
1342 Value *RHS = vectorizeTree(RHSVL);
1344 if (LHS == RHS && isa<Instruction>(LHS)) {
1345 assert((VL0->getOperand(0) == VL0->getOperand(1)) && "Invalid order");
1348 if (Value *V = alreadyVectorized(E->Scalars))
1351 BinaryOperator *BinOp = cast<BinaryOperator>(VL0);
1352 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), LHS, RHS);
1353 E->VectorizedValue = V;
1356 case Instruction::Load: {
1357 // Loads are inserted at the head of the tree because we don't want to
1358 // sink them all the way down past store instructions.
1359 setInsertPointAfterBundle(E->Scalars);
1361 LoadInst *LI = cast<LoadInst>(VL0);
1362 unsigned AS = LI->getPointerAddressSpace();
1364 Value *VecPtr = Builder.CreateBitCast(LI->getPointerOperand(),
1365 VecTy->getPointerTo(AS));
1366 unsigned Alignment = LI->getAlignment();
1367 LI = Builder.CreateLoad(VecPtr);
1368 LI->setAlignment(Alignment);
1369 E->VectorizedValue = LI;
1372 case Instruction::Store: {
1373 StoreInst *SI = cast<StoreInst>(VL0);
1374 unsigned Alignment = SI->getAlignment();
1375 unsigned AS = SI->getPointerAddressSpace();
1378 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1379 ValueOp.push_back(cast<StoreInst>(E->Scalars[i])->getValueOperand());
1381 setInsertPointAfterBundle(E->Scalars);
1383 Value *VecValue = vectorizeTree(ValueOp);
1384 Value *VecPtr = Builder.CreateBitCast(SI->getPointerOperand(),
1385 VecTy->getPointerTo(AS));
1386 StoreInst *S = Builder.CreateStore(VecValue, VecPtr);
1387 S->setAlignment(Alignment);
1388 E->VectorizedValue = S;
1392 llvm_unreachable("unknown inst");
1397 Value *BoUpSLP::vectorizeTree() {
1398 Builder.SetInsertPoint(F->getEntryBlock().begin());
1399 vectorizeTree(&VectorizableTree[0]);
1401 DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() << " values .\n");
1403 // Extract all of the elements with the external uses.
1404 for (UserList::iterator it = ExternalUses.begin(), e = ExternalUses.end();
1406 Value *Scalar = it->Scalar;
1407 llvm::User *User = it->User;
1409 // Skip users that we already RAUW. This happens when one instruction
1410 // has multiple uses of the same value.
1411 if (std::find(Scalar->use_begin(), Scalar->use_end(), User) ==
1414 assert(ScalarToTreeEntry.count(Scalar) && "Invalid scalar");
1416 int Idx = ScalarToTreeEntry[Scalar];
1417 TreeEntry *E = &VectorizableTree[Idx];
1418 assert(!E->NeedToGather && "Extracting from a gather list");
1420 Value *Vec = E->VectorizedValue;
1421 assert(Vec && "Can't find vectorizable value");
1423 Value *Lane = Builder.getInt32(it->Lane);
1424 // Generate extracts for out-of-tree users.
1425 // Find the insertion point for the extractelement lane.
1426 if (PHINode *PN = dyn_cast<PHINode>(Vec)) {
1427 Builder.SetInsertPoint(PN->getParent()->getFirstInsertionPt());
1428 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1429 User->replaceUsesOfWith(Scalar, Ex);
1430 } else if (isa<Instruction>(Vec)){
1431 if (PHINode *PH = dyn_cast<PHINode>(User)) {
1432 for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
1433 if (PH->getIncomingValue(i) == Scalar) {
1434 Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
1435 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1436 PH->setOperand(i, Ex);
1440 Builder.SetInsertPoint(cast<Instruction>(User));
1441 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1442 User->replaceUsesOfWith(Scalar, Ex);
1445 Builder.SetInsertPoint(F->getEntryBlock().begin());
1446 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1447 User->replaceUsesOfWith(Scalar, Ex);
1450 DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
1453 // For each vectorized value:
1454 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
1455 TreeEntry *Entry = &VectorizableTree[EIdx];
1458 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
1459 Value *Scalar = Entry->Scalars[Lane];
1461 // No need to handle users of gathered values.
1462 if (Entry->NeedToGather)
1465 assert(Entry->VectorizedValue && "Can't find vectorizable value");
1467 Type *Ty = Scalar->getType();
1468 if (!Ty->isVoidTy()) {
1469 for (Value::use_iterator User = Scalar->use_begin(),
1470 UE = Scalar->use_end(); User != UE; ++User) {
1471 DEBUG(dbgs() << "SLP: \tvalidating user:" << **User << ".\n");
1472 assert(!MustGather.count(*User) &&
1473 "Replacing gathered value with undef");
1475 assert((ScalarToTreeEntry.count(*User) ||
1476 // It is legal to replace the reduction users by undef.
1477 (RdxOps && RdxOps->count(*User))) &&
1478 "Replacing out-of-tree value with undef");
1480 Value *Undef = UndefValue::get(Ty);
1481 Scalar->replaceAllUsesWith(Undef);
1483 DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
1484 cast<Instruction>(Scalar)->eraseFromParent();
1488 for (Function::iterator it = F->begin(), e = F->end(); it != e; ++it) {
1489 BlocksNumbers[it].forget();
1491 Builder.ClearInsertionPoint();
1493 return VectorizableTree[0].VectorizedValue;
1496 void BoUpSLP::optimizeGatherSequence() {
1497 DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
1498 << " gather sequences instructions.\n");
1499 // LICM InsertElementInst sequences.
1500 for (SetVector<Instruction *>::iterator it = GatherSeq.begin(),
1501 e = GatherSeq.end(); it != e; ++it) {
1502 InsertElementInst *Insert = dyn_cast<InsertElementInst>(*it);
1507 // Check if this block is inside a loop.
1508 Loop *L = LI->getLoopFor(Insert->getParent());
1512 // Check if it has a preheader.
1513 BasicBlock *PreHeader = L->getLoopPreheader();
1517 // If the vector or the element that we insert into it are
1518 // instructions that are defined in this basic block then we can't
1519 // hoist this instruction.
1520 Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
1521 Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
1522 if (CurrVec && L->contains(CurrVec))
1524 if (NewElem && L->contains(NewElem))
1527 // We can hoist this instruction. Move it to the pre-header.
1528 Insert->moveBefore(PreHeader->getTerminator());
1531 // Perform O(N^2) search over the gather sequences and merge identical
1532 // instructions. TODO: We can further optimize this scan if we split the
1533 // instructions into different buckets based on the insert lane.
1534 SmallPtrSet<Instruction*, 16> Visited;
1535 SmallVector<Instruction*, 16> ToRemove;
1536 ReversePostOrderTraversal<Function*> RPOT(F);
1537 for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
1538 E = RPOT.end(); I != E; ++I) {
1539 BasicBlock *BB = *I;
1540 // For all instructions in the function:
1541 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1542 Instruction *In = it;
1543 if ((!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In)) ||
1544 !GatherSeq.count(In))
1547 // Check if we can replace this instruction with any of the
1548 // visited instructions.
1549 for (SmallPtrSet<Instruction*, 16>::iterator v = Visited.begin(),
1550 ve = Visited.end(); v != ve; ++v) {
1551 if (In->isIdenticalTo(*v) &&
1552 DT->dominates((*v)->getParent(), In->getParent())) {
1553 In->replaceAllUsesWith(*v);
1554 ToRemove.push_back(In);
1564 // Erase all of the instructions that we RAUWed.
1565 for (SmallVectorImpl<Instruction *>::iterator v = ToRemove.begin(),
1566 ve = ToRemove.end(); v != ve; ++v) {
1567 assert((*v)->getNumUses() == 0 && "Can't remove instructions with uses");
1568 (*v)->eraseFromParent();
1572 /// The SLPVectorizer Pass.
1573 struct SLPVectorizer : public FunctionPass {
1574 typedef SmallVector<StoreInst *, 8> StoreList;
1575 typedef MapVector<Value *, StoreList> StoreListMap;
1577 /// Pass identification, replacement for typeid
1580 explicit SLPVectorizer() : FunctionPass(ID) {
1581 initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
1584 ScalarEvolution *SE;
1586 TargetTransformInfo *TTI;
1591 virtual bool runOnFunction(Function &F) {
1592 SE = &getAnalysis<ScalarEvolution>();
1593 DL = getAnalysisIfAvailable<DataLayout>();
1594 TTI = &getAnalysis<TargetTransformInfo>();
1595 AA = &getAnalysis<AliasAnalysis>();
1596 LI = &getAnalysis<LoopInfo>();
1597 DT = &getAnalysis<DominatorTree>();
1600 bool Changed = false;
1602 // If the target claims to have no vector registers don't attempt
1604 if (!TTI->getNumberOfRegisters(true))
1607 // Must have DataLayout. We can't require it because some tests run w/o
1612 // Don't vectorize when the attribute NoImplicitFloat is used.
1613 if (F.hasFnAttribute(Attribute::NoImplicitFloat))
1616 DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
1618 // Use the bollom up slp vectorizer to construct chains that start with
1619 // he store instructions.
1620 BoUpSLP R(&F, SE, DL, TTI, AA, LI, DT);
1622 // Scan the blocks in the function in post order.
1623 for (po_iterator<BasicBlock*> it = po_begin(&F.getEntryBlock()),
1624 e = po_end(&F.getEntryBlock()); it != e; ++it) {
1625 BasicBlock *BB = *it;
1627 // Vectorize trees that end at stores.
1628 if (unsigned count = collectStores(BB, R)) {
1630 DEBUG(dbgs() << "SLP: Found " << count << " stores to vectorize.\n");
1631 Changed |= vectorizeStoreChains(R);
1634 // Vectorize trees that end at reductions.
1635 Changed |= vectorizeChainsInBlock(BB, R);
1639 R.optimizeGatherSequence();
1640 DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
1641 DEBUG(verifyFunction(F));
1646 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1647 FunctionPass::getAnalysisUsage(AU);
1648 AU.addRequired<ScalarEvolution>();
1649 AU.addRequired<AliasAnalysis>();
1650 AU.addRequired<TargetTransformInfo>();
1651 AU.addRequired<LoopInfo>();
1652 AU.addRequired<DominatorTree>();
1653 AU.addPreserved<LoopInfo>();
1654 AU.addPreserved<DominatorTree>();
1655 AU.setPreservesCFG();
1660 /// \brief Collect memory references and sort them according to their base
1661 /// object. We sort the stores to their base objects to reduce the cost of the
1662 /// quadratic search on the stores. TODO: We can further reduce this cost
1663 /// if we flush the chain creation every time we run into a memory barrier.
1664 unsigned collectStores(BasicBlock *BB, BoUpSLP &R);
1666 /// \brief Try to vectorize a chain that starts at two arithmetic instrs.
1667 bool tryToVectorizePair(Value *A, Value *B, BoUpSLP &R);
1669 /// \brief Try to vectorize a list of operands.
1670 /// \returns true if a value was vectorized.
1671 bool tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R);
1673 /// \brief Try to vectorize a chain that may start at the operands of \V;
1674 bool tryToVectorize(BinaryOperator *V, BoUpSLP &R);
1676 /// \brief Vectorize the stores that were collected in StoreRefs.
1677 bool vectorizeStoreChains(BoUpSLP &R);
1679 /// \brief Scan the basic block and look for patterns that are likely to start
1680 /// a vectorization chain.
1681 bool vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R);
1683 bool vectorizeStoreChain(ArrayRef<Value *> Chain, int CostThreshold,
1686 bool vectorizeStores(ArrayRef<StoreInst *> Stores, int costThreshold,
1689 StoreListMap StoreRefs;
1692 bool SLPVectorizer::vectorizeStoreChain(ArrayRef<Value *> Chain,
1693 int CostThreshold, BoUpSLP &R) {
1694 unsigned ChainLen = Chain.size();
1695 DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
1697 Type *StoreTy = cast<StoreInst>(Chain[0])->getValueOperand()->getType();
1698 unsigned Sz = DL->getTypeSizeInBits(StoreTy);
1699 unsigned VF = MinVecRegSize / Sz;
1701 if (!isPowerOf2_32(Sz) || VF < 2)
1704 bool Changed = false;
1705 // Look for profitable vectorizable trees at all offsets, starting at zero.
1706 for (unsigned i = 0, e = ChainLen; i < e; ++i) {
1709 DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
1711 ArrayRef<Value *> Operands = Chain.slice(i, VF);
1713 R.buildTree(Operands);
1715 int Cost = R.getTreeCost();
1717 DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
1718 if (Cost < CostThreshold) {
1719 DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
1722 // Move to the next bundle.
1731 bool SLPVectorizer::vectorizeStores(ArrayRef<StoreInst *> Stores,
1732 int costThreshold, BoUpSLP &R) {
1733 SetVector<Value *> Heads, Tails;
1734 SmallDenseMap<Value *, Value *> ConsecutiveChain;
1736 // We may run into multiple chains that merge into a single chain. We mark the
1737 // stores that we vectorized so that we don't visit the same store twice.
1738 BoUpSLP::ValueSet VectorizedStores;
1739 bool Changed = false;
1741 // Do a quadratic search on all of the given stores and find
1742 // all of the pairs of stores that follow each other.
1743 for (unsigned i = 0, e = Stores.size(); i < e; ++i) {
1744 for (unsigned j = 0; j < e; ++j) {
1748 if (R.isConsecutiveAccess(Stores[i], Stores[j])) {
1749 Tails.insert(Stores[j]);
1750 Heads.insert(Stores[i]);
1751 ConsecutiveChain[Stores[i]] = Stores[j];
1756 // For stores that start but don't end a link in the chain:
1757 for (SetVector<Value *>::iterator it = Heads.begin(), e = Heads.end();
1759 if (Tails.count(*it))
1762 // We found a store instr that starts a chain. Now follow the chain and try
1764 BoUpSLP::ValueList Operands;
1766 // Collect the chain into a list.
1767 while (Tails.count(I) || Heads.count(I)) {
1768 if (VectorizedStores.count(I))
1770 Operands.push_back(I);
1771 // Move to the next value in the chain.
1772 I = ConsecutiveChain[I];
1775 bool Vectorized = vectorizeStoreChain(Operands, costThreshold, R);
1777 // Mark the vectorized stores so that we don't vectorize them again.
1779 VectorizedStores.insert(Operands.begin(), Operands.end());
1780 Changed |= Vectorized;
1787 unsigned SLPVectorizer::collectStores(BasicBlock *BB, BoUpSLP &R) {
1790 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1791 StoreInst *SI = dyn_cast<StoreInst>(it);
1795 // Check that the pointer points to scalars.
1796 Type *Ty = SI->getValueOperand()->getType();
1797 if (Ty->isAggregateType() || Ty->isVectorTy())
1800 // Find the base pointer.
1801 Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), DL);
1803 // Save the store locations.
1804 StoreRefs[Ptr].push_back(SI);
1810 bool SLPVectorizer::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
1813 Value *VL[] = { A, B };
1814 return tryToVectorizeList(VL, R);
1817 bool SLPVectorizer::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R) {
1821 DEBUG(dbgs() << "SLP: Vectorizing a list of length = " << VL.size() << ".\n");
1823 // Check that all of the parts are scalar instructions of the same type.
1824 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
1828 unsigned Opcode0 = I0->getOpcode();
1830 Type *Ty0 = I0->getType();
1831 unsigned Sz = DL->getTypeSizeInBits(Ty0);
1832 unsigned VF = MinVecRegSize / Sz;
1834 for (int i = 0, e = VL.size(); i < e; ++i) {
1835 Type *Ty = VL[i]->getType();
1836 if (Ty->isAggregateType() || Ty->isVectorTy())
1838 Instruction *Inst = dyn_cast<Instruction>(VL[i]);
1839 if (!Inst || Inst->getOpcode() != Opcode0)
1843 bool Changed = false;
1845 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
1846 unsigned OpsWidth = 0;
1853 if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
1856 DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations " << "\n");
1857 ArrayRef<Value *> Ops = VL.slice(i, OpsWidth);
1860 int Cost = R.getTreeCost();
1862 if (Cost < -SLPCostThreshold) {
1863 DEBUG(dbgs() << "SLP: Vectorizing pair at cost:" << Cost << ".\n");
1866 // Move to the next bundle.
1875 bool SLPVectorizer::tryToVectorize(BinaryOperator *V, BoUpSLP &R) {
1879 // Try to vectorize V.
1880 if (tryToVectorizePair(V->getOperand(0), V->getOperand(1), R))
1883 BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0));
1884 BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1));
1886 if (B && B->hasOneUse()) {
1887 BinaryOperator *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
1888 BinaryOperator *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
1889 if (tryToVectorizePair(A, B0, R)) {
1893 if (tryToVectorizePair(A, B1, R)) {
1900 if (A && A->hasOneUse()) {
1901 BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
1902 BinaryOperator *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
1903 if (tryToVectorizePair(A0, B, R)) {
1907 if (tryToVectorizePair(A1, B, R)) {
1915 /// \brief Generate a shuffle mask to be used in a reduction tree.
1917 /// \param VecLen The length of the vector to be reduced.
1918 /// \param NumEltsToRdx The number of elements that should be reduced in the
1920 /// \param IsPairwise Whether the reduction is a pairwise or splitting
1921 /// reduction. A pairwise reduction will generate a mask of
1922 /// <0,2,...> or <1,3,..> while a splitting reduction will generate
1923 /// <2,3, undef,undef> for a vector of 4 and NumElts = 2.
1924 /// \param IsLeft True will generate a mask of even elements, odd otherwise.
1925 static Value *createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx,
1926 bool IsPairwise, bool IsLeft,
1927 IRBuilder<> &Builder) {
1928 assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask");
1930 SmallVector<Constant *, 32> ShuffleMask(
1931 VecLen, UndefValue::get(Builder.getInt32Ty()));
1934 // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
1935 for (unsigned i = 0; i != NumEltsToRdx; ++i)
1936 ShuffleMask[i] = Builder.getInt32(2 * i + !IsLeft);
1938 // Move the upper half of the vector to the lower half.
1939 for (unsigned i = 0; i != NumEltsToRdx; ++i)
1940 ShuffleMask[i] = Builder.getInt32(NumEltsToRdx + i);
1942 return ConstantVector::get(ShuffleMask);
1946 /// Model horizontal reductions.
1948 /// A horizontal reduction is a tree of reduction operations (currently add and
1949 /// fadd) that has operations that can be put into a vector as its leaf.
1950 /// For example, this tree:
1957 /// This tree has "mul" as its reduced values and "+" as its reduction
1958 /// operations. A reduction might be feeding into a store or a binary operation
1973 class HorizontalReduction {
1974 SmallPtrSet<Value *, 16> ReductionOps;
1975 SmallVector<Value *, 32> ReducedVals;
1977 BinaryOperator *ReductionRoot;
1978 PHINode *ReductionPHI;
1980 /// The opcode of the reduction.
1981 unsigned ReductionOpcode;
1982 /// The opcode of the values we perform a reduction on.
1983 unsigned ReducedValueOpcode;
1984 /// The width of one full horizontal reduction operation.
1985 unsigned ReduxWidth;
1986 /// Should we model this reduction as a pairwise reduction tree or a tree that
1987 /// splits the vector in halves and adds those halves.
1988 bool IsPairwiseReduction;
1991 HorizontalReduction()
1992 : ReductionRoot(0), ReductionPHI(0), ReductionOpcode(0),
1993 ReducedValueOpcode(0), ReduxWidth(0), IsPairwiseReduction(false) {}
1995 /// \brief Try to find a reduction tree.
1996 bool matchAssociativeReduction(PHINode *Phi, BinaryOperator *B,
1999 std::find(Phi->op_begin(), Phi->op_end(), B) != Phi->op_end()) &&
2000 "Thi phi needs to use the binary operator");
2002 // We could have a initial reductions that is not an add.
2003 // r *= v1 + v2 + v3 + v4
2004 // In such a case start looking for a tree rooted in the first '+'.
2006 if (B->getOperand(0) == Phi) {
2008 B = dyn_cast<BinaryOperator>(B->getOperand(1));
2009 } else if (B->getOperand(1) == Phi) {
2011 B = dyn_cast<BinaryOperator>(B->getOperand(0));
2018 Type *Ty = B->getType();
2019 if (Ty->isVectorTy())
2022 ReductionOpcode = B->getOpcode();
2023 ReducedValueOpcode = 0;
2024 ReduxWidth = MinVecRegSize / DL->getTypeSizeInBits(Ty);
2031 // We currently only support adds.
2032 if (ReductionOpcode != Instruction::Add &&
2033 ReductionOpcode != Instruction::FAdd)
2036 // Post order traverse the reduction tree starting at B. We only handle true
2037 // trees containing only binary operators.
2038 SmallVector<std::pair<BinaryOperator *, unsigned>, 32> Stack;
2039 Stack.push_back(std::make_pair(B, 0));
2040 while (!Stack.empty()) {
2041 BinaryOperator *TreeN = Stack.back().first;
2042 unsigned EdgeToVist = Stack.back().second++;
2043 bool IsReducedValue = TreeN->getOpcode() != ReductionOpcode;
2045 // Only handle trees in the current basic block.
2046 if (TreeN->getParent() != B->getParent())
2049 // Each tree node needs to have one user except for the ultimate
2051 if (!TreeN->hasOneUse() && TreeN != B)
2055 if (EdgeToVist == 2 || IsReducedValue) {
2056 if (IsReducedValue) {
2057 // Make sure that the opcodes of the operations that we are going to
2059 if (!ReducedValueOpcode)
2060 ReducedValueOpcode = TreeN->getOpcode();
2061 else if (ReducedValueOpcode != TreeN->getOpcode())
2063 ReducedVals.push_back(TreeN);
2065 // We need to be able to reassociate the adds.
2066 if (!TreeN->isAssociative())
2068 ReductionOps.insert(TreeN);
2075 // Visit left or right.
2076 Value *NextV = TreeN->getOperand(EdgeToVist);
2077 BinaryOperator *Next = dyn_cast<BinaryOperator>(NextV);
2079 Stack.push_back(std::make_pair(Next, 0));
2080 else if (NextV != Phi)
2086 /// \brief Attempt to vectorize the tree found by
2087 /// matchAssociativeReduction.
2088 bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
2089 if (ReducedVals.empty())
2092 unsigned NumReducedVals = ReducedVals.size();
2093 if (NumReducedVals < ReduxWidth)
2096 Value *VectorizedTree = 0;
2097 IRBuilder<> Builder(ReductionRoot);
2098 FastMathFlags Unsafe;
2099 Unsafe.setUnsafeAlgebra();
2100 Builder.SetFastMathFlags(Unsafe);
2103 for (; i < NumReducedVals - ReduxWidth + 1; i += ReduxWidth) {
2104 ArrayRef<Value *> ValsToReduce(&ReducedVals[i], ReduxWidth);
2105 V.buildTree(ValsToReduce, &ReductionOps);
2108 int Cost = V.getTreeCost() + getReductionCost(TTI, ReducedVals[i]);
2109 if (Cost >= -SLPCostThreshold)
2112 DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" << Cost
2115 // Vectorize a tree.
2116 DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
2117 Value *VectorizedRoot = V.vectorizeTree();
2119 // Emit a reduction.
2120 Value *ReducedSubTree = emitReduction(VectorizedRoot, Builder);
2121 if (VectorizedTree) {
2122 Builder.SetCurrentDebugLocation(Loc);
2123 VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
2124 ReducedSubTree, "bin.rdx");
2126 VectorizedTree = ReducedSubTree;
2129 if (VectorizedTree) {
2130 // Finish the reduction.
2131 for (; i < NumReducedVals; ++i) {
2132 Builder.SetCurrentDebugLocation(
2133 cast<Instruction>(ReducedVals[i])->getDebugLoc());
2134 VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
2139 assert(ReductionRoot != NULL && "Need a reduction operation");
2140 ReductionRoot->setOperand(0, VectorizedTree);
2141 ReductionRoot->setOperand(1, ReductionPHI);
2143 ReductionRoot->replaceAllUsesWith(VectorizedTree);
2145 return VectorizedTree != 0;
2150 /// \brief Calcuate the cost of a reduction.
2151 int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal) {
2152 Type *ScalarTy = FirstReducedVal->getType();
2153 Type *VecTy = VectorType::get(ScalarTy, ReduxWidth);
2155 int PairwiseRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, true);
2156 int SplittingRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, false);
2158 IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
2159 int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
2161 int ScalarReduxCost =
2162 ReduxWidth * TTI->getArithmeticInstrCost(ReductionOpcode, VecTy);
2164 DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost
2165 << " for reduction that starts with " << *FirstReducedVal
2167 << (IsPairwiseReduction ? "pairwise" : "splitting")
2168 << " reduction)\n");
2170 return VecReduxCost - ScalarReduxCost;
2173 static Value *createBinOp(IRBuilder<> &Builder, unsigned Opcode, Value *L,
2174 Value *R, const Twine &Name = "") {
2175 if (Opcode == Instruction::FAdd)
2176 return Builder.CreateFAdd(L, R, Name);
2177 return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, L, R, Name);
2180 /// \brief Emit a horizontal reduction of the vectorized value.
2181 Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder) {
2182 assert(VectorizedValue && "Need to have a vectorized tree node");
2183 Instruction *ValToReduce = dyn_cast<Instruction>(VectorizedValue);
2184 assert(isPowerOf2_32(ReduxWidth) &&
2185 "We only handle power-of-two reductions for now");
2187 Value *TmpVec = ValToReduce;
2188 for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
2189 if (IsPairwiseReduction) {
2191 createRdxShuffleMask(ReduxWidth, i, true, true, Builder);
2193 createRdxShuffleMask(ReduxWidth, i, true, false, Builder);
2195 Value *LeftShuf = Builder.CreateShuffleVector(
2196 TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l");
2197 Value *RightShuf = Builder.CreateShuffleVector(
2198 TmpVec, UndefValue::get(TmpVec->getType()), (RightMask),
2200 TmpVec = createBinOp(Builder, ReductionOpcode, LeftShuf, RightShuf,
2204 createRdxShuffleMask(ReduxWidth, i, false, false, Builder);
2205 Value *Shuf = Builder.CreateShuffleVector(
2206 TmpVec, UndefValue::get(TmpVec->getType()), UpperHalf, "rdx.shuf");
2207 TmpVec = createBinOp(Builder, ReductionOpcode, TmpVec, Shuf, "bin.rdx");
2211 // The result is in the first element of the vector.
2212 return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
2216 /// \brief Recognize construction of vectors like
2217 /// %ra = insertelement <4 x float> undef, float %s0, i32 0
2218 /// %rb = insertelement <4 x float> %ra, float %s1, i32 1
2219 /// %rc = insertelement <4 x float> %rb, float %s2, i32 2
2220 /// %rd = insertelement <4 x float> %rc, float %s3, i32 3
2222 /// Returns true if it matches
2224 static bool findBuildVector(InsertElementInst *IE,
2225 SmallVectorImpl<Value *> &Ops) {
2226 if (!isa<UndefValue>(IE->getOperand(0)))
2230 Ops.push_back(IE->getOperand(1));
2232 if (IE->use_empty())
2235 InsertElementInst *NextUse = dyn_cast<InsertElementInst>(IE->use_back());
2239 // If this isn't the final use, make sure the next insertelement is the only
2240 // use. It's OK if the final constructed vector is used multiple times
2241 if (!IE->hasOneUse())
2250 bool SLPVectorizer::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
2251 bool Changed = false;
2252 SmallVector<Value *, 4> Incoming;
2253 SmallSet<Instruction *, 16> VisitedInstrs;
2255 // Collect the incoming values from the PHIs.
2256 for (BasicBlock::iterator instr = BB->begin(), ie = BB->end(); instr != ie;
2258 PHINode *P = dyn_cast<PHINode>(instr);
2263 // We may go through BB multiple times so skip the one we have checked.
2264 if (!VisitedInstrs.insert(instr))
2267 // Stop constructing the list when you reach a different type.
2268 if (Incoming.size() && P->getType() != Incoming[0]->getType()) {
2269 if (tryToVectorizeList(Incoming, R)) {
2270 // We would like to start over since some instructions are deleted
2271 // and the iterator may become invalid value.
2273 instr = BB->begin();
2280 Incoming.push_back(P);
2283 if (Incoming.size() > 1)
2284 Changed |= tryToVectorizeList(Incoming, R);
2286 VisitedInstrs.clear();
2288 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) {
2289 // We may go through BB multiple times so skip the one we have checked.
2290 if (!VisitedInstrs.insert(it))
2293 if (isa<DbgInfoIntrinsic>(it))
2296 // Try to vectorize reductions that use PHINodes.
2297 if (PHINode *P = dyn_cast<PHINode>(it)) {
2298 // Check that the PHI is a reduction PHI.
2299 if (P->getNumIncomingValues() != 2)
2302 (P->getIncomingBlock(0) == BB
2303 ? (P->getIncomingValue(0))
2304 : (P->getIncomingBlock(1) == BB ? P->getIncomingValue(1) : 0));
2305 // Check if this is a Binary Operator.
2306 BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx);
2310 // Try to match and vectorize a horizontal reduction.
2311 HorizontalReduction HorRdx;
2312 if (ShouldVectorizeHor &&
2313 HorRdx.matchAssociativeReduction(P, BI, DL) &&
2314 HorRdx.tryToReduce(R, TTI)) {
2321 Value *Inst = BI->getOperand(0);
2323 Inst = BI->getOperand(1);
2325 if (tryToVectorize(dyn_cast<BinaryOperator>(Inst), R)) {
2326 // We would like to start over since some instructions are deleted
2327 // and the iterator may become invalid value.
2337 // Try to vectorize horizontal reductions feeding into a store.
2338 if (ShouldStartVectorizeHorAtStore)
2339 if (StoreInst *SI = dyn_cast<StoreInst>(it))
2340 if (BinaryOperator *BinOp =
2341 dyn_cast<BinaryOperator>(SI->getValueOperand())) {
2342 HorizontalReduction HorRdx;
2343 if (((HorRdx.matchAssociativeReduction(0, BinOp, DL) &&
2344 HorRdx.tryToReduce(R, TTI)) ||
2345 tryToVectorize(BinOp, R))) {
2353 // Try to vectorize trees that start at compare instructions.
2354 if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
2355 if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) {
2357 // We would like to start over since some instructions are deleted
2358 // and the iterator may become invalid value.
2364 for (int i = 0; i < 2; ++i) {
2365 if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i))) {
2366 if (tryToVectorizePair(BI->getOperand(0), BI->getOperand(1), R)) {
2368 // We would like to start over since some instructions are deleted
2369 // and the iterator may become invalid value.
2378 // Try to vectorize trees that start at insertelement instructions.
2379 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(it)) {
2380 SmallVector<Value *, 8> Ops;
2381 if (!findBuildVector(IE, Ops))
2384 if (tryToVectorizeList(Ops, R)) {
2397 bool SLPVectorizer::vectorizeStoreChains(BoUpSLP &R) {
2398 bool Changed = false;
2399 // Attempt to sort and vectorize each of the store-groups.
2400 for (StoreListMap::iterator it = StoreRefs.begin(), e = StoreRefs.end();
2402 if (it->second.size() < 2)
2405 DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
2406 << it->second.size() << ".\n");
2408 // Process the stores in chunks of 16.
2409 for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI+=16) {
2410 unsigned Len = std::min<unsigned>(CE - CI, 16);
2411 ArrayRef<StoreInst *> Chunk(&it->second[CI], Len);
2412 Changed |= vectorizeStores(Chunk, -SLPCostThreshold, R);
2418 } // end anonymous namespace
2420 char SLPVectorizer::ID = 0;
2421 static const char lv_name[] = "SLP Vectorizer";
2422 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
2423 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
2424 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
2425 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
2426 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
2427 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
2430 Pass *createSLPVectorizerPass() { return new SLPVectorizer(); }