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);
315 TreeEntry() : Scalars(), VectorizedValue(0), LastScalarIndex(0),
318 /// \returns true if the scalars in VL are equal to this entry.
319 bool isSame(ArrayRef<Value *> VL) const {
320 assert(VL.size() == Scalars.size() && "Invalid size");
321 return std::equal(VL.begin(), VL.end(), Scalars.begin());
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 /// Reduction operators.
397 // Analysis and block reference.
401 TargetTransformInfo *TTI;
405 /// Instruction builder to construct the vectorized tree.
409 void BoUpSLP::buildTree(ArrayRef<Value *> Roots, ValueSet *Rdx) {
412 if (!getSameType(Roots))
414 buildTree_rec(Roots, 0);
416 // Collect the values that we need to extract from the tree.
417 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
418 TreeEntry *Entry = &VectorizableTree[EIdx];
421 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
422 Value *Scalar = Entry->Scalars[Lane];
424 // No need to handle users of gathered values.
425 if (Entry->NeedToGather)
428 for (Value::use_iterator User = Scalar->use_begin(),
429 UE = Scalar->use_end(); User != UE; ++User) {
430 DEBUG(dbgs() << "SLP: Checking user:" << **User << ".\n");
432 bool Gathered = MustGather.count(*User);
434 // Skip in-tree scalars that become vectors.
435 if (ScalarToTreeEntry.count(*User) && !Gathered) {
436 DEBUG(dbgs() << "SLP: \tInternal user will be removed:" <<
438 int Idx = ScalarToTreeEntry[*User]; (void) Idx;
439 assert(!VectorizableTree[Idx].NeedToGather && "Bad state");
442 Instruction *UserInst = dyn_cast<Instruction>(*User);
446 // Ignore uses that are part of the reduction.
447 if (Rdx && std::find(Rdx->begin(), Rdx->end(), UserInst) != Rdx->end())
450 DEBUG(dbgs() << "SLP: Need to extract:" << **User << " from lane " <<
451 Lane << " from " << *Scalar << ".\n");
452 ExternalUses.push_back(ExternalUser(Scalar, *User, Lane));
459 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth) {
460 bool SameTy = getSameType(VL); (void)SameTy;
461 assert(SameTy && "Invalid types!");
463 if (Depth == RecursionMaxDepth) {
464 DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
465 newTreeEntry(VL, false);
469 // Don't handle vectors.
470 if (VL[0]->getType()->isVectorTy()) {
471 DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
472 newTreeEntry(VL, false);
476 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
477 if (SI->getValueOperand()->getType()->isVectorTy()) {
478 DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
479 newTreeEntry(VL, false);
483 // If all of the operands are identical or constant we have a simple solution.
484 if (allConstant(VL) || isSplat(VL) || !getSameBlock(VL) ||
485 !getSameOpcode(VL)) {
486 DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
487 newTreeEntry(VL, false);
491 // We now know that this is a vector of instructions of the same type from
494 // Check if this is a duplicate of another entry.
495 if (ScalarToTreeEntry.count(VL[0])) {
496 int Idx = ScalarToTreeEntry[VL[0]];
497 TreeEntry *E = &VectorizableTree[Idx];
498 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
499 DEBUG(dbgs() << "SLP: \tChecking bundle: " << *VL[i] << ".\n");
500 if (E->Scalars[i] != VL[i]) {
501 DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
502 newTreeEntry(VL, false);
506 DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *VL[0] << ".\n");
510 // Check that none of the instructions in the bundle are already in the tree.
511 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
512 if (ScalarToTreeEntry.count(VL[i])) {
513 DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
514 ") is already in tree.\n");
515 newTreeEntry(VL, false);
520 // If any of the scalars appears in the table OR it is marked as a value that
521 // needs to stat scalar then we need to gather the scalars.
522 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
523 if (ScalarToTreeEntry.count(VL[i]) || MustGather.count(VL[i])) {
524 DEBUG(dbgs() << "SLP: Gathering due to gathered scalar. \n");
525 newTreeEntry(VL, false);
530 // Check that all of the users of the scalars that we want to vectorize are
532 Instruction *VL0 = cast<Instruction>(VL[0]);
533 int MyLastIndex = getLastIndex(VL);
534 BasicBlock *BB = cast<Instruction>(VL0)->getParent();
536 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
537 Instruction *Scalar = cast<Instruction>(VL[i]);
538 DEBUG(dbgs() << "SLP: Checking users of " << *Scalar << ". \n");
539 for (Value::use_iterator U = Scalar->use_begin(), UE = Scalar->use_end();
541 DEBUG(dbgs() << "SLP: \tUser " << **U << ". \n");
542 Instruction *User = dyn_cast<Instruction>(*U);
544 DEBUG(dbgs() << "SLP: Gathering due unknown user. \n");
545 newTreeEntry(VL, false);
549 // We don't care if the user is in a different basic block.
550 BasicBlock *UserBlock = User->getParent();
551 if (UserBlock != BB) {
552 DEBUG(dbgs() << "SLP: User from a different basic block "
557 // If this is a PHINode within this basic block then we can place the
558 // extract wherever we want.
559 if (isa<PHINode>(*User)) {
560 DEBUG(dbgs() << "SLP: \tWe can schedule PHIs:" << *User << ". \n");
564 // Check if this is a safe in-tree user.
565 if (ScalarToTreeEntry.count(User)) {
566 int Idx = ScalarToTreeEntry[User];
567 int VecLocation = VectorizableTree[Idx].LastScalarIndex;
568 if (VecLocation <= MyLastIndex) {
569 DEBUG(dbgs() << "SLP: Gathering due to unschedulable vector. \n");
570 newTreeEntry(VL, false);
573 DEBUG(dbgs() << "SLP: In-tree user (" << *User << ") at #" <<
574 VecLocation << " vector value (" << *Scalar << ") at #"
575 << MyLastIndex << ".\n");
579 // This user is part of the reduction.
580 if (RdxOps && RdxOps->count(User))
583 // Make sure that we can schedule this unknown user.
584 BlockNumbering &BN = BlocksNumbers[BB];
585 int UserIndex = BN.getIndex(User);
586 if (UserIndex < MyLastIndex) {
588 DEBUG(dbgs() << "SLP: Can't schedule extractelement for "
590 newTreeEntry(VL, false);
596 // Check that every instructions appears once in this bundle.
597 for (unsigned i = 0, e = VL.size(); i < e; ++i)
598 for (unsigned j = i+1; j < e; ++j)
599 if (VL[i] == VL[j]) {
600 DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
601 newTreeEntry(VL, false);
605 // Check that instructions in this bundle don't reference other instructions.
606 // The runtime of this check is O(N * N-1 * uses(N)) and a typical N is 4.
607 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
608 for (Value::use_iterator U = VL[i]->use_begin(), UE = VL[i]->use_end();
610 for (unsigned j = 0; j < e; ++j) {
611 if (i != j && *U == VL[j]) {
612 DEBUG(dbgs() << "SLP: Intra-bundle dependencies!" << **U << ". \n");
613 newTreeEntry(VL, false);
620 DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
622 unsigned Opcode = getSameOpcode(VL);
624 // Check if it is safe to sink the loads or the stores.
625 if (Opcode == Instruction::Load || Opcode == Instruction::Store) {
626 Instruction *Last = getLastInstruction(VL);
628 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
631 Value *Barrier = getSinkBarrier(cast<Instruction>(VL[i]), Last);
633 DEBUG(dbgs() << "SLP: Can't sink " << *VL[i] << "\n down to " << *Last
634 << "\n because of " << *Barrier << ". Gathering.\n");
635 newTreeEntry(VL, false);
642 case Instruction::PHI: {
643 PHINode *PH = dyn_cast<PHINode>(VL0);
645 // Check for terminator values (e.g. invoke).
646 for (unsigned j = 0; j < VL.size(); ++j)
647 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
648 TerminatorInst *Term = dyn_cast<TerminatorInst>(cast<PHINode>(VL[j])->getIncomingValue(i));
650 DEBUG(dbgs() << "SLP: Need to swizzle PHINodes (TerminatorInst use).\n");
651 newTreeEntry(VL, false);
656 newTreeEntry(VL, true);
657 DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
659 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
661 // Prepare the operand vector.
662 for (unsigned j = 0; j < VL.size(); ++j)
663 Operands.push_back(cast<PHINode>(VL[j])->getIncomingValue(i));
665 buildTree_rec(Operands, Depth + 1);
669 case Instruction::ExtractElement: {
670 bool Reuse = CanReuseExtract(VL);
672 DEBUG(dbgs() << "SLP: Reusing extract sequence.\n");
674 newTreeEntry(VL, Reuse);
677 case Instruction::Load: {
678 // Check if the loads are consecutive or of we need to swizzle them.
679 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
680 if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
681 newTreeEntry(VL, false);
682 DEBUG(dbgs() << "SLP: Need to swizzle loads.\n");
686 newTreeEntry(VL, true);
687 DEBUG(dbgs() << "SLP: added a vector of loads.\n");
690 case Instruction::ZExt:
691 case Instruction::SExt:
692 case Instruction::FPToUI:
693 case Instruction::FPToSI:
694 case Instruction::FPExt:
695 case Instruction::PtrToInt:
696 case Instruction::IntToPtr:
697 case Instruction::SIToFP:
698 case Instruction::UIToFP:
699 case Instruction::Trunc:
700 case Instruction::FPTrunc:
701 case Instruction::BitCast: {
702 Type *SrcTy = VL0->getOperand(0)->getType();
703 for (unsigned i = 0; i < VL.size(); ++i) {
704 Type *Ty = cast<Instruction>(VL[i])->getOperand(0)->getType();
705 if (Ty != SrcTy || Ty->isAggregateType() || Ty->isVectorTy()) {
706 newTreeEntry(VL, false);
707 DEBUG(dbgs() << "SLP: Gathering casts with different src types.\n");
711 newTreeEntry(VL, true);
712 DEBUG(dbgs() << "SLP: added a vector of casts.\n");
714 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
716 // Prepare the operand vector.
717 for (unsigned j = 0; j < VL.size(); ++j)
718 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
720 buildTree_rec(Operands, Depth+1);
724 case Instruction::ICmp:
725 case Instruction::FCmp: {
726 // Check that all of the compares have the same predicate.
727 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
728 Type *ComparedTy = cast<Instruction>(VL[0])->getOperand(0)->getType();
729 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
730 CmpInst *Cmp = cast<CmpInst>(VL[i]);
731 if (Cmp->getPredicate() != P0 ||
732 Cmp->getOperand(0)->getType() != ComparedTy) {
733 newTreeEntry(VL, false);
734 DEBUG(dbgs() << "SLP: Gathering cmp with different predicate.\n");
739 newTreeEntry(VL, true);
740 DEBUG(dbgs() << "SLP: added a vector of compares.\n");
742 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
744 // Prepare the operand vector.
745 for (unsigned j = 0; j < VL.size(); ++j)
746 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
748 buildTree_rec(Operands, Depth+1);
752 case Instruction::Select:
753 case Instruction::Add:
754 case Instruction::FAdd:
755 case Instruction::Sub:
756 case Instruction::FSub:
757 case Instruction::Mul:
758 case Instruction::FMul:
759 case Instruction::UDiv:
760 case Instruction::SDiv:
761 case Instruction::FDiv:
762 case Instruction::URem:
763 case Instruction::SRem:
764 case Instruction::FRem:
765 case Instruction::Shl:
766 case Instruction::LShr:
767 case Instruction::AShr:
768 case Instruction::And:
769 case Instruction::Or:
770 case Instruction::Xor: {
771 newTreeEntry(VL, true);
772 DEBUG(dbgs() << "SLP: added a vector of bin op.\n");
774 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
776 // Prepare the operand vector.
777 for (unsigned j = 0; j < VL.size(); ++j)
778 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
780 buildTree_rec(Operands, Depth+1);
784 case Instruction::Store: {
785 // Check if the stores are consecutive or of we need to swizzle them.
786 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
787 if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
788 newTreeEntry(VL, false);
789 DEBUG(dbgs() << "SLP: Non consecutive store.\n");
793 newTreeEntry(VL, true);
794 DEBUG(dbgs() << "SLP: added a vector of stores.\n");
797 for (unsigned j = 0; j < VL.size(); ++j)
798 Operands.push_back(cast<Instruction>(VL[j])->getOperand(0));
800 // We can ignore these values because we are sinking them down.
801 MemBarrierIgnoreList.insert(VL.begin(), VL.end());
802 buildTree_rec(Operands, Depth + 1);
806 newTreeEntry(VL, false);
807 DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
812 int BoUpSLP::getEntryCost(TreeEntry *E) {
813 ArrayRef<Value*> VL = E->Scalars;
815 Type *ScalarTy = VL[0]->getType();
816 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
817 ScalarTy = SI->getValueOperand()->getType();
818 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
820 if (E->NeedToGather) {
824 return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
826 return getGatherCost(E->Scalars);
829 assert(getSameOpcode(VL) && getSameType(VL) && getSameBlock(VL) &&
831 Instruction *VL0 = cast<Instruction>(VL[0]);
832 unsigned Opcode = VL0->getOpcode();
834 case Instruction::PHI: {
837 case Instruction::ExtractElement: {
838 if (CanReuseExtract(VL))
840 return getGatherCost(VecTy);
842 case Instruction::ZExt:
843 case Instruction::SExt:
844 case Instruction::FPToUI:
845 case Instruction::FPToSI:
846 case Instruction::FPExt:
847 case Instruction::PtrToInt:
848 case Instruction::IntToPtr:
849 case Instruction::SIToFP:
850 case Instruction::UIToFP:
851 case Instruction::Trunc:
852 case Instruction::FPTrunc:
853 case Instruction::BitCast: {
854 Type *SrcTy = VL0->getOperand(0)->getType();
856 // Calculate the cost of this instruction.
857 int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(),
858 VL0->getType(), SrcTy);
860 VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
861 int VecCost = TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy);
862 return VecCost - ScalarCost;
864 case Instruction::FCmp:
865 case Instruction::ICmp:
866 case Instruction::Select:
867 case Instruction::Add:
868 case Instruction::FAdd:
869 case Instruction::Sub:
870 case Instruction::FSub:
871 case Instruction::Mul:
872 case Instruction::FMul:
873 case Instruction::UDiv:
874 case Instruction::SDiv:
875 case Instruction::FDiv:
876 case Instruction::URem:
877 case Instruction::SRem:
878 case Instruction::FRem:
879 case Instruction::Shl:
880 case Instruction::LShr:
881 case Instruction::AShr:
882 case Instruction::And:
883 case Instruction::Or:
884 case Instruction::Xor: {
885 // Calculate the cost of this instruction.
888 if (Opcode == Instruction::FCmp || Opcode == Instruction::ICmp ||
889 Opcode == Instruction::Select) {
890 VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
891 ScalarCost = VecTy->getNumElements() *
892 TTI->getCmpSelInstrCost(Opcode, ScalarTy, Builder.getInt1Ty());
893 VecCost = TTI->getCmpSelInstrCost(Opcode, VecTy, MaskTy);
895 ScalarCost = VecTy->getNumElements() *
896 TTI->getArithmeticInstrCost(Opcode, ScalarTy);
897 VecCost = TTI->getArithmeticInstrCost(Opcode, VecTy);
899 return VecCost - ScalarCost;
901 case Instruction::Load: {
902 // Cost of wide load - cost of scalar loads.
903 int ScalarLdCost = VecTy->getNumElements() *
904 TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
905 int VecLdCost = TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
906 return VecLdCost - ScalarLdCost;
908 case Instruction::Store: {
909 // We know that we can merge the stores. Calculate the cost.
910 int ScalarStCost = VecTy->getNumElements() *
911 TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
912 int VecStCost = TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
913 return VecStCost - ScalarStCost;
916 llvm_unreachable("Unknown instruction");
920 int BoUpSLP::getTreeCost() {
922 DEBUG(dbgs() << "SLP: Calculating cost for tree of size " <<
923 VectorizableTree.size() << ".\n");
925 // Don't vectorize tiny trees. Small load/store chains or consecutive stores
926 // of constants will be vectoried in SelectionDAG in MergeConsecutiveStores.
927 // The SelectionDAG vectorizer can only handle pairs (trees of height = 2).
928 if (VectorizableTree.size() < 3) {
929 if (!VectorizableTree.size()) {
930 assert(!ExternalUses.size() && "We should not have any external users");
935 unsigned BundleWidth = VectorizableTree[0].Scalars.size();
937 for (unsigned i = 0, e = VectorizableTree.size(); i != e; ++i) {
938 int C = getEntryCost(&VectorizableTree[i]);
939 DEBUG(dbgs() << "SLP: Adding cost " << C << " for bundle that starts with "
940 << *VectorizableTree[i].Scalars[0] << " .\n");
945 for (UserList::iterator I = ExternalUses.begin(), E = ExternalUses.end();
948 VectorType *VecTy = VectorType::get(I->Scalar->getType(), BundleWidth);
949 ExtractCost += TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy,
954 DEBUG(dbgs() << "SLP: Total Cost " << Cost + ExtractCost<< ".\n");
955 return Cost + ExtractCost;
958 int BoUpSLP::getGatherCost(Type *Ty) {
960 for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
961 Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
965 int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) {
966 // Find the type of the operands in VL.
967 Type *ScalarTy = VL[0]->getType();
968 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
969 ScalarTy = SI->getValueOperand()->getType();
970 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
971 // Find the cost of inserting/extracting values from the vector.
972 return getGatherCost(VecTy);
975 AliasAnalysis::Location BoUpSLP::getLocation(Instruction *I) {
976 if (StoreInst *SI = dyn_cast<StoreInst>(I))
977 return AA->getLocation(SI);
978 if (LoadInst *LI = dyn_cast<LoadInst>(I))
979 return AA->getLocation(LI);
980 return AliasAnalysis::Location();
983 Value *BoUpSLP::getPointerOperand(Value *I) {
984 if (LoadInst *LI = dyn_cast<LoadInst>(I))
985 return LI->getPointerOperand();
986 if (StoreInst *SI = dyn_cast<StoreInst>(I))
987 return SI->getPointerOperand();
991 unsigned BoUpSLP::getAddressSpaceOperand(Value *I) {
992 if (LoadInst *L = dyn_cast<LoadInst>(I))
993 return L->getPointerAddressSpace();
994 if (StoreInst *S = dyn_cast<StoreInst>(I))
995 return S->getPointerAddressSpace();
999 bool BoUpSLP::isConsecutiveAccess(Value *A, Value *B) {
1000 Value *PtrA = getPointerOperand(A);
1001 Value *PtrB = getPointerOperand(B);
1002 unsigned ASA = getAddressSpaceOperand(A);
1003 unsigned ASB = getAddressSpaceOperand(B);
1005 // Check that the address spaces match and that the pointers are valid.
1006 if (!PtrA || !PtrB || (ASA != ASB))
1009 // Make sure that A and B are different pointers of the same type.
1010 if (PtrA == PtrB || PtrA->getType() != PtrB->getType())
1013 unsigned PtrBitWidth = DL->getPointerSizeInBits(ASA);
1014 Type *Ty = cast<PointerType>(PtrA->getType())->getElementType();
1015 APInt Size(PtrBitWidth, DL->getTypeStoreSize(Ty));
1017 APInt OffsetA(PtrBitWidth, 0), OffsetB(PtrBitWidth, 0);
1018 PtrA = PtrA->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetA);
1019 PtrB = PtrB->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetB);
1021 APInt OffsetDelta = OffsetB - OffsetA;
1023 // Check if they are based on the same pointer. That makes the offsets
1026 return OffsetDelta == Size;
1028 // Compute the necessary base pointer delta to have the necessary final delta
1029 // equal to the size.
1030 APInt BaseDelta = Size - OffsetDelta;
1032 // Otherwise compute the distance with SCEV between the base pointers.
1033 const SCEV *PtrSCEVA = SE->getSCEV(PtrA);
1034 const SCEV *PtrSCEVB = SE->getSCEV(PtrB);
1035 const SCEV *C = SE->getConstant(BaseDelta);
1036 const SCEV *X = SE->getAddExpr(PtrSCEVA, C);
1037 return X == PtrSCEVB;
1040 Value *BoUpSLP::getSinkBarrier(Instruction *Src, Instruction *Dst) {
1041 assert(Src->getParent() == Dst->getParent() && "Not the same BB");
1042 BasicBlock::iterator I = Src, E = Dst;
1043 /// Scan all of the instruction from SRC to DST and check if
1044 /// the source may alias.
1045 for (++I; I != E; ++I) {
1046 // Ignore store instructions that are marked as 'ignore'.
1047 if (MemBarrierIgnoreList.count(I))
1049 if (Src->mayWriteToMemory()) /* Write */ {
1050 if (!I->mayReadOrWriteMemory())
1053 if (!I->mayWriteToMemory())
1056 AliasAnalysis::Location A = getLocation(&*I);
1057 AliasAnalysis::Location B = getLocation(Src);
1059 if (!A.Ptr || !B.Ptr || AA->alias(A, B))
1065 int BoUpSLP::getLastIndex(ArrayRef<Value *> VL) {
1066 BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
1067 assert(BB == getSameBlock(VL) && BlocksNumbers.count(BB) && "Invalid block");
1068 BlockNumbering &BN = BlocksNumbers[BB];
1070 int MaxIdx = BN.getIndex(BB->getFirstNonPHI());
1071 for (unsigned i = 0, e = VL.size(); i < e; ++i)
1072 MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
1076 Instruction *BoUpSLP::getLastInstruction(ArrayRef<Value *> VL) {
1077 BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
1078 assert(BB == getSameBlock(VL) && BlocksNumbers.count(BB) && "Invalid block");
1079 BlockNumbering &BN = BlocksNumbers[BB];
1081 int MaxIdx = BN.getIndex(cast<Instruction>(VL[0]));
1082 for (unsigned i = 1, e = VL.size(); i < e; ++i)
1083 MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
1084 Instruction *I = BN.getInstruction(MaxIdx);
1085 assert(I && "bad location");
1089 void BoUpSLP::setInsertPointAfterBundle(ArrayRef<Value *> VL) {
1090 Instruction *VL0 = cast<Instruction>(VL[0]);
1091 Instruction *LastInst = getLastInstruction(VL);
1092 BasicBlock::iterator NextInst = LastInst;
1094 Builder.SetInsertPoint(VL0->getParent(), NextInst);
1095 Builder.SetCurrentDebugLocation(VL0->getDebugLoc());
1098 Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
1099 Value *Vec = UndefValue::get(Ty);
1100 // Generate the 'InsertElement' instruction.
1101 for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
1102 Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
1103 if (Instruction *Insrt = dyn_cast<Instruction>(Vec)) {
1104 GatherSeq.insert(Insrt);
1106 // Add to our 'need-to-extract' list.
1107 if (ScalarToTreeEntry.count(VL[i])) {
1108 int Idx = ScalarToTreeEntry[VL[i]];
1109 TreeEntry *E = &VectorizableTree[Idx];
1110 // Find which lane we need to extract.
1112 for (unsigned Lane = 0, LE = VL.size(); Lane != LE; ++Lane) {
1113 // Is this the lane of the scalar that we are looking for ?
1114 if (E->Scalars[Lane] == VL[i]) {
1119 assert(FoundLane >= 0 && "Could not find the correct lane");
1120 ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
1128 Value *BoUpSLP::alreadyVectorized(ArrayRef<Value *> VL) const {
1129 SmallDenseMap<Value*, int>::const_iterator Entry
1130 = ScalarToTreeEntry.find(VL[0]);
1131 if (Entry != ScalarToTreeEntry.end()) {
1132 int Idx = Entry->second;
1133 const TreeEntry *En = &VectorizableTree[Idx];
1134 if (En->isSame(VL) && En->VectorizedValue)
1135 return En->VectorizedValue;
1140 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
1141 if (ScalarToTreeEntry.count(VL[0])) {
1142 int Idx = ScalarToTreeEntry[VL[0]];
1143 TreeEntry *E = &VectorizableTree[Idx];
1145 return vectorizeTree(E);
1148 Type *ScalarTy = VL[0]->getType();
1149 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1150 ScalarTy = SI->getValueOperand()->getType();
1151 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1153 return Gather(VL, VecTy);
1156 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
1157 IRBuilder<>::InsertPointGuard Guard(Builder);
1159 if (E->VectorizedValue) {
1160 DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
1161 return E->VectorizedValue;
1164 Instruction *VL0 = cast<Instruction>(E->Scalars[0]);
1165 Type *ScalarTy = VL0->getType();
1166 if (StoreInst *SI = dyn_cast<StoreInst>(VL0))
1167 ScalarTy = SI->getValueOperand()->getType();
1168 VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size());
1170 if (E->NeedToGather) {
1171 setInsertPointAfterBundle(E->Scalars);
1172 return Gather(E->Scalars, VecTy);
1175 unsigned Opcode = VL0->getOpcode();
1176 assert(Opcode == getSameOpcode(E->Scalars) && "Invalid opcode");
1179 case Instruction::PHI: {
1180 PHINode *PH = dyn_cast<PHINode>(VL0);
1181 Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
1182 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1183 PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
1184 E->VectorizedValue = NewPhi;
1186 // PHINodes may have multiple entries from the same block. We want to
1187 // visit every block once.
1188 SmallSet<BasicBlock*, 4> VisitedBBs;
1190 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1192 BasicBlock *IBB = PH->getIncomingBlock(i);
1194 if (!VisitedBBs.insert(IBB)) {
1195 NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
1199 // Prepare the operand vector.
1200 for (unsigned j = 0; j < E->Scalars.size(); ++j)
1201 Operands.push_back(cast<PHINode>(E->Scalars[j])->
1202 getIncomingValueForBlock(IBB));
1204 Builder.SetInsertPoint(IBB->getTerminator());
1205 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1206 Value *Vec = vectorizeTree(Operands);
1207 NewPhi->addIncoming(Vec, IBB);
1210 assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
1211 "Invalid number of incoming values");
1215 case Instruction::ExtractElement: {
1216 if (CanReuseExtract(E->Scalars)) {
1217 Value *V = VL0->getOperand(0);
1218 E->VectorizedValue = V;
1221 return Gather(E->Scalars, VecTy);
1223 case Instruction::ZExt:
1224 case Instruction::SExt:
1225 case Instruction::FPToUI:
1226 case Instruction::FPToSI:
1227 case Instruction::FPExt:
1228 case Instruction::PtrToInt:
1229 case Instruction::IntToPtr:
1230 case Instruction::SIToFP:
1231 case Instruction::UIToFP:
1232 case Instruction::Trunc:
1233 case Instruction::FPTrunc:
1234 case Instruction::BitCast: {
1236 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1237 INVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1239 setInsertPointAfterBundle(E->Scalars);
1241 Value *InVec = vectorizeTree(INVL);
1243 if (Value *V = alreadyVectorized(E->Scalars))
1246 CastInst *CI = dyn_cast<CastInst>(VL0);
1247 Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
1248 E->VectorizedValue = V;
1251 case Instruction::FCmp:
1252 case Instruction::ICmp: {
1253 ValueList LHSV, RHSV;
1254 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1255 LHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1256 RHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1259 setInsertPointAfterBundle(E->Scalars);
1261 Value *L = vectorizeTree(LHSV);
1262 Value *R = vectorizeTree(RHSV);
1264 if (Value *V = alreadyVectorized(E->Scalars))
1267 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
1269 if (Opcode == Instruction::FCmp)
1270 V = Builder.CreateFCmp(P0, L, R);
1272 V = Builder.CreateICmp(P0, L, R);
1274 E->VectorizedValue = V;
1277 case Instruction::Select: {
1278 ValueList TrueVec, FalseVec, CondVec;
1279 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1280 CondVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1281 TrueVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1282 FalseVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(2));
1285 setInsertPointAfterBundle(E->Scalars);
1287 Value *Cond = vectorizeTree(CondVec);
1288 Value *True = vectorizeTree(TrueVec);
1289 Value *False = vectorizeTree(FalseVec);
1291 if (Value *V = alreadyVectorized(E->Scalars))
1294 Value *V = Builder.CreateSelect(Cond, True, False);
1295 E->VectorizedValue = V;
1298 case Instruction::Add:
1299 case Instruction::FAdd:
1300 case Instruction::Sub:
1301 case Instruction::FSub:
1302 case Instruction::Mul:
1303 case Instruction::FMul:
1304 case Instruction::UDiv:
1305 case Instruction::SDiv:
1306 case Instruction::FDiv:
1307 case Instruction::URem:
1308 case Instruction::SRem:
1309 case Instruction::FRem:
1310 case Instruction::Shl:
1311 case Instruction::LShr:
1312 case Instruction::AShr:
1313 case Instruction::And:
1314 case Instruction::Or:
1315 case Instruction::Xor: {
1316 ValueList LHSVL, RHSVL;
1317 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1318 LHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1319 RHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1322 setInsertPointAfterBundle(E->Scalars);
1324 Value *LHS = vectorizeTree(LHSVL);
1325 Value *RHS = vectorizeTree(RHSVL);
1327 if (LHS == RHS && isa<Instruction>(LHS)) {
1328 assert((VL0->getOperand(0) == VL0->getOperand(1)) && "Invalid order");
1331 if (Value *V = alreadyVectorized(E->Scalars))
1334 BinaryOperator *BinOp = cast<BinaryOperator>(VL0);
1335 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), LHS, RHS);
1336 E->VectorizedValue = V;
1339 case Instruction::Load: {
1340 // Loads are inserted at the head of the tree because we don't want to
1341 // sink them all the way down past store instructions.
1342 setInsertPointAfterBundle(E->Scalars);
1344 LoadInst *LI = cast<LoadInst>(VL0);
1345 unsigned AS = LI->getPointerAddressSpace();
1347 Value *VecPtr = Builder.CreateBitCast(LI->getPointerOperand(),
1348 VecTy->getPointerTo(AS));
1349 unsigned Alignment = LI->getAlignment();
1350 LI = Builder.CreateLoad(VecPtr);
1351 LI->setAlignment(Alignment);
1352 E->VectorizedValue = LI;
1355 case Instruction::Store: {
1356 StoreInst *SI = cast<StoreInst>(VL0);
1357 unsigned Alignment = SI->getAlignment();
1358 unsigned AS = SI->getPointerAddressSpace();
1361 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1362 ValueOp.push_back(cast<StoreInst>(E->Scalars[i])->getValueOperand());
1364 setInsertPointAfterBundle(E->Scalars);
1366 Value *VecValue = vectorizeTree(ValueOp);
1367 Value *VecPtr = Builder.CreateBitCast(SI->getPointerOperand(),
1368 VecTy->getPointerTo(AS));
1369 StoreInst *S = Builder.CreateStore(VecValue, VecPtr);
1370 S->setAlignment(Alignment);
1371 E->VectorizedValue = S;
1375 llvm_unreachable("unknown inst");
1380 Value *BoUpSLP::vectorizeTree() {
1381 Builder.SetInsertPoint(F->getEntryBlock().begin());
1382 vectorizeTree(&VectorizableTree[0]);
1384 DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() << " values .\n");
1386 // Extract all of the elements with the external uses.
1387 for (UserList::iterator it = ExternalUses.begin(), e = ExternalUses.end();
1389 Value *Scalar = it->Scalar;
1390 llvm::User *User = it->User;
1392 // Skip users that we already RAUW. This happens when one instruction
1393 // has multiple uses of the same value.
1394 if (std::find(Scalar->use_begin(), Scalar->use_end(), User) ==
1397 assert(ScalarToTreeEntry.count(Scalar) && "Invalid scalar");
1399 int Idx = ScalarToTreeEntry[Scalar];
1400 TreeEntry *E = &VectorizableTree[Idx];
1401 assert(!E->NeedToGather && "Extracting from a gather list");
1403 Value *Vec = E->VectorizedValue;
1404 assert(Vec && "Can't find vectorizable value");
1406 Value *Lane = Builder.getInt32(it->Lane);
1407 // Generate extracts for out-of-tree users.
1408 // Find the insertion point for the extractelement lane.
1409 if (PHINode *PN = dyn_cast<PHINode>(Vec)) {
1410 Builder.SetInsertPoint(PN->getParent()->getFirstInsertionPt());
1411 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1412 User->replaceUsesOfWith(Scalar, Ex);
1413 } else if (isa<Instruction>(Vec)){
1414 if (PHINode *PH = dyn_cast<PHINode>(User)) {
1415 for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
1416 if (PH->getIncomingValue(i) == Scalar) {
1417 Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
1418 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1419 PH->setOperand(i, Ex);
1423 Builder.SetInsertPoint(cast<Instruction>(User));
1424 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1425 User->replaceUsesOfWith(Scalar, Ex);
1428 Builder.SetInsertPoint(F->getEntryBlock().begin());
1429 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1430 User->replaceUsesOfWith(Scalar, Ex);
1433 DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
1436 // For each vectorized value:
1437 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
1438 TreeEntry *Entry = &VectorizableTree[EIdx];
1441 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
1442 Value *Scalar = Entry->Scalars[Lane];
1444 // No need to handle users of gathered values.
1445 if (Entry->NeedToGather)
1448 assert(Entry->VectorizedValue && "Can't find vectorizable value");
1450 Type *Ty = Scalar->getType();
1451 if (!Ty->isVoidTy()) {
1452 for (Value::use_iterator User = Scalar->use_begin(),
1453 UE = Scalar->use_end(); User != UE; ++User) {
1454 DEBUG(dbgs() << "SLP: \tvalidating user:" << **User << ".\n");
1455 assert(!MustGather.count(*User) &&
1456 "Replacing gathered value with undef");
1458 assert((ScalarToTreeEntry.count(*User) ||
1459 // It is legal to replace the reduction users by undef.
1460 (RdxOps && RdxOps->count(*User))) &&
1461 "Replacing out-of-tree value with undef");
1463 Value *Undef = UndefValue::get(Ty);
1464 Scalar->replaceAllUsesWith(Undef);
1466 DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
1467 cast<Instruction>(Scalar)->eraseFromParent();
1471 for (Function::iterator it = F->begin(), e = F->end(); it != e; ++it) {
1472 BlocksNumbers[it].forget();
1474 Builder.ClearInsertionPoint();
1476 return VectorizableTree[0].VectorizedValue;
1479 void BoUpSLP::optimizeGatherSequence() {
1480 DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
1481 << " gather sequences instructions.\n");
1482 // LICM InsertElementInst sequences.
1483 for (SetVector<Instruction *>::iterator it = GatherSeq.begin(),
1484 e = GatherSeq.end(); it != e; ++it) {
1485 InsertElementInst *Insert = dyn_cast<InsertElementInst>(*it);
1490 // Check if this block is inside a loop.
1491 Loop *L = LI->getLoopFor(Insert->getParent());
1495 // Check if it has a preheader.
1496 BasicBlock *PreHeader = L->getLoopPreheader();
1500 // If the vector or the element that we insert into it are
1501 // instructions that are defined in this basic block then we can't
1502 // hoist this instruction.
1503 Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
1504 Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
1505 if (CurrVec && L->contains(CurrVec))
1507 if (NewElem && L->contains(NewElem))
1510 // We can hoist this instruction. Move it to the pre-header.
1511 Insert->moveBefore(PreHeader->getTerminator());
1514 // Perform O(N^2) search over the gather sequences and merge identical
1515 // instructions. TODO: We can further optimize this scan if we split the
1516 // instructions into different buckets based on the insert lane.
1517 SmallPtrSet<Instruction*, 16> Visited;
1518 SmallVector<Instruction*, 16> ToRemove;
1519 ReversePostOrderTraversal<Function*> RPOT(F);
1520 for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
1521 E = RPOT.end(); I != E; ++I) {
1522 BasicBlock *BB = *I;
1523 // For all instructions in the function:
1524 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1525 Instruction *In = it;
1526 if ((!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In)) ||
1527 !GatherSeq.count(In))
1530 // Check if we can replace this instruction with any of the
1531 // visited instructions.
1532 for (SmallPtrSet<Instruction*, 16>::iterator v = Visited.begin(),
1533 ve = Visited.end(); v != ve; ++v) {
1534 if (In->isIdenticalTo(*v) &&
1535 DT->dominates((*v)->getParent(), In->getParent())) {
1536 In->replaceAllUsesWith(*v);
1537 ToRemove.push_back(In);
1547 // Erase all of the instructions that we RAUWed.
1548 for (SmallVectorImpl<Instruction *>::iterator v = ToRemove.begin(),
1549 ve = ToRemove.end(); v != ve; ++v) {
1550 assert((*v)->getNumUses() == 0 && "Can't remove instructions with uses");
1551 (*v)->eraseFromParent();
1555 /// The SLPVectorizer Pass.
1556 struct SLPVectorizer : public FunctionPass {
1557 typedef SmallVector<StoreInst *, 8> StoreList;
1558 typedef MapVector<Value *, StoreList> StoreListMap;
1560 /// Pass identification, replacement for typeid
1563 explicit SLPVectorizer() : FunctionPass(ID) {
1564 initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
1567 ScalarEvolution *SE;
1569 TargetTransformInfo *TTI;
1574 virtual bool runOnFunction(Function &F) {
1575 SE = &getAnalysis<ScalarEvolution>();
1576 DL = getAnalysisIfAvailable<DataLayout>();
1577 TTI = &getAnalysis<TargetTransformInfo>();
1578 AA = &getAnalysis<AliasAnalysis>();
1579 LI = &getAnalysis<LoopInfo>();
1580 DT = &getAnalysis<DominatorTree>();
1583 bool Changed = false;
1585 // If the target claims to have no vector registers don't attempt
1587 if (!TTI->getNumberOfRegisters(true))
1590 // Must have DataLayout. We can't require it because some tests run w/o
1595 // Don't vectorize when the attribute NoImplicitFloat is used.
1596 if (F.hasFnAttribute(Attribute::NoImplicitFloat))
1599 DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
1601 // Use the bollom up slp vectorizer to construct chains that start with
1602 // he store instructions.
1603 BoUpSLP R(&F, SE, DL, TTI, AA, LI, DT);
1605 // Scan the blocks in the function in post order.
1606 for (po_iterator<BasicBlock*> it = po_begin(&F.getEntryBlock()),
1607 e = po_end(&F.getEntryBlock()); it != e; ++it) {
1608 BasicBlock *BB = *it;
1610 // Vectorize trees that end at stores.
1611 if (unsigned count = collectStores(BB, R)) {
1613 DEBUG(dbgs() << "SLP: Found " << count << " stores to vectorize.\n");
1614 Changed |= vectorizeStoreChains(R);
1617 // Vectorize trees that end at reductions.
1618 Changed |= vectorizeChainsInBlock(BB, R);
1622 R.optimizeGatherSequence();
1623 DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
1624 DEBUG(verifyFunction(F));
1629 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1630 FunctionPass::getAnalysisUsage(AU);
1631 AU.addRequired<ScalarEvolution>();
1632 AU.addRequired<AliasAnalysis>();
1633 AU.addRequired<TargetTransformInfo>();
1634 AU.addRequired<LoopInfo>();
1635 AU.addRequired<DominatorTree>();
1636 AU.addPreserved<LoopInfo>();
1637 AU.addPreserved<DominatorTree>();
1638 AU.setPreservesCFG();
1643 /// \brief Collect memory references and sort them according to their base
1644 /// object. We sort the stores to their base objects to reduce the cost of the
1645 /// quadratic search on the stores. TODO: We can further reduce this cost
1646 /// if we flush the chain creation every time we run into a memory barrier.
1647 unsigned collectStores(BasicBlock *BB, BoUpSLP &R);
1649 /// \brief Try to vectorize a chain that starts at two arithmetic instrs.
1650 bool tryToVectorizePair(Value *A, Value *B, BoUpSLP &R);
1652 /// \brief Try to vectorize a list of operands.
1653 /// \returns true if a value was vectorized.
1654 bool tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R);
1656 /// \brief Try to vectorize a chain that may start at the operands of \V;
1657 bool tryToVectorize(BinaryOperator *V, BoUpSLP &R);
1659 /// \brief Vectorize the stores that were collected in StoreRefs.
1660 bool vectorizeStoreChains(BoUpSLP &R);
1662 /// \brief Scan the basic block and look for patterns that are likely to start
1663 /// a vectorization chain.
1664 bool vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R);
1666 bool vectorizeStoreChain(ArrayRef<Value *> Chain, int CostThreshold,
1669 bool vectorizeStores(ArrayRef<StoreInst *> Stores, int costThreshold,
1672 StoreListMap StoreRefs;
1675 bool SLPVectorizer::vectorizeStoreChain(ArrayRef<Value *> Chain,
1676 int CostThreshold, BoUpSLP &R) {
1677 unsigned ChainLen = Chain.size();
1678 DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
1680 Type *StoreTy = cast<StoreInst>(Chain[0])->getValueOperand()->getType();
1681 unsigned Sz = DL->getTypeSizeInBits(StoreTy);
1682 unsigned VF = MinVecRegSize / Sz;
1684 if (!isPowerOf2_32(Sz) || VF < 2)
1687 bool Changed = false;
1688 // Look for profitable vectorizable trees at all offsets, starting at zero.
1689 for (unsigned i = 0, e = ChainLen; i < e; ++i) {
1692 DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
1694 ArrayRef<Value *> Operands = Chain.slice(i, VF);
1696 R.buildTree(Operands);
1698 int Cost = R.getTreeCost();
1700 DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
1701 if (Cost < CostThreshold) {
1702 DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
1705 // Move to the next bundle.
1714 bool SLPVectorizer::vectorizeStores(ArrayRef<StoreInst *> Stores,
1715 int costThreshold, BoUpSLP &R) {
1716 SetVector<Value *> Heads, Tails;
1717 SmallDenseMap<Value *, Value *> ConsecutiveChain;
1719 // We may run into multiple chains that merge into a single chain. We mark the
1720 // stores that we vectorized so that we don't visit the same store twice.
1721 BoUpSLP::ValueSet VectorizedStores;
1722 bool Changed = false;
1724 // Do a quadratic search on all of the given stores and find
1725 // all of the pairs of stores that follow each other.
1726 for (unsigned i = 0, e = Stores.size(); i < e; ++i) {
1727 for (unsigned j = 0; j < e; ++j) {
1731 if (R.isConsecutiveAccess(Stores[i], Stores[j])) {
1732 Tails.insert(Stores[j]);
1733 Heads.insert(Stores[i]);
1734 ConsecutiveChain[Stores[i]] = Stores[j];
1739 // For stores that start but don't end a link in the chain:
1740 for (SetVector<Value *>::iterator it = Heads.begin(), e = Heads.end();
1742 if (Tails.count(*it))
1745 // We found a store instr that starts a chain. Now follow the chain and try
1747 BoUpSLP::ValueList Operands;
1749 // Collect the chain into a list.
1750 while (Tails.count(I) || Heads.count(I)) {
1751 if (VectorizedStores.count(I))
1753 Operands.push_back(I);
1754 // Move to the next value in the chain.
1755 I = ConsecutiveChain[I];
1758 bool Vectorized = vectorizeStoreChain(Operands, costThreshold, R);
1760 // Mark the vectorized stores so that we don't vectorize them again.
1762 VectorizedStores.insert(Operands.begin(), Operands.end());
1763 Changed |= Vectorized;
1770 unsigned SLPVectorizer::collectStores(BasicBlock *BB, BoUpSLP &R) {
1773 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1774 StoreInst *SI = dyn_cast<StoreInst>(it);
1778 // Check that the pointer points to scalars.
1779 Type *Ty = SI->getValueOperand()->getType();
1780 if (Ty->isAggregateType() || Ty->isVectorTy())
1783 // Find the base pointer.
1784 Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), DL);
1786 // Save the store locations.
1787 StoreRefs[Ptr].push_back(SI);
1793 bool SLPVectorizer::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
1796 Value *VL[] = { A, B };
1797 return tryToVectorizeList(VL, R);
1800 bool SLPVectorizer::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R) {
1804 DEBUG(dbgs() << "SLP: Vectorizing a list of length = " << VL.size() << ".\n");
1806 // Check that all of the parts are scalar instructions of the same type.
1807 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
1811 unsigned Opcode0 = I0->getOpcode();
1813 Type *Ty0 = I0->getType();
1814 unsigned Sz = DL->getTypeSizeInBits(Ty0);
1815 unsigned VF = MinVecRegSize / Sz;
1817 for (int i = 0, e = VL.size(); i < e; ++i) {
1818 Type *Ty = VL[i]->getType();
1819 if (Ty->isAggregateType() || Ty->isVectorTy())
1821 Instruction *Inst = dyn_cast<Instruction>(VL[i]);
1822 if (!Inst || Inst->getOpcode() != Opcode0)
1826 bool Changed = false;
1828 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
1829 unsigned OpsWidth = 0;
1836 if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
1839 DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations " << "\n");
1840 ArrayRef<Value *> Ops = VL.slice(i, OpsWidth);
1843 int Cost = R.getTreeCost();
1845 if (Cost < -SLPCostThreshold) {
1846 DEBUG(dbgs() << "SLP: Vectorizing pair at cost:" << Cost << ".\n");
1849 // Move to the next bundle.
1858 bool SLPVectorizer::tryToVectorize(BinaryOperator *V, BoUpSLP &R) {
1862 // Try to vectorize V.
1863 if (tryToVectorizePair(V->getOperand(0), V->getOperand(1), R))
1866 BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0));
1867 BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1));
1869 if (B && B->hasOneUse()) {
1870 BinaryOperator *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
1871 BinaryOperator *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
1872 if (tryToVectorizePair(A, B0, R)) {
1876 if (tryToVectorizePair(A, B1, R)) {
1883 if (A && A->hasOneUse()) {
1884 BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
1885 BinaryOperator *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
1886 if (tryToVectorizePair(A0, B, R)) {
1890 if (tryToVectorizePair(A1, B, R)) {
1898 /// \brief Generate a shuffle mask to be used in a reduction tree.
1900 /// \param VecLen The length of the vector to be reduced.
1901 /// \param NumEltsToRdx The number of elements that should be reduced in the
1903 /// \param IsPairwise Whether the reduction is a pairwise or splitting
1904 /// reduction. A pairwise reduction will generate a mask of
1905 /// <0,2,...> or <1,3,..> while a splitting reduction will generate
1906 /// <2,3, undef,undef> for a vector of 4 and NumElts = 2.
1907 /// \param IsLeft True will generate a mask of even elements, odd otherwise.
1908 static Value *createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx,
1909 bool IsPairwise, bool IsLeft,
1910 IRBuilder<> &Builder) {
1911 assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask");
1913 SmallVector<Constant *, 32> ShuffleMask(
1914 VecLen, UndefValue::get(Builder.getInt32Ty()));
1917 // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
1918 for (unsigned i = 0; i != NumEltsToRdx; ++i)
1919 ShuffleMask[i] = Builder.getInt32(2 * i + !IsLeft);
1921 // Move the upper half of the vector to the lower half.
1922 for (unsigned i = 0; i != NumEltsToRdx; ++i)
1923 ShuffleMask[i] = Builder.getInt32(NumEltsToRdx + i);
1925 return ConstantVector::get(ShuffleMask);
1929 /// Model horizontal reductions.
1931 /// A horizontal reduction is a tree of reduction operations (currently add and
1932 /// fadd) that has operations that can be put into a vector as its leaf.
1933 /// For example, this tree:
1940 /// This tree has "mul" as its reduced values and "+" as its reduction
1941 /// operations. A reduction might be feeding into a store or a binary operation
1956 class HorizontalReduction {
1957 SmallPtrSet<Value *, 16> ReductionOps;
1958 SmallVector<Value *, 32> ReducedVals;
1960 BinaryOperator *ReductionRoot;
1961 PHINode *ReductionPHI;
1963 /// The opcode of the reduction.
1964 unsigned ReductionOpcode;
1965 /// The opcode of the values we perform a reduction on.
1966 unsigned ReducedValueOpcode;
1967 /// The width of one full horizontal reduction operation.
1968 unsigned ReduxWidth;
1969 /// Should we model this reduction as a pairwise reduction tree or a tree that
1970 /// splits the vector in halves and adds those halves.
1971 bool IsPairwiseReduction;
1974 HorizontalReduction()
1975 : ReductionRoot(0), ReductionPHI(0), ReductionOpcode(0),
1976 ReducedValueOpcode(0), ReduxWidth(0), IsPairwiseReduction(false) {}
1978 /// \brief Try to find a reduction tree.
1979 bool matchAssociativeReduction(PHINode *Phi, BinaryOperator *B,
1982 std::find(Phi->op_begin(), Phi->op_end(), B) != Phi->op_end()) &&
1983 "Thi phi needs to use the binary operator");
1985 // We could have a initial reductions that is not an add.
1986 // r *= v1 + v2 + v3 + v4
1987 // In such a case start looking for a tree rooted in the first '+'.
1989 if (B->getOperand(0) == Phi) {
1991 B = dyn_cast<BinaryOperator>(B->getOperand(1));
1992 } else if (B->getOperand(1) == Phi) {
1994 B = dyn_cast<BinaryOperator>(B->getOperand(0));
2001 Type *Ty = B->getType();
2002 if (Ty->isVectorTy())
2005 ReductionOpcode = B->getOpcode();
2006 ReducedValueOpcode = 0;
2007 ReduxWidth = MinVecRegSize / DL->getTypeSizeInBits(Ty);
2014 // We currently only support adds.
2015 if (ReductionOpcode != Instruction::Add &&
2016 ReductionOpcode != Instruction::FAdd)
2019 // Post order traverse the reduction tree starting at B. We only handle true
2020 // trees containing only binary operators.
2021 SmallVector<std::pair<BinaryOperator *, unsigned>, 32> Stack;
2022 Stack.push_back(std::make_pair(B, 0));
2023 while (!Stack.empty()) {
2024 BinaryOperator *TreeN = Stack.back().first;
2025 unsigned EdgeToVist = Stack.back().second++;
2026 bool IsReducedValue = TreeN->getOpcode() != ReductionOpcode;
2028 // Only handle trees in the current basic block.
2029 if (TreeN->getParent() != B->getParent())
2032 // Each tree node needs to have one user except for the ultimate
2034 if (!TreeN->hasOneUse() && TreeN != B)
2038 if (EdgeToVist == 2 || IsReducedValue) {
2039 if (IsReducedValue) {
2040 // Make sure that the opcodes of the operations that we are going to
2042 if (!ReducedValueOpcode)
2043 ReducedValueOpcode = TreeN->getOpcode();
2044 else if (ReducedValueOpcode != TreeN->getOpcode())
2046 ReducedVals.push_back(TreeN);
2048 // We need to be able to reassociate the adds.
2049 if (!TreeN->isAssociative())
2051 ReductionOps.insert(TreeN);
2058 // Visit left or right.
2059 Value *NextV = TreeN->getOperand(EdgeToVist);
2060 BinaryOperator *Next = dyn_cast<BinaryOperator>(NextV);
2062 Stack.push_back(std::make_pair(Next, 0));
2063 else if (NextV != Phi)
2069 /// \brief Attempt to vectorize the tree found by
2070 /// matchAssociativeReduction.
2071 bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
2072 if (ReducedVals.empty())
2075 unsigned NumReducedVals = ReducedVals.size();
2076 if (NumReducedVals < ReduxWidth)
2079 Value *VectorizedTree = 0;
2080 IRBuilder<> Builder(ReductionRoot);
2081 FastMathFlags Unsafe;
2082 Unsafe.setUnsafeAlgebra();
2083 Builder.SetFastMathFlags(Unsafe);
2086 for (; i < NumReducedVals - ReduxWidth + 1; i += ReduxWidth) {
2087 ArrayRef<Value *> ValsToReduce(&ReducedVals[i], ReduxWidth);
2088 V.buildTree(ValsToReduce, &ReductionOps);
2091 int Cost = V.getTreeCost() + getReductionCost(TTI, ReducedVals[i]);
2092 if (Cost >= -SLPCostThreshold)
2095 DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" << Cost
2098 // Vectorize a tree.
2099 DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
2100 Value *VectorizedRoot = V.vectorizeTree();
2102 // Emit a reduction.
2103 Value *ReducedSubTree = emitReduction(VectorizedRoot, Builder);
2104 if (VectorizedTree) {
2105 Builder.SetCurrentDebugLocation(Loc);
2106 VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
2107 ReducedSubTree, "bin.rdx");
2109 VectorizedTree = ReducedSubTree;
2112 if (VectorizedTree) {
2113 // Finish the reduction.
2114 for (; i < NumReducedVals; ++i) {
2115 Builder.SetCurrentDebugLocation(
2116 cast<Instruction>(ReducedVals[i])->getDebugLoc());
2117 VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
2122 assert(ReductionRoot != NULL && "Need a reduction operation");
2123 ReductionRoot->setOperand(0, VectorizedTree);
2124 ReductionRoot->setOperand(1, ReductionPHI);
2126 ReductionRoot->replaceAllUsesWith(VectorizedTree);
2128 return VectorizedTree != 0;
2133 /// \brief Calcuate the cost of a reduction.
2134 int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal) {
2135 Type *ScalarTy = FirstReducedVal->getType();
2136 Type *VecTy = VectorType::get(ScalarTy, ReduxWidth);
2138 int PairwiseRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, true);
2139 int SplittingRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, false);
2141 IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
2142 int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
2144 int ScalarReduxCost =
2145 ReduxWidth * TTI->getArithmeticInstrCost(ReductionOpcode, VecTy);
2147 DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost
2148 << " for reduction that starts with " << *FirstReducedVal
2150 << (IsPairwiseReduction ? "pairwise" : "splitting")
2151 << " reduction)\n");
2153 return VecReduxCost - ScalarReduxCost;
2156 static Value *createBinOp(IRBuilder<> &Builder, unsigned Opcode, Value *L,
2157 Value *R, const Twine &Name = "") {
2158 if (Opcode == Instruction::FAdd)
2159 return Builder.CreateFAdd(L, R, Name);
2160 return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, L, R, Name);
2163 /// \brief Emit a horizontal reduction of the vectorized value.
2164 Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder) {
2165 assert(VectorizedValue && "Need to have a vectorized tree node");
2166 Instruction *ValToReduce = dyn_cast<Instruction>(VectorizedValue);
2167 assert(isPowerOf2_32(ReduxWidth) &&
2168 "We only handle power-of-two reductions for now");
2170 Value *TmpVec = ValToReduce;
2171 for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
2172 if (IsPairwiseReduction) {
2174 createRdxShuffleMask(ReduxWidth, i, true, true, Builder);
2176 createRdxShuffleMask(ReduxWidth, i, true, false, Builder);
2178 Value *LeftShuf = Builder.CreateShuffleVector(
2179 TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l");
2180 Value *RightShuf = Builder.CreateShuffleVector(
2181 TmpVec, UndefValue::get(TmpVec->getType()), (RightMask),
2183 TmpVec = createBinOp(Builder, ReductionOpcode, LeftShuf, RightShuf,
2187 createRdxShuffleMask(ReduxWidth, i, false, false, Builder);
2188 Value *Shuf = Builder.CreateShuffleVector(
2189 TmpVec, UndefValue::get(TmpVec->getType()), UpperHalf, "rdx.shuf");
2190 TmpVec = createBinOp(Builder, ReductionOpcode, TmpVec, Shuf, "bin.rdx");
2194 // The result is in the first element of the vector.
2195 return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
2199 /// \brief Recognize construction of vectors like
2200 /// %ra = insertelement <4 x float> undef, float %s0, i32 0
2201 /// %rb = insertelement <4 x float> %ra, float %s1, i32 1
2202 /// %rc = insertelement <4 x float> %rb, float %s2, i32 2
2203 /// %rd = insertelement <4 x float> %rc, float %s3, i32 3
2205 /// Returns true if it matches
2207 static bool findBuildVector(InsertElementInst *IE,
2208 SmallVectorImpl<Value *> &Ops) {
2209 if (!isa<UndefValue>(IE->getOperand(0)))
2213 Ops.push_back(IE->getOperand(1));
2215 if (IE->use_empty())
2218 InsertElementInst *NextUse = dyn_cast<InsertElementInst>(IE->use_back());
2222 // If this isn't the final use, make sure the next insertelement is the only
2223 // use. It's OK if the final constructed vector is used multiple times
2224 if (!IE->hasOneUse())
2233 bool SLPVectorizer::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
2234 bool Changed = false;
2235 SmallVector<Value *, 4> Incoming;
2236 SmallSet<Instruction *, 16> VisitedInstrs;
2238 // Collect the incoming values from the PHIs.
2239 for (BasicBlock::iterator instr = BB->begin(), ie = BB->end(); instr != ie;
2241 PHINode *P = dyn_cast<PHINode>(instr);
2246 // We may go through BB multiple times so skip the one we have checked.
2247 if (!VisitedInstrs.insert(instr))
2250 // Stop constructing the list when you reach a different type.
2251 if (Incoming.size() && P->getType() != Incoming[0]->getType()) {
2252 if (tryToVectorizeList(Incoming, R)) {
2253 // We would like to start over since some instructions are deleted
2254 // and the iterator may become invalid value.
2256 instr = BB->begin();
2263 Incoming.push_back(P);
2266 if (Incoming.size() > 1)
2267 Changed |= tryToVectorizeList(Incoming, R);
2269 VisitedInstrs.clear();
2271 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) {
2272 // We may go through BB multiple times so skip the one we have checked.
2273 if (!VisitedInstrs.insert(it))
2276 if (isa<DbgInfoIntrinsic>(it))
2279 // Try to vectorize reductions that use PHINodes.
2280 if (PHINode *P = dyn_cast<PHINode>(it)) {
2281 // Check that the PHI is a reduction PHI.
2282 if (P->getNumIncomingValues() != 2)
2285 (P->getIncomingBlock(0) == BB
2286 ? (P->getIncomingValue(0))
2287 : (P->getIncomingBlock(1) == BB ? P->getIncomingValue(1) : 0));
2288 // Check if this is a Binary Operator.
2289 BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx);
2293 // Try to match and vectorize a horizontal reduction.
2294 HorizontalReduction HorRdx;
2295 if (ShouldVectorizeHor &&
2296 HorRdx.matchAssociativeReduction(P, BI, DL) &&
2297 HorRdx.tryToReduce(R, TTI)) {
2304 Value *Inst = BI->getOperand(0);
2306 Inst = BI->getOperand(1);
2308 if (tryToVectorize(dyn_cast<BinaryOperator>(Inst), R)) {
2309 // We would like to start over since some instructions are deleted
2310 // and the iterator may become invalid value.
2320 // Try to vectorize horizontal reductions feeding into a store.
2321 if (ShouldStartVectorizeHorAtStore)
2322 if (StoreInst *SI = dyn_cast<StoreInst>(it))
2323 if (BinaryOperator *BinOp =
2324 dyn_cast<BinaryOperator>(SI->getValueOperand())) {
2325 HorizontalReduction HorRdx;
2326 if (((HorRdx.matchAssociativeReduction(0, BinOp, DL) &&
2327 HorRdx.tryToReduce(R, TTI)) ||
2328 tryToVectorize(BinOp, R))) {
2336 // Try to vectorize trees that start at compare instructions.
2337 if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
2338 if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) {
2340 // We would like to start over since some instructions are deleted
2341 // and the iterator may become invalid value.
2347 for (int i = 0; i < 2; ++i) {
2348 if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i))) {
2349 if (tryToVectorizePair(BI->getOperand(0), BI->getOperand(1), R)) {
2351 // We would like to start over since some instructions are deleted
2352 // and the iterator may become invalid value.
2361 // Try to vectorize trees that start at insertelement instructions.
2362 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(it)) {
2363 SmallVector<Value *, 8> Ops;
2364 if (!findBuildVector(IE, Ops))
2367 if (tryToVectorizeList(Ops, R)) {
2380 bool SLPVectorizer::vectorizeStoreChains(BoUpSLP &R) {
2381 bool Changed = false;
2382 // Attempt to sort and vectorize each of the store-groups.
2383 for (StoreListMap::iterator it = StoreRefs.begin(), e = StoreRefs.end();
2385 if (it->second.size() < 2)
2388 DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
2389 << it->second.size() << ".\n");
2391 // Process the stores in chunks of 16.
2392 for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI+=16) {
2393 unsigned Len = std::min<unsigned>(CE - CI, 16);
2394 ArrayRef<StoreInst *> Chunk(&it->second[CI], Len);
2395 Changed |= vectorizeStores(Chunk, -SLPCostThreshold, R);
2401 } // end anonymous namespace
2403 char SLPVectorizer::ID = 0;
2404 static const char lv_name[] = "SLP Vectorizer";
2405 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
2406 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
2407 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
2408 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
2409 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
2410 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
2413 Pass *createSLPVectorizerPass() { return new SLPVectorizer(); }