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 static bool all_equal(SmallVectorImpl<Value *> &V) {
211 for (int i = 1, e = V.size(); i != e; ++i)
217 static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
218 SmallVectorImpl<Value *> &Left,
219 SmallVectorImpl<Value *> &Right) {
221 SmallVector<Value *, 16> OrigLeft, OrigRight;
223 bool AllSameOpcodeLeft = true;
224 bool AllSameOpcodeRight = true;
225 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
226 Instruction *I = cast<Instruction>(VL[i]);
227 Value *V0 = I->getOperand(0);
228 Value *V1 = I->getOperand(1);
230 OrigLeft.push_back(V0);
231 OrigRight.push_back(V1);
233 Instruction *I0 = dyn_cast<Instruction>(V0);
234 Instruction *I1 = dyn_cast<Instruction>(V1);
236 // Check whether all operands on one side have the same opcode. In this case
237 // we want to preserve the original order and not make things worse by
239 AllSameOpcodeLeft = I0;
240 AllSameOpcodeRight = I1;
242 if (i && AllSameOpcodeLeft) {
243 if(Instruction *P0 = dyn_cast<Instruction>(OrigLeft[i-1])) {
244 if(P0->getOpcode() != I0->getOpcode())
245 AllSameOpcodeLeft = false;
247 AllSameOpcodeLeft = false;
249 if (i && AllSameOpcodeRight) {
250 if(Instruction *P1 = dyn_cast<Instruction>(OrigRight[i-1])) {
251 if(P1->getOpcode() != I1->getOpcode())
252 AllSameOpcodeRight = false;
254 AllSameOpcodeRight = false;
257 // Sort two opcodes. In the code below we try to preserve the ability to use
258 // broadcast of values instead of individual inserts.
265 // If we just sorted according to opcode we would leave the first line in
266 // tact but we would swap vl2 with vr2 because opcode(phi) > opcode(load).
269 // Because vr2 and vr1 are from the same load we loose the opportunity of a
270 // broadcast for the packed right side in the backend: we have [vr1, vl2]
271 // instead of [vr1, vr2=vr1].
273 if(!i && I0->getOpcode() > I1->getOpcode()) {
276 } else if (i && I0->getOpcode() > I1->getOpcode() && Right[i-1] != I1) {
277 // Try not to destroy a broad cast for no apparent benefit.
280 } else if (i && I0->getOpcode() == I1->getOpcode() && Right[i-1] == I0) {
281 // Try preserve broadcasts.
284 } else if (i && I0->getOpcode() == I1->getOpcode() && Left[i-1] == I1) {
285 // Try preserve broadcasts.
294 // One opcode, put the instruction on the right.
304 bool LeftBroadcast = all_equal(Left);
305 bool RightBroadcast = all_equal(Right);
307 // Don't reorder if the operands where good to begin with.
308 if (!(LeftBroadcast || RightBroadcast) &&
309 (AllSameOpcodeRight || AllSameOpcodeLeft)) {
315 /// Bottom Up SLP Vectorizer.
318 typedef SmallVector<Value *, 8> ValueList;
319 typedef SmallVector<Instruction *, 16> InstrList;
320 typedef SmallPtrSet<Value *, 16> ValueSet;
321 typedef SmallVector<StoreInst *, 8> StoreList;
323 BoUpSLP(Function *Func, ScalarEvolution *Se, DataLayout *Dl,
324 TargetTransformInfo *Tti, AliasAnalysis *Aa, LoopInfo *Li,
326 F(Func), SE(Se), DL(Dl), TTI(Tti), AA(Aa), LI(Li), DT(Dt),
327 Builder(Se->getContext()) {
328 // Setup the block numbering utility for all of the blocks in the
330 for (Function::iterator it = F->begin(), e = F->end(); it != e; ++it) {
332 BlocksNumbers[BB] = BlockNumbering(BB);
336 /// \brief Vectorize the tree that starts with the elements in \p VL.
337 /// Returns the vectorized root.
338 Value *vectorizeTree();
340 /// \returns the vectorization cost of the subtree that starts at \p VL.
341 /// A negative number means that this is profitable.
344 /// Construct a vectorizable tree that starts at \p Roots and is possibly
345 /// used by a reduction of \p RdxOps.
346 void buildTree(ArrayRef<Value *> Roots, ValueSet *RdxOps = 0);
348 /// Clear the internal data structures that are created by 'buildTree'.
351 VectorizableTree.clear();
352 ScalarToTreeEntry.clear();
354 ExternalUses.clear();
355 MemBarrierIgnoreList.clear();
358 /// \returns true if the memory operations A and B are consecutive.
359 bool isConsecutiveAccess(Value *A, Value *B);
361 /// \brief Perform LICM and CSE on the newly generated gather sequences.
362 void optimizeGatherSequence();
366 /// \returns the cost of the vectorizable entry.
367 int getEntryCost(TreeEntry *E);
369 /// This is the recursive part of buildTree.
370 void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth);
372 /// Vectorize a single entry in the tree.
373 Value *vectorizeTree(TreeEntry *E);
375 /// Vectorize a single entry in the tree, starting in \p VL.
376 Value *vectorizeTree(ArrayRef<Value *> VL);
378 /// \returns the pointer to the vectorized value if \p VL is already
379 /// vectorized, or NULL. They may happen in cycles.
380 Value *alreadyVectorized(ArrayRef<Value *> VL) const;
382 /// \brief Take the pointer operand from the Load/Store instruction.
383 /// \returns NULL if this is not a valid Load/Store instruction.
384 static Value *getPointerOperand(Value *I);
386 /// \brief Take the address space operand from the Load/Store instruction.
387 /// \returns -1 if this is not a valid Load/Store instruction.
388 static unsigned getAddressSpaceOperand(Value *I);
390 /// \returns the scalarization cost for this type. Scalarization in this
391 /// context means the creation of vectors from a group of scalars.
392 int getGatherCost(Type *Ty);
394 /// \returns the scalarization cost for this list of values. Assuming that
395 /// this subtree gets vectorized, we may need to extract the values from the
396 /// roots. This method calculates the cost of extracting the values.
397 int getGatherCost(ArrayRef<Value *> VL);
399 /// \returns the AA location that is being access by the instruction.
400 AliasAnalysis::Location getLocation(Instruction *I);
402 /// \brief Checks if it is possible to sink an instruction from
403 /// \p Src to \p Dst.
404 /// \returns the pointer to the barrier instruction if we can't sink.
405 Value *getSinkBarrier(Instruction *Src, Instruction *Dst);
407 /// \returns the index of the last instruction in the BB from \p VL.
408 int getLastIndex(ArrayRef<Value *> VL);
410 /// \returns the Instruction in the bundle \p VL.
411 Instruction *getLastInstruction(ArrayRef<Value *> VL);
413 /// \brief Set the Builder insert point to one after the last instruction in
415 void setInsertPointAfterBundle(ArrayRef<Value *> VL);
417 /// \returns a vector from a collection of scalars in \p VL.
418 Value *Gather(ArrayRef<Value *> VL, VectorType *Ty);
420 /// \returns whether the VectorizableTree is fully vectoriable and will
421 /// be beneficial even the tree height is tiny.
422 bool isFullyVectorizableTinyTree();
425 TreeEntry() : Scalars(), VectorizedValue(0), LastScalarIndex(0),
428 /// \returns true if the scalars in VL are equal to this entry.
429 bool isSame(ArrayRef<Value *> VL) const {
430 assert(VL.size() == Scalars.size() && "Invalid size");
431 return std::equal(VL.begin(), VL.end(), Scalars.begin());
434 /// A vector of scalars.
437 /// The Scalars are vectorized into this value. It is initialized to Null.
438 Value *VectorizedValue;
440 /// The index in the basic block of the last scalar.
443 /// Do we need to gather this sequence ?
447 /// Create a new VectorizableTree entry.
448 TreeEntry *newTreeEntry(ArrayRef<Value *> VL, bool Vectorized) {
449 VectorizableTree.push_back(TreeEntry());
450 int idx = VectorizableTree.size() - 1;
451 TreeEntry *Last = &VectorizableTree[idx];
452 Last->Scalars.insert(Last->Scalars.begin(), VL.begin(), VL.end());
453 Last->NeedToGather = !Vectorized;
455 Last->LastScalarIndex = getLastIndex(VL);
456 for (int i = 0, e = VL.size(); i != e; ++i) {
457 assert(!ScalarToTreeEntry.count(VL[i]) && "Scalar already in tree!");
458 ScalarToTreeEntry[VL[i]] = idx;
461 Last->LastScalarIndex = 0;
462 MustGather.insert(VL.begin(), VL.end());
467 /// -- Vectorization State --
468 /// Holds all of the tree entries.
469 std::vector<TreeEntry> VectorizableTree;
471 /// Maps a specific scalar to its tree entry.
472 SmallDenseMap<Value*, int> ScalarToTreeEntry;
474 /// A list of scalars that we found that we need to keep as scalars.
477 /// This POD struct describes one external user in the vectorized tree.
478 struct ExternalUser {
479 ExternalUser (Value *S, llvm::User *U, int L) :
480 Scalar(S), User(U), Lane(L){};
481 // Which scalar in our function.
483 // Which user that uses the scalar.
485 // Which lane does the scalar belong to.
488 typedef SmallVector<ExternalUser, 16> UserList;
490 /// A list of values that need to extracted out of the tree.
491 /// This list holds pairs of (Internal Scalar : External User).
492 UserList ExternalUses;
494 /// A list of instructions to ignore while sinking
495 /// memory instructions. This map must be reset between runs of getCost.
496 ValueSet MemBarrierIgnoreList;
498 /// Holds all of the instructions that we gathered.
499 SetVector<Instruction *> GatherSeq;
501 /// Numbers instructions in different blocks.
502 DenseMap<BasicBlock *, BlockNumbering> BlocksNumbers;
504 /// Reduction operators.
507 // Analysis and block reference.
511 TargetTransformInfo *TTI;
515 /// Instruction builder to construct the vectorized tree.
519 void BoUpSLP::buildTree(ArrayRef<Value *> Roots, ValueSet *Rdx) {
522 if (!getSameType(Roots))
524 buildTree_rec(Roots, 0);
526 // Collect the values that we need to extract from the tree.
527 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
528 TreeEntry *Entry = &VectorizableTree[EIdx];
531 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
532 Value *Scalar = Entry->Scalars[Lane];
534 // No need to handle users of gathered values.
535 if (Entry->NeedToGather)
538 for (Value::use_iterator User = Scalar->use_begin(),
539 UE = Scalar->use_end(); User != UE; ++User) {
540 DEBUG(dbgs() << "SLP: Checking user:" << **User << ".\n");
542 bool Gathered = MustGather.count(*User);
544 // Skip in-tree scalars that become vectors.
545 if (ScalarToTreeEntry.count(*User) && !Gathered) {
546 DEBUG(dbgs() << "SLP: \tInternal user will be removed:" <<
548 int Idx = ScalarToTreeEntry[*User]; (void) Idx;
549 assert(!VectorizableTree[Idx].NeedToGather && "Bad state");
552 Instruction *UserInst = dyn_cast<Instruction>(*User);
556 // Ignore uses that are part of the reduction.
557 if (Rdx && std::find(Rdx->begin(), Rdx->end(), UserInst) != Rdx->end())
560 DEBUG(dbgs() << "SLP: Need to extract:" << **User << " from lane " <<
561 Lane << " from " << *Scalar << ".\n");
562 ExternalUses.push_back(ExternalUser(Scalar, *User, Lane));
569 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth) {
570 bool SameTy = getSameType(VL); (void)SameTy;
571 assert(SameTy && "Invalid types!");
573 if (Depth == RecursionMaxDepth) {
574 DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
575 newTreeEntry(VL, false);
579 // Don't handle vectors.
580 if (VL[0]->getType()->isVectorTy()) {
581 DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
582 newTreeEntry(VL, false);
586 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
587 if (SI->getValueOperand()->getType()->isVectorTy()) {
588 DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
589 newTreeEntry(VL, false);
593 // If all of the operands are identical or constant we have a simple solution.
594 if (allConstant(VL) || isSplat(VL) || !getSameBlock(VL) ||
595 !getSameOpcode(VL)) {
596 DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
597 newTreeEntry(VL, false);
601 // We now know that this is a vector of instructions of the same type from
604 // Check if this is a duplicate of another entry.
605 if (ScalarToTreeEntry.count(VL[0])) {
606 int Idx = ScalarToTreeEntry[VL[0]];
607 TreeEntry *E = &VectorizableTree[Idx];
608 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
609 DEBUG(dbgs() << "SLP: \tChecking bundle: " << *VL[i] << ".\n");
610 if (E->Scalars[i] != VL[i]) {
611 DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
612 newTreeEntry(VL, false);
616 DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *VL[0] << ".\n");
620 // Check that none of the instructions in the bundle are already in the tree.
621 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
622 if (ScalarToTreeEntry.count(VL[i])) {
623 DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
624 ") is already in tree.\n");
625 newTreeEntry(VL, false);
630 // If any of the scalars appears in the table OR it is marked as a value that
631 // needs to stat scalar then we need to gather the scalars.
632 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
633 if (ScalarToTreeEntry.count(VL[i]) || MustGather.count(VL[i])) {
634 DEBUG(dbgs() << "SLP: Gathering due to gathered scalar. \n");
635 newTreeEntry(VL, false);
640 // Check that all of the users of the scalars that we want to vectorize are
642 Instruction *VL0 = cast<Instruction>(VL[0]);
643 int MyLastIndex = getLastIndex(VL);
644 BasicBlock *BB = cast<Instruction>(VL0)->getParent();
646 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
647 Instruction *Scalar = cast<Instruction>(VL[i]);
648 DEBUG(dbgs() << "SLP: Checking users of " << *Scalar << ". \n");
649 for (Value::use_iterator U = Scalar->use_begin(), UE = Scalar->use_end();
651 DEBUG(dbgs() << "SLP: \tUser " << **U << ". \n");
652 Instruction *User = dyn_cast<Instruction>(*U);
654 DEBUG(dbgs() << "SLP: Gathering due unknown user. \n");
655 newTreeEntry(VL, false);
659 // We don't care if the user is in a different basic block.
660 BasicBlock *UserBlock = User->getParent();
661 if (UserBlock != BB) {
662 DEBUG(dbgs() << "SLP: User from a different basic block "
667 // If this is a PHINode within this basic block then we can place the
668 // extract wherever we want.
669 if (isa<PHINode>(*User)) {
670 DEBUG(dbgs() << "SLP: \tWe can schedule PHIs:" << *User << ". \n");
674 // Check if this is a safe in-tree user.
675 if (ScalarToTreeEntry.count(User)) {
676 int Idx = ScalarToTreeEntry[User];
677 int VecLocation = VectorizableTree[Idx].LastScalarIndex;
678 if (VecLocation <= MyLastIndex) {
679 DEBUG(dbgs() << "SLP: Gathering due to unschedulable vector. \n");
680 newTreeEntry(VL, false);
683 DEBUG(dbgs() << "SLP: In-tree user (" << *User << ") at #" <<
684 VecLocation << " vector value (" << *Scalar << ") at #"
685 << MyLastIndex << ".\n");
689 // This user is part of the reduction.
690 if (RdxOps && RdxOps->count(User))
693 // Make sure that we can schedule this unknown user.
694 BlockNumbering &BN = BlocksNumbers[BB];
695 int UserIndex = BN.getIndex(User);
696 if (UserIndex < MyLastIndex) {
698 DEBUG(dbgs() << "SLP: Can't schedule extractelement for "
700 newTreeEntry(VL, false);
706 // Check that every instructions appears once in this bundle.
707 for (unsigned i = 0, e = VL.size(); i < e; ++i)
708 for (unsigned j = i+1; j < e; ++j)
709 if (VL[i] == VL[j]) {
710 DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
711 newTreeEntry(VL, false);
715 // Check that instructions in this bundle don't reference other instructions.
716 // The runtime of this check is O(N * N-1 * uses(N)) and a typical N is 4.
717 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
718 for (Value::use_iterator U = VL[i]->use_begin(), UE = VL[i]->use_end();
720 for (unsigned j = 0; j < e; ++j) {
721 if (i != j && *U == VL[j]) {
722 DEBUG(dbgs() << "SLP: Intra-bundle dependencies!" << **U << ". \n");
723 newTreeEntry(VL, false);
730 DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
732 unsigned Opcode = getSameOpcode(VL);
734 // Check if it is safe to sink the loads or the stores.
735 if (Opcode == Instruction::Load || Opcode == Instruction::Store) {
736 Instruction *Last = getLastInstruction(VL);
738 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
741 Value *Barrier = getSinkBarrier(cast<Instruction>(VL[i]), Last);
743 DEBUG(dbgs() << "SLP: Can't sink " << *VL[i] << "\n down to " << *Last
744 << "\n because of " << *Barrier << ". Gathering.\n");
745 newTreeEntry(VL, false);
752 case Instruction::PHI: {
753 PHINode *PH = dyn_cast<PHINode>(VL0);
755 // Check for terminator values (e.g. invoke).
756 for (unsigned j = 0; j < VL.size(); ++j)
757 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
758 TerminatorInst *Term = dyn_cast<TerminatorInst>(cast<PHINode>(VL[j])->getIncomingValue(i));
760 DEBUG(dbgs() << "SLP: Need to swizzle PHINodes (TerminatorInst use).\n");
761 newTreeEntry(VL, false);
766 newTreeEntry(VL, true);
767 DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
769 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
771 // Prepare the operand vector.
772 for (unsigned j = 0; j < VL.size(); ++j)
773 Operands.push_back(cast<PHINode>(VL[j])->getIncomingValue(i));
775 buildTree_rec(Operands, Depth + 1);
779 case Instruction::ExtractElement: {
780 bool Reuse = CanReuseExtract(VL);
782 DEBUG(dbgs() << "SLP: Reusing extract sequence.\n");
784 newTreeEntry(VL, Reuse);
787 case Instruction::Load: {
788 // Check if the loads are consecutive or of we need to swizzle them.
789 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
790 if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
791 newTreeEntry(VL, false);
792 DEBUG(dbgs() << "SLP: Need to swizzle loads.\n");
796 newTreeEntry(VL, true);
797 DEBUG(dbgs() << "SLP: added a vector of loads.\n");
800 case Instruction::ZExt:
801 case Instruction::SExt:
802 case Instruction::FPToUI:
803 case Instruction::FPToSI:
804 case Instruction::FPExt:
805 case Instruction::PtrToInt:
806 case Instruction::IntToPtr:
807 case Instruction::SIToFP:
808 case Instruction::UIToFP:
809 case Instruction::Trunc:
810 case Instruction::FPTrunc:
811 case Instruction::BitCast: {
812 Type *SrcTy = VL0->getOperand(0)->getType();
813 for (unsigned i = 0; i < VL.size(); ++i) {
814 Type *Ty = cast<Instruction>(VL[i])->getOperand(0)->getType();
815 if (Ty != SrcTy || Ty->isAggregateType() || Ty->isVectorTy()) {
816 newTreeEntry(VL, false);
817 DEBUG(dbgs() << "SLP: Gathering casts with different src types.\n");
821 newTreeEntry(VL, true);
822 DEBUG(dbgs() << "SLP: added a vector of casts.\n");
824 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
826 // Prepare the operand vector.
827 for (unsigned j = 0; j < VL.size(); ++j)
828 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
830 buildTree_rec(Operands, Depth+1);
834 case Instruction::ICmp:
835 case Instruction::FCmp: {
836 // Check that all of the compares have the same predicate.
837 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
838 Type *ComparedTy = cast<Instruction>(VL[0])->getOperand(0)->getType();
839 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
840 CmpInst *Cmp = cast<CmpInst>(VL[i]);
841 if (Cmp->getPredicate() != P0 ||
842 Cmp->getOperand(0)->getType() != ComparedTy) {
843 newTreeEntry(VL, false);
844 DEBUG(dbgs() << "SLP: Gathering cmp with different predicate.\n");
849 newTreeEntry(VL, true);
850 DEBUG(dbgs() << "SLP: added a vector of compares.\n");
852 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
854 // Prepare the operand vector.
855 for (unsigned j = 0; j < VL.size(); ++j)
856 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
858 buildTree_rec(Operands, Depth+1);
862 case Instruction::Select:
863 case Instruction::Add:
864 case Instruction::FAdd:
865 case Instruction::Sub:
866 case Instruction::FSub:
867 case Instruction::Mul:
868 case Instruction::FMul:
869 case Instruction::UDiv:
870 case Instruction::SDiv:
871 case Instruction::FDiv:
872 case Instruction::URem:
873 case Instruction::SRem:
874 case Instruction::FRem:
875 case Instruction::Shl:
876 case Instruction::LShr:
877 case Instruction::AShr:
878 case Instruction::And:
879 case Instruction::Or:
880 case Instruction::Xor: {
881 newTreeEntry(VL, true);
882 DEBUG(dbgs() << "SLP: added a vector of bin op.\n");
884 // Sort operands of the instructions so that each side is more likely to
885 // have the same opcode.
886 if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
887 ValueList Left, Right;
888 reorderInputsAccordingToOpcode(VL, Left, Right);
889 buildTree_rec(Left, Depth + 1);
890 buildTree_rec(Right, Depth + 1);
894 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
896 // Prepare the operand vector.
897 for (unsigned j = 0; j < VL.size(); ++j)
898 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
900 buildTree_rec(Operands, Depth+1);
904 case Instruction::Store: {
905 // Check if the stores are consecutive or of we need to swizzle them.
906 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
907 if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
908 newTreeEntry(VL, false);
909 DEBUG(dbgs() << "SLP: Non consecutive store.\n");
913 newTreeEntry(VL, true);
914 DEBUG(dbgs() << "SLP: added a vector of stores.\n");
917 for (unsigned j = 0; j < VL.size(); ++j)
918 Operands.push_back(cast<Instruction>(VL[j])->getOperand(0));
920 // We can ignore these values because we are sinking them down.
921 MemBarrierIgnoreList.insert(VL.begin(), VL.end());
922 buildTree_rec(Operands, Depth + 1);
926 newTreeEntry(VL, false);
927 DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
932 int BoUpSLP::getEntryCost(TreeEntry *E) {
933 ArrayRef<Value*> VL = E->Scalars;
935 Type *ScalarTy = VL[0]->getType();
936 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
937 ScalarTy = SI->getValueOperand()->getType();
938 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
940 if (E->NeedToGather) {
944 return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
946 return getGatherCost(E->Scalars);
949 assert(getSameOpcode(VL) && getSameType(VL) && getSameBlock(VL) &&
951 Instruction *VL0 = cast<Instruction>(VL[0]);
952 unsigned Opcode = VL0->getOpcode();
954 case Instruction::PHI: {
957 case Instruction::ExtractElement: {
958 if (CanReuseExtract(VL))
960 return getGatherCost(VecTy);
962 case Instruction::ZExt:
963 case Instruction::SExt:
964 case Instruction::FPToUI:
965 case Instruction::FPToSI:
966 case Instruction::FPExt:
967 case Instruction::PtrToInt:
968 case Instruction::IntToPtr:
969 case Instruction::SIToFP:
970 case Instruction::UIToFP:
971 case Instruction::Trunc:
972 case Instruction::FPTrunc:
973 case Instruction::BitCast: {
974 Type *SrcTy = VL0->getOperand(0)->getType();
976 // Calculate the cost of this instruction.
977 int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(),
978 VL0->getType(), SrcTy);
980 VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
981 int VecCost = TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy);
982 return VecCost - ScalarCost;
984 case Instruction::FCmp:
985 case Instruction::ICmp:
986 case Instruction::Select:
987 case Instruction::Add:
988 case Instruction::FAdd:
989 case Instruction::Sub:
990 case Instruction::FSub:
991 case Instruction::Mul:
992 case Instruction::FMul:
993 case Instruction::UDiv:
994 case Instruction::SDiv:
995 case Instruction::FDiv:
996 case Instruction::URem:
997 case Instruction::SRem:
998 case Instruction::FRem:
999 case Instruction::Shl:
1000 case Instruction::LShr:
1001 case Instruction::AShr:
1002 case Instruction::And:
1003 case Instruction::Or:
1004 case Instruction::Xor: {
1005 // Calculate the cost of this instruction.
1008 if (Opcode == Instruction::FCmp || Opcode == Instruction::ICmp ||
1009 Opcode == Instruction::Select) {
1010 VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
1011 ScalarCost = VecTy->getNumElements() *
1012 TTI->getCmpSelInstrCost(Opcode, ScalarTy, Builder.getInt1Ty());
1013 VecCost = TTI->getCmpSelInstrCost(Opcode, VecTy, MaskTy);
1015 ScalarCost = VecTy->getNumElements() *
1016 TTI->getArithmeticInstrCost(Opcode, ScalarTy);
1017 VecCost = TTI->getArithmeticInstrCost(Opcode, VecTy);
1019 return VecCost - ScalarCost;
1021 case Instruction::Load: {
1022 // Cost of wide load - cost of scalar loads.
1023 int ScalarLdCost = VecTy->getNumElements() *
1024 TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
1025 int VecLdCost = TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
1026 return VecLdCost - ScalarLdCost;
1028 case Instruction::Store: {
1029 // We know that we can merge the stores. Calculate the cost.
1030 int ScalarStCost = VecTy->getNumElements() *
1031 TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
1032 int VecStCost = TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
1033 return VecStCost - ScalarStCost;
1036 llvm_unreachable("Unknown instruction");
1040 bool BoUpSLP::isFullyVectorizableTinyTree() {
1041 DEBUG(dbgs() << "SLP: Check whether the tree with height " <<
1042 VectorizableTree.size() << " is fully vectorizable .\n");
1044 // We only handle trees of height 2.
1045 if (VectorizableTree.size() != 2)
1048 // Gathering cost would be too much for tiny trees.
1049 if (VectorizableTree[0].NeedToGather || VectorizableTree[1].NeedToGather)
1055 int BoUpSLP::getTreeCost() {
1057 DEBUG(dbgs() << "SLP: Calculating cost for tree of size " <<
1058 VectorizableTree.size() << ".\n");
1060 // We only vectorize tiny trees if it is fully vectorizable.
1061 if (VectorizableTree.size() < 3 && !isFullyVectorizableTinyTree()) {
1062 if (!VectorizableTree.size()) {
1063 assert(!ExternalUses.size() && "We should not have any external users");
1068 unsigned BundleWidth = VectorizableTree[0].Scalars.size();
1070 for (unsigned i = 0, e = VectorizableTree.size(); i != e; ++i) {
1071 int C = getEntryCost(&VectorizableTree[i]);
1072 DEBUG(dbgs() << "SLP: Adding cost " << C << " for bundle that starts with "
1073 << *VectorizableTree[i].Scalars[0] << " .\n");
1077 int ExtractCost = 0;
1078 for (UserList::iterator I = ExternalUses.begin(), E = ExternalUses.end();
1081 VectorType *VecTy = VectorType::get(I->Scalar->getType(), BundleWidth);
1082 ExtractCost += TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy,
1087 DEBUG(dbgs() << "SLP: Total Cost " << Cost + ExtractCost<< ".\n");
1088 return Cost + ExtractCost;
1091 int BoUpSLP::getGatherCost(Type *Ty) {
1093 for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
1094 Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
1098 int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) {
1099 // Find the type of the operands in VL.
1100 Type *ScalarTy = VL[0]->getType();
1101 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1102 ScalarTy = SI->getValueOperand()->getType();
1103 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1104 // Find the cost of inserting/extracting values from the vector.
1105 return getGatherCost(VecTy);
1108 AliasAnalysis::Location BoUpSLP::getLocation(Instruction *I) {
1109 if (StoreInst *SI = dyn_cast<StoreInst>(I))
1110 return AA->getLocation(SI);
1111 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1112 return AA->getLocation(LI);
1113 return AliasAnalysis::Location();
1116 Value *BoUpSLP::getPointerOperand(Value *I) {
1117 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1118 return LI->getPointerOperand();
1119 if (StoreInst *SI = dyn_cast<StoreInst>(I))
1120 return SI->getPointerOperand();
1124 unsigned BoUpSLP::getAddressSpaceOperand(Value *I) {
1125 if (LoadInst *L = dyn_cast<LoadInst>(I))
1126 return L->getPointerAddressSpace();
1127 if (StoreInst *S = dyn_cast<StoreInst>(I))
1128 return S->getPointerAddressSpace();
1132 bool BoUpSLP::isConsecutiveAccess(Value *A, Value *B) {
1133 Value *PtrA = getPointerOperand(A);
1134 Value *PtrB = getPointerOperand(B);
1135 unsigned ASA = getAddressSpaceOperand(A);
1136 unsigned ASB = getAddressSpaceOperand(B);
1138 // Check that the address spaces match and that the pointers are valid.
1139 if (!PtrA || !PtrB || (ASA != ASB))
1142 // Make sure that A and B are different pointers of the same type.
1143 if (PtrA == PtrB || PtrA->getType() != PtrB->getType())
1146 unsigned PtrBitWidth = DL->getPointerSizeInBits(ASA);
1147 Type *Ty = cast<PointerType>(PtrA->getType())->getElementType();
1148 APInt Size(PtrBitWidth, DL->getTypeStoreSize(Ty));
1150 APInt OffsetA(PtrBitWidth, 0), OffsetB(PtrBitWidth, 0);
1151 PtrA = PtrA->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetA);
1152 PtrB = PtrB->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetB);
1154 APInt OffsetDelta = OffsetB - OffsetA;
1156 // Check if they are based on the same pointer. That makes the offsets
1159 return OffsetDelta == Size;
1161 // Compute the necessary base pointer delta to have the necessary final delta
1162 // equal to the size.
1163 APInt BaseDelta = Size - OffsetDelta;
1165 // Otherwise compute the distance with SCEV between the base pointers.
1166 const SCEV *PtrSCEVA = SE->getSCEV(PtrA);
1167 const SCEV *PtrSCEVB = SE->getSCEV(PtrB);
1168 const SCEV *C = SE->getConstant(BaseDelta);
1169 const SCEV *X = SE->getAddExpr(PtrSCEVA, C);
1170 return X == PtrSCEVB;
1173 Value *BoUpSLP::getSinkBarrier(Instruction *Src, Instruction *Dst) {
1174 assert(Src->getParent() == Dst->getParent() && "Not the same BB");
1175 BasicBlock::iterator I = Src, E = Dst;
1176 /// Scan all of the instruction from SRC to DST and check if
1177 /// the source may alias.
1178 for (++I; I != E; ++I) {
1179 // Ignore store instructions that are marked as 'ignore'.
1180 if (MemBarrierIgnoreList.count(I))
1182 if (Src->mayWriteToMemory()) /* Write */ {
1183 if (!I->mayReadOrWriteMemory())
1186 if (!I->mayWriteToMemory())
1189 AliasAnalysis::Location A = getLocation(&*I);
1190 AliasAnalysis::Location B = getLocation(Src);
1192 if (!A.Ptr || !B.Ptr || AA->alias(A, B))
1198 int BoUpSLP::getLastIndex(ArrayRef<Value *> VL) {
1199 BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
1200 assert(BB == getSameBlock(VL) && BlocksNumbers.count(BB) && "Invalid block");
1201 BlockNumbering &BN = BlocksNumbers[BB];
1203 int MaxIdx = BN.getIndex(BB->getFirstNonPHI());
1204 for (unsigned i = 0, e = VL.size(); i < e; ++i)
1205 MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
1209 Instruction *BoUpSLP::getLastInstruction(ArrayRef<Value *> VL) {
1210 BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
1211 assert(BB == getSameBlock(VL) && BlocksNumbers.count(BB) && "Invalid block");
1212 BlockNumbering &BN = BlocksNumbers[BB];
1214 int MaxIdx = BN.getIndex(cast<Instruction>(VL[0]));
1215 for (unsigned i = 1, e = VL.size(); i < e; ++i)
1216 MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
1217 Instruction *I = BN.getInstruction(MaxIdx);
1218 assert(I && "bad location");
1222 void BoUpSLP::setInsertPointAfterBundle(ArrayRef<Value *> VL) {
1223 Instruction *VL0 = cast<Instruction>(VL[0]);
1224 Instruction *LastInst = getLastInstruction(VL);
1225 BasicBlock::iterator NextInst = LastInst;
1227 Builder.SetInsertPoint(VL0->getParent(), NextInst);
1228 Builder.SetCurrentDebugLocation(VL0->getDebugLoc());
1231 Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
1232 Value *Vec = UndefValue::get(Ty);
1233 // Generate the 'InsertElement' instruction.
1234 for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
1235 Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
1236 if (Instruction *Insrt = dyn_cast<Instruction>(Vec)) {
1237 GatherSeq.insert(Insrt);
1239 // Add to our 'need-to-extract' list.
1240 if (ScalarToTreeEntry.count(VL[i])) {
1241 int Idx = ScalarToTreeEntry[VL[i]];
1242 TreeEntry *E = &VectorizableTree[Idx];
1243 // Find which lane we need to extract.
1245 for (unsigned Lane = 0, LE = VL.size(); Lane != LE; ++Lane) {
1246 // Is this the lane of the scalar that we are looking for ?
1247 if (E->Scalars[Lane] == VL[i]) {
1252 assert(FoundLane >= 0 && "Could not find the correct lane");
1253 ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
1261 Value *BoUpSLP::alreadyVectorized(ArrayRef<Value *> VL) const {
1262 SmallDenseMap<Value*, int>::const_iterator Entry
1263 = ScalarToTreeEntry.find(VL[0]);
1264 if (Entry != ScalarToTreeEntry.end()) {
1265 int Idx = Entry->second;
1266 const TreeEntry *En = &VectorizableTree[Idx];
1267 if (En->isSame(VL) && En->VectorizedValue)
1268 return En->VectorizedValue;
1273 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
1274 if (ScalarToTreeEntry.count(VL[0])) {
1275 int Idx = ScalarToTreeEntry[VL[0]];
1276 TreeEntry *E = &VectorizableTree[Idx];
1278 return vectorizeTree(E);
1281 Type *ScalarTy = VL[0]->getType();
1282 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1283 ScalarTy = SI->getValueOperand()->getType();
1284 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1286 return Gather(VL, VecTy);
1289 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
1290 IRBuilder<>::InsertPointGuard Guard(Builder);
1292 if (E->VectorizedValue) {
1293 DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
1294 return E->VectorizedValue;
1297 Instruction *VL0 = cast<Instruction>(E->Scalars[0]);
1298 Type *ScalarTy = VL0->getType();
1299 if (StoreInst *SI = dyn_cast<StoreInst>(VL0))
1300 ScalarTy = SI->getValueOperand()->getType();
1301 VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size());
1303 if (E->NeedToGather) {
1304 setInsertPointAfterBundle(E->Scalars);
1305 return Gather(E->Scalars, VecTy);
1308 unsigned Opcode = VL0->getOpcode();
1309 assert(Opcode == getSameOpcode(E->Scalars) && "Invalid opcode");
1312 case Instruction::PHI: {
1313 PHINode *PH = dyn_cast<PHINode>(VL0);
1314 Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
1315 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1316 PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
1317 E->VectorizedValue = NewPhi;
1319 // PHINodes may have multiple entries from the same block. We want to
1320 // visit every block once.
1321 SmallSet<BasicBlock*, 4> VisitedBBs;
1323 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1325 BasicBlock *IBB = PH->getIncomingBlock(i);
1327 if (!VisitedBBs.insert(IBB)) {
1328 NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
1332 // Prepare the operand vector.
1333 for (unsigned j = 0; j < E->Scalars.size(); ++j)
1334 Operands.push_back(cast<PHINode>(E->Scalars[j])->
1335 getIncomingValueForBlock(IBB));
1337 Builder.SetInsertPoint(IBB->getTerminator());
1338 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1339 Value *Vec = vectorizeTree(Operands);
1340 NewPhi->addIncoming(Vec, IBB);
1343 assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
1344 "Invalid number of incoming values");
1348 case Instruction::ExtractElement: {
1349 if (CanReuseExtract(E->Scalars)) {
1350 Value *V = VL0->getOperand(0);
1351 E->VectorizedValue = V;
1354 return Gather(E->Scalars, VecTy);
1356 case Instruction::ZExt:
1357 case Instruction::SExt:
1358 case Instruction::FPToUI:
1359 case Instruction::FPToSI:
1360 case Instruction::FPExt:
1361 case Instruction::PtrToInt:
1362 case Instruction::IntToPtr:
1363 case Instruction::SIToFP:
1364 case Instruction::UIToFP:
1365 case Instruction::Trunc:
1366 case Instruction::FPTrunc:
1367 case Instruction::BitCast: {
1369 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1370 INVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1372 setInsertPointAfterBundle(E->Scalars);
1374 Value *InVec = vectorizeTree(INVL);
1376 if (Value *V = alreadyVectorized(E->Scalars))
1379 CastInst *CI = dyn_cast<CastInst>(VL0);
1380 Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
1381 E->VectorizedValue = V;
1384 case Instruction::FCmp:
1385 case Instruction::ICmp: {
1386 ValueList LHSV, RHSV;
1387 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1388 LHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1389 RHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1392 setInsertPointAfterBundle(E->Scalars);
1394 Value *L = vectorizeTree(LHSV);
1395 Value *R = vectorizeTree(RHSV);
1397 if (Value *V = alreadyVectorized(E->Scalars))
1400 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
1402 if (Opcode == Instruction::FCmp)
1403 V = Builder.CreateFCmp(P0, L, R);
1405 V = Builder.CreateICmp(P0, L, R);
1407 E->VectorizedValue = V;
1410 case Instruction::Select: {
1411 ValueList TrueVec, FalseVec, CondVec;
1412 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1413 CondVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1414 TrueVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1415 FalseVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(2));
1418 setInsertPointAfterBundle(E->Scalars);
1420 Value *Cond = vectorizeTree(CondVec);
1421 Value *True = vectorizeTree(TrueVec);
1422 Value *False = vectorizeTree(FalseVec);
1424 if (Value *V = alreadyVectorized(E->Scalars))
1427 Value *V = Builder.CreateSelect(Cond, True, False);
1428 E->VectorizedValue = V;
1431 case Instruction::Add:
1432 case Instruction::FAdd:
1433 case Instruction::Sub:
1434 case Instruction::FSub:
1435 case Instruction::Mul:
1436 case Instruction::FMul:
1437 case Instruction::UDiv:
1438 case Instruction::SDiv:
1439 case Instruction::FDiv:
1440 case Instruction::URem:
1441 case Instruction::SRem:
1442 case Instruction::FRem:
1443 case Instruction::Shl:
1444 case Instruction::LShr:
1445 case Instruction::AShr:
1446 case Instruction::And:
1447 case Instruction::Or:
1448 case Instruction::Xor: {
1449 ValueList LHSVL, RHSVL;
1450 if (isa<BinaryOperator>(VL0) && VL0->isCommutative())
1451 reorderInputsAccordingToOpcode(E->Scalars, LHSVL, RHSVL);
1453 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1454 LHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1455 RHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1458 setInsertPointAfterBundle(E->Scalars);
1460 Value *LHS = vectorizeTree(LHSVL);
1461 Value *RHS = vectorizeTree(RHSVL);
1463 if (LHS == RHS && isa<Instruction>(LHS)) {
1464 assert((VL0->getOperand(0) == VL0->getOperand(1)) && "Invalid order");
1467 if (Value *V = alreadyVectorized(E->Scalars))
1470 BinaryOperator *BinOp = cast<BinaryOperator>(VL0);
1471 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), LHS, RHS);
1472 E->VectorizedValue = V;
1475 case Instruction::Load: {
1476 // Loads are inserted at the head of the tree because we don't want to
1477 // sink them all the way down past store instructions.
1478 setInsertPointAfterBundle(E->Scalars);
1480 LoadInst *LI = cast<LoadInst>(VL0);
1481 unsigned AS = LI->getPointerAddressSpace();
1483 Value *VecPtr = Builder.CreateBitCast(LI->getPointerOperand(),
1484 VecTy->getPointerTo(AS));
1485 unsigned Alignment = LI->getAlignment();
1486 LI = Builder.CreateLoad(VecPtr);
1487 LI->setAlignment(Alignment);
1488 E->VectorizedValue = LI;
1491 case Instruction::Store: {
1492 StoreInst *SI = cast<StoreInst>(VL0);
1493 unsigned Alignment = SI->getAlignment();
1494 unsigned AS = SI->getPointerAddressSpace();
1497 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1498 ValueOp.push_back(cast<StoreInst>(E->Scalars[i])->getValueOperand());
1500 setInsertPointAfterBundle(E->Scalars);
1502 Value *VecValue = vectorizeTree(ValueOp);
1503 Value *VecPtr = Builder.CreateBitCast(SI->getPointerOperand(),
1504 VecTy->getPointerTo(AS));
1505 StoreInst *S = Builder.CreateStore(VecValue, VecPtr);
1506 S->setAlignment(Alignment);
1507 E->VectorizedValue = S;
1511 llvm_unreachable("unknown inst");
1516 Value *BoUpSLP::vectorizeTree() {
1517 Builder.SetInsertPoint(F->getEntryBlock().begin());
1518 vectorizeTree(&VectorizableTree[0]);
1520 DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() << " values .\n");
1522 // Extract all of the elements with the external uses.
1523 for (UserList::iterator it = ExternalUses.begin(), e = ExternalUses.end();
1525 Value *Scalar = it->Scalar;
1526 llvm::User *User = it->User;
1528 // Skip users that we already RAUW. This happens when one instruction
1529 // has multiple uses of the same value.
1530 if (std::find(Scalar->use_begin(), Scalar->use_end(), User) ==
1533 assert(ScalarToTreeEntry.count(Scalar) && "Invalid scalar");
1535 int Idx = ScalarToTreeEntry[Scalar];
1536 TreeEntry *E = &VectorizableTree[Idx];
1537 assert(!E->NeedToGather && "Extracting from a gather list");
1539 Value *Vec = E->VectorizedValue;
1540 assert(Vec && "Can't find vectorizable value");
1542 Value *Lane = Builder.getInt32(it->Lane);
1543 // Generate extracts for out-of-tree users.
1544 // Find the insertion point for the extractelement lane.
1545 if (PHINode *PN = dyn_cast<PHINode>(Vec)) {
1546 Builder.SetInsertPoint(PN->getParent()->getFirstInsertionPt());
1547 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1548 User->replaceUsesOfWith(Scalar, Ex);
1549 } else if (isa<Instruction>(Vec)){
1550 if (PHINode *PH = dyn_cast<PHINode>(User)) {
1551 for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
1552 if (PH->getIncomingValue(i) == Scalar) {
1553 Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
1554 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1555 PH->setOperand(i, Ex);
1559 Builder.SetInsertPoint(cast<Instruction>(User));
1560 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1561 User->replaceUsesOfWith(Scalar, Ex);
1564 Builder.SetInsertPoint(F->getEntryBlock().begin());
1565 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1566 User->replaceUsesOfWith(Scalar, Ex);
1569 DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
1572 // For each vectorized value:
1573 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
1574 TreeEntry *Entry = &VectorizableTree[EIdx];
1577 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
1578 Value *Scalar = Entry->Scalars[Lane];
1580 // No need to handle users of gathered values.
1581 if (Entry->NeedToGather)
1584 assert(Entry->VectorizedValue && "Can't find vectorizable value");
1586 Type *Ty = Scalar->getType();
1587 if (!Ty->isVoidTy()) {
1588 for (Value::use_iterator User = Scalar->use_begin(),
1589 UE = Scalar->use_end(); User != UE; ++User) {
1590 DEBUG(dbgs() << "SLP: \tvalidating user:" << **User << ".\n");
1591 assert(!MustGather.count(*User) &&
1592 "Replacing gathered value with undef");
1594 assert((ScalarToTreeEntry.count(*User) ||
1595 // It is legal to replace the reduction users by undef.
1596 (RdxOps && RdxOps->count(*User))) &&
1597 "Replacing out-of-tree value with undef");
1599 Value *Undef = UndefValue::get(Ty);
1600 Scalar->replaceAllUsesWith(Undef);
1602 DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
1603 cast<Instruction>(Scalar)->eraseFromParent();
1607 for (Function::iterator it = F->begin(), e = F->end(); it != e; ++it) {
1608 BlocksNumbers[it].forget();
1610 Builder.ClearInsertionPoint();
1612 return VectorizableTree[0].VectorizedValue;
1615 void BoUpSLP::optimizeGatherSequence() {
1616 DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
1617 << " gather sequences instructions.\n");
1618 // LICM InsertElementInst sequences.
1619 for (SetVector<Instruction *>::iterator it = GatherSeq.begin(),
1620 e = GatherSeq.end(); it != e; ++it) {
1621 InsertElementInst *Insert = dyn_cast<InsertElementInst>(*it);
1626 // Check if this block is inside a loop.
1627 Loop *L = LI->getLoopFor(Insert->getParent());
1631 // Check if it has a preheader.
1632 BasicBlock *PreHeader = L->getLoopPreheader();
1636 // If the vector or the element that we insert into it are
1637 // instructions that are defined in this basic block then we can't
1638 // hoist this instruction.
1639 Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
1640 Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
1641 if (CurrVec && L->contains(CurrVec))
1643 if (NewElem && L->contains(NewElem))
1646 // We can hoist this instruction. Move it to the pre-header.
1647 Insert->moveBefore(PreHeader->getTerminator());
1650 // Perform O(N^2) search over the gather sequences and merge identical
1651 // instructions. TODO: We can further optimize this scan if we split the
1652 // instructions into different buckets based on the insert lane.
1653 SmallPtrSet<Instruction*, 16> Visited;
1654 SmallVector<Instruction*, 16> ToRemove;
1655 ReversePostOrderTraversal<Function*> RPOT(F);
1656 for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
1657 E = RPOT.end(); I != E; ++I) {
1658 BasicBlock *BB = *I;
1659 // For all instructions in the function:
1660 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1661 Instruction *In = it;
1662 if ((!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In)) ||
1663 !GatherSeq.count(In))
1666 // Check if we can replace this instruction with any of the
1667 // visited instructions.
1668 for (SmallPtrSet<Instruction*, 16>::iterator v = Visited.begin(),
1669 ve = Visited.end(); v != ve; ++v) {
1670 if (In->isIdenticalTo(*v) &&
1671 DT->dominates((*v)->getParent(), In->getParent())) {
1672 In->replaceAllUsesWith(*v);
1673 ToRemove.push_back(In);
1683 // Erase all of the instructions that we RAUWed.
1684 for (SmallVectorImpl<Instruction *>::iterator v = ToRemove.begin(),
1685 ve = ToRemove.end(); v != ve; ++v) {
1686 assert((*v)->getNumUses() == 0 && "Can't remove instructions with uses");
1687 (*v)->eraseFromParent();
1691 /// The SLPVectorizer Pass.
1692 struct SLPVectorizer : public FunctionPass {
1693 typedef SmallVector<StoreInst *, 8> StoreList;
1694 typedef MapVector<Value *, StoreList> StoreListMap;
1696 /// Pass identification, replacement for typeid
1699 explicit SLPVectorizer() : FunctionPass(ID) {
1700 initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
1703 ScalarEvolution *SE;
1705 TargetTransformInfo *TTI;
1710 virtual bool runOnFunction(Function &F) {
1711 SE = &getAnalysis<ScalarEvolution>();
1712 DL = getAnalysisIfAvailable<DataLayout>();
1713 TTI = &getAnalysis<TargetTransformInfo>();
1714 AA = &getAnalysis<AliasAnalysis>();
1715 LI = &getAnalysis<LoopInfo>();
1716 DT = &getAnalysis<DominatorTree>();
1719 bool Changed = false;
1721 // If the target claims to have no vector registers don't attempt
1723 if (!TTI->getNumberOfRegisters(true))
1726 // Must have DataLayout. We can't require it because some tests run w/o
1731 // Don't vectorize when the attribute NoImplicitFloat is used.
1732 if (F.hasFnAttribute(Attribute::NoImplicitFloat))
1735 DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
1737 // Use the bollom up slp vectorizer to construct chains that start with
1738 // he store instructions.
1739 BoUpSLP R(&F, SE, DL, TTI, AA, LI, DT);
1741 // Scan the blocks in the function in post order.
1742 for (po_iterator<BasicBlock*> it = po_begin(&F.getEntryBlock()),
1743 e = po_end(&F.getEntryBlock()); it != e; ++it) {
1744 BasicBlock *BB = *it;
1746 // Vectorize trees that end at stores.
1747 if (unsigned count = collectStores(BB, R)) {
1749 DEBUG(dbgs() << "SLP: Found " << count << " stores to vectorize.\n");
1750 Changed |= vectorizeStoreChains(R);
1753 // Vectorize trees that end at reductions.
1754 Changed |= vectorizeChainsInBlock(BB, R);
1758 R.optimizeGatherSequence();
1759 DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
1760 DEBUG(verifyFunction(F));
1765 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1766 FunctionPass::getAnalysisUsage(AU);
1767 AU.addRequired<ScalarEvolution>();
1768 AU.addRequired<AliasAnalysis>();
1769 AU.addRequired<TargetTransformInfo>();
1770 AU.addRequired<LoopInfo>();
1771 AU.addRequired<DominatorTree>();
1772 AU.addPreserved<LoopInfo>();
1773 AU.addPreserved<DominatorTree>();
1774 AU.setPreservesCFG();
1779 /// \brief Collect memory references and sort them according to their base
1780 /// object. We sort the stores to their base objects to reduce the cost of the
1781 /// quadratic search on the stores. TODO: We can further reduce this cost
1782 /// if we flush the chain creation every time we run into a memory barrier.
1783 unsigned collectStores(BasicBlock *BB, BoUpSLP &R);
1785 /// \brief Try to vectorize a chain that starts at two arithmetic instrs.
1786 bool tryToVectorizePair(Value *A, Value *B, BoUpSLP &R);
1788 /// \brief Try to vectorize a list of operands.
1789 /// \returns true if a value was vectorized.
1790 bool tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R);
1792 /// \brief Try to vectorize a chain that may start at the operands of \V;
1793 bool tryToVectorize(BinaryOperator *V, BoUpSLP &R);
1795 /// \brief Vectorize the stores that were collected in StoreRefs.
1796 bool vectorizeStoreChains(BoUpSLP &R);
1798 /// \brief Scan the basic block and look for patterns that are likely to start
1799 /// a vectorization chain.
1800 bool vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R);
1802 bool vectorizeStoreChain(ArrayRef<Value *> Chain, int CostThreshold,
1805 bool vectorizeStores(ArrayRef<StoreInst *> Stores, int costThreshold,
1808 StoreListMap StoreRefs;
1811 bool SLPVectorizer::vectorizeStoreChain(ArrayRef<Value *> Chain,
1812 int CostThreshold, BoUpSLP &R) {
1813 unsigned ChainLen = Chain.size();
1814 DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
1816 Type *StoreTy = cast<StoreInst>(Chain[0])->getValueOperand()->getType();
1817 unsigned Sz = DL->getTypeSizeInBits(StoreTy);
1818 unsigned VF = MinVecRegSize / Sz;
1820 if (!isPowerOf2_32(Sz) || VF < 2)
1823 bool Changed = false;
1824 // Look for profitable vectorizable trees at all offsets, starting at zero.
1825 for (unsigned i = 0, e = ChainLen; i < e; ++i) {
1828 DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
1830 ArrayRef<Value *> Operands = Chain.slice(i, VF);
1832 R.buildTree(Operands);
1834 int Cost = R.getTreeCost();
1836 DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
1837 if (Cost < CostThreshold) {
1838 DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
1841 // Move to the next bundle.
1850 bool SLPVectorizer::vectorizeStores(ArrayRef<StoreInst *> Stores,
1851 int costThreshold, BoUpSLP &R) {
1852 SetVector<Value *> Heads, Tails;
1853 SmallDenseMap<Value *, Value *> ConsecutiveChain;
1855 // We may run into multiple chains that merge into a single chain. We mark the
1856 // stores that we vectorized so that we don't visit the same store twice.
1857 BoUpSLP::ValueSet VectorizedStores;
1858 bool Changed = false;
1860 // Do a quadratic search on all of the given stores and find
1861 // all of the pairs of stores that follow each other.
1862 for (unsigned i = 0, e = Stores.size(); i < e; ++i) {
1863 for (unsigned j = 0; j < e; ++j) {
1867 if (R.isConsecutiveAccess(Stores[i], Stores[j])) {
1868 Tails.insert(Stores[j]);
1869 Heads.insert(Stores[i]);
1870 ConsecutiveChain[Stores[i]] = Stores[j];
1875 // For stores that start but don't end a link in the chain:
1876 for (SetVector<Value *>::iterator it = Heads.begin(), e = Heads.end();
1878 if (Tails.count(*it))
1881 // We found a store instr that starts a chain. Now follow the chain and try
1883 BoUpSLP::ValueList Operands;
1885 // Collect the chain into a list.
1886 while (Tails.count(I) || Heads.count(I)) {
1887 if (VectorizedStores.count(I))
1889 Operands.push_back(I);
1890 // Move to the next value in the chain.
1891 I = ConsecutiveChain[I];
1894 bool Vectorized = vectorizeStoreChain(Operands, costThreshold, R);
1896 // Mark the vectorized stores so that we don't vectorize them again.
1898 VectorizedStores.insert(Operands.begin(), Operands.end());
1899 Changed |= Vectorized;
1906 unsigned SLPVectorizer::collectStores(BasicBlock *BB, BoUpSLP &R) {
1909 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1910 StoreInst *SI = dyn_cast<StoreInst>(it);
1914 // Check that the pointer points to scalars.
1915 Type *Ty = SI->getValueOperand()->getType();
1916 if (Ty->isAggregateType() || Ty->isVectorTy())
1919 // Find the base pointer.
1920 Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), DL);
1922 // Save the store locations.
1923 StoreRefs[Ptr].push_back(SI);
1929 bool SLPVectorizer::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
1932 Value *VL[] = { A, B };
1933 return tryToVectorizeList(VL, R);
1936 bool SLPVectorizer::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R) {
1940 DEBUG(dbgs() << "SLP: Vectorizing a list of length = " << VL.size() << ".\n");
1942 // Check that all of the parts are scalar instructions of the same type.
1943 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
1947 unsigned Opcode0 = I0->getOpcode();
1949 Type *Ty0 = I0->getType();
1950 unsigned Sz = DL->getTypeSizeInBits(Ty0);
1951 unsigned VF = MinVecRegSize / Sz;
1953 for (int i = 0, e = VL.size(); i < e; ++i) {
1954 Type *Ty = VL[i]->getType();
1955 if (Ty->isAggregateType() || Ty->isVectorTy())
1957 Instruction *Inst = dyn_cast<Instruction>(VL[i]);
1958 if (!Inst || Inst->getOpcode() != Opcode0)
1962 bool Changed = false;
1964 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
1965 unsigned OpsWidth = 0;
1972 if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
1975 DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations " << "\n");
1976 ArrayRef<Value *> Ops = VL.slice(i, OpsWidth);
1979 int Cost = R.getTreeCost();
1981 if (Cost < -SLPCostThreshold) {
1982 DEBUG(dbgs() << "SLP: Vectorizing pair at cost:" << Cost << ".\n");
1985 // Move to the next bundle.
1994 bool SLPVectorizer::tryToVectorize(BinaryOperator *V, BoUpSLP &R) {
1998 // Try to vectorize V.
1999 if (tryToVectorizePair(V->getOperand(0), V->getOperand(1), R))
2002 BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0));
2003 BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1));
2005 if (B && B->hasOneUse()) {
2006 BinaryOperator *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
2007 BinaryOperator *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
2008 if (tryToVectorizePair(A, B0, R)) {
2012 if (tryToVectorizePair(A, B1, R)) {
2019 if (A && A->hasOneUse()) {
2020 BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
2021 BinaryOperator *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
2022 if (tryToVectorizePair(A0, B, R)) {
2026 if (tryToVectorizePair(A1, B, R)) {
2034 /// \brief Generate a shuffle mask to be used in a reduction tree.
2036 /// \param VecLen The length of the vector to be reduced.
2037 /// \param NumEltsToRdx The number of elements that should be reduced in the
2039 /// \param IsPairwise Whether the reduction is a pairwise or splitting
2040 /// reduction. A pairwise reduction will generate a mask of
2041 /// <0,2,...> or <1,3,..> while a splitting reduction will generate
2042 /// <2,3, undef,undef> for a vector of 4 and NumElts = 2.
2043 /// \param IsLeft True will generate a mask of even elements, odd otherwise.
2044 static Value *createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx,
2045 bool IsPairwise, bool IsLeft,
2046 IRBuilder<> &Builder) {
2047 assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask");
2049 SmallVector<Constant *, 32> ShuffleMask(
2050 VecLen, UndefValue::get(Builder.getInt32Ty()));
2053 // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
2054 for (unsigned i = 0; i != NumEltsToRdx; ++i)
2055 ShuffleMask[i] = Builder.getInt32(2 * i + !IsLeft);
2057 // Move the upper half of the vector to the lower half.
2058 for (unsigned i = 0; i != NumEltsToRdx; ++i)
2059 ShuffleMask[i] = Builder.getInt32(NumEltsToRdx + i);
2061 return ConstantVector::get(ShuffleMask);
2065 /// Model horizontal reductions.
2067 /// A horizontal reduction is a tree of reduction operations (currently add and
2068 /// fadd) that has operations that can be put into a vector as its leaf.
2069 /// For example, this tree:
2076 /// This tree has "mul" as its reduced values and "+" as its reduction
2077 /// operations. A reduction might be feeding into a store or a binary operation
2092 class HorizontalReduction {
2093 SmallPtrSet<Value *, 16> ReductionOps;
2094 SmallVector<Value *, 32> ReducedVals;
2096 BinaryOperator *ReductionRoot;
2097 PHINode *ReductionPHI;
2099 /// The opcode of the reduction.
2100 unsigned ReductionOpcode;
2101 /// The opcode of the values we perform a reduction on.
2102 unsigned ReducedValueOpcode;
2103 /// The width of one full horizontal reduction operation.
2104 unsigned ReduxWidth;
2105 /// Should we model this reduction as a pairwise reduction tree or a tree that
2106 /// splits the vector in halves and adds those halves.
2107 bool IsPairwiseReduction;
2110 HorizontalReduction()
2111 : ReductionRoot(0), ReductionPHI(0), ReductionOpcode(0),
2112 ReducedValueOpcode(0), ReduxWidth(0), IsPairwiseReduction(false) {}
2114 /// \brief Try to find a reduction tree.
2115 bool matchAssociativeReduction(PHINode *Phi, BinaryOperator *B,
2118 std::find(Phi->op_begin(), Phi->op_end(), B) != Phi->op_end()) &&
2119 "Thi phi needs to use the binary operator");
2121 // We could have a initial reductions that is not an add.
2122 // r *= v1 + v2 + v3 + v4
2123 // In such a case start looking for a tree rooted in the first '+'.
2125 if (B->getOperand(0) == Phi) {
2127 B = dyn_cast<BinaryOperator>(B->getOperand(1));
2128 } else if (B->getOperand(1) == Phi) {
2130 B = dyn_cast<BinaryOperator>(B->getOperand(0));
2137 Type *Ty = B->getType();
2138 if (Ty->isVectorTy())
2141 ReductionOpcode = B->getOpcode();
2142 ReducedValueOpcode = 0;
2143 ReduxWidth = MinVecRegSize / DL->getTypeSizeInBits(Ty);
2150 // We currently only support adds.
2151 if (ReductionOpcode != Instruction::Add &&
2152 ReductionOpcode != Instruction::FAdd)
2155 // Post order traverse the reduction tree starting at B. We only handle true
2156 // trees containing only binary operators.
2157 SmallVector<std::pair<BinaryOperator *, unsigned>, 32> Stack;
2158 Stack.push_back(std::make_pair(B, 0));
2159 while (!Stack.empty()) {
2160 BinaryOperator *TreeN = Stack.back().first;
2161 unsigned EdgeToVist = Stack.back().second++;
2162 bool IsReducedValue = TreeN->getOpcode() != ReductionOpcode;
2164 // Only handle trees in the current basic block.
2165 if (TreeN->getParent() != B->getParent())
2168 // Each tree node needs to have one user except for the ultimate
2170 if (!TreeN->hasOneUse() && TreeN != B)
2174 if (EdgeToVist == 2 || IsReducedValue) {
2175 if (IsReducedValue) {
2176 // Make sure that the opcodes of the operations that we are going to
2178 if (!ReducedValueOpcode)
2179 ReducedValueOpcode = TreeN->getOpcode();
2180 else if (ReducedValueOpcode != TreeN->getOpcode())
2182 ReducedVals.push_back(TreeN);
2184 // We need to be able to reassociate the adds.
2185 if (!TreeN->isAssociative())
2187 ReductionOps.insert(TreeN);
2194 // Visit left or right.
2195 Value *NextV = TreeN->getOperand(EdgeToVist);
2196 BinaryOperator *Next = dyn_cast<BinaryOperator>(NextV);
2198 Stack.push_back(std::make_pair(Next, 0));
2199 else if (NextV != Phi)
2205 /// \brief Attempt to vectorize the tree found by
2206 /// matchAssociativeReduction.
2207 bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
2208 if (ReducedVals.empty())
2211 unsigned NumReducedVals = ReducedVals.size();
2212 if (NumReducedVals < ReduxWidth)
2215 Value *VectorizedTree = 0;
2216 IRBuilder<> Builder(ReductionRoot);
2217 FastMathFlags Unsafe;
2218 Unsafe.setUnsafeAlgebra();
2219 Builder.SetFastMathFlags(Unsafe);
2222 for (; i < NumReducedVals - ReduxWidth + 1; i += ReduxWidth) {
2223 ArrayRef<Value *> ValsToReduce(&ReducedVals[i], ReduxWidth);
2224 V.buildTree(ValsToReduce, &ReductionOps);
2227 int Cost = V.getTreeCost() + getReductionCost(TTI, ReducedVals[i]);
2228 if (Cost >= -SLPCostThreshold)
2231 DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" << Cost
2234 // Vectorize a tree.
2235 DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
2236 Value *VectorizedRoot = V.vectorizeTree();
2238 // Emit a reduction.
2239 Value *ReducedSubTree = emitReduction(VectorizedRoot, Builder);
2240 if (VectorizedTree) {
2241 Builder.SetCurrentDebugLocation(Loc);
2242 VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
2243 ReducedSubTree, "bin.rdx");
2245 VectorizedTree = ReducedSubTree;
2248 if (VectorizedTree) {
2249 // Finish the reduction.
2250 for (; i < NumReducedVals; ++i) {
2251 Builder.SetCurrentDebugLocation(
2252 cast<Instruction>(ReducedVals[i])->getDebugLoc());
2253 VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
2258 assert(ReductionRoot != NULL && "Need a reduction operation");
2259 ReductionRoot->setOperand(0, VectorizedTree);
2260 ReductionRoot->setOperand(1, ReductionPHI);
2262 ReductionRoot->replaceAllUsesWith(VectorizedTree);
2264 return VectorizedTree != 0;
2269 /// \brief Calcuate the cost of a reduction.
2270 int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal) {
2271 Type *ScalarTy = FirstReducedVal->getType();
2272 Type *VecTy = VectorType::get(ScalarTy, ReduxWidth);
2274 int PairwiseRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, true);
2275 int SplittingRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, false);
2277 IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
2278 int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
2280 int ScalarReduxCost =
2281 ReduxWidth * TTI->getArithmeticInstrCost(ReductionOpcode, VecTy);
2283 DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost
2284 << " for reduction that starts with " << *FirstReducedVal
2286 << (IsPairwiseReduction ? "pairwise" : "splitting")
2287 << " reduction)\n");
2289 return VecReduxCost - ScalarReduxCost;
2292 static Value *createBinOp(IRBuilder<> &Builder, unsigned Opcode, Value *L,
2293 Value *R, const Twine &Name = "") {
2294 if (Opcode == Instruction::FAdd)
2295 return Builder.CreateFAdd(L, R, Name);
2296 return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, L, R, Name);
2299 /// \brief Emit a horizontal reduction of the vectorized value.
2300 Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder) {
2301 assert(VectorizedValue && "Need to have a vectorized tree node");
2302 Instruction *ValToReduce = dyn_cast<Instruction>(VectorizedValue);
2303 assert(isPowerOf2_32(ReduxWidth) &&
2304 "We only handle power-of-two reductions for now");
2306 Value *TmpVec = ValToReduce;
2307 for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
2308 if (IsPairwiseReduction) {
2310 createRdxShuffleMask(ReduxWidth, i, true, true, Builder);
2312 createRdxShuffleMask(ReduxWidth, i, true, false, Builder);
2314 Value *LeftShuf = Builder.CreateShuffleVector(
2315 TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l");
2316 Value *RightShuf = Builder.CreateShuffleVector(
2317 TmpVec, UndefValue::get(TmpVec->getType()), (RightMask),
2319 TmpVec = createBinOp(Builder, ReductionOpcode, LeftShuf, RightShuf,
2323 createRdxShuffleMask(ReduxWidth, i, false, false, Builder);
2324 Value *Shuf = Builder.CreateShuffleVector(
2325 TmpVec, UndefValue::get(TmpVec->getType()), UpperHalf, "rdx.shuf");
2326 TmpVec = createBinOp(Builder, ReductionOpcode, TmpVec, Shuf, "bin.rdx");
2330 // The result is in the first element of the vector.
2331 return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
2335 /// \brief Recognize construction of vectors like
2336 /// %ra = insertelement <4 x float> undef, float %s0, i32 0
2337 /// %rb = insertelement <4 x float> %ra, float %s1, i32 1
2338 /// %rc = insertelement <4 x float> %rb, float %s2, i32 2
2339 /// %rd = insertelement <4 x float> %rc, float %s3, i32 3
2341 /// Returns true if it matches
2343 static bool findBuildVector(InsertElementInst *IE,
2344 SmallVectorImpl<Value *> &Ops) {
2345 if (!isa<UndefValue>(IE->getOperand(0)))
2349 Ops.push_back(IE->getOperand(1));
2351 if (IE->use_empty())
2354 InsertElementInst *NextUse = dyn_cast<InsertElementInst>(IE->use_back());
2358 // If this isn't the final use, make sure the next insertelement is the only
2359 // use. It's OK if the final constructed vector is used multiple times
2360 if (!IE->hasOneUse())
2369 static bool PhiTypeSorterFunc(Value *V, Value *V2) {
2370 return V->getType() < V2->getType();
2373 bool SLPVectorizer::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
2374 bool Changed = false;
2375 SmallVector<Value *, 4> Incoming;
2376 SmallSet<Value *, 16> VisitedInstrs;
2378 bool HaveVectorizedPhiNodes = true;
2379 while (HaveVectorizedPhiNodes) {
2380 HaveVectorizedPhiNodes = false;
2382 // Collect the incoming values from the PHIs.
2384 for (BasicBlock::iterator instr = BB->begin(), ie = BB->end(); instr != ie;
2386 PHINode *P = dyn_cast<PHINode>(instr);
2390 if (!VisitedInstrs.count(P))
2391 Incoming.push_back(P);
2395 std::stable_sort(Incoming.begin(), Incoming.end(), PhiTypeSorterFunc);
2397 // Try to vectorize elements base on their type.
2398 for (SmallVector<Value *, 4>::iterator IncIt = Incoming.begin(),
2402 // Look for the next elements with the same type.
2403 SmallVector<Value *, 4>::iterator SameTypeIt = IncIt;
2404 while (SameTypeIt != E &&
2405 (*SameTypeIt)->getType() == (*IncIt)->getType()) {
2406 VisitedInstrs.insert(*SameTypeIt);
2410 // Try to vectorize them.
2411 unsigned NumElts = (SameTypeIt - IncIt);
2412 DEBUG(errs() << "SLP: Trying to vectorize starting at PHIs (" << NumElts << ")\n");
2414 tryToVectorizeList(ArrayRef<Value *>(IncIt, NumElts), R)) {
2415 // Success start over because instructions might have been changed.
2416 HaveVectorizedPhiNodes = true;
2421 // Start over at the next instruction of a differnt type (or the end).
2426 VisitedInstrs.clear();
2428 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) {
2429 // We may go through BB multiple times so skip the one we have checked.
2430 if (!VisitedInstrs.insert(it))
2433 if (isa<DbgInfoIntrinsic>(it))
2436 // Try to vectorize reductions that use PHINodes.
2437 if (PHINode *P = dyn_cast<PHINode>(it)) {
2438 // Check that the PHI is a reduction PHI.
2439 if (P->getNumIncomingValues() != 2)
2442 (P->getIncomingBlock(0) == BB
2443 ? (P->getIncomingValue(0))
2444 : (P->getIncomingBlock(1) == BB ? P->getIncomingValue(1) : 0));
2445 // Check if this is a Binary Operator.
2446 BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx);
2450 // Try to match and vectorize a horizontal reduction.
2451 HorizontalReduction HorRdx;
2452 if (ShouldVectorizeHor &&
2453 HorRdx.matchAssociativeReduction(P, BI, DL) &&
2454 HorRdx.tryToReduce(R, TTI)) {
2461 Value *Inst = BI->getOperand(0);
2463 Inst = BI->getOperand(1);
2465 if (tryToVectorize(dyn_cast<BinaryOperator>(Inst), R)) {
2466 // We would like to start over since some instructions are deleted
2467 // and the iterator may become invalid value.
2477 // Try to vectorize horizontal reductions feeding into a store.
2478 if (ShouldStartVectorizeHorAtStore)
2479 if (StoreInst *SI = dyn_cast<StoreInst>(it))
2480 if (BinaryOperator *BinOp =
2481 dyn_cast<BinaryOperator>(SI->getValueOperand())) {
2482 HorizontalReduction HorRdx;
2483 if (((HorRdx.matchAssociativeReduction(0, BinOp, DL) &&
2484 HorRdx.tryToReduce(R, TTI)) ||
2485 tryToVectorize(BinOp, R))) {
2493 // Try to vectorize trees that start at compare instructions.
2494 if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
2495 if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) {
2497 // We would like to start over since some instructions are deleted
2498 // and the iterator may become invalid value.
2504 for (int i = 0; i < 2; ++i) {
2505 if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i))) {
2506 if (tryToVectorizePair(BI->getOperand(0), BI->getOperand(1), R)) {
2508 // We would like to start over since some instructions are deleted
2509 // and the iterator may become invalid value.
2518 // Try to vectorize trees that start at insertelement instructions.
2519 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(it)) {
2520 SmallVector<Value *, 8> Ops;
2521 if (!findBuildVector(IE, Ops))
2524 if (tryToVectorizeList(Ops, R)) {
2537 bool SLPVectorizer::vectorizeStoreChains(BoUpSLP &R) {
2538 bool Changed = false;
2539 // Attempt to sort and vectorize each of the store-groups.
2540 for (StoreListMap::iterator it = StoreRefs.begin(), e = StoreRefs.end();
2542 if (it->second.size() < 2)
2545 DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
2546 << it->second.size() << ".\n");
2548 // Process the stores in chunks of 16.
2549 for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI+=16) {
2550 unsigned Len = std::min<unsigned>(CE - CI, 16);
2551 ArrayRef<StoreInst *> Chunk(&it->second[CI], Len);
2552 Changed |= vectorizeStores(Chunk, -SLPCostThreshold, R);
2558 } // end anonymous namespace
2560 char SLPVectorizer::ID = 0;
2561 static const char lv_name[] = "SLP Vectorizer";
2562 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
2563 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
2564 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
2565 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
2566 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
2567 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
2570 Pass *createSLPVectorizerPass() { return new SLPVectorizer(); }