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 void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
210 SmallVectorImpl<Value *> &Left,
211 SmallVectorImpl<Value *> &Right) {
213 SmallVector<Value *, 16> OrigLeft, OrigRight;
215 bool AllSameOpcodeLeft = true;
216 bool AllSameOpcodeRight = true;
217 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
218 Instruction *I = cast<Instruction>(VL[i]);
219 Value *V0 = I->getOperand(0);
220 Value *V1 = I->getOperand(1);
222 OrigLeft.push_back(V0);
223 OrigRight.push_back(V1);
225 Instruction *I0 = dyn_cast<Instruction>(V0);
226 Instruction *I1 = dyn_cast<Instruction>(V1);
228 // Check whether all operands on one side have the same opcode. In this case
229 // we want to preserve the original order and not make things worse by
231 AllSameOpcodeLeft = I0;
232 AllSameOpcodeRight = I1;
234 if (i && AllSameOpcodeLeft) {
235 if(Instruction *P0 = dyn_cast<Instruction>(OrigLeft[i-1])) {
236 if(P0->getOpcode() != I0->getOpcode())
237 AllSameOpcodeLeft = false;
239 AllSameOpcodeLeft = false;
241 if (i && AllSameOpcodeRight) {
242 if(Instruction *P1 = dyn_cast<Instruction>(OrigRight[i-1])) {
243 if(P1->getOpcode() != I1->getOpcode())
244 AllSameOpcodeRight = false;
246 AllSameOpcodeRight = false;
249 // Sort two opcodes. In the code below we try to preserve the ability to use
250 // broadcast of values instead of individual inserts.
257 // If we just sorted according to opcode we would leave the first line in
258 // tact but we would swap vl2 with vr2 because opcode(phi) > opcode(load).
261 // Because vr2 and vr1 are from the same load we loose the opportunity of a
262 // broadcast for the packed right side in the backend: we have [vr1, vl2]
263 // instead of [vr1, vr2=vr1].
265 if(!i && I0->getOpcode() > I1->getOpcode()) {
268 } else if (i && I0->getOpcode() > I1->getOpcode() && Right[i-1] != I1) {
269 // Try not to destroy a broad cast for no apparent benefit.
272 } else if (i && I0->getOpcode() == I1->getOpcode() && Right[i-1] == I0) {
273 // Try preserve broadcasts.
276 } else if (i && I0->getOpcode() == I1->getOpcode() && Left[i-1] == I1) {
277 // Try preserve broadcasts.
286 // One opcode, put the instruction on the right.
296 bool LeftBroadcast = isSplat(Left);
297 bool RightBroadcast = isSplat(Right);
299 // Don't reorder if the operands where good to begin with.
300 if (!(LeftBroadcast || RightBroadcast) &&
301 (AllSameOpcodeRight || AllSameOpcodeLeft)) {
307 /// Bottom Up SLP Vectorizer.
310 typedef SmallVector<Value *, 8> ValueList;
311 typedef SmallVector<Instruction *, 16> InstrList;
312 typedef SmallPtrSet<Value *, 16> ValueSet;
313 typedef SmallVector<StoreInst *, 8> StoreList;
315 BoUpSLP(Function *Func, ScalarEvolution *Se, DataLayout *Dl,
316 TargetTransformInfo *Tti, AliasAnalysis *Aa, LoopInfo *Li,
318 F(Func), SE(Se), DL(Dl), TTI(Tti), AA(Aa), LI(Li), DT(Dt),
319 Builder(Se->getContext()) {
320 // Setup the block numbering utility for all of the blocks in the
322 for (Function::iterator it = F->begin(), e = F->end(); it != e; ++it) {
324 BlocksNumbers[BB] = BlockNumbering(BB);
328 /// \brief Vectorize the tree that starts with the elements in \p VL.
329 /// Returns the vectorized root.
330 Value *vectorizeTree();
332 /// \returns the vectorization cost of the subtree that starts at \p VL.
333 /// A negative number means that this is profitable.
336 /// Construct a vectorizable tree that starts at \p Roots and is possibly
337 /// used by a reduction of \p RdxOps.
338 void buildTree(ArrayRef<Value *> Roots, ValueSet *RdxOps = 0);
340 /// Clear the internal data structures that are created by 'buildTree'.
343 VectorizableTree.clear();
344 ScalarToTreeEntry.clear();
346 ExternalUses.clear();
347 MemBarrierIgnoreList.clear();
350 /// \returns true if the memory operations A and B are consecutive.
351 bool isConsecutiveAccess(Value *A, Value *B);
353 /// \brief Perform LICM and CSE on the newly generated gather sequences.
354 void optimizeGatherSequence();
358 /// \returns the cost of the vectorizable entry.
359 int getEntryCost(TreeEntry *E);
361 /// This is the recursive part of buildTree.
362 void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth);
364 /// Vectorize a single entry in the tree.
365 Value *vectorizeTree(TreeEntry *E);
367 /// Vectorize a single entry in the tree, starting in \p VL.
368 Value *vectorizeTree(ArrayRef<Value *> VL);
370 /// \returns the pointer to the vectorized value if \p VL is already
371 /// vectorized, or NULL. They may happen in cycles.
372 Value *alreadyVectorized(ArrayRef<Value *> VL) const;
374 /// \brief Take the pointer operand from the Load/Store instruction.
375 /// \returns NULL if this is not a valid Load/Store instruction.
376 static Value *getPointerOperand(Value *I);
378 /// \brief Take the address space operand from the Load/Store instruction.
379 /// \returns -1 if this is not a valid Load/Store instruction.
380 static unsigned getAddressSpaceOperand(Value *I);
382 /// \returns the scalarization cost for this type. Scalarization in this
383 /// context means the creation of vectors from a group of scalars.
384 int getGatherCost(Type *Ty);
386 /// \returns the scalarization cost for this list of values. Assuming that
387 /// this subtree gets vectorized, we may need to extract the values from the
388 /// roots. This method calculates the cost of extracting the values.
389 int getGatherCost(ArrayRef<Value *> VL);
391 /// \returns the AA location that is being access by the instruction.
392 AliasAnalysis::Location getLocation(Instruction *I);
394 /// \brief Checks if it is possible to sink an instruction from
395 /// \p Src to \p Dst.
396 /// \returns the pointer to the barrier instruction if we can't sink.
397 Value *getSinkBarrier(Instruction *Src, Instruction *Dst);
399 /// \returns the index of the last instruction in the BB from \p VL.
400 int getLastIndex(ArrayRef<Value *> VL);
402 /// \returns the Instruction in the bundle \p VL.
403 Instruction *getLastInstruction(ArrayRef<Value *> VL);
405 /// \brief Set the Builder insert point to one after the last instruction in
407 void setInsertPointAfterBundle(ArrayRef<Value *> VL);
409 /// \returns a vector from a collection of scalars in \p VL.
410 Value *Gather(ArrayRef<Value *> VL, VectorType *Ty);
412 /// \returns whether the VectorizableTree is fully vectoriable and will
413 /// be beneficial even the tree height is tiny.
414 bool isFullyVectorizableTinyTree();
417 TreeEntry() : Scalars(), VectorizedValue(0), LastScalarIndex(0),
420 /// \returns true if the scalars in VL are equal to this entry.
421 bool isSame(ArrayRef<Value *> VL) const {
422 assert(VL.size() == Scalars.size() && "Invalid size");
423 return std::equal(VL.begin(), VL.end(), Scalars.begin());
426 /// A vector of scalars.
429 /// The Scalars are vectorized into this value. It is initialized to Null.
430 Value *VectorizedValue;
432 /// The index in the basic block of the last scalar.
435 /// Do we need to gather this sequence ?
439 /// Create a new VectorizableTree entry.
440 TreeEntry *newTreeEntry(ArrayRef<Value *> VL, bool Vectorized) {
441 VectorizableTree.push_back(TreeEntry());
442 int idx = VectorizableTree.size() - 1;
443 TreeEntry *Last = &VectorizableTree[idx];
444 Last->Scalars.insert(Last->Scalars.begin(), VL.begin(), VL.end());
445 Last->NeedToGather = !Vectorized;
447 Last->LastScalarIndex = getLastIndex(VL);
448 for (int i = 0, e = VL.size(); i != e; ++i) {
449 assert(!ScalarToTreeEntry.count(VL[i]) && "Scalar already in tree!");
450 ScalarToTreeEntry[VL[i]] = idx;
453 Last->LastScalarIndex = 0;
454 MustGather.insert(VL.begin(), VL.end());
459 /// -- Vectorization State --
460 /// Holds all of the tree entries.
461 std::vector<TreeEntry> VectorizableTree;
463 /// Maps a specific scalar to its tree entry.
464 SmallDenseMap<Value*, int> ScalarToTreeEntry;
466 /// A list of scalars that we found that we need to keep as scalars.
469 /// This POD struct describes one external user in the vectorized tree.
470 struct ExternalUser {
471 ExternalUser (Value *S, llvm::User *U, int L) :
472 Scalar(S), User(U), Lane(L){};
473 // Which scalar in our function.
475 // Which user that uses the scalar.
477 // Which lane does the scalar belong to.
480 typedef SmallVector<ExternalUser, 16> UserList;
482 /// A list of values that need to extracted out of the tree.
483 /// This list holds pairs of (Internal Scalar : External User).
484 UserList ExternalUses;
486 /// A list of instructions to ignore while sinking
487 /// memory instructions. This map must be reset between runs of getCost.
488 ValueSet MemBarrierIgnoreList;
490 /// Holds all of the instructions that we gathered.
491 SetVector<Instruction *> GatherSeq;
493 /// Numbers instructions in different blocks.
494 DenseMap<BasicBlock *, BlockNumbering> BlocksNumbers;
496 /// Reduction operators.
499 // Analysis and block reference.
503 TargetTransformInfo *TTI;
507 /// Instruction builder to construct the vectorized tree.
511 void BoUpSLP::buildTree(ArrayRef<Value *> Roots, ValueSet *Rdx) {
514 if (!getSameType(Roots))
516 buildTree_rec(Roots, 0);
518 // Collect the values that we need to extract from the tree.
519 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
520 TreeEntry *Entry = &VectorizableTree[EIdx];
523 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
524 Value *Scalar = Entry->Scalars[Lane];
526 // No need to handle users of gathered values.
527 if (Entry->NeedToGather)
530 for (Value::use_iterator User = Scalar->use_begin(),
531 UE = Scalar->use_end(); User != UE; ++User) {
532 DEBUG(dbgs() << "SLP: Checking user:" << **User << ".\n");
534 bool Gathered = MustGather.count(*User);
536 // Skip in-tree scalars that become vectors.
537 if (ScalarToTreeEntry.count(*User) && !Gathered) {
538 DEBUG(dbgs() << "SLP: \tInternal user will be removed:" <<
540 int Idx = ScalarToTreeEntry[*User]; (void) Idx;
541 assert(!VectorizableTree[Idx].NeedToGather && "Bad state");
544 Instruction *UserInst = dyn_cast<Instruction>(*User);
548 // Ignore uses that are part of the reduction.
549 if (Rdx && std::find(Rdx->begin(), Rdx->end(), UserInst) != Rdx->end())
552 DEBUG(dbgs() << "SLP: Need to extract:" << **User << " from lane " <<
553 Lane << " from " << *Scalar << ".\n");
554 ExternalUses.push_back(ExternalUser(Scalar, *User, Lane));
561 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth) {
562 bool SameTy = getSameType(VL); (void)SameTy;
563 assert(SameTy && "Invalid types!");
565 if (Depth == RecursionMaxDepth) {
566 DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
567 newTreeEntry(VL, false);
571 // Don't handle vectors.
572 if (VL[0]->getType()->isVectorTy()) {
573 DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
574 newTreeEntry(VL, false);
578 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
579 if (SI->getValueOperand()->getType()->isVectorTy()) {
580 DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
581 newTreeEntry(VL, false);
585 // If all of the operands are identical or constant we have a simple solution.
586 if (allConstant(VL) || isSplat(VL) || !getSameBlock(VL) ||
587 !getSameOpcode(VL)) {
588 DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
589 newTreeEntry(VL, false);
593 // We now know that this is a vector of instructions of the same type from
596 // Check if this is a duplicate of another entry.
597 if (ScalarToTreeEntry.count(VL[0])) {
598 int Idx = ScalarToTreeEntry[VL[0]];
599 TreeEntry *E = &VectorizableTree[Idx];
600 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
601 DEBUG(dbgs() << "SLP: \tChecking bundle: " << *VL[i] << ".\n");
602 if (E->Scalars[i] != VL[i]) {
603 DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
604 newTreeEntry(VL, false);
608 DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *VL[0] << ".\n");
612 // Check that none of the instructions in the bundle are already in the tree.
613 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
614 if (ScalarToTreeEntry.count(VL[i])) {
615 DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
616 ") is already in tree.\n");
617 newTreeEntry(VL, false);
622 // If any of the scalars appears in the table OR it is marked as a value that
623 // needs to stat scalar then we need to gather the scalars.
624 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
625 if (ScalarToTreeEntry.count(VL[i]) || MustGather.count(VL[i])) {
626 DEBUG(dbgs() << "SLP: Gathering due to gathered scalar. \n");
627 newTreeEntry(VL, false);
632 // Check that all of the users of the scalars that we want to vectorize are
634 Instruction *VL0 = cast<Instruction>(VL[0]);
635 int MyLastIndex = getLastIndex(VL);
636 BasicBlock *BB = cast<Instruction>(VL0)->getParent();
638 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
639 Instruction *Scalar = cast<Instruction>(VL[i]);
640 DEBUG(dbgs() << "SLP: Checking users of " << *Scalar << ". \n");
641 for (Value::use_iterator U = Scalar->use_begin(), UE = Scalar->use_end();
643 DEBUG(dbgs() << "SLP: \tUser " << **U << ". \n");
644 Instruction *User = dyn_cast<Instruction>(*U);
646 DEBUG(dbgs() << "SLP: Gathering due unknown user. \n");
647 newTreeEntry(VL, false);
651 // We don't care if the user is in a different basic block.
652 BasicBlock *UserBlock = User->getParent();
653 if (UserBlock != BB) {
654 DEBUG(dbgs() << "SLP: User from a different basic block "
659 // If this is a PHINode within this basic block then we can place the
660 // extract wherever we want.
661 if (isa<PHINode>(*User)) {
662 DEBUG(dbgs() << "SLP: \tWe can schedule PHIs:" << *User << ". \n");
666 // Check if this is a safe in-tree user.
667 if (ScalarToTreeEntry.count(User)) {
668 int Idx = ScalarToTreeEntry[User];
669 int VecLocation = VectorizableTree[Idx].LastScalarIndex;
670 if (VecLocation <= MyLastIndex) {
671 DEBUG(dbgs() << "SLP: Gathering due to unschedulable vector. \n");
672 newTreeEntry(VL, false);
675 DEBUG(dbgs() << "SLP: In-tree user (" << *User << ") at #" <<
676 VecLocation << " vector value (" << *Scalar << ") at #"
677 << MyLastIndex << ".\n");
681 // This user is part of the reduction.
682 if (RdxOps && RdxOps->count(User))
685 // Make sure that we can schedule this unknown user.
686 BlockNumbering &BN = BlocksNumbers[BB];
687 int UserIndex = BN.getIndex(User);
688 if (UserIndex < MyLastIndex) {
690 DEBUG(dbgs() << "SLP: Can't schedule extractelement for "
692 newTreeEntry(VL, false);
698 // Check that every instructions appears once in this bundle.
699 for (unsigned i = 0, e = VL.size(); i < e; ++i)
700 for (unsigned j = i+1; j < e; ++j)
701 if (VL[i] == VL[j]) {
702 DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
703 newTreeEntry(VL, false);
707 // Check that instructions in this bundle don't reference other instructions.
708 // The runtime of this check is O(N * N-1 * uses(N)) and a typical N is 4.
709 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
710 for (Value::use_iterator U = VL[i]->use_begin(), UE = VL[i]->use_end();
712 for (unsigned j = 0; j < e; ++j) {
713 if (i != j && *U == VL[j]) {
714 DEBUG(dbgs() << "SLP: Intra-bundle dependencies!" << **U << ". \n");
715 newTreeEntry(VL, false);
722 DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
724 unsigned Opcode = getSameOpcode(VL);
726 // Check if it is safe to sink the loads or the stores.
727 if (Opcode == Instruction::Load || Opcode == Instruction::Store) {
728 Instruction *Last = getLastInstruction(VL);
730 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
733 Value *Barrier = getSinkBarrier(cast<Instruction>(VL[i]), Last);
735 DEBUG(dbgs() << "SLP: Can't sink " << *VL[i] << "\n down to " << *Last
736 << "\n because of " << *Barrier << ". Gathering.\n");
737 newTreeEntry(VL, false);
744 case Instruction::PHI: {
745 PHINode *PH = dyn_cast<PHINode>(VL0);
747 // Check for terminator values (e.g. invoke).
748 for (unsigned j = 0; j < VL.size(); ++j)
749 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
750 TerminatorInst *Term = dyn_cast<TerminatorInst>(cast<PHINode>(VL[j])->getIncomingValue(i));
752 DEBUG(dbgs() << "SLP: Need to swizzle PHINodes (TerminatorInst use).\n");
753 newTreeEntry(VL, false);
758 newTreeEntry(VL, true);
759 DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
761 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
763 // Prepare the operand vector.
764 for (unsigned j = 0; j < VL.size(); ++j)
765 Operands.push_back(cast<PHINode>(VL[j])->getIncomingValue(i));
767 buildTree_rec(Operands, Depth + 1);
771 case Instruction::ExtractElement: {
772 bool Reuse = CanReuseExtract(VL);
774 DEBUG(dbgs() << "SLP: Reusing extract sequence.\n");
776 newTreeEntry(VL, Reuse);
779 case Instruction::Load: {
780 // Check if the loads are consecutive or of we need to swizzle them.
781 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i) {
782 LoadInst *L = cast<LoadInst>(VL[i]);
783 if (!L->isSimple() || !isConsecutiveAccess(VL[i], VL[i + 1])) {
784 newTreeEntry(VL, false);
785 DEBUG(dbgs() << "SLP: Need to swizzle loads.\n");
789 newTreeEntry(VL, true);
790 DEBUG(dbgs() << "SLP: added a vector of loads.\n");
793 case Instruction::ZExt:
794 case Instruction::SExt:
795 case Instruction::FPToUI:
796 case Instruction::FPToSI:
797 case Instruction::FPExt:
798 case Instruction::PtrToInt:
799 case Instruction::IntToPtr:
800 case Instruction::SIToFP:
801 case Instruction::UIToFP:
802 case Instruction::Trunc:
803 case Instruction::FPTrunc:
804 case Instruction::BitCast: {
805 Type *SrcTy = VL0->getOperand(0)->getType();
806 for (unsigned i = 0; i < VL.size(); ++i) {
807 Type *Ty = cast<Instruction>(VL[i])->getOperand(0)->getType();
808 if (Ty != SrcTy || Ty->isAggregateType() || Ty->isVectorTy()) {
809 newTreeEntry(VL, false);
810 DEBUG(dbgs() << "SLP: Gathering casts with different src types.\n");
814 newTreeEntry(VL, true);
815 DEBUG(dbgs() << "SLP: added a vector of casts.\n");
817 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
819 // Prepare the operand vector.
820 for (unsigned j = 0; j < VL.size(); ++j)
821 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
823 buildTree_rec(Operands, Depth+1);
827 case Instruction::ICmp:
828 case Instruction::FCmp: {
829 // Check that all of the compares have the same predicate.
830 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
831 Type *ComparedTy = cast<Instruction>(VL[0])->getOperand(0)->getType();
832 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
833 CmpInst *Cmp = cast<CmpInst>(VL[i]);
834 if (Cmp->getPredicate() != P0 ||
835 Cmp->getOperand(0)->getType() != ComparedTy) {
836 newTreeEntry(VL, false);
837 DEBUG(dbgs() << "SLP: Gathering cmp with different predicate.\n");
842 newTreeEntry(VL, true);
843 DEBUG(dbgs() << "SLP: added a vector of compares.\n");
845 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
847 // Prepare the operand vector.
848 for (unsigned j = 0; j < VL.size(); ++j)
849 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
851 buildTree_rec(Operands, Depth+1);
855 case Instruction::Select:
856 case Instruction::Add:
857 case Instruction::FAdd:
858 case Instruction::Sub:
859 case Instruction::FSub:
860 case Instruction::Mul:
861 case Instruction::FMul:
862 case Instruction::UDiv:
863 case Instruction::SDiv:
864 case Instruction::FDiv:
865 case Instruction::URem:
866 case Instruction::SRem:
867 case Instruction::FRem:
868 case Instruction::Shl:
869 case Instruction::LShr:
870 case Instruction::AShr:
871 case Instruction::And:
872 case Instruction::Or:
873 case Instruction::Xor: {
874 newTreeEntry(VL, true);
875 DEBUG(dbgs() << "SLP: added a vector of bin op.\n");
877 // Sort operands of the instructions so that each side is more likely to
878 // have the same opcode.
879 if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
880 ValueList Left, Right;
881 reorderInputsAccordingToOpcode(VL, Left, Right);
882 buildTree_rec(Left, Depth + 1);
883 buildTree_rec(Right, Depth + 1);
887 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
889 // Prepare the operand vector.
890 for (unsigned j = 0; j < VL.size(); ++j)
891 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
893 buildTree_rec(Operands, Depth+1);
897 case Instruction::Store: {
898 // Check if the stores are consecutive or of we need to swizzle them.
899 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
900 if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
901 newTreeEntry(VL, false);
902 DEBUG(dbgs() << "SLP: Non consecutive store.\n");
906 newTreeEntry(VL, true);
907 DEBUG(dbgs() << "SLP: added a vector of stores.\n");
910 for (unsigned j = 0; j < VL.size(); ++j)
911 Operands.push_back(cast<Instruction>(VL[j])->getOperand(0));
913 // We can ignore these values because we are sinking them down.
914 MemBarrierIgnoreList.insert(VL.begin(), VL.end());
915 buildTree_rec(Operands, Depth + 1);
919 newTreeEntry(VL, false);
920 DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
925 int BoUpSLP::getEntryCost(TreeEntry *E) {
926 ArrayRef<Value*> VL = E->Scalars;
928 Type *ScalarTy = VL[0]->getType();
929 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
930 ScalarTy = SI->getValueOperand()->getType();
931 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
933 if (E->NeedToGather) {
937 return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
939 return getGatherCost(E->Scalars);
942 assert(getSameOpcode(VL) && getSameType(VL) && getSameBlock(VL) &&
944 Instruction *VL0 = cast<Instruction>(VL[0]);
945 unsigned Opcode = VL0->getOpcode();
947 case Instruction::PHI: {
950 case Instruction::ExtractElement: {
951 if (CanReuseExtract(VL))
953 return getGatherCost(VecTy);
955 case Instruction::ZExt:
956 case Instruction::SExt:
957 case Instruction::FPToUI:
958 case Instruction::FPToSI:
959 case Instruction::FPExt:
960 case Instruction::PtrToInt:
961 case Instruction::IntToPtr:
962 case Instruction::SIToFP:
963 case Instruction::UIToFP:
964 case Instruction::Trunc:
965 case Instruction::FPTrunc:
966 case Instruction::BitCast: {
967 Type *SrcTy = VL0->getOperand(0)->getType();
969 // Calculate the cost of this instruction.
970 int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(),
971 VL0->getType(), SrcTy);
973 VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
974 int VecCost = TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy);
975 return VecCost - ScalarCost;
977 case Instruction::FCmp:
978 case Instruction::ICmp:
979 case Instruction::Select:
980 case Instruction::Add:
981 case Instruction::FAdd:
982 case Instruction::Sub:
983 case Instruction::FSub:
984 case Instruction::Mul:
985 case Instruction::FMul:
986 case Instruction::UDiv:
987 case Instruction::SDiv:
988 case Instruction::FDiv:
989 case Instruction::URem:
990 case Instruction::SRem:
991 case Instruction::FRem:
992 case Instruction::Shl:
993 case Instruction::LShr:
994 case Instruction::AShr:
995 case Instruction::And:
996 case Instruction::Or:
997 case Instruction::Xor: {
998 // Calculate the cost of this instruction.
1001 if (Opcode == Instruction::FCmp || Opcode == Instruction::ICmp ||
1002 Opcode == Instruction::Select) {
1003 VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
1004 ScalarCost = VecTy->getNumElements() *
1005 TTI->getCmpSelInstrCost(Opcode, ScalarTy, Builder.getInt1Ty());
1006 VecCost = TTI->getCmpSelInstrCost(Opcode, VecTy, MaskTy);
1008 // Certain instructions can be cheaper to vectorize if they have a
1009 // constant second vector operand.
1010 TargetTransformInfo::OperandValueKind Op1VK =
1011 TargetTransformInfo::OK_AnyValue;
1012 TargetTransformInfo::OperandValueKind Op2VK =
1013 TargetTransformInfo::OK_UniformConstantValue;
1015 // Check whether all second operands are constant.
1016 for (unsigned i = 0; i < VL.size(); ++i)
1017 if (!isa<ConstantInt>(cast<Instruction>(VL[i])->getOperand(1))) {
1018 Op2VK = TargetTransformInfo::OK_AnyValue;
1023 VecTy->getNumElements() *
1024 TTI->getArithmeticInstrCost(Opcode, ScalarTy, Op1VK, Op2VK);
1025 VecCost = TTI->getArithmeticInstrCost(Opcode, VecTy, Op1VK, Op2VK);
1027 return VecCost - ScalarCost;
1029 case Instruction::Load: {
1030 // Cost of wide load - cost of scalar loads.
1031 int ScalarLdCost = VecTy->getNumElements() *
1032 TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
1033 int VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, 1, 0);
1034 return VecLdCost - ScalarLdCost;
1036 case Instruction::Store: {
1037 // We know that we can merge the stores. Calculate the cost.
1038 int ScalarStCost = VecTy->getNumElements() *
1039 TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
1040 int VecStCost = TTI->getMemoryOpCost(Instruction::Store, VecTy, 1, 0);
1041 return VecStCost - ScalarStCost;
1044 llvm_unreachable("Unknown instruction");
1048 bool BoUpSLP::isFullyVectorizableTinyTree() {
1049 DEBUG(dbgs() << "SLP: Check whether the tree with height " <<
1050 VectorizableTree.size() << " is fully vectorizable .\n");
1052 // We only handle trees of height 2.
1053 if (VectorizableTree.size() != 2)
1056 // Gathering cost would be too much for tiny trees.
1057 if (VectorizableTree[0].NeedToGather || VectorizableTree[1].NeedToGather)
1063 int BoUpSLP::getTreeCost() {
1065 DEBUG(dbgs() << "SLP: Calculating cost for tree of size " <<
1066 VectorizableTree.size() << ".\n");
1068 // We only vectorize tiny trees if it is fully vectorizable.
1069 if (VectorizableTree.size() < 3 && !isFullyVectorizableTinyTree()) {
1070 if (!VectorizableTree.size()) {
1071 assert(!ExternalUses.size() && "We should not have any external users");
1076 unsigned BundleWidth = VectorizableTree[0].Scalars.size();
1078 for (unsigned i = 0, e = VectorizableTree.size(); i != e; ++i) {
1079 int C = getEntryCost(&VectorizableTree[i]);
1080 DEBUG(dbgs() << "SLP: Adding cost " << C << " for bundle that starts with "
1081 << *VectorizableTree[i].Scalars[0] << " .\n");
1085 int ExtractCost = 0;
1086 for (UserList::iterator I = ExternalUses.begin(), E = ExternalUses.end();
1089 VectorType *VecTy = VectorType::get(I->Scalar->getType(), BundleWidth);
1090 ExtractCost += TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy,
1095 DEBUG(dbgs() << "SLP: Total Cost " << Cost + ExtractCost<< ".\n");
1096 return Cost + ExtractCost;
1099 int BoUpSLP::getGatherCost(Type *Ty) {
1101 for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
1102 Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
1106 int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) {
1107 // Find the type of the operands in VL.
1108 Type *ScalarTy = VL[0]->getType();
1109 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1110 ScalarTy = SI->getValueOperand()->getType();
1111 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1112 // Find the cost of inserting/extracting values from the vector.
1113 return getGatherCost(VecTy);
1116 AliasAnalysis::Location BoUpSLP::getLocation(Instruction *I) {
1117 if (StoreInst *SI = dyn_cast<StoreInst>(I))
1118 return AA->getLocation(SI);
1119 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1120 return AA->getLocation(LI);
1121 return AliasAnalysis::Location();
1124 Value *BoUpSLP::getPointerOperand(Value *I) {
1125 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1126 return LI->getPointerOperand();
1127 if (StoreInst *SI = dyn_cast<StoreInst>(I))
1128 return SI->getPointerOperand();
1132 unsigned BoUpSLP::getAddressSpaceOperand(Value *I) {
1133 if (LoadInst *L = dyn_cast<LoadInst>(I))
1134 return L->getPointerAddressSpace();
1135 if (StoreInst *S = dyn_cast<StoreInst>(I))
1136 return S->getPointerAddressSpace();
1140 bool BoUpSLP::isConsecutiveAccess(Value *A, Value *B) {
1141 Value *PtrA = getPointerOperand(A);
1142 Value *PtrB = getPointerOperand(B);
1143 unsigned ASA = getAddressSpaceOperand(A);
1144 unsigned ASB = getAddressSpaceOperand(B);
1146 // Check that the address spaces match and that the pointers are valid.
1147 if (!PtrA || !PtrB || (ASA != ASB))
1150 // Make sure that A and B are different pointers of the same type.
1151 if (PtrA == PtrB || PtrA->getType() != PtrB->getType())
1154 unsigned PtrBitWidth = DL->getPointerSizeInBits(ASA);
1155 Type *Ty = cast<PointerType>(PtrA->getType())->getElementType();
1156 APInt Size(PtrBitWidth, DL->getTypeStoreSize(Ty));
1158 APInt OffsetA(PtrBitWidth, 0), OffsetB(PtrBitWidth, 0);
1159 PtrA = PtrA->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetA);
1160 PtrB = PtrB->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetB);
1162 APInt OffsetDelta = OffsetB - OffsetA;
1164 // Check if they are based on the same pointer. That makes the offsets
1167 return OffsetDelta == Size;
1169 // Compute the necessary base pointer delta to have the necessary final delta
1170 // equal to the size.
1171 APInt BaseDelta = Size - OffsetDelta;
1173 // Otherwise compute the distance with SCEV between the base pointers.
1174 const SCEV *PtrSCEVA = SE->getSCEV(PtrA);
1175 const SCEV *PtrSCEVB = SE->getSCEV(PtrB);
1176 const SCEV *C = SE->getConstant(BaseDelta);
1177 const SCEV *X = SE->getAddExpr(PtrSCEVA, C);
1178 return X == PtrSCEVB;
1181 Value *BoUpSLP::getSinkBarrier(Instruction *Src, Instruction *Dst) {
1182 assert(Src->getParent() == Dst->getParent() && "Not the same BB");
1183 BasicBlock::iterator I = Src, E = Dst;
1184 /// Scan all of the instruction from SRC to DST and check if
1185 /// the source may alias.
1186 for (++I; I != E; ++I) {
1187 // Ignore store instructions that are marked as 'ignore'.
1188 if (MemBarrierIgnoreList.count(I))
1190 if (Src->mayWriteToMemory()) /* Write */ {
1191 if (!I->mayReadOrWriteMemory())
1194 if (!I->mayWriteToMemory())
1197 AliasAnalysis::Location A = getLocation(&*I);
1198 AliasAnalysis::Location B = getLocation(Src);
1200 if (!A.Ptr || !B.Ptr || AA->alias(A, B))
1206 int BoUpSLP::getLastIndex(ArrayRef<Value *> VL) {
1207 BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
1208 assert(BB == getSameBlock(VL) && BlocksNumbers.count(BB) && "Invalid block");
1209 BlockNumbering &BN = BlocksNumbers[BB];
1211 int MaxIdx = BN.getIndex(BB->getFirstNonPHI());
1212 for (unsigned i = 0, e = VL.size(); i < e; ++i)
1213 MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
1217 Instruction *BoUpSLP::getLastInstruction(ArrayRef<Value *> VL) {
1218 BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
1219 assert(BB == getSameBlock(VL) && BlocksNumbers.count(BB) && "Invalid block");
1220 BlockNumbering &BN = BlocksNumbers[BB];
1222 int MaxIdx = BN.getIndex(cast<Instruction>(VL[0]));
1223 for (unsigned i = 1, e = VL.size(); i < e; ++i)
1224 MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
1225 Instruction *I = BN.getInstruction(MaxIdx);
1226 assert(I && "bad location");
1230 void BoUpSLP::setInsertPointAfterBundle(ArrayRef<Value *> VL) {
1231 Instruction *VL0 = cast<Instruction>(VL[0]);
1232 Instruction *LastInst = getLastInstruction(VL);
1233 BasicBlock::iterator NextInst = LastInst;
1235 Builder.SetInsertPoint(VL0->getParent(), NextInst);
1236 Builder.SetCurrentDebugLocation(VL0->getDebugLoc());
1239 Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
1240 Value *Vec = UndefValue::get(Ty);
1241 // Generate the 'InsertElement' instruction.
1242 for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
1243 Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
1244 if (Instruction *Insrt = dyn_cast<Instruction>(Vec)) {
1245 GatherSeq.insert(Insrt);
1247 // Add to our 'need-to-extract' list.
1248 if (ScalarToTreeEntry.count(VL[i])) {
1249 int Idx = ScalarToTreeEntry[VL[i]];
1250 TreeEntry *E = &VectorizableTree[Idx];
1251 // Find which lane we need to extract.
1253 for (unsigned Lane = 0, LE = VL.size(); Lane != LE; ++Lane) {
1254 // Is this the lane of the scalar that we are looking for ?
1255 if (E->Scalars[Lane] == VL[i]) {
1260 assert(FoundLane >= 0 && "Could not find the correct lane");
1261 ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
1269 Value *BoUpSLP::alreadyVectorized(ArrayRef<Value *> VL) const {
1270 SmallDenseMap<Value*, int>::const_iterator Entry
1271 = ScalarToTreeEntry.find(VL[0]);
1272 if (Entry != ScalarToTreeEntry.end()) {
1273 int Idx = Entry->second;
1274 const TreeEntry *En = &VectorizableTree[Idx];
1275 if (En->isSame(VL) && En->VectorizedValue)
1276 return En->VectorizedValue;
1281 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
1282 if (ScalarToTreeEntry.count(VL[0])) {
1283 int Idx = ScalarToTreeEntry[VL[0]];
1284 TreeEntry *E = &VectorizableTree[Idx];
1286 return vectorizeTree(E);
1289 Type *ScalarTy = VL[0]->getType();
1290 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1291 ScalarTy = SI->getValueOperand()->getType();
1292 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1294 return Gather(VL, VecTy);
1297 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
1298 IRBuilder<>::InsertPointGuard Guard(Builder);
1300 if (E->VectorizedValue) {
1301 DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
1302 return E->VectorizedValue;
1305 Instruction *VL0 = cast<Instruction>(E->Scalars[0]);
1306 Type *ScalarTy = VL0->getType();
1307 if (StoreInst *SI = dyn_cast<StoreInst>(VL0))
1308 ScalarTy = SI->getValueOperand()->getType();
1309 VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size());
1311 if (E->NeedToGather) {
1312 setInsertPointAfterBundle(E->Scalars);
1313 return Gather(E->Scalars, VecTy);
1316 unsigned Opcode = VL0->getOpcode();
1317 assert(Opcode == getSameOpcode(E->Scalars) && "Invalid opcode");
1320 case Instruction::PHI: {
1321 PHINode *PH = dyn_cast<PHINode>(VL0);
1322 Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
1323 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1324 PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
1325 E->VectorizedValue = NewPhi;
1327 // PHINodes may have multiple entries from the same block. We want to
1328 // visit every block once.
1329 SmallSet<BasicBlock*, 4> VisitedBBs;
1331 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1333 BasicBlock *IBB = PH->getIncomingBlock(i);
1335 if (!VisitedBBs.insert(IBB)) {
1336 NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
1340 // Prepare the operand vector.
1341 for (unsigned j = 0; j < E->Scalars.size(); ++j)
1342 Operands.push_back(cast<PHINode>(E->Scalars[j])->
1343 getIncomingValueForBlock(IBB));
1345 Builder.SetInsertPoint(IBB->getTerminator());
1346 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1347 Value *Vec = vectorizeTree(Operands);
1348 NewPhi->addIncoming(Vec, IBB);
1351 assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
1352 "Invalid number of incoming values");
1356 case Instruction::ExtractElement: {
1357 if (CanReuseExtract(E->Scalars)) {
1358 Value *V = VL0->getOperand(0);
1359 E->VectorizedValue = V;
1362 return Gather(E->Scalars, VecTy);
1364 case Instruction::ZExt:
1365 case Instruction::SExt:
1366 case Instruction::FPToUI:
1367 case Instruction::FPToSI:
1368 case Instruction::FPExt:
1369 case Instruction::PtrToInt:
1370 case Instruction::IntToPtr:
1371 case Instruction::SIToFP:
1372 case Instruction::UIToFP:
1373 case Instruction::Trunc:
1374 case Instruction::FPTrunc:
1375 case Instruction::BitCast: {
1377 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1378 INVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1380 setInsertPointAfterBundle(E->Scalars);
1382 Value *InVec = vectorizeTree(INVL);
1384 if (Value *V = alreadyVectorized(E->Scalars))
1387 CastInst *CI = dyn_cast<CastInst>(VL0);
1388 Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
1389 E->VectorizedValue = V;
1392 case Instruction::FCmp:
1393 case Instruction::ICmp: {
1394 ValueList LHSV, RHSV;
1395 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1396 LHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1397 RHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1400 setInsertPointAfterBundle(E->Scalars);
1402 Value *L = vectorizeTree(LHSV);
1403 Value *R = vectorizeTree(RHSV);
1405 if (Value *V = alreadyVectorized(E->Scalars))
1408 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
1410 if (Opcode == Instruction::FCmp)
1411 V = Builder.CreateFCmp(P0, L, R);
1413 V = Builder.CreateICmp(P0, L, R);
1415 E->VectorizedValue = V;
1418 case Instruction::Select: {
1419 ValueList TrueVec, FalseVec, CondVec;
1420 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1421 CondVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1422 TrueVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1423 FalseVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(2));
1426 setInsertPointAfterBundle(E->Scalars);
1428 Value *Cond = vectorizeTree(CondVec);
1429 Value *True = vectorizeTree(TrueVec);
1430 Value *False = vectorizeTree(FalseVec);
1432 if (Value *V = alreadyVectorized(E->Scalars))
1435 Value *V = Builder.CreateSelect(Cond, True, False);
1436 E->VectorizedValue = V;
1439 case Instruction::Add:
1440 case Instruction::FAdd:
1441 case Instruction::Sub:
1442 case Instruction::FSub:
1443 case Instruction::Mul:
1444 case Instruction::FMul:
1445 case Instruction::UDiv:
1446 case Instruction::SDiv:
1447 case Instruction::FDiv:
1448 case Instruction::URem:
1449 case Instruction::SRem:
1450 case Instruction::FRem:
1451 case Instruction::Shl:
1452 case Instruction::LShr:
1453 case Instruction::AShr:
1454 case Instruction::And:
1455 case Instruction::Or:
1456 case Instruction::Xor: {
1457 ValueList LHSVL, RHSVL;
1458 if (isa<BinaryOperator>(VL0) && VL0->isCommutative())
1459 reorderInputsAccordingToOpcode(E->Scalars, LHSVL, RHSVL);
1461 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1462 LHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1463 RHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1466 setInsertPointAfterBundle(E->Scalars);
1468 Value *LHS = vectorizeTree(LHSVL);
1469 Value *RHS = vectorizeTree(RHSVL);
1471 if (LHS == RHS && isa<Instruction>(LHS)) {
1472 assert((VL0->getOperand(0) == VL0->getOperand(1)) && "Invalid order");
1475 if (Value *V = alreadyVectorized(E->Scalars))
1478 BinaryOperator *BinOp = cast<BinaryOperator>(VL0);
1479 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), LHS, RHS);
1480 E->VectorizedValue = V;
1483 case Instruction::Load: {
1484 // Loads are inserted at the head of the tree because we don't want to
1485 // sink them all the way down past store instructions.
1486 setInsertPointAfterBundle(E->Scalars);
1488 LoadInst *LI = cast<LoadInst>(VL0);
1489 unsigned AS = LI->getPointerAddressSpace();
1491 Value *VecPtr = Builder.CreateBitCast(LI->getPointerOperand(),
1492 VecTy->getPointerTo(AS));
1493 unsigned Alignment = LI->getAlignment();
1494 LI = Builder.CreateLoad(VecPtr);
1495 LI->setAlignment(Alignment);
1496 E->VectorizedValue = LI;
1499 case Instruction::Store: {
1500 StoreInst *SI = cast<StoreInst>(VL0);
1501 unsigned Alignment = SI->getAlignment();
1502 unsigned AS = SI->getPointerAddressSpace();
1505 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1506 ValueOp.push_back(cast<StoreInst>(E->Scalars[i])->getValueOperand());
1508 setInsertPointAfterBundle(E->Scalars);
1510 Value *VecValue = vectorizeTree(ValueOp);
1511 Value *VecPtr = Builder.CreateBitCast(SI->getPointerOperand(),
1512 VecTy->getPointerTo(AS));
1513 StoreInst *S = Builder.CreateStore(VecValue, VecPtr);
1514 S->setAlignment(Alignment);
1515 E->VectorizedValue = S;
1519 llvm_unreachable("unknown inst");
1524 Value *BoUpSLP::vectorizeTree() {
1525 Builder.SetInsertPoint(F->getEntryBlock().begin());
1526 vectorizeTree(&VectorizableTree[0]);
1528 DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() << " values .\n");
1530 // Extract all of the elements with the external uses.
1531 for (UserList::iterator it = ExternalUses.begin(), e = ExternalUses.end();
1533 Value *Scalar = it->Scalar;
1534 llvm::User *User = it->User;
1536 // Skip users that we already RAUW. This happens when one instruction
1537 // has multiple uses of the same value.
1538 if (std::find(Scalar->use_begin(), Scalar->use_end(), User) ==
1541 assert(ScalarToTreeEntry.count(Scalar) && "Invalid scalar");
1543 int Idx = ScalarToTreeEntry[Scalar];
1544 TreeEntry *E = &VectorizableTree[Idx];
1545 assert(!E->NeedToGather && "Extracting from a gather list");
1547 Value *Vec = E->VectorizedValue;
1548 assert(Vec && "Can't find vectorizable value");
1550 Value *Lane = Builder.getInt32(it->Lane);
1551 // Generate extracts for out-of-tree users.
1552 // Find the insertion point for the extractelement lane.
1553 if (PHINode *PN = dyn_cast<PHINode>(Vec)) {
1554 Builder.SetInsertPoint(PN->getParent()->getFirstInsertionPt());
1555 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1556 User->replaceUsesOfWith(Scalar, Ex);
1557 } else if (isa<Instruction>(Vec)){
1558 if (PHINode *PH = dyn_cast<PHINode>(User)) {
1559 for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
1560 if (PH->getIncomingValue(i) == Scalar) {
1561 Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
1562 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1563 PH->setOperand(i, Ex);
1567 Builder.SetInsertPoint(cast<Instruction>(User));
1568 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1569 User->replaceUsesOfWith(Scalar, Ex);
1572 Builder.SetInsertPoint(F->getEntryBlock().begin());
1573 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1574 User->replaceUsesOfWith(Scalar, Ex);
1577 DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
1580 // For each vectorized value:
1581 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
1582 TreeEntry *Entry = &VectorizableTree[EIdx];
1585 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
1586 Value *Scalar = Entry->Scalars[Lane];
1588 // No need to handle users of gathered values.
1589 if (Entry->NeedToGather)
1592 assert(Entry->VectorizedValue && "Can't find vectorizable value");
1594 Type *Ty = Scalar->getType();
1595 if (!Ty->isVoidTy()) {
1596 for (Value::use_iterator User = Scalar->use_begin(),
1597 UE = Scalar->use_end(); User != UE; ++User) {
1598 DEBUG(dbgs() << "SLP: \tvalidating user:" << **User << ".\n");
1599 assert(!MustGather.count(*User) &&
1600 "Replacing gathered value with undef");
1602 assert((ScalarToTreeEntry.count(*User) ||
1603 // It is legal to replace the reduction users by undef.
1604 (RdxOps && RdxOps->count(*User))) &&
1605 "Replacing out-of-tree value with undef");
1607 Value *Undef = UndefValue::get(Ty);
1608 Scalar->replaceAllUsesWith(Undef);
1610 DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
1611 cast<Instruction>(Scalar)->eraseFromParent();
1615 for (Function::iterator it = F->begin(), e = F->end(); it != e; ++it) {
1616 BlocksNumbers[it].forget();
1618 Builder.ClearInsertionPoint();
1620 return VectorizableTree[0].VectorizedValue;
1624 const DominatorTree *DT;
1627 DTCmp(const DominatorTree *DT) : DT(DT) {}
1628 bool operator()(const BasicBlock *A, const BasicBlock *B) const {
1629 return DT->dominates(A, B);
1633 void BoUpSLP::optimizeGatherSequence() {
1634 DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
1635 << " gather sequences instructions.\n");
1636 // Keep a list of visited BBs to run CSE on. It is typically small.
1637 SmallPtrSet<BasicBlock *, 4> VisitedBBs;
1638 SmallVector<BasicBlock *, 4> CSEWorkList;
1639 // LICM InsertElementInst sequences.
1640 for (SetVector<Instruction *>::iterator it = GatherSeq.begin(),
1641 e = GatherSeq.end(); it != e; ++it) {
1642 InsertElementInst *Insert = dyn_cast<InsertElementInst>(*it);
1647 if (VisitedBBs.insert(Insert->getParent()))
1648 CSEWorkList.push_back(Insert->getParent());
1650 // Check if this block is inside a loop.
1651 Loop *L = LI->getLoopFor(Insert->getParent());
1655 // Check if it has a preheader.
1656 BasicBlock *PreHeader = L->getLoopPreheader();
1660 // If the vector or the element that we insert into it are
1661 // instructions that are defined in this basic block then we can't
1662 // hoist this instruction.
1663 Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
1664 Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
1665 if (CurrVec && L->contains(CurrVec))
1667 if (NewElem && L->contains(NewElem))
1670 // We can hoist this instruction. Move it to the pre-header.
1671 Insert->moveBefore(PreHeader->getTerminator());
1674 // Sort blocks by domination. This ensures we visit a block after all blocks
1675 // dominating it are visited.
1676 std::stable_sort(CSEWorkList.begin(), CSEWorkList.end(), DTCmp(DT));
1678 // Perform O(N^2) search over the gather sequences and merge identical
1679 // instructions. TODO: We can further optimize this scan if we split the
1680 // instructions into different buckets based on the insert lane.
1681 SmallVector<Instruction *, 16> Visited;
1682 for (SmallVectorImpl<BasicBlock *>::iterator I = CSEWorkList.begin(),
1683 E = CSEWorkList.end();
1685 assert((I == CSEWorkList.begin() || !DT->dominates(*I, *llvm::prior(I))) &&
1686 "Worklist not sorted properly!");
1687 BasicBlock *BB = *I;
1688 // For all instructions in blocks containing gather sequences:
1689 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) {
1690 Instruction *In = it++;
1691 if ((!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In)) ||
1692 !GatherSeq.count(In))
1695 // Check if we can replace this instruction with any of the
1696 // visited instructions.
1697 for (SmallVectorImpl<Instruction *>::iterator v = Visited.begin(),
1700 if (In->isIdenticalTo(*v) &&
1701 DT->dominates((*v)->getParent(), In->getParent())) {
1702 In->replaceAllUsesWith(*v);
1703 In->eraseFromParent();
1709 assert(std::find(Visited.begin(), Visited.end(), In) == Visited.end());
1710 Visited.push_back(In);
1716 /// The SLPVectorizer Pass.
1717 struct SLPVectorizer : public FunctionPass {
1718 typedef SmallVector<StoreInst *, 8> StoreList;
1719 typedef MapVector<Value *, StoreList> StoreListMap;
1721 /// Pass identification, replacement for typeid
1724 explicit SLPVectorizer() : FunctionPass(ID) {
1725 initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
1728 ScalarEvolution *SE;
1730 TargetTransformInfo *TTI;
1735 virtual bool runOnFunction(Function &F) {
1736 SE = &getAnalysis<ScalarEvolution>();
1737 DL = getAnalysisIfAvailable<DataLayout>();
1738 TTI = &getAnalysis<TargetTransformInfo>();
1739 AA = &getAnalysis<AliasAnalysis>();
1740 LI = &getAnalysis<LoopInfo>();
1741 DT = &getAnalysis<DominatorTree>();
1744 bool Changed = false;
1746 // If the target claims to have no vector registers don't attempt
1748 if (!TTI->getNumberOfRegisters(true))
1751 // Must have DataLayout. We can't require it because some tests run w/o
1756 // Don't vectorize when the attribute NoImplicitFloat is used.
1757 if (F.hasFnAttribute(Attribute::NoImplicitFloat))
1760 DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
1762 // Use the bollom up slp vectorizer to construct chains that start with
1763 // he store instructions.
1764 BoUpSLP R(&F, SE, DL, TTI, AA, LI, DT);
1766 // Scan the blocks in the function in post order.
1767 for (po_iterator<BasicBlock*> it = po_begin(&F.getEntryBlock()),
1768 e = po_end(&F.getEntryBlock()); it != e; ++it) {
1769 BasicBlock *BB = *it;
1771 // Vectorize trees that end at stores.
1772 if (unsigned count = collectStores(BB, R)) {
1774 DEBUG(dbgs() << "SLP: Found " << count << " stores to vectorize.\n");
1775 Changed |= vectorizeStoreChains(R);
1778 // Vectorize trees that end at reductions.
1779 Changed |= vectorizeChainsInBlock(BB, R);
1783 R.optimizeGatherSequence();
1784 DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
1785 DEBUG(verifyFunction(F));
1790 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1791 FunctionPass::getAnalysisUsage(AU);
1792 AU.addRequired<ScalarEvolution>();
1793 AU.addRequired<AliasAnalysis>();
1794 AU.addRequired<TargetTransformInfo>();
1795 AU.addRequired<LoopInfo>();
1796 AU.addRequired<DominatorTree>();
1797 AU.addPreserved<LoopInfo>();
1798 AU.addPreserved<DominatorTree>();
1799 AU.setPreservesCFG();
1804 /// \brief Collect memory references and sort them according to their base
1805 /// object. We sort the stores to their base objects to reduce the cost of the
1806 /// quadratic search on the stores. TODO: We can further reduce this cost
1807 /// if we flush the chain creation every time we run into a memory barrier.
1808 unsigned collectStores(BasicBlock *BB, BoUpSLP &R);
1810 /// \brief Try to vectorize a chain that starts at two arithmetic instrs.
1811 bool tryToVectorizePair(Value *A, Value *B, BoUpSLP &R);
1813 /// \brief Try to vectorize a list of operands.
1814 /// \returns true if a value was vectorized.
1815 bool tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R);
1817 /// \brief Try to vectorize a chain that may start at the operands of \V;
1818 bool tryToVectorize(BinaryOperator *V, BoUpSLP &R);
1820 /// \brief Vectorize the stores that were collected in StoreRefs.
1821 bool vectorizeStoreChains(BoUpSLP &R);
1823 /// \brief Scan the basic block and look for patterns that are likely to start
1824 /// a vectorization chain.
1825 bool vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R);
1827 bool vectorizeStoreChain(ArrayRef<Value *> Chain, int CostThreshold,
1830 bool vectorizeStores(ArrayRef<StoreInst *> Stores, int costThreshold,
1833 StoreListMap StoreRefs;
1836 bool SLPVectorizer::vectorizeStoreChain(ArrayRef<Value *> Chain,
1837 int CostThreshold, BoUpSLP &R) {
1838 unsigned ChainLen = Chain.size();
1839 DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
1841 Type *StoreTy = cast<StoreInst>(Chain[0])->getValueOperand()->getType();
1842 unsigned Sz = DL->getTypeSizeInBits(StoreTy);
1843 unsigned VF = MinVecRegSize / Sz;
1845 if (!isPowerOf2_32(Sz) || VF < 2)
1848 bool Changed = false;
1849 // Look for profitable vectorizable trees at all offsets, starting at zero.
1850 for (unsigned i = 0, e = ChainLen; i < e; ++i) {
1853 DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
1855 ArrayRef<Value *> Operands = Chain.slice(i, VF);
1857 R.buildTree(Operands);
1859 int Cost = R.getTreeCost();
1861 DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
1862 if (Cost < CostThreshold) {
1863 DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
1866 // Move to the next bundle.
1875 bool SLPVectorizer::vectorizeStores(ArrayRef<StoreInst *> Stores,
1876 int costThreshold, BoUpSLP &R) {
1877 SetVector<Value *> Heads, Tails;
1878 SmallDenseMap<Value *, Value *> ConsecutiveChain;
1880 // We may run into multiple chains that merge into a single chain. We mark the
1881 // stores that we vectorized so that we don't visit the same store twice.
1882 BoUpSLP::ValueSet VectorizedStores;
1883 bool Changed = false;
1885 // Do a quadratic search on all of the given stores and find
1886 // all of the pairs of stores that follow each other.
1887 for (unsigned i = 0, e = Stores.size(); i < e; ++i) {
1888 for (unsigned j = 0; j < e; ++j) {
1892 if (R.isConsecutiveAccess(Stores[i], Stores[j])) {
1893 Tails.insert(Stores[j]);
1894 Heads.insert(Stores[i]);
1895 ConsecutiveChain[Stores[i]] = Stores[j];
1900 // For stores that start but don't end a link in the chain:
1901 for (SetVector<Value *>::iterator it = Heads.begin(), e = Heads.end();
1903 if (Tails.count(*it))
1906 // We found a store instr that starts a chain. Now follow the chain and try
1908 BoUpSLP::ValueList Operands;
1910 // Collect the chain into a list.
1911 while (Tails.count(I) || Heads.count(I)) {
1912 if (VectorizedStores.count(I))
1914 Operands.push_back(I);
1915 // Move to the next value in the chain.
1916 I = ConsecutiveChain[I];
1919 bool Vectorized = vectorizeStoreChain(Operands, costThreshold, R);
1921 // Mark the vectorized stores so that we don't vectorize them again.
1923 VectorizedStores.insert(Operands.begin(), Operands.end());
1924 Changed |= Vectorized;
1931 unsigned SLPVectorizer::collectStores(BasicBlock *BB, BoUpSLP &R) {
1934 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1935 StoreInst *SI = dyn_cast<StoreInst>(it);
1939 // Don't touch volatile stores.
1940 if (!SI->isSimple())
1943 // Check that the pointer points to scalars.
1944 Type *Ty = SI->getValueOperand()->getType();
1945 if (Ty->isAggregateType() || Ty->isVectorTy())
1948 // Find the base pointer.
1949 Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), DL);
1951 // Save the store locations.
1952 StoreRefs[Ptr].push_back(SI);
1958 bool SLPVectorizer::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
1961 Value *VL[] = { A, B };
1962 return tryToVectorizeList(VL, R);
1965 bool SLPVectorizer::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R) {
1969 DEBUG(dbgs() << "SLP: Vectorizing a list of length = " << VL.size() << ".\n");
1971 // Check that all of the parts are scalar instructions of the same type.
1972 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
1976 unsigned Opcode0 = I0->getOpcode();
1978 Type *Ty0 = I0->getType();
1979 unsigned Sz = DL->getTypeSizeInBits(Ty0);
1980 unsigned VF = MinVecRegSize / Sz;
1982 for (int i = 0, e = VL.size(); i < e; ++i) {
1983 Type *Ty = VL[i]->getType();
1984 if (Ty->isAggregateType() || Ty->isVectorTy())
1986 Instruction *Inst = dyn_cast<Instruction>(VL[i]);
1987 if (!Inst || Inst->getOpcode() != Opcode0)
1991 bool Changed = false;
1993 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
1994 unsigned OpsWidth = 0;
2001 if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
2004 DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations " << "\n");
2005 ArrayRef<Value *> Ops = VL.slice(i, OpsWidth);
2008 int Cost = R.getTreeCost();
2010 if (Cost < -SLPCostThreshold) {
2011 DEBUG(dbgs() << "SLP: Vectorizing pair at cost:" << Cost << ".\n");
2014 // Move to the next bundle.
2023 bool SLPVectorizer::tryToVectorize(BinaryOperator *V, BoUpSLP &R) {
2027 // Try to vectorize V.
2028 if (tryToVectorizePair(V->getOperand(0), V->getOperand(1), R))
2031 BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0));
2032 BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1));
2034 if (B && B->hasOneUse()) {
2035 BinaryOperator *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
2036 BinaryOperator *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
2037 if (tryToVectorizePair(A, B0, R)) {
2041 if (tryToVectorizePair(A, B1, R)) {
2048 if (A && A->hasOneUse()) {
2049 BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
2050 BinaryOperator *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
2051 if (tryToVectorizePair(A0, B, R)) {
2055 if (tryToVectorizePair(A1, B, R)) {
2063 /// \brief Generate a shuffle mask to be used in a reduction tree.
2065 /// \param VecLen The length of the vector to be reduced.
2066 /// \param NumEltsToRdx The number of elements that should be reduced in the
2068 /// \param IsPairwise Whether the reduction is a pairwise or splitting
2069 /// reduction. A pairwise reduction will generate a mask of
2070 /// <0,2,...> or <1,3,..> while a splitting reduction will generate
2071 /// <2,3, undef,undef> for a vector of 4 and NumElts = 2.
2072 /// \param IsLeft True will generate a mask of even elements, odd otherwise.
2073 static Value *createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx,
2074 bool IsPairwise, bool IsLeft,
2075 IRBuilder<> &Builder) {
2076 assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask");
2078 SmallVector<Constant *, 32> ShuffleMask(
2079 VecLen, UndefValue::get(Builder.getInt32Ty()));
2082 // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
2083 for (unsigned i = 0; i != NumEltsToRdx; ++i)
2084 ShuffleMask[i] = Builder.getInt32(2 * i + !IsLeft);
2086 // Move the upper half of the vector to the lower half.
2087 for (unsigned i = 0; i != NumEltsToRdx; ++i)
2088 ShuffleMask[i] = Builder.getInt32(NumEltsToRdx + i);
2090 return ConstantVector::get(ShuffleMask);
2094 /// Model horizontal reductions.
2096 /// A horizontal reduction is a tree of reduction operations (currently add and
2097 /// fadd) that has operations that can be put into a vector as its leaf.
2098 /// For example, this tree:
2105 /// This tree has "mul" as its reduced values and "+" as its reduction
2106 /// operations. A reduction might be feeding into a store or a binary operation
2121 class HorizontalReduction {
2122 SmallPtrSet<Value *, 16> ReductionOps;
2123 SmallVector<Value *, 32> ReducedVals;
2125 BinaryOperator *ReductionRoot;
2126 PHINode *ReductionPHI;
2128 /// The opcode of the reduction.
2129 unsigned ReductionOpcode;
2130 /// The opcode of the values we perform a reduction on.
2131 unsigned ReducedValueOpcode;
2132 /// The width of one full horizontal reduction operation.
2133 unsigned ReduxWidth;
2134 /// Should we model this reduction as a pairwise reduction tree or a tree that
2135 /// splits the vector in halves and adds those halves.
2136 bool IsPairwiseReduction;
2139 HorizontalReduction()
2140 : ReductionRoot(0), ReductionPHI(0), ReductionOpcode(0),
2141 ReducedValueOpcode(0), ReduxWidth(0), IsPairwiseReduction(false) {}
2143 /// \brief Try to find a reduction tree.
2144 bool matchAssociativeReduction(PHINode *Phi, BinaryOperator *B,
2147 std::find(Phi->op_begin(), Phi->op_end(), B) != Phi->op_end()) &&
2148 "Thi phi needs to use the binary operator");
2150 // We could have a initial reductions that is not an add.
2151 // r *= v1 + v2 + v3 + v4
2152 // In such a case start looking for a tree rooted in the first '+'.
2154 if (B->getOperand(0) == Phi) {
2156 B = dyn_cast<BinaryOperator>(B->getOperand(1));
2157 } else if (B->getOperand(1) == Phi) {
2159 B = dyn_cast<BinaryOperator>(B->getOperand(0));
2166 Type *Ty = B->getType();
2167 if (Ty->isVectorTy())
2170 ReductionOpcode = B->getOpcode();
2171 ReducedValueOpcode = 0;
2172 ReduxWidth = MinVecRegSize / DL->getTypeSizeInBits(Ty);
2179 // We currently only support adds.
2180 if (ReductionOpcode != Instruction::Add &&
2181 ReductionOpcode != Instruction::FAdd)
2184 // Post order traverse the reduction tree starting at B. We only handle true
2185 // trees containing only binary operators.
2186 SmallVector<std::pair<BinaryOperator *, unsigned>, 32> Stack;
2187 Stack.push_back(std::make_pair(B, 0));
2188 while (!Stack.empty()) {
2189 BinaryOperator *TreeN = Stack.back().first;
2190 unsigned EdgeToVist = Stack.back().second++;
2191 bool IsReducedValue = TreeN->getOpcode() != ReductionOpcode;
2193 // Only handle trees in the current basic block.
2194 if (TreeN->getParent() != B->getParent())
2197 // Each tree node needs to have one user except for the ultimate
2199 if (!TreeN->hasOneUse() && TreeN != B)
2203 if (EdgeToVist == 2 || IsReducedValue) {
2204 if (IsReducedValue) {
2205 // Make sure that the opcodes of the operations that we are going to
2207 if (!ReducedValueOpcode)
2208 ReducedValueOpcode = TreeN->getOpcode();
2209 else if (ReducedValueOpcode != TreeN->getOpcode())
2211 ReducedVals.push_back(TreeN);
2213 // We need to be able to reassociate the adds.
2214 if (!TreeN->isAssociative())
2216 ReductionOps.insert(TreeN);
2223 // Visit left or right.
2224 Value *NextV = TreeN->getOperand(EdgeToVist);
2225 BinaryOperator *Next = dyn_cast<BinaryOperator>(NextV);
2227 Stack.push_back(std::make_pair(Next, 0));
2228 else if (NextV != Phi)
2234 /// \brief Attempt to vectorize the tree found by
2235 /// matchAssociativeReduction.
2236 bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
2237 if (ReducedVals.empty())
2240 unsigned NumReducedVals = ReducedVals.size();
2241 if (NumReducedVals < ReduxWidth)
2244 Value *VectorizedTree = 0;
2245 IRBuilder<> Builder(ReductionRoot);
2246 FastMathFlags Unsafe;
2247 Unsafe.setUnsafeAlgebra();
2248 Builder.SetFastMathFlags(Unsafe);
2251 for (; i < NumReducedVals - ReduxWidth + 1; i += ReduxWidth) {
2252 ArrayRef<Value *> ValsToReduce(&ReducedVals[i], ReduxWidth);
2253 V.buildTree(ValsToReduce, &ReductionOps);
2256 int Cost = V.getTreeCost() + getReductionCost(TTI, ReducedVals[i]);
2257 if (Cost >= -SLPCostThreshold)
2260 DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" << Cost
2263 // Vectorize a tree.
2264 DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
2265 Value *VectorizedRoot = V.vectorizeTree();
2267 // Emit a reduction.
2268 Value *ReducedSubTree = emitReduction(VectorizedRoot, Builder);
2269 if (VectorizedTree) {
2270 Builder.SetCurrentDebugLocation(Loc);
2271 VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
2272 ReducedSubTree, "bin.rdx");
2274 VectorizedTree = ReducedSubTree;
2277 if (VectorizedTree) {
2278 // Finish the reduction.
2279 for (; i < NumReducedVals; ++i) {
2280 Builder.SetCurrentDebugLocation(
2281 cast<Instruction>(ReducedVals[i])->getDebugLoc());
2282 VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
2287 assert(ReductionRoot != NULL && "Need a reduction operation");
2288 ReductionRoot->setOperand(0, VectorizedTree);
2289 ReductionRoot->setOperand(1, ReductionPHI);
2291 ReductionRoot->replaceAllUsesWith(VectorizedTree);
2293 return VectorizedTree != 0;
2298 /// \brief Calcuate the cost of a reduction.
2299 int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal) {
2300 Type *ScalarTy = FirstReducedVal->getType();
2301 Type *VecTy = VectorType::get(ScalarTy, ReduxWidth);
2303 int PairwiseRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, true);
2304 int SplittingRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, false);
2306 IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
2307 int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
2309 int ScalarReduxCost =
2310 ReduxWidth * TTI->getArithmeticInstrCost(ReductionOpcode, VecTy);
2312 DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost
2313 << " for reduction that starts with " << *FirstReducedVal
2315 << (IsPairwiseReduction ? "pairwise" : "splitting")
2316 << " reduction)\n");
2318 return VecReduxCost - ScalarReduxCost;
2321 static Value *createBinOp(IRBuilder<> &Builder, unsigned Opcode, Value *L,
2322 Value *R, const Twine &Name = "") {
2323 if (Opcode == Instruction::FAdd)
2324 return Builder.CreateFAdd(L, R, Name);
2325 return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, L, R, Name);
2328 /// \brief Emit a horizontal reduction of the vectorized value.
2329 Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder) {
2330 assert(VectorizedValue && "Need to have a vectorized tree node");
2331 Instruction *ValToReduce = dyn_cast<Instruction>(VectorizedValue);
2332 assert(isPowerOf2_32(ReduxWidth) &&
2333 "We only handle power-of-two reductions for now");
2335 Value *TmpVec = ValToReduce;
2336 for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
2337 if (IsPairwiseReduction) {
2339 createRdxShuffleMask(ReduxWidth, i, true, true, Builder);
2341 createRdxShuffleMask(ReduxWidth, i, true, false, Builder);
2343 Value *LeftShuf = Builder.CreateShuffleVector(
2344 TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l");
2345 Value *RightShuf = Builder.CreateShuffleVector(
2346 TmpVec, UndefValue::get(TmpVec->getType()), (RightMask),
2348 TmpVec = createBinOp(Builder, ReductionOpcode, LeftShuf, RightShuf,
2352 createRdxShuffleMask(ReduxWidth, i, false, false, Builder);
2353 Value *Shuf = Builder.CreateShuffleVector(
2354 TmpVec, UndefValue::get(TmpVec->getType()), UpperHalf, "rdx.shuf");
2355 TmpVec = createBinOp(Builder, ReductionOpcode, TmpVec, Shuf, "bin.rdx");
2359 // The result is in the first element of the vector.
2360 return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
2364 /// \brief Recognize construction of vectors like
2365 /// %ra = insertelement <4 x float> undef, float %s0, i32 0
2366 /// %rb = insertelement <4 x float> %ra, float %s1, i32 1
2367 /// %rc = insertelement <4 x float> %rb, float %s2, i32 2
2368 /// %rd = insertelement <4 x float> %rc, float %s3, i32 3
2370 /// Returns true if it matches
2372 static bool findBuildVector(InsertElementInst *IE,
2373 SmallVectorImpl<Value *> &Ops) {
2374 if (!isa<UndefValue>(IE->getOperand(0)))
2378 Ops.push_back(IE->getOperand(1));
2380 if (IE->use_empty())
2383 InsertElementInst *NextUse = dyn_cast<InsertElementInst>(IE->use_back());
2387 // If this isn't the final use, make sure the next insertelement is the only
2388 // use. It's OK if the final constructed vector is used multiple times
2389 if (!IE->hasOneUse())
2398 static bool PhiTypeSorterFunc(Value *V, Value *V2) {
2399 return V->getType() < V2->getType();
2402 bool SLPVectorizer::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
2403 bool Changed = false;
2404 SmallVector<Value *, 4> Incoming;
2405 SmallSet<Value *, 16> VisitedInstrs;
2407 bool HaveVectorizedPhiNodes = true;
2408 while (HaveVectorizedPhiNodes) {
2409 HaveVectorizedPhiNodes = false;
2411 // Collect the incoming values from the PHIs.
2413 for (BasicBlock::iterator instr = BB->begin(), ie = BB->end(); instr != ie;
2415 PHINode *P = dyn_cast<PHINode>(instr);
2419 if (!VisitedInstrs.count(P))
2420 Incoming.push_back(P);
2424 std::stable_sort(Incoming.begin(), Incoming.end(), PhiTypeSorterFunc);
2426 // Try to vectorize elements base on their type.
2427 for (SmallVector<Value *, 4>::iterator IncIt = Incoming.begin(),
2431 // Look for the next elements with the same type.
2432 SmallVector<Value *, 4>::iterator SameTypeIt = IncIt;
2433 while (SameTypeIt != E &&
2434 (*SameTypeIt)->getType() == (*IncIt)->getType()) {
2435 VisitedInstrs.insert(*SameTypeIt);
2439 // Try to vectorize them.
2440 unsigned NumElts = (SameTypeIt - IncIt);
2441 DEBUG(errs() << "SLP: Trying to vectorize starting at PHIs (" << NumElts << ")\n");
2443 tryToVectorizeList(ArrayRef<Value *>(IncIt, NumElts), R)) {
2444 // Success start over because instructions might have been changed.
2445 HaveVectorizedPhiNodes = true;
2450 // Start over at the next instruction of a differnt type (or the end).
2455 VisitedInstrs.clear();
2457 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) {
2458 // We may go through BB multiple times so skip the one we have checked.
2459 if (!VisitedInstrs.insert(it))
2462 if (isa<DbgInfoIntrinsic>(it))
2465 // Try to vectorize reductions that use PHINodes.
2466 if (PHINode *P = dyn_cast<PHINode>(it)) {
2467 // Check that the PHI is a reduction PHI.
2468 if (P->getNumIncomingValues() != 2)
2471 (P->getIncomingBlock(0) == BB
2472 ? (P->getIncomingValue(0))
2473 : (P->getIncomingBlock(1) == BB ? P->getIncomingValue(1) : 0));
2474 // Check if this is a Binary Operator.
2475 BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx);
2479 // Try to match and vectorize a horizontal reduction.
2480 HorizontalReduction HorRdx;
2481 if (ShouldVectorizeHor &&
2482 HorRdx.matchAssociativeReduction(P, BI, DL) &&
2483 HorRdx.tryToReduce(R, TTI)) {
2490 Value *Inst = BI->getOperand(0);
2492 Inst = BI->getOperand(1);
2494 if (tryToVectorize(dyn_cast<BinaryOperator>(Inst), R)) {
2495 // We would like to start over since some instructions are deleted
2496 // and the iterator may become invalid value.
2506 // Try to vectorize horizontal reductions feeding into a store.
2507 if (ShouldStartVectorizeHorAtStore)
2508 if (StoreInst *SI = dyn_cast<StoreInst>(it))
2509 if (BinaryOperator *BinOp =
2510 dyn_cast<BinaryOperator>(SI->getValueOperand())) {
2511 HorizontalReduction HorRdx;
2512 if (((HorRdx.matchAssociativeReduction(0, BinOp, DL) &&
2513 HorRdx.tryToReduce(R, TTI)) ||
2514 tryToVectorize(BinOp, R))) {
2522 // Try to vectorize trees that start at compare instructions.
2523 if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
2524 if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) {
2526 // We would like to start over since some instructions are deleted
2527 // and the iterator may become invalid value.
2533 for (int i = 0; i < 2; ++i) {
2534 if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i))) {
2535 if (tryToVectorizePair(BI->getOperand(0), BI->getOperand(1), R)) {
2537 // We would like to start over since some instructions are deleted
2538 // and the iterator may become invalid value.
2547 // Try to vectorize trees that start at insertelement instructions.
2548 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(it)) {
2549 SmallVector<Value *, 8> Ops;
2550 if (!findBuildVector(IE, Ops))
2553 if (tryToVectorizeList(Ops, R)) {
2566 bool SLPVectorizer::vectorizeStoreChains(BoUpSLP &R) {
2567 bool Changed = false;
2568 // Attempt to sort and vectorize each of the store-groups.
2569 for (StoreListMap::iterator it = StoreRefs.begin(), e = StoreRefs.end();
2571 if (it->second.size() < 2)
2574 DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
2575 << it->second.size() << ".\n");
2577 // Process the stores in chunks of 16.
2578 for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI+=16) {
2579 unsigned Len = std::min<unsigned>(CE - CI, 16);
2580 ArrayRef<StoreInst *> Chunk(&it->second[CI], Len);
2581 Changed |= vectorizeStores(Chunk, -SLPCostThreshold, R);
2587 } // end anonymous namespace
2589 char SLPVectorizer::ID = 0;
2590 static const char lv_name[] = "SLP Vectorizer";
2591 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
2592 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
2593 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
2594 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
2595 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
2596 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
2599 Pass *createSLPVectorizerPass() { return new SLPVectorizer(); }