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/Dominators.h"
27 #include "llvm/Analysis/ScalarEvolution.h"
28 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
29 #include "llvm/Analysis/TargetTransformInfo.h"
30 #include "llvm/Analysis/ValueTracking.h"
31 #include "llvm/Analysis/Verifier.h"
32 #include "llvm/Analysis/LoopInfo.h"
33 #include "llvm/IR/DataLayout.h"
34 #include "llvm/IR/Instructions.h"
35 #include "llvm/IR/IntrinsicInst.h"
36 #include "llvm/IR/IRBuilder.h"
37 #include "llvm/IR/Module.h"
38 #include "llvm/IR/Type.h"
39 #include "llvm/IR/Value.h"
40 #include "llvm/Pass.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/raw_ostream.h"
50 SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
51 cl::desc("Only vectorize if you gain more than this "
55 ShouldVectorizeHor("slp-vectorize-hor", cl::init(false), cl::Hidden,
56 cl::desc("Attempt to vectorize horizontal reductions"));
58 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
59 "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
61 "Attempt to vectorize horizontal reductions feeding into a store"));
65 static const unsigned MinVecRegSize = 128;
67 static const unsigned RecursionMaxDepth = 12;
69 /// A helper class for numbering instructions in multiple blocks.
70 /// Numbers start at zero for each basic block.
71 struct BlockNumbering {
73 BlockNumbering(BasicBlock *Bb) : BB(Bb), Valid(false) {}
75 BlockNumbering() : BB(0), Valid(false) {}
77 void numberInstructions() {
81 // Number the instructions in the block.
82 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
84 InstrVec.push_back(it);
85 assert(InstrVec[InstrIdx[it]] == it && "Invalid allocation");
90 int getIndex(Instruction *I) {
91 assert(I->getParent() == BB && "Invalid instruction");
94 assert(InstrIdx.count(I) && "Unknown instruction");
98 Instruction *getInstruction(unsigned loc) {
100 numberInstructions();
101 assert(InstrVec.size() > loc && "Invalid Index");
102 return InstrVec[loc];
105 void forget() { Valid = false; }
108 /// The block we are numbering.
110 /// Is the block numbered.
112 /// Maps instructions to numbers and back.
113 SmallDenseMap<Instruction *, int> InstrIdx;
114 /// Maps integers to Instructions.
115 SmallVector<Instruction *, 32> InstrVec;
118 /// \returns the parent basic block if all of the instructions in \p VL
119 /// are in the same block or null otherwise.
120 static BasicBlock *getSameBlock(ArrayRef<Value *> VL) {
121 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
124 BasicBlock *BB = I0->getParent();
125 for (int i = 1, e = VL.size(); i < e; i++) {
126 Instruction *I = dyn_cast<Instruction>(VL[i]);
130 if (BB != I->getParent())
136 /// \returns True if all of the values in \p VL are constants.
137 static bool allConstant(ArrayRef<Value *> VL) {
138 for (unsigned i = 0, e = VL.size(); i < e; ++i)
139 if (!isa<Constant>(VL[i]))
144 /// \returns True if all of the values in \p VL are identical.
145 static bool isSplat(ArrayRef<Value *> VL) {
146 for (unsigned i = 1, e = VL.size(); i < e; ++i)
152 /// \returns The opcode if all of the Instructions in \p VL have the same
154 static unsigned getSameOpcode(ArrayRef<Value *> VL) {
155 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
158 unsigned Opcode = I0->getOpcode();
159 for (int i = 1, e = VL.size(); i < e; i++) {
160 Instruction *I = dyn_cast<Instruction>(VL[i]);
161 if (!I || Opcode != I->getOpcode())
167 /// \returns \p I after propagating metadata from \p VL.
168 static Instruction *propagateMetadata(Instruction *I, ArrayRef<Value *> VL) {
169 Instruction *I0 = cast<Instruction>(VL[0]);
170 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
171 I0->getAllMetadataOtherThanDebugLoc(Metadata);
173 for (unsigned i = 0, n = Metadata.size(); i != n; ++i) {
174 unsigned Kind = Metadata[i].first;
175 MDNode *MD = Metadata[i].second;
177 for (int i = 1, e = VL.size(); MD && i != e; i++) {
178 Instruction *I = cast<Instruction>(VL[i]);
179 MDNode *IMD = I->getMetadata(Kind);
183 MD = 0; // Remove unknown metadata
185 case LLVMContext::MD_tbaa:
186 MD = MDNode::getMostGenericTBAA(MD, IMD);
188 case LLVMContext::MD_fpmath:
189 MD = MDNode::getMostGenericFPMath(MD, IMD);
193 I->setMetadata(Kind, MD);
198 /// \returns The type that all of the values in \p VL have or null if there
199 /// are different types.
200 static Type* getSameType(ArrayRef<Value *> VL) {
201 Type *Ty = VL[0]->getType();
202 for (int i = 1, e = VL.size(); i < e; i++)
203 if (VL[i]->getType() != Ty)
209 /// \returns True if the ExtractElement instructions in VL can be vectorized
210 /// to use the original vector.
211 static bool CanReuseExtract(ArrayRef<Value *> VL) {
212 assert(Instruction::ExtractElement == getSameOpcode(VL) && "Invalid opcode");
213 // Check if all of the extracts come from the same vector and from the
216 ExtractElementInst *E0 = cast<ExtractElementInst>(VL0);
217 Value *Vec = E0->getOperand(0);
219 // We have to extract from the same vector type.
220 unsigned NElts = Vec->getType()->getVectorNumElements();
222 if (NElts != VL.size())
225 // Check that all of the indices extract from the correct offset.
226 ConstantInt *CI = dyn_cast<ConstantInt>(E0->getOperand(1));
227 if (!CI || CI->getZExtValue())
230 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
231 ExtractElementInst *E = cast<ExtractElementInst>(VL[i]);
232 ConstantInt *CI = dyn_cast<ConstantInt>(E->getOperand(1));
234 if (!CI || CI->getZExtValue() != i || E->getOperand(0) != Vec)
241 static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
242 SmallVectorImpl<Value *> &Left,
243 SmallVectorImpl<Value *> &Right) {
245 SmallVector<Value *, 16> OrigLeft, OrigRight;
247 bool AllSameOpcodeLeft = true;
248 bool AllSameOpcodeRight = true;
249 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
250 Instruction *I = cast<Instruction>(VL[i]);
251 Value *V0 = I->getOperand(0);
252 Value *V1 = I->getOperand(1);
254 OrigLeft.push_back(V0);
255 OrigRight.push_back(V1);
257 Instruction *I0 = dyn_cast<Instruction>(V0);
258 Instruction *I1 = dyn_cast<Instruction>(V1);
260 // Check whether all operands on one side have the same opcode. In this case
261 // we want to preserve the original order and not make things worse by
263 AllSameOpcodeLeft = I0;
264 AllSameOpcodeRight = I1;
266 if (i && AllSameOpcodeLeft) {
267 if(Instruction *P0 = dyn_cast<Instruction>(OrigLeft[i-1])) {
268 if(P0->getOpcode() != I0->getOpcode())
269 AllSameOpcodeLeft = false;
271 AllSameOpcodeLeft = false;
273 if (i && AllSameOpcodeRight) {
274 if(Instruction *P1 = dyn_cast<Instruction>(OrigRight[i-1])) {
275 if(P1->getOpcode() != I1->getOpcode())
276 AllSameOpcodeRight = false;
278 AllSameOpcodeRight = false;
281 // Sort two opcodes. In the code below we try to preserve the ability to use
282 // broadcast of values instead of individual inserts.
289 // If we just sorted according to opcode we would leave the first line in
290 // tact but we would swap vl2 with vr2 because opcode(phi) > opcode(load).
293 // Because vr2 and vr1 are from the same load we loose the opportunity of a
294 // broadcast for the packed right side in the backend: we have [vr1, vl2]
295 // instead of [vr1, vr2=vr1].
297 if(!i && I0->getOpcode() > I1->getOpcode()) {
300 } else if (i && I0->getOpcode() > I1->getOpcode() && Right[i-1] != I1) {
301 // Try not to destroy a broad cast for no apparent benefit.
304 } else if (i && I0->getOpcode() == I1->getOpcode() && Right[i-1] == I0) {
305 // Try preserve broadcasts.
308 } else if (i && I0->getOpcode() == I1->getOpcode() && Left[i-1] == I1) {
309 // Try preserve broadcasts.
318 // One opcode, put the instruction on the right.
328 bool LeftBroadcast = isSplat(Left);
329 bool RightBroadcast = isSplat(Right);
331 // Don't reorder if the operands where good to begin with.
332 if (!(LeftBroadcast || RightBroadcast) &&
333 (AllSameOpcodeRight || AllSameOpcodeLeft)) {
339 /// Bottom Up SLP Vectorizer.
342 typedef SmallVector<Value *, 8> ValueList;
343 typedef SmallVector<Instruction *, 16> InstrList;
344 typedef SmallPtrSet<Value *, 16> ValueSet;
345 typedef SmallVector<StoreInst *, 8> StoreList;
347 BoUpSLP(Function *Func, ScalarEvolution *Se, DataLayout *Dl,
348 TargetTransformInfo *Tti, AliasAnalysis *Aa, LoopInfo *Li,
350 F(Func), SE(Se), DL(Dl), TTI(Tti), AA(Aa), LI(Li), DT(Dt),
351 Builder(Se->getContext()) {
352 // Setup the block numbering utility for all of the blocks in the
354 for (Function::iterator it = F->begin(), e = F->end(); it != e; ++it) {
356 BlocksNumbers[BB] = BlockNumbering(BB);
360 /// \brief Vectorize the tree that starts with the elements in \p VL.
361 /// Returns the vectorized root.
362 Value *vectorizeTree();
364 /// \returns the vectorization cost of the subtree that starts at \p VL.
365 /// A negative number means that this is profitable.
368 /// Construct a vectorizable tree that starts at \p Roots and is possibly
369 /// used by a reduction of \p RdxOps.
370 void buildTree(ArrayRef<Value *> Roots, ValueSet *RdxOps = 0);
372 /// Clear the internal data structures that are created by 'buildTree'.
375 VectorizableTree.clear();
376 ScalarToTreeEntry.clear();
378 ExternalUses.clear();
379 MemBarrierIgnoreList.clear();
382 /// \returns true if the memory operations A and B are consecutive.
383 bool isConsecutiveAccess(Value *A, Value *B);
385 /// \brief Perform LICM and CSE on the newly generated gather sequences.
386 void optimizeGatherSequence();
390 /// \returns the cost of the vectorizable entry.
391 int getEntryCost(TreeEntry *E);
393 /// This is the recursive part of buildTree.
394 void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth);
396 /// Vectorize a single entry in the tree.
397 Value *vectorizeTree(TreeEntry *E);
399 /// Vectorize a single entry in the tree, starting in \p VL.
400 Value *vectorizeTree(ArrayRef<Value *> VL);
402 /// \returns the pointer to the vectorized value if \p VL is already
403 /// vectorized, or NULL. They may happen in cycles.
404 Value *alreadyVectorized(ArrayRef<Value *> VL) const;
406 /// \brief Take the pointer operand from the Load/Store instruction.
407 /// \returns NULL if this is not a valid Load/Store instruction.
408 static Value *getPointerOperand(Value *I);
410 /// \brief Take the address space operand from the Load/Store instruction.
411 /// \returns -1 if this is not a valid Load/Store instruction.
412 static unsigned getAddressSpaceOperand(Value *I);
414 /// \returns the scalarization cost for this type. Scalarization in this
415 /// context means the creation of vectors from a group of scalars.
416 int getGatherCost(Type *Ty);
418 /// \returns the scalarization cost for this list of values. Assuming that
419 /// this subtree gets vectorized, we may need to extract the values from the
420 /// roots. This method calculates the cost of extracting the values.
421 int getGatherCost(ArrayRef<Value *> VL);
423 /// \returns the AA location that is being access by the instruction.
424 AliasAnalysis::Location getLocation(Instruction *I);
426 /// \brief Checks if it is possible to sink an instruction from
427 /// \p Src to \p Dst.
428 /// \returns the pointer to the barrier instruction if we can't sink.
429 Value *getSinkBarrier(Instruction *Src, Instruction *Dst);
431 /// \returns the index of the last instruction in the BB from \p VL.
432 int getLastIndex(ArrayRef<Value *> VL);
434 /// \returns the Instruction in the bundle \p VL.
435 Instruction *getLastInstruction(ArrayRef<Value *> VL);
437 /// \brief Set the Builder insert point to one after the last instruction in
439 void setInsertPointAfterBundle(ArrayRef<Value *> VL);
441 /// \returns a vector from a collection of scalars in \p VL.
442 Value *Gather(ArrayRef<Value *> VL, VectorType *Ty);
444 /// \returns whether the VectorizableTree is fully vectoriable and will
445 /// be beneficial even the tree height is tiny.
446 bool isFullyVectorizableTinyTree();
449 TreeEntry() : Scalars(), VectorizedValue(0), LastScalarIndex(0),
452 /// \returns true if the scalars in VL are equal to this entry.
453 bool isSame(ArrayRef<Value *> VL) const {
454 assert(VL.size() == Scalars.size() && "Invalid size");
455 return std::equal(VL.begin(), VL.end(), Scalars.begin());
458 /// A vector of scalars.
461 /// The Scalars are vectorized into this value. It is initialized to Null.
462 Value *VectorizedValue;
464 /// The index in the basic block of the last scalar.
467 /// Do we need to gather this sequence ?
471 /// Create a new VectorizableTree entry.
472 TreeEntry *newTreeEntry(ArrayRef<Value *> VL, bool Vectorized) {
473 VectorizableTree.push_back(TreeEntry());
474 int idx = VectorizableTree.size() - 1;
475 TreeEntry *Last = &VectorizableTree[idx];
476 Last->Scalars.insert(Last->Scalars.begin(), VL.begin(), VL.end());
477 Last->NeedToGather = !Vectorized;
479 Last->LastScalarIndex = getLastIndex(VL);
480 for (int i = 0, e = VL.size(); i != e; ++i) {
481 assert(!ScalarToTreeEntry.count(VL[i]) && "Scalar already in tree!");
482 ScalarToTreeEntry[VL[i]] = idx;
485 Last->LastScalarIndex = 0;
486 MustGather.insert(VL.begin(), VL.end());
491 /// -- Vectorization State --
492 /// Holds all of the tree entries.
493 std::vector<TreeEntry> VectorizableTree;
495 /// Maps a specific scalar to its tree entry.
496 SmallDenseMap<Value*, int> ScalarToTreeEntry;
498 /// A list of scalars that we found that we need to keep as scalars.
501 /// This POD struct describes one external user in the vectorized tree.
502 struct ExternalUser {
503 ExternalUser (Value *S, llvm::User *U, int L) :
504 Scalar(S), User(U), Lane(L){};
505 // Which scalar in our function.
507 // Which user that uses the scalar.
509 // Which lane does the scalar belong to.
512 typedef SmallVector<ExternalUser, 16> UserList;
514 /// A list of values that need to extracted out of the tree.
515 /// This list holds pairs of (Internal Scalar : External User).
516 UserList ExternalUses;
518 /// A list of instructions to ignore while sinking
519 /// memory instructions. This map must be reset between runs of getCost.
520 ValueSet MemBarrierIgnoreList;
522 /// Holds all of the instructions that we gathered.
523 SetVector<Instruction *> GatherSeq;
524 /// A list of blocks that we are going to CSE.
525 SetVector<BasicBlock *> CSEBlocks;
527 /// Numbers instructions in different blocks.
528 DenseMap<BasicBlock *, BlockNumbering> BlocksNumbers;
530 /// Reduction operators.
533 // Analysis and block reference.
537 TargetTransformInfo *TTI;
541 /// Instruction builder to construct the vectorized tree.
545 void BoUpSLP::buildTree(ArrayRef<Value *> Roots, ValueSet *Rdx) {
548 if (!getSameType(Roots))
550 buildTree_rec(Roots, 0);
552 // Collect the values that we need to extract from the tree.
553 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
554 TreeEntry *Entry = &VectorizableTree[EIdx];
557 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
558 Value *Scalar = Entry->Scalars[Lane];
560 // No need to handle users of gathered values.
561 if (Entry->NeedToGather)
564 for (Value::use_iterator User = Scalar->use_begin(),
565 UE = Scalar->use_end(); User != UE; ++User) {
566 DEBUG(dbgs() << "SLP: Checking user:" << **User << ".\n");
568 // Skip in-tree scalars that become vectors.
569 if (ScalarToTreeEntry.count(*User)) {
570 DEBUG(dbgs() << "SLP: \tInternal user will be removed:" <<
572 int Idx = ScalarToTreeEntry[*User]; (void) Idx;
573 assert(!VectorizableTree[Idx].NeedToGather && "Bad state");
576 Instruction *UserInst = dyn_cast<Instruction>(*User);
580 // Ignore uses that are part of the reduction.
581 if (Rdx && std::find(Rdx->begin(), Rdx->end(), UserInst) != Rdx->end())
584 DEBUG(dbgs() << "SLP: Need to extract:" << **User << " from lane " <<
585 Lane << " from " << *Scalar << ".\n");
586 ExternalUses.push_back(ExternalUser(Scalar, *User, Lane));
593 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth) {
594 bool SameTy = getSameType(VL); (void)SameTy;
595 assert(SameTy && "Invalid types!");
597 if (Depth == RecursionMaxDepth) {
598 DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
599 newTreeEntry(VL, false);
603 // Don't handle vectors.
604 if (VL[0]->getType()->isVectorTy()) {
605 DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
606 newTreeEntry(VL, false);
610 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
611 if (SI->getValueOperand()->getType()->isVectorTy()) {
612 DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
613 newTreeEntry(VL, false);
617 // If all of the operands are identical or constant we have a simple solution.
618 if (allConstant(VL) || isSplat(VL) || !getSameBlock(VL) ||
619 !getSameOpcode(VL)) {
620 DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
621 newTreeEntry(VL, false);
625 // We now know that this is a vector of instructions of the same type from
628 // Check if this is a duplicate of another entry.
629 if (ScalarToTreeEntry.count(VL[0])) {
630 int Idx = ScalarToTreeEntry[VL[0]];
631 TreeEntry *E = &VectorizableTree[Idx];
632 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
633 DEBUG(dbgs() << "SLP: \tChecking bundle: " << *VL[i] << ".\n");
634 if (E->Scalars[i] != VL[i]) {
635 DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
636 newTreeEntry(VL, false);
640 DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *VL[0] << ".\n");
644 // Check that none of the instructions in the bundle are already in the tree.
645 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
646 if (ScalarToTreeEntry.count(VL[i])) {
647 DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
648 ") is already in tree.\n");
649 newTreeEntry(VL, false);
654 // If any of the scalars appears in the table OR it is marked as a value that
655 // needs to stat scalar then we need to gather the scalars.
656 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
657 if (ScalarToTreeEntry.count(VL[i]) || MustGather.count(VL[i])) {
658 DEBUG(dbgs() << "SLP: Gathering due to gathered scalar. \n");
659 newTreeEntry(VL, false);
664 // Check that all of the users of the scalars that we want to vectorize are
666 Instruction *VL0 = cast<Instruction>(VL[0]);
667 int MyLastIndex = getLastIndex(VL);
668 BasicBlock *BB = cast<Instruction>(VL0)->getParent();
670 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
671 Instruction *Scalar = cast<Instruction>(VL[i]);
672 DEBUG(dbgs() << "SLP: Checking users of " << *Scalar << ". \n");
673 for (Value::use_iterator U = Scalar->use_begin(), UE = Scalar->use_end();
675 DEBUG(dbgs() << "SLP: \tUser " << **U << ". \n");
676 Instruction *User = dyn_cast<Instruction>(*U);
678 DEBUG(dbgs() << "SLP: Gathering due unknown user. \n");
679 newTreeEntry(VL, false);
683 // We don't care if the user is in a different basic block.
684 BasicBlock *UserBlock = User->getParent();
685 if (UserBlock != BB) {
686 DEBUG(dbgs() << "SLP: User from a different basic block "
691 // If this is a PHINode within this basic block then we can place the
692 // extract wherever we want.
693 if (isa<PHINode>(*User)) {
694 DEBUG(dbgs() << "SLP: \tWe can schedule PHIs:" << *User << ". \n");
698 // Check if this is a safe in-tree user.
699 if (ScalarToTreeEntry.count(User)) {
700 int Idx = ScalarToTreeEntry[User];
701 int VecLocation = VectorizableTree[Idx].LastScalarIndex;
702 if (VecLocation <= MyLastIndex) {
703 DEBUG(dbgs() << "SLP: Gathering due to unschedulable vector. \n");
704 newTreeEntry(VL, false);
707 DEBUG(dbgs() << "SLP: In-tree user (" << *User << ") at #" <<
708 VecLocation << " vector value (" << *Scalar << ") at #"
709 << MyLastIndex << ".\n");
713 // This user is part of the reduction.
714 if (RdxOps && RdxOps->count(User))
717 // Make sure that we can schedule this unknown user.
718 BlockNumbering &BN = BlocksNumbers[BB];
719 int UserIndex = BN.getIndex(User);
720 if (UserIndex < MyLastIndex) {
722 DEBUG(dbgs() << "SLP: Can't schedule extractelement for "
724 newTreeEntry(VL, false);
730 // Check that every instructions appears once in this bundle.
731 for (unsigned i = 0, e = VL.size(); i < e; ++i)
732 for (unsigned j = i+1; j < e; ++j)
733 if (VL[i] == VL[j]) {
734 DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
735 newTreeEntry(VL, false);
739 // Check that instructions in this bundle don't reference other instructions.
740 // The runtime of this check is O(N * N-1 * uses(N)) and a typical N is 4.
741 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
742 for (Value::use_iterator U = VL[i]->use_begin(), UE = VL[i]->use_end();
744 for (unsigned j = 0; j < e; ++j) {
745 if (i != j && *U == VL[j]) {
746 DEBUG(dbgs() << "SLP: Intra-bundle dependencies!" << **U << ". \n");
747 newTreeEntry(VL, false);
754 DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
756 unsigned Opcode = getSameOpcode(VL);
758 // Check if it is safe to sink the loads or the stores.
759 if (Opcode == Instruction::Load || Opcode == Instruction::Store) {
760 Instruction *Last = getLastInstruction(VL);
762 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
765 Value *Barrier = getSinkBarrier(cast<Instruction>(VL[i]), Last);
767 DEBUG(dbgs() << "SLP: Can't sink " << *VL[i] << "\n down to " << *Last
768 << "\n because of " << *Barrier << ". Gathering.\n");
769 newTreeEntry(VL, false);
776 case Instruction::PHI: {
777 PHINode *PH = dyn_cast<PHINode>(VL0);
779 // Check for terminator values (e.g. invoke).
780 for (unsigned j = 0; j < VL.size(); ++j)
781 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
782 TerminatorInst *Term = dyn_cast<TerminatorInst>(cast<PHINode>(VL[j])->getIncomingValue(i));
784 DEBUG(dbgs() << "SLP: Need to swizzle PHINodes (TerminatorInst use).\n");
785 newTreeEntry(VL, false);
790 newTreeEntry(VL, true);
791 DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
793 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
795 // Prepare the operand vector.
796 for (unsigned j = 0; j < VL.size(); ++j)
797 Operands.push_back(cast<PHINode>(VL[j])->getIncomingValue(i));
799 buildTree_rec(Operands, Depth + 1);
803 case Instruction::ExtractElement: {
804 bool Reuse = CanReuseExtract(VL);
806 DEBUG(dbgs() << "SLP: Reusing extract sequence.\n");
808 newTreeEntry(VL, Reuse);
811 case Instruction::Load: {
812 // Check if the loads are consecutive or of we need to swizzle them.
813 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i) {
814 LoadInst *L = cast<LoadInst>(VL[i]);
815 if (!L->isSimple() || !isConsecutiveAccess(VL[i], VL[i + 1])) {
816 newTreeEntry(VL, false);
817 DEBUG(dbgs() << "SLP: Need to swizzle loads.\n");
821 newTreeEntry(VL, true);
822 DEBUG(dbgs() << "SLP: added a vector of loads.\n");
825 case Instruction::ZExt:
826 case Instruction::SExt:
827 case Instruction::FPToUI:
828 case Instruction::FPToSI:
829 case Instruction::FPExt:
830 case Instruction::PtrToInt:
831 case Instruction::IntToPtr:
832 case Instruction::SIToFP:
833 case Instruction::UIToFP:
834 case Instruction::Trunc:
835 case Instruction::FPTrunc:
836 case Instruction::BitCast: {
837 Type *SrcTy = VL0->getOperand(0)->getType();
838 for (unsigned i = 0; i < VL.size(); ++i) {
839 Type *Ty = cast<Instruction>(VL[i])->getOperand(0)->getType();
840 if (Ty != SrcTy || Ty->isAggregateType() || Ty->isVectorTy()) {
841 newTreeEntry(VL, false);
842 DEBUG(dbgs() << "SLP: Gathering casts with different src types.\n");
846 newTreeEntry(VL, true);
847 DEBUG(dbgs() << "SLP: added a vector of casts.\n");
849 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
851 // Prepare the operand vector.
852 for (unsigned j = 0; j < VL.size(); ++j)
853 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
855 buildTree_rec(Operands, Depth+1);
859 case Instruction::ICmp:
860 case Instruction::FCmp: {
861 // Check that all of the compares have the same predicate.
862 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
863 Type *ComparedTy = cast<Instruction>(VL[0])->getOperand(0)->getType();
864 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
865 CmpInst *Cmp = cast<CmpInst>(VL[i]);
866 if (Cmp->getPredicate() != P0 ||
867 Cmp->getOperand(0)->getType() != ComparedTy) {
868 newTreeEntry(VL, false);
869 DEBUG(dbgs() << "SLP: Gathering cmp with different predicate.\n");
874 newTreeEntry(VL, true);
875 DEBUG(dbgs() << "SLP: added a vector of compares.\n");
877 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
879 // Prepare the operand vector.
880 for (unsigned j = 0; j < VL.size(); ++j)
881 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
883 buildTree_rec(Operands, Depth+1);
887 case Instruction::Select:
888 case Instruction::Add:
889 case Instruction::FAdd:
890 case Instruction::Sub:
891 case Instruction::FSub:
892 case Instruction::Mul:
893 case Instruction::FMul:
894 case Instruction::UDiv:
895 case Instruction::SDiv:
896 case Instruction::FDiv:
897 case Instruction::URem:
898 case Instruction::SRem:
899 case Instruction::FRem:
900 case Instruction::Shl:
901 case Instruction::LShr:
902 case Instruction::AShr:
903 case Instruction::And:
904 case Instruction::Or:
905 case Instruction::Xor: {
906 newTreeEntry(VL, true);
907 DEBUG(dbgs() << "SLP: added a vector of bin op.\n");
909 // Sort operands of the instructions so that each side is more likely to
910 // have the same opcode.
911 if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
912 ValueList Left, Right;
913 reorderInputsAccordingToOpcode(VL, Left, Right);
914 buildTree_rec(Left, Depth + 1);
915 buildTree_rec(Right, Depth + 1);
919 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
921 // Prepare the operand vector.
922 for (unsigned j = 0; j < VL.size(); ++j)
923 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
925 buildTree_rec(Operands, Depth+1);
929 case Instruction::Store: {
930 // Check if the stores are consecutive or of we need to swizzle them.
931 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
932 if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
933 newTreeEntry(VL, false);
934 DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
938 newTreeEntry(VL, true);
939 DEBUG(dbgs() << "SLP: added a vector of stores.\n");
942 for (unsigned j = 0; j < VL.size(); ++j)
943 Operands.push_back(cast<Instruction>(VL[j])->getOperand(0));
945 // We can ignore these values because we are sinking them down.
946 MemBarrierIgnoreList.insert(VL.begin(), VL.end());
947 buildTree_rec(Operands, Depth + 1);
951 newTreeEntry(VL, false);
952 DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
957 int BoUpSLP::getEntryCost(TreeEntry *E) {
958 ArrayRef<Value*> VL = E->Scalars;
960 Type *ScalarTy = VL[0]->getType();
961 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
962 ScalarTy = SI->getValueOperand()->getType();
963 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
965 if (E->NeedToGather) {
969 return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
971 return getGatherCost(E->Scalars);
974 assert(getSameOpcode(VL) && getSameType(VL) && getSameBlock(VL) &&
976 Instruction *VL0 = cast<Instruction>(VL[0]);
977 unsigned Opcode = VL0->getOpcode();
979 case Instruction::PHI: {
982 case Instruction::ExtractElement: {
983 if (CanReuseExtract(VL))
985 return getGatherCost(VecTy);
987 case Instruction::ZExt:
988 case Instruction::SExt:
989 case Instruction::FPToUI:
990 case Instruction::FPToSI:
991 case Instruction::FPExt:
992 case Instruction::PtrToInt:
993 case Instruction::IntToPtr:
994 case Instruction::SIToFP:
995 case Instruction::UIToFP:
996 case Instruction::Trunc:
997 case Instruction::FPTrunc:
998 case Instruction::BitCast: {
999 Type *SrcTy = VL0->getOperand(0)->getType();
1001 // Calculate the cost of this instruction.
1002 int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(),
1003 VL0->getType(), SrcTy);
1005 VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
1006 int VecCost = TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy);
1007 return VecCost - ScalarCost;
1009 case Instruction::FCmp:
1010 case Instruction::ICmp:
1011 case Instruction::Select:
1012 case Instruction::Add:
1013 case Instruction::FAdd:
1014 case Instruction::Sub:
1015 case Instruction::FSub:
1016 case Instruction::Mul:
1017 case Instruction::FMul:
1018 case Instruction::UDiv:
1019 case Instruction::SDiv:
1020 case Instruction::FDiv:
1021 case Instruction::URem:
1022 case Instruction::SRem:
1023 case Instruction::FRem:
1024 case Instruction::Shl:
1025 case Instruction::LShr:
1026 case Instruction::AShr:
1027 case Instruction::And:
1028 case Instruction::Or:
1029 case Instruction::Xor: {
1030 // Calculate the cost of this instruction.
1033 if (Opcode == Instruction::FCmp || Opcode == Instruction::ICmp ||
1034 Opcode == Instruction::Select) {
1035 VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
1036 ScalarCost = VecTy->getNumElements() *
1037 TTI->getCmpSelInstrCost(Opcode, ScalarTy, Builder.getInt1Ty());
1038 VecCost = TTI->getCmpSelInstrCost(Opcode, VecTy, MaskTy);
1040 // Certain instructions can be cheaper to vectorize if they have a
1041 // constant second vector operand.
1042 TargetTransformInfo::OperandValueKind Op1VK =
1043 TargetTransformInfo::OK_AnyValue;
1044 TargetTransformInfo::OperandValueKind Op2VK =
1045 TargetTransformInfo::OK_UniformConstantValue;
1047 // Check whether all second operands are constant.
1048 for (unsigned i = 0; i < VL.size(); ++i)
1049 if (!isa<ConstantInt>(cast<Instruction>(VL[i])->getOperand(1))) {
1050 Op2VK = TargetTransformInfo::OK_AnyValue;
1055 VecTy->getNumElements() *
1056 TTI->getArithmeticInstrCost(Opcode, ScalarTy, Op1VK, Op2VK);
1057 VecCost = TTI->getArithmeticInstrCost(Opcode, VecTy, Op1VK, Op2VK);
1059 return VecCost - ScalarCost;
1061 case Instruction::Load: {
1062 // Cost of wide load - cost of scalar loads.
1063 int ScalarLdCost = VecTy->getNumElements() *
1064 TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
1065 int VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, 1, 0);
1066 return VecLdCost - ScalarLdCost;
1068 case Instruction::Store: {
1069 // We know that we can merge the stores. Calculate the cost.
1070 int ScalarStCost = VecTy->getNumElements() *
1071 TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
1072 int VecStCost = TTI->getMemoryOpCost(Instruction::Store, VecTy, 1, 0);
1073 return VecStCost - ScalarStCost;
1076 llvm_unreachable("Unknown instruction");
1080 bool BoUpSLP::isFullyVectorizableTinyTree() {
1081 DEBUG(dbgs() << "SLP: Check whether the tree with height " <<
1082 VectorizableTree.size() << " is fully vectorizable .\n");
1084 // We only handle trees of height 2.
1085 if (VectorizableTree.size() != 2)
1088 // Gathering cost would be too much for tiny trees.
1089 if (VectorizableTree[0].NeedToGather || VectorizableTree[1].NeedToGather)
1095 int BoUpSLP::getTreeCost() {
1097 DEBUG(dbgs() << "SLP: Calculating cost for tree of size " <<
1098 VectorizableTree.size() << ".\n");
1100 // We only vectorize tiny trees if it is fully vectorizable.
1101 if (VectorizableTree.size() < 3 && !isFullyVectorizableTinyTree()) {
1102 if (!VectorizableTree.size()) {
1103 assert(!ExternalUses.size() && "We should not have any external users");
1108 unsigned BundleWidth = VectorizableTree[0].Scalars.size();
1110 for (unsigned i = 0, e = VectorizableTree.size(); i != e; ++i) {
1111 int C = getEntryCost(&VectorizableTree[i]);
1112 DEBUG(dbgs() << "SLP: Adding cost " << C << " for bundle that starts with "
1113 << *VectorizableTree[i].Scalars[0] << " .\n");
1117 SmallSet<Value *, 16> ExtractCostCalculated;
1118 int ExtractCost = 0;
1119 for (UserList::iterator I = ExternalUses.begin(), E = ExternalUses.end();
1121 // We only add extract cost once for the same scalar.
1122 if (!ExtractCostCalculated.insert(I->Scalar))
1125 VectorType *VecTy = VectorType::get(I->Scalar->getType(), BundleWidth);
1126 ExtractCost += TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy,
1130 DEBUG(dbgs() << "SLP: Total Cost " << Cost + ExtractCost<< ".\n");
1131 return Cost + ExtractCost;
1134 int BoUpSLP::getGatherCost(Type *Ty) {
1136 for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
1137 Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
1141 int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) {
1142 // Find the type of the operands in VL.
1143 Type *ScalarTy = VL[0]->getType();
1144 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1145 ScalarTy = SI->getValueOperand()->getType();
1146 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1147 // Find the cost of inserting/extracting values from the vector.
1148 return getGatherCost(VecTy);
1151 AliasAnalysis::Location BoUpSLP::getLocation(Instruction *I) {
1152 if (StoreInst *SI = dyn_cast<StoreInst>(I))
1153 return AA->getLocation(SI);
1154 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1155 return AA->getLocation(LI);
1156 return AliasAnalysis::Location();
1159 Value *BoUpSLP::getPointerOperand(Value *I) {
1160 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1161 return LI->getPointerOperand();
1162 if (StoreInst *SI = dyn_cast<StoreInst>(I))
1163 return SI->getPointerOperand();
1167 unsigned BoUpSLP::getAddressSpaceOperand(Value *I) {
1168 if (LoadInst *L = dyn_cast<LoadInst>(I))
1169 return L->getPointerAddressSpace();
1170 if (StoreInst *S = dyn_cast<StoreInst>(I))
1171 return S->getPointerAddressSpace();
1175 bool BoUpSLP::isConsecutiveAccess(Value *A, Value *B) {
1176 Value *PtrA = getPointerOperand(A);
1177 Value *PtrB = getPointerOperand(B);
1178 unsigned ASA = getAddressSpaceOperand(A);
1179 unsigned ASB = getAddressSpaceOperand(B);
1181 // Check that the address spaces match and that the pointers are valid.
1182 if (!PtrA || !PtrB || (ASA != ASB))
1185 // Make sure that A and B are different pointers of the same type.
1186 if (PtrA == PtrB || PtrA->getType() != PtrB->getType())
1189 unsigned PtrBitWidth = DL->getPointerSizeInBits(ASA);
1190 Type *Ty = cast<PointerType>(PtrA->getType())->getElementType();
1191 APInt Size(PtrBitWidth, DL->getTypeStoreSize(Ty));
1193 APInt OffsetA(PtrBitWidth, 0), OffsetB(PtrBitWidth, 0);
1194 PtrA = PtrA->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetA);
1195 PtrB = PtrB->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetB);
1197 APInt OffsetDelta = OffsetB - OffsetA;
1199 // Check if they are based on the same pointer. That makes the offsets
1202 return OffsetDelta == Size;
1204 // Compute the necessary base pointer delta to have the necessary final delta
1205 // equal to the size.
1206 APInt BaseDelta = Size - OffsetDelta;
1208 // Otherwise compute the distance with SCEV between the base pointers.
1209 const SCEV *PtrSCEVA = SE->getSCEV(PtrA);
1210 const SCEV *PtrSCEVB = SE->getSCEV(PtrB);
1211 const SCEV *C = SE->getConstant(BaseDelta);
1212 const SCEV *X = SE->getAddExpr(PtrSCEVA, C);
1213 return X == PtrSCEVB;
1216 Value *BoUpSLP::getSinkBarrier(Instruction *Src, Instruction *Dst) {
1217 assert(Src->getParent() == Dst->getParent() && "Not the same BB");
1218 BasicBlock::iterator I = Src, E = Dst;
1219 /// Scan all of the instruction from SRC to DST and check if
1220 /// the source may alias.
1221 for (++I; I != E; ++I) {
1222 // Ignore store instructions that are marked as 'ignore'.
1223 if (MemBarrierIgnoreList.count(I))
1225 if (Src->mayWriteToMemory()) /* Write */ {
1226 if (!I->mayReadOrWriteMemory())
1229 if (!I->mayWriteToMemory())
1232 AliasAnalysis::Location A = getLocation(&*I);
1233 AliasAnalysis::Location B = getLocation(Src);
1235 if (!A.Ptr || !B.Ptr || AA->alias(A, B))
1241 int BoUpSLP::getLastIndex(ArrayRef<Value *> VL) {
1242 BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
1243 assert(BB == getSameBlock(VL) && BlocksNumbers.count(BB) && "Invalid block");
1244 BlockNumbering &BN = BlocksNumbers[BB];
1246 int MaxIdx = BN.getIndex(BB->getFirstNonPHI());
1247 for (unsigned i = 0, e = VL.size(); i < e; ++i)
1248 MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
1252 Instruction *BoUpSLP::getLastInstruction(ArrayRef<Value *> VL) {
1253 BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
1254 assert(BB == getSameBlock(VL) && BlocksNumbers.count(BB) && "Invalid block");
1255 BlockNumbering &BN = BlocksNumbers[BB];
1257 int MaxIdx = BN.getIndex(cast<Instruction>(VL[0]));
1258 for (unsigned i = 1, e = VL.size(); i < e; ++i)
1259 MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
1260 Instruction *I = BN.getInstruction(MaxIdx);
1261 assert(I && "bad location");
1265 void BoUpSLP::setInsertPointAfterBundle(ArrayRef<Value *> VL) {
1266 Instruction *VL0 = cast<Instruction>(VL[0]);
1267 Instruction *LastInst = getLastInstruction(VL);
1268 BasicBlock::iterator NextInst = LastInst;
1270 Builder.SetInsertPoint(VL0->getParent(), NextInst);
1271 Builder.SetCurrentDebugLocation(VL0->getDebugLoc());
1274 Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
1275 Value *Vec = UndefValue::get(Ty);
1276 // Generate the 'InsertElement' instruction.
1277 for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
1278 Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
1279 if (Instruction *Insrt = dyn_cast<Instruction>(Vec)) {
1280 GatherSeq.insert(Insrt);
1281 CSEBlocks.insert(Insrt->getParent());
1283 // Add to our 'need-to-extract' list.
1284 if (ScalarToTreeEntry.count(VL[i])) {
1285 int Idx = ScalarToTreeEntry[VL[i]];
1286 TreeEntry *E = &VectorizableTree[Idx];
1287 // Find which lane we need to extract.
1289 for (unsigned Lane = 0, LE = VL.size(); Lane != LE; ++Lane) {
1290 // Is this the lane of the scalar that we are looking for ?
1291 if (E->Scalars[Lane] == VL[i]) {
1296 assert(FoundLane >= 0 && "Could not find the correct lane");
1297 ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
1305 Value *BoUpSLP::alreadyVectorized(ArrayRef<Value *> VL) const {
1306 SmallDenseMap<Value*, int>::const_iterator Entry
1307 = ScalarToTreeEntry.find(VL[0]);
1308 if (Entry != ScalarToTreeEntry.end()) {
1309 int Idx = Entry->second;
1310 const TreeEntry *En = &VectorizableTree[Idx];
1311 if (En->isSame(VL) && En->VectorizedValue)
1312 return En->VectorizedValue;
1317 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
1318 if (ScalarToTreeEntry.count(VL[0])) {
1319 int Idx = ScalarToTreeEntry[VL[0]];
1320 TreeEntry *E = &VectorizableTree[Idx];
1322 return vectorizeTree(E);
1325 Type *ScalarTy = VL[0]->getType();
1326 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1327 ScalarTy = SI->getValueOperand()->getType();
1328 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1330 return Gather(VL, VecTy);
1333 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
1334 IRBuilder<>::InsertPointGuard Guard(Builder);
1336 if (E->VectorizedValue) {
1337 DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
1338 return E->VectorizedValue;
1341 Instruction *VL0 = cast<Instruction>(E->Scalars[0]);
1342 Type *ScalarTy = VL0->getType();
1343 if (StoreInst *SI = dyn_cast<StoreInst>(VL0))
1344 ScalarTy = SI->getValueOperand()->getType();
1345 VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size());
1347 if (E->NeedToGather) {
1348 setInsertPointAfterBundle(E->Scalars);
1349 return Gather(E->Scalars, VecTy);
1352 unsigned Opcode = VL0->getOpcode();
1353 assert(Opcode == getSameOpcode(E->Scalars) && "Invalid opcode");
1356 case Instruction::PHI: {
1357 PHINode *PH = dyn_cast<PHINode>(VL0);
1358 Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
1359 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1360 PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
1361 E->VectorizedValue = NewPhi;
1363 // PHINodes may have multiple entries from the same block. We want to
1364 // visit every block once.
1365 SmallSet<BasicBlock*, 4> VisitedBBs;
1367 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1369 BasicBlock *IBB = PH->getIncomingBlock(i);
1371 if (!VisitedBBs.insert(IBB)) {
1372 NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
1376 // Prepare the operand vector.
1377 for (unsigned j = 0; j < E->Scalars.size(); ++j)
1378 Operands.push_back(cast<PHINode>(E->Scalars[j])->
1379 getIncomingValueForBlock(IBB));
1381 Builder.SetInsertPoint(IBB->getTerminator());
1382 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1383 Value *Vec = vectorizeTree(Operands);
1384 NewPhi->addIncoming(Vec, IBB);
1387 assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
1388 "Invalid number of incoming values");
1392 case Instruction::ExtractElement: {
1393 if (CanReuseExtract(E->Scalars)) {
1394 Value *V = VL0->getOperand(0);
1395 E->VectorizedValue = V;
1398 return Gather(E->Scalars, VecTy);
1400 case Instruction::ZExt:
1401 case Instruction::SExt:
1402 case Instruction::FPToUI:
1403 case Instruction::FPToSI:
1404 case Instruction::FPExt:
1405 case Instruction::PtrToInt:
1406 case Instruction::IntToPtr:
1407 case Instruction::SIToFP:
1408 case Instruction::UIToFP:
1409 case Instruction::Trunc:
1410 case Instruction::FPTrunc:
1411 case Instruction::BitCast: {
1413 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1414 INVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1416 setInsertPointAfterBundle(E->Scalars);
1418 Value *InVec = vectorizeTree(INVL);
1420 if (Value *V = alreadyVectorized(E->Scalars))
1423 CastInst *CI = dyn_cast<CastInst>(VL0);
1424 Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
1425 E->VectorizedValue = V;
1428 case Instruction::FCmp:
1429 case Instruction::ICmp: {
1430 ValueList LHSV, RHSV;
1431 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1432 LHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1433 RHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1436 setInsertPointAfterBundle(E->Scalars);
1438 Value *L = vectorizeTree(LHSV);
1439 Value *R = vectorizeTree(RHSV);
1441 if (Value *V = alreadyVectorized(E->Scalars))
1444 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
1446 if (Opcode == Instruction::FCmp)
1447 V = Builder.CreateFCmp(P0, L, R);
1449 V = Builder.CreateICmp(P0, L, R);
1451 E->VectorizedValue = V;
1454 case Instruction::Select: {
1455 ValueList TrueVec, FalseVec, CondVec;
1456 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1457 CondVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1458 TrueVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1459 FalseVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(2));
1462 setInsertPointAfterBundle(E->Scalars);
1464 Value *Cond = vectorizeTree(CondVec);
1465 Value *True = vectorizeTree(TrueVec);
1466 Value *False = vectorizeTree(FalseVec);
1468 if (Value *V = alreadyVectorized(E->Scalars))
1471 Value *V = Builder.CreateSelect(Cond, True, False);
1472 E->VectorizedValue = V;
1475 case Instruction::Add:
1476 case Instruction::FAdd:
1477 case Instruction::Sub:
1478 case Instruction::FSub:
1479 case Instruction::Mul:
1480 case Instruction::FMul:
1481 case Instruction::UDiv:
1482 case Instruction::SDiv:
1483 case Instruction::FDiv:
1484 case Instruction::URem:
1485 case Instruction::SRem:
1486 case Instruction::FRem:
1487 case Instruction::Shl:
1488 case Instruction::LShr:
1489 case Instruction::AShr:
1490 case Instruction::And:
1491 case Instruction::Or:
1492 case Instruction::Xor: {
1493 ValueList LHSVL, RHSVL;
1494 if (isa<BinaryOperator>(VL0) && VL0->isCommutative())
1495 reorderInputsAccordingToOpcode(E->Scalars, LHSVL, RHSVL);
1497 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1498 LHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1499 RHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1502 setInsertPointAfterBundle(E->Scalars);
1504 Value *LHS = vectorizeTree(LHSVL);
1505 Value *RHS = vectorizeTree(RHSVL);
1507 if (LHS == RHS && isa<Instruction>(LHS)) {
1508 assert((VL0->getOperand(0) == VL0->getOperand(1)) && "Invalid order");
1511 if (Value *V = alreadyVectorized(E->Scalars))
1514 BinaryOperator *BinOp = cast<BinaryOperator>(VL0);
1515 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), LHS, RHS);
1516 E->VectorizedValue = V;
1518 if (Instruction *I = dyn_cast<Instruction>(V))
1519 return propagateMetadata(I, E->Scalars);
1523 case Instruction::Load: {
1524 // Loads are inserted at the head of the tree because we don't want to
1525 // sink them all the way down past store instructions.
1526 setInsertPointAfterBundle(E->Scalars);
1528 LoadInst *LI = cast<LoadInst>(VL0);
1529 unsigned AS = LI->getPointerAddressSpace();
1531 Value *VecPtr = Builder.CreateBitCast(LI->getPointerOperand(),
1532 VecTy->getPointerTo(AS));
1533 unsigned Alignment = LI->getAlignment();
1534 LI = Builder.CreateLoad(VecPtr);
1535 LI->setAlignment(Alignment);
1536 E->VectorizedValue = LI;
1537 return propagateMetadata(LI, E->Scalars);
1539 case Instruction::Store: {
1540 StoreInst *SI = cast<StoreInst>(VL0);
1541 unsigned Alignment = SI->getAlignment();
1542 unsigned AS = SI->getPointerAddressSpace();
1545 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1546 ValueOp.push_back(cast<StoreInst>(E->Scalars[i])->getValueOperand());
1548 setInsertPointAfterBundle(E->Scalars);
1550 Value *VecValue = vectorizeTree(ValueOp);
1551 Value *VecPtr = Builder.CreateBitCast(SI->getPointerOperand(),
1552 VecTy->getPointerTo(AS));
1553 StoreInst *S = Builder.CreateStore(VecValue, VecPtr);
1554 S->setAlignment(Alignment);
1555 E->VectorizedValue = S;
1556 return propagateMetadata(S, E->Scalars);
1559 llvm_unreachable("unknown inst");
1564 Value *BoUpSLP::vectorizeTree() {
1565 Builder.SetInsertPoint(F->getEntryBlock().begin());
1566 vectorizeTree(&VectorizableTree[0]);
1568 DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() << " values .\n");
1570 // Extract all of the elements with the external uses.
1571 for (UserList::iterator it = ExternalUses.begin(), e = ExternalUses.end();
1573 Value *Scalar = it->Scalar;
1574 llvm::User *User = it->User;
1576 // Skip users that we already RAUW. This happens when one instruction
1577 // has multiple uses of the same value.
1578 if (std::find(Scalar->use_begin(), Scalar->use_end(), User) ==
1581 assert(ScalarToTreeEntry.count(Scalar) && "Invalid scalar");
1583 int Idx = ScalarToTreeEntry[Scalar];
1584 TreeEntry *E = &VectorizableTree[Idx];
1585 assert(!E->NeedToGather && "Extracting from a gather list");
1587 Value *Vec = E->VectorizedValue;
1588 assert(Vec && "Can't find vectorizable value");
1590 Value *Lane = Builder.getInt32(it->Lane);
1591 // Generate extracts for out-of-tree users.
1592 // Find the insertion point for the extractelement lane.
1593 if (PHINode *PN = dyn_cast<PHINode>(Vec)) {
1594 Builder.SetInsertPoint(PN->getParent()->getFirstInsertionPt());
1595 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1596 CSEBlocks.insert(PN->getParent());
1597 User->replaceUsesOfWith(Scalar, Ex);
1598 } else if (isa<Instruction>(Vec)){
1599 if (PHINode *PH = dyn_cast<PHINode>(User)) {
1600 for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
1601 if (PH->getIncomingValue(i) == Scalar) {
1602 Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
1603 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1604 CSEBlocks.insert(PH->getIncomingBlock(i));
1605 PH->setOperand(i, Ex);
1609 Builder.SetInsertPoint(cast<Instruction>(User));
1610 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1611 CSEBlocks.insert(cast<Instruction>(User)->getParent());
1612 User->replaceUsesOfWith(Scalar, Ex);
1615 Builder.SetInsertPoint(F->getEntryBlock().begin());
1616 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1617 CSEBlocks.insert(&F->getEntryBlock());
1618 User->replaceUsesOfWith(Scalar, Ex);
1621 DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
1624 // For each vectorized value:
1625 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
1626 TreeEntry *Entry = &VectorizableTree[EIdx];
1629 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
1630 Value *Scalar = Entry->Scalars[Lane];
1632 // No need to handle users of gathered values.
1633 if (Entry->NeedToGather)
1636 assert(Entry->VectorizedValue && "Can't find vectorizable value");
1638 Type *Ty = Scalar->getType();
1639 if (!Ty->isVoidTy()) {
1640 for (Value::use_iterator User = Scalar->use_begin(),
1641 UE = Scalar->use_end(); User != UE; ++User) {
1642 DEBUG(dbgs() << "SLP: \tvalidating user:" << **User << ".\n");
1644 assert((ScalarToTreeEntry.count(*User) ||
1645 // It is legal to replace the reduction users by undef.
1646 (RdxOps && RdxOps->count(*User))) &&
1647 "Replacing out-of-tree value with undef");
1649 Value *Undef = UndefValue::get(Ty);
1650 Scalar->replaceAllUsesWith(Undef);
1652 DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
1653 cast<Instruction>(Scalar)->eraseFromParent();
1657 for (Function::iterator it = F->begin(), e = F->end(); it != e; ++it) {
1658 BlocksNumbers[it].forget();
1660 Builder.ClearInsertionPoint();
1662 return VectorizableTree[0].VectorizedValue;
1666 const DominatorTree *DT;
1669 DTCmp(const DominatorTree *DT) : DT(DT) {}
1670 bool operator()(const BasicBlock *A, const BasicBlock *B) const {
1671 return DT->properlyDominates(A, B);
1675 void BoUpSLP::optimizeGatherSequence() {
1676 DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
1677 << " gather sequences instructions.\n");
1678 // LICM InsertElementInst sequences.
1679 for (SetVector<Instruction *>::iterator it = GatherSeq.begin(),
1680 e = GatherSeq.end(); it != e; ++it) {
1681 InsertElementInst *Insert = dyn_cast<InsertElementInst>(*it);
1686 // Check if this block is inside a loop.
1687 Loop *L = LI->getLoopFor(Insert->getParent());
1691 // Check if it has a preheader.
1692 BasicBlock *PreHeader = L->getLoopPreheader();
1696 // If the vector or the element that we insert into it are
1697 // instructions that are defined in this basic block then we can't
1698 // hoist this instruction.
1699 Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
1700 Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
1701 if (CurrVec && L->contains(CurrVec))
1703 if (NewElem && L->contains(NewElem))
1706 // We can hoist this instruction. Move it to the pre-header.
1707 Insert->moveBefore(PreHeader->getTerminator());
1710 // Sort blocks by domination. This ensures we visit a block after all blocks
1711 // dominating it are visited.
1712 SmallVector<BasicBlock *, 8> CSEWorkList(CSEBlocks.begin(), CSEBlocks.end());
1713 std::stable_sort(CSEWorkList.begin(), CSEWorkList.end(), DTCmp(DT));
1715 // Perform O(N^2) search over the gather sequences and merge identical
1716 // instructions. TODO: We can further optimize this scan if we split the
1717 // instructions into different buckets based on the insert lane.
1718 SmallVector<Instruction *, 16> Visited;
1719 for (SmallVectorImpl<BasicBlock *>::iterator I = CSEWorkList.begin(),
1720 E = CSEWorkList.end();
1722 assert((I == CSEWorkList.begin() || !DT->dominates(*I, *llvm::prior(I))) &&
1723 "Worklist not sorted properly!");
1724 BasicBlock *BB = *I;
1725 // For all instructions in blocks containing gather sequences:
1726 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) {
1727 Instruction *In = it++;
1728 if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In))
1731 // Check if we can replace this instruction with any of the
1732 // visited instructions.
1733 for (SmallVectorImpl<Instruction *>::iterator v = Visited.begin(),
1736 if (In->isIdenticalTo(*v) &&
1737 DT->dominates((*v)->getParent(), In->getParent())) {
1738 In->replaceAllUsesWith(*v);
1739 In->eraseFromParent();
1745 assert(std::find(Visited.begin(), Visited.end(), In) == Visited.end());
1746 Visited.push_back(In);
1754 /// The SLPVectorizer Pass.
1755 struct SLPVectorizer : public FunctionPass {
1756 typedef SmallVector<StoreInst *, 8> StoreList;
1757 typedef MapVector<Value *, StoreList> StoreListMap;
1759 /// Pass identification, replacement for typeid
1762 explicit SLPVectorizer() : FunctionPass(ID) {
1763 initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
1766 ScalarEvolution *SE;
1768 TargetTransformInfo *TTI;
1773 virtual bool runOnFunction(Function &F) {
1774 SE = &getAnalysis<ScalarEvolution>();
1775 DL = getAnalysisIfAvailable<DataLayout>();
1776 TTI = &getAnalysis<TargetTransformInfo>();
1777 AA = &getAnalysis<AliasAnalysis>();
1778 LI = &getAnalysis<LoopInfo>();
1779 DT = &getAnalysis<DominatorTree>();
1782 bool Changed = false;
1784 // If the target claims to have no vector registers don't attempt
1786 if (!TTI->getNumberOfRegisters(true))
1789 // Must have DataLayout. We can't require it because some tests run w/o
1794 // Don't vectorize when the attribute NoImplicitFloat is used.
1795 if (F.hasFnAttribute(Attribute::NoImplicitFloat))
1798 DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
1800 // Use the bollom up slp vectorizer to construct chains that start with
1801 // he store instructions.
1802 BoUpSLP R(&F, SE, DL, TTI, AA, LI, DT);
1804 // Scan the blocks in the function in post order.
1805 for (po_iterator<BasicBlock*> it = po_begin(&F.getEntryBlock()),
1806 e = po_end(&F.getEntryBlock()); it != e; ++it) {
1807 BasicBlock *BB = *it;
1809 // Vectorize trees that end at stores.
1810 if (unsigned count = collectStores(BB, R)) {
1812 DEBUG(dbgs() << "SLP: Found " << count << " stores to vectorize.\n");
1813 Changed |= vectorizeStoreChains(R);
1816 // Vectorize trees that end at reductions.
1817 Changed |= vectorizeChainsInBlock(BB, R);
1821 R.optimizeGatherSequence();
1822 DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
1823 DEBUG(verifyFunction(F));
1828 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1829 FunctionPass::getAnalysisUsage(AU);
1830 AU.addRequired<ScalarEvolution>();
1831 AU.addRequired<AliasAnalysis>();
1832 AU.addRequired<TargetTransformInfo>();
1833 AU.addRequired<LoopInfo>();
1834 AU.addRequired<DominatorTree>();
1835 AU.addPreserved<LoopInfo>();
1836 AU.addPreserved<DominatorTree>();
1837 AU.setPreservesCFG();
1842 /// \brief Collect memory references and sort them according to their base
1843 /// object. We sort the stores to their base objects to reduce the cost of the
1844 /// quadratic search on the stores. TODO: We can further reduce this cost
1845 /// if we flush the chain creation every time we run into a memory barrier.
1846 unsigned collectStores(BasicBlock *BB, BoUpSLP &R);
1848 /// \brief Try to vectorize a chain that starts at two arithmetic instrs.
1849 bool tryToVectorizePair(Value *A, Value *B, BoUpSLP &R);
1851 /// \brief Try to vectorize a list of operands.
1852 /// \returns true if a value was vectorized.
1853 bool tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R);
1855 /// \brief Try to vectorize a chain that may start at the operands of \V;
1856 bool tryToVectorize(BinaryOperator *V, BoUpSLP &R);
1858 /// \brief Vectorize the stores that were collected in StoreRefs.
1859 bool vectorizeStoreChains(BoUpSLP &R);
1861 /// \brief Scan the basic block and look for patterns that are likely to start
1862 /// a vectorization chain.
1863 bool vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R);
1865 bool vectorizeStoreChain(ArrayRef<Value *> Chain, int CostThreshold,
1868 bool vectorizeStores(ArrayRef<StoreInst *> Stores, int costThreshold,
1871 StoreListMap StoreRefs;
1874 /// \brief Check that the Values in the slice in VL array are still existant in
1875 /// the WeakVH array.
1876 /// Vectorization of part of the VL array may cause later values in the VL array
1877 /// to become invalid. We track when this has happened in the WeakVH array.
1878 static bool hasValueBeenRAUWed(ArrayRef<Value *> &VL,
1879 SmallVectorImpl<WeakVH> &VH,
1880 unsigned SliceBegin,
1881 unsigned SliceSize) {
1882 for (unsigned i = SliceBegin; i < SliceBegin + SliceSize; ++i)
1889 bool SLPVectorizer::vectorizeStoreChain(ArrayRef<Value *> Chain,
1890 int CostThreshold, BoUpSLP &R) {
1891 unsigned ChainLen = Chain.size();
1892 DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
1894 Type *StoreTy = cast<StoreInst>(Chain[0])->getValueOperand()->getType();
1895 unsigned Sz = DL->getTypeSizeInBits(StoreTy);
1896 unsigned VF = MinVecRegSize / Sz;
1898 if (!isPowerOf2_32(Sz) || VF < 2)
1901 // Keep track of values that were delete by vectorizing in the loop below.
1902 SmallVector<WeakVH, 8> TrackValues(Chain.begin(), Chain.end());
1904 bool Changed = false;
1905 // Look for profitable vectorizable trees at all offsets, starting at zero.
1906 for (unsigned i = 0, e = ChainLen; i < e; ++i) {
1910 // Check that a previous iteration of this loop did not delete the Value.
1911 if (hasValueBeenRAUWed(Chain, TrackValues, i, VF))
1914 DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
1916 ArrayRef<Value *> Operands = Chain.slice(i, VF);
1918 R.buildTree(Operands);
1920 int Cost = R.getTreeCost();
1922 DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
1923 if (Cost < CostThreshold) {
1924 DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
1927 // Move to the next bundle.
1936 bool SLPVectorizer::vectorizeStores(ArrayRef<StoreInst *> Stores,
1937 int costThreshold, BoUpSLP &R) {
1938 SetVector<Value *> Heads, Tails;
1939 SmallDenseMap<Value *, Value *> ConsecutiveChain;
1941 // We may run into multiple chains that merge into a single chain. We mark the
1942 // stores that we vectorized so that we don't visit the same store twice.
1943 BoUpSLP::ValueSet VectorizedStores;
1944 bool Changed = false;
1946 // Do a quadratic search on all of the given stores and find
1947 // all of the pairs of stores that follow each other.
1948 for (unsigned i = 0, e = Stores.size(); i < e; ++i) {
1949 for (unsigned j = 0; j < e; ++j) {
1953 if (R.isConsecutiveAccess(Stores[i], Stores[j])) {
1954 Tails.insert(Stores[j]);
1955 Heads.insert(Stores[i]);
1956 ConsecutiveChain[Stores[i]] = Stores[j];
1961 // For stores that start but don't end a link in the chain:
1962 for (SetVector<Value *>::iterator it = Heads.begin(), e = Heads.end();
1964 if (Tails.count(*it))
1967 // We found a store instr that starts a chain. Now follow the chain and try
1969 BoUpSLP::ValueList Operands;
1971 // Collect the chain into a list.
1972 while (Tails.count(I) || Heads.count(I)) {
1973 if (VectorizedStores.count(I))
1975 Operands.push_back(I);
1976 // Move to the next value in the chain.
1977 I = ConsecutiveChain[I];
1980 bool Vectorized = vectorizeStoreChain(Operands, costThreshold, R);
1982 // Mark the vectorized stores so that we don't vectorize them again.
1984 VectorizedStores.insert(Operands.begin(), Operands.end());
1985 Changed |= Vectorized;
1992 unsigned SLPVectorizer::collectStores(BasicBlock *BB, BoUpSLP &R) {
1995 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1996 StoreInst *SI = dyn_cast<StoreInst>(it);
2000 // Don't touch volatile stores.
2001 if (!SI->isSimple())
2004 // Check that the pointer points to scalars.
2005 Type *Ty = SI->getValueOperand()->getType();
2006 if (Ty->isAggregateType() || Ty->isVectorTy())
2009 // Find the base pointer.
2010 Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), DL);
2012 // Save the store locations.
2013 StoreRefs[Ptr].push_back(SI);
2019 bool SLPVectorizer::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
2022 Value *VL[] = { A, B };
2023 return tryToVectorizeList(VL, R);
2026 bool SLPVectorizer::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R) {
2030 DEBUG(dbgs() << "SLP: Vectorizing a list of length = " << VL.size() << ".\n");
2032 // Check that all of the parts are scalar instructions of the same type.
2033 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
2037 unsigned Opcode0 = I0->getOpcode();
2039 Type *Ty0 = I0->getType();
2040 unsigned Sz = DL->getTypeSizeInBits(Ty0);
2041 unsigned VF = MinVecRegSize / Sz;
2043 for (int i = 0, e = VL.size(); i < e; ++i) {
2044 Type *Ty = VL[i]->getType();
2045 if (Ty->isAggregateType() || Ty->isVectorTy())
2047 Instruction *Inst = dyn_cast<Instruction>(VL[i]);
2048 if (!Inst || Inst->getOpcode() != Opcode0)
2052 bool Changed = false;
2054 // Keep track of values that were delete by vectorizing in the loop below.
2055 SmallVector<WeakVH, 8> TrackValues(VL.begin(), VL.end());
2057 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
2058 unsigned OpsWidth = 0;
2065 if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
2068 // Check that a previous iteration of this loop did not delete the Value.
2069 if (hasValueBeenRAUWed(VL, TrackValues, i, OpsWidth))
2072 DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
2074 ArrayRef<Value *> Ops = VL.slice(i, OpsWidth);
2077 int Cost = R.getTreeCost();
2079 if (Cost < -SLPCostThreshold) {
2080 DEBUG(dbgs() << "SLP: Vectorizing pair at cost:" << Cost << ".\n");
2083 // Move to the next bundle.
2092 bool SLPVectorizer::tryToVectorize(BinaryOperator *V, BoUpSLP &R) {
2096 // Try to vectorize V.
2097 if (tryToVectorizePair(V->getOperand(0), V->getOperand(1), R))
2100 BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0));
2101 BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1));
2103 if (B && B->hasOneUse()) {
2104 BinaryOperator *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
2105 BinaryOperator *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
2106 if (tryToVectorizePair(A, B0, R)) {
2110 if (tryToVectorizePair(A, B1, R)) {
2117 if (A && A->hasOneUse()) {
2118 BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
2119 BinaryOperator *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
2120 if (tryToVectorizePair(A0, B, R)) {
2124 if (tryToVectorizePair(A1, B, R)) {
2132 /// \brief Generate a shuffle mask to be used in a reduction tree.
2134 /// \param VecLen The length of the vector to be reduced.
2135 /// \param NumEltsToRdx The number of elements that should be reduced in the
2137 /// \param IsPairwise Whether the reduction is a pairwise or splitting
2138 /// reduction. A pairwise reduction will generate a mask of
2139 /// <0,2,...> or <1,3,..> while a splitting reduction will generate
2140 /// <2,3, undef,undef> for a vector of 4 and NumElts = 2.
2141 /// \param IsLeft True will generate a mask of even elements, odd otherwise.
2142 static Value *createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx,
2143 bool IsPairwise, bool IsLeft,
2144 IRBuilder<> &Builder) {
2145 assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask");
2147 SmallVector<Constant *, 32> ShuffleMask(
2148 VecLen, UndefValue::get(Builder.getInt32Ty()));
2151 // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
2152 for (unsigned i = 0; i != NumEltsToRdx; ++i)
2153 ShuffleMask[i] = Builder.getInt32(2 * i + !IsLeft);
2155 // Move the upper half of the vector to the lower half.
2156 for (unsigned i = 0; i != NumEltsToRdx; ++i)
2157 ShuffleMask[i] = Builder.getInt32(NumEltsToRdx + i);
2159 return ConstantVector::get(ShuffleMask);
2163 /// Model horizontal reductions.
2165 /// A horizontal reduction is a tree of reduction operations (currently add and
2166 /// fadd) that has operations that can be put into a vector as its leaf.
2167 /// For example, this tree:
2174 /// This tree has "mul" as its reduced values and "+" as its reduction
2175 /// operations. A reduction might be feeding into a store or a binary operation
2190 class HorizontalReduction {
2191 SmallPtrSet<Value *, 16> ReductionOps;
2192 SmallVector<Value *, 32> ReducedVals;
2194 BinaryOperator *ReductionRoot;
2195 PHINode *ReductionPHI;
2197 /// The opcode of the reduction.
2198 unsigned ReductionOpcode;
2199 /// The opcode of the values we perform a reduction on.
2200 unsigned ReducedValueOpcode;
2201 /// The width of one full horizontal reduction operation.
2202 unsigned ReduxWidth;
2203 /// Should we model this reduction as a pairwise reduction tree or a tree that
2204 /// splits the vector in halves and adds those halves.
2205 bool IsPairwiseReduction;
2208 HorizontalReduction()
2209 : ReductionRoot(0), ReductionPHI(0), ReductionOpcode(0),
2210 ReducedValueOpcode(0), ReduxWidth(0), IsPairwiseReduction(false) {}
2212 /// \brief Try to find a reduction tree.
2213 bool matchAssociativeReduction(PHINode *Phi, BinaryOperator *B,
2216 std::find(Phi->op_begin(), Phi->op_end(), B) != Phi->op_end()) &&
2217 "Thi phi needs to use the binary operator");
2219 // We could have a initial reductions that is not an add.
2220 // r *= v1 + v2 + v3 + v4
2221 // In such a case start looking for a tree rooted in the first '+'.
2223 if (B->getOperand(0) == Phi) {
2225 B = dyn_cast<BinaryOperator>(B->getOperand(1));
2226 } else if (B->getOperand(1) == Phi) {
2228 B = dyn_cast<BinaryOperator>(B->getOperand(0));
2235 Type *Ty = B->getType();
2236 if (Ty->isVectorTy())
2239 ReductionOpcode = B->getOpcode();
2240 ReducedValueOpcode = 0;
2241 ReduxWidth = MinVecRegSize / DL->getTypeSizeInBits(Ty);
2248 // We currently only support adds.
2249 if (ReductionOpcode != Instruction::Add &&
2250 ReductionOpcode != Instruction::FAdd)
2253 // Post order traverse the reduction tree starting at B. We only handle true
2254 // trees containing only binary operators.
2255 SmallVector<std::pair<BinaryOperator *, unsigned>, 32> Stack;
2256 Stack.push_back(std::make_pair(B, 0));
2257 while (!Stack.empty()) {
2258 BinaryOperator *TreeN = Stack.back().first;
2259 unsigned EdgeToVist = Stack.back().second++;
2260 bool IsReducedValue = TreeN->getOpcode() != ReductionOpcode;
2262 // Only handle trees in the current basic block.
2263 if (TreeN->getParent() != B->getParent())
2266 // Each tree node needs to have one user except for the ultimate
2268 if (!TreeN->hasOneUse() && TreeN != B)
2272 if (EdgeToVist == 2 || IsReducedValue) {
2273 if (IsReducedValue) {
2274 // Make sure that the opcodes of the operations that we are going to
2276 if (!ReducedValueOpcode)
2277 ReducedValueOpcode = TreeN->getOpcode();
2278 else if (ReducedValueOpcode != TreeN->getOpcode())
2280 ReducedVals.push_back(TreeN);
2282 // We need to be able to reassociate the adds.
2283 if (!TreeN->isAssociative())
2285 ReductionOps.insert(TreeN);
2292 // Visit left or right.
2293 Value *NextV = TreeN->getOperand(EdgeToVist);
2294 BinaryOperator *Next = dyn_cast<BinaryOperator>(NextV);
2296 Stack.push_back(std::make_pair(Next, 0));
2297 else if (NextV != Phi)
2303 /// \brief Attempt to vectorize the tree found by
2304 /// matchAssociativeReduction.
2305 bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
2306 if (ReducedVals.empty())
2309 unsigned NumReducedVals = ReducedVals.size();
2310 if (NumReducedVals < ReduxWidth)
2313 Value *VectorizedTree = 0;
2314 IRBuilder<> Builder(ReductionRoot);
2315 FastMathFlags Unsafe;
2316 Unsafe.setUnsafeAlgebra();
2317 Builder.SetFastMathFlags(Unsafe);
2320 for (; i < NumReducedVals - ReduxWidth + 1; i += ReduxWidth) {
2321 ArrayRef<Value *> ValsToReduce(&ReducedVals[i], ReduxWidth);
2322 V.buildTree(ValsToReduce, &ReductionOps);
2325 int Cost = V.getTreeCost() + getReductionCost(TTI, ReducedVals[i]);
2326 if (Cost >= -SLPCostThreshold)
2329 DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" << Cost
2332 // Vectorize a tree.
2333 DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
2334 Value *VectorizedRoot = V.vectorizeTree();
2336 // Emit a reduction.
2337 Value *ReducedSubTree = emitReduction(VectorizedRoot, Builder);
2338 if (VectorizedTree) {
2339 Builder.SetCurrentDebugLocation(Loc);
2340 VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
2341 ReducedSubTree, "bin.rdx");
2343 VectorizedTree = ReducedSubTree;
2346 if (VectorizedTree) {
2347 // Finish the reduction.
2348 for (; i < NumReducedVals; ++i) {
2349 Builder.SetCurrentDebugLocation(
2350 cast<Instruction>(ReducedVals[i])->getDebugLoc());
2351 VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
2356 assert(ReductionRoot != NULL && "Need a reduction operation");
2357 ReductionRoot->setOperand(0, VectorizedTree);
2358 ReductionRoot->setOperand(1, ReductionPHI);
2360 ReductionRoot->replaceAllUsesWith(VectorizedTree);
2362 return VectorizedTree != 0;
2367 /// \brief Calcuate the cost of a reduction.
2368 int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal) {
2369 Type *ScalarTy = FirstReducedVal->getType();
2370 Type *VecTy = VectorType::get(ScalarTy, ReduxWidth);
2372 int PairwiseRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, true);
2373 int SplittingRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, false);
2375 IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
2376 int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
2378 int ScalarReduxCost =
2379 ReduxWidth * TTI->getArithmeticInstrCost(ReductionOpcode, VecTy);
2381 DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost
2382 << " for reduction that starts with " << *FirstReducedVal
2384 << (IsPairwiseReduction ? "pairwise" : "splitting")
2385 << " reduction)\n");
2387 return VecReduxCost - ScalarReduxCost;
2390 static Value *createBinOp(IRBuilder<> &Builder, unsigned Opcode, Value *L,
2391 Value *R, const Twine &Name = "") {
2392 if (Opcode == Instruction::FAdd)
2393 return Builder.CreateFAdd(L, R, Name);
2394 return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, L, R, Name);
2397 /// \brief Emit a horizontal reduction of the vectorized value.
2398 Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder) {
2399 assert(VectorizedValue && "Need to have a vectorized tree node");
2400 Instruction *ValToReduce = dyn_cast<Instruction>(VectorizedValue);
2401 assert(isPowerOf2_32(ReduxWidth) &&
2402 "We only handle power-of-two reductions for now");
2404 Value *TmpVec = ValToReduce;
2405 for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
2406 if (IsPairwiseReduction) {
2408 createRdxShuffleMask(ReduxWidth, i, true, true, Builder);
2410 createRdxShuffleMask(ReduxWidth, i, true, false, Builder);
2412 Value *LeftShuf = Builder.CreateShuffleVector(
2413 TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l");
2414 Value *RightShuf = Builder.CreateShuffleVector(
2415 TmpVec, UndefValue::get(TmpVec->getType()), (RightMask),
2417 TmpVec = createBinOp(Builder, ReductionOpcode, LeftShuf, RightShuf,
2421 createRdxShuffleMask(ReduxWidth, i, false, false, Builder);
2422 Value *Shuf = Builder.CreateShuffleVector(
2423 TmpVec, UndefValue::get(TmpVec->getType()), UpperHalf, "rdx.shuf");
2424 TmpVec = createBinOp(Builder, ReductionOpcode, TmpVec, Shuf, "bin.rdx");
2428 // The result is in the first element of the vector.
2429 return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
2433 /// \brief Recognize construction of vectors like
2434 /// %ra = insertelement <4 x float> undef, float %s0, i32 0
2435 /// %rb = insertelement <4 x float> %ra, float %s1, i32 1
2436 /// %rc = insertelement <4 x float> %rb, float %s2, i32 2
2437 /// %rd = insertelement <4 x float> %rc, float %s3, i32 3
2439 /// Returns true if it matches
2441 static bool findBuildVector(InsertElementInst *IE,
2442 SmallVectorImpl<Value *> &Ops) {
2443 if (!isa<UndefValue>(IE->getOperand(0)))
2447 Ops.push_back(IE->getOperand(1));
2449 if (IE->use_empty())
2452 InsertElementInst *NextUse = dyn_cast<InsertElementInst>(IE->use_back());
2456 // If this isn't the final use, make sure the next insertelement is the only
2457 // use. It's OK if the final constructed vector is used multiple times
2458 if (!IE->hasOneUse())
2467 static bool PhiTypeSorterFunc(Value *V, Value *V2) {
2468 return V->getType() < V2->getType();
2471 bool SLPVectorizer::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
2472 bool Changed = false;
2473 SmallVector<Value *, 4> Incoming;
2474 SmallSet<Value *, 16> VisitedInstrs;
2476 bool HaveVectorizedPhiNodes = true;
2477 while (HaveVectorizedPhiNodes) {
2478 HaveVectorizedPhiNodes = false;
2480 // Collect the incoming values from the PHIs.
2482 for (BasicBlock::iterator instr = BB->begin(), ie = BB->end(); instr != ie;
2484 PHINode *P = dyn_cast<PHINode>(instr);
2488 if (!VisitedInstrs.count(P))
2489 Incoming.push_back(P);
2493 std::stable_sort(Incoming.begin(), Incoming.end(), PhiTypeSorterFunc);
2495 // Try to vectorize elements base on their type.
2496 for (SmallVector<Value *, 4>::iterator IncIt = Incoming.begin(),
2500 // Look for the next elements with the same type.
2501 SmallVector<Value *, 4>::iterator SameTypeIt = IncIt;
2502 while (SameTypeIt != E &&
2503 (*SameTypeIt)->getType() == (*IncIt)->getType()) {
2504 VisitedInstrs.insert(*SameTypeIt);
2508 // Try to vectorize them.
2509 unsigned NumElts = (SameTypeIt - IncIt);
2510 DEBUG(errs() << "SLP: Trying to vectorize starting at PHIs (" << NumElts << ")\n");
2512 tryToVectorizeList(ArrayRef<Value *>(IncIt, NumElts), R)) {
2513 // Success start over because instructions might have been changed.
2514 HaveVectorizedPhiNodes = true;
2519 // Start over at the next instruction of a differnt type (or the end).
2524 VisitedInstrs.clear();
2526 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) {
2527 // We may go through BB multiple times so skip the one we have checked.
2528 if (!VisitedInstrs.insert(it))
2531 if (isa<DbgInfoIntrinsic>(it))
2534 // Try to vectorize reductions that use PHINodes.
2535 if (PHINode *P = dyn_cast<PHINode>(it)) {
2536 // Check that the PHI is a reduction PHI.
2537 if (P->getNumIncomingValues() != 2)
2540 (P->getIncomingBlock(0) == BB
2541 ? (P->getIncomingValue(0))
2542 : (P->getIncomingBlock(1) == BB ? P->getIncomingValue(1) : 0));
2543 // Check if this is a Binary Operator.
2544 BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx);
2548 // Try to match and vectorize a horizontal reduction.
2549 HorizontalReduction HorRdx;
2550 if (ShouldVectorizeHor &&
2551 HorRdx.matchAssociativeReduction(P, BI, DL) &&
2552 HorRdx.tryToReduce(R, TTI)) {
2559 Value *Inst = BI->getOperand(0);
2561 Inst = BI->getOperand(1);
2563 if (tryToVectorize(dyn_cast<BinaryOperator>(Inst), R)) {
2564 // We would like to start over since some instructions are deleted
2565 // and the iterator may become invalid value.
2575 // Try to vectorize horizontal reductions feeding into a store.
2576 if (ShouldStartVectorizeHorAtStore)
2577 if (StoreInst *SI = dyn_cast<StoreInst>(it))
2578 if (BinaryOperator *BinOp =
2579 dyn_cast<BinaryOperator>(SI->getValueOperand())) {
2580 HorizontalReduction HorRdx;
2581 if (((HorRdx.matchAssociativeReduction(0, BinOp, DL) &&
2582 HorRdx.tryToReduce(R, TTI)) ||
2583 tryToVectorize(BinOp, R))) {
2591 // Try to vectorize trees that start at compare instructions.
2592 if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
2593 if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) {
2595 // We would like to start over since some instructions are deleted
2596 // and the iterator may become invalid value.
2602 for (int i = 0; i < 2; ++i) {
2603 if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i))) {
2604 if (tryToVectorizePair(BI->getOperand(0), BI->getOperand(1), R)) {
2606 // We would like to start over since some instructions are deleted
2607 // and the iterator may become invalid value.
2616 // Try to vectorize trees that start at insertelement instructions.
2617 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(it)) {
2618 SmallVector<Value *, 8> Ops;
2619 if (!findBuildVector(IE, Ops))
2622 if (tryToVectorizeList(Ops, R)) {
2635 bool SLPVectorizer::vectorizeStoreChains(BoUpSLP &R) {
2636 bool Changed = false;
2637 // Attempt to sort and vectorize each of the store-groups.
2638 for (StoreListMap::iterator it = StoreRefs.begin(), e = StoreRefs.end();
2640 if (it->second.size() < 2)
2643 DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
2644 << it->second.size() << ".\n");
2646 // Process the stores in chunks of 16.
2647 for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI+=16) {
2648 unsigned Len = std::min<unsigned>(CE - CI, 16);
2649 ArrayRef<StoreInst *> Chunk(&it->second[CI], Len);
2650 Changed |= vectorizeStores(Chunk, -SLPCostThreshold, R);
2656 } // end anonymous namespace
2658 char SLPVectorizer::ID = 0;
2659 static const char lv_name[] = "SLP Vectorizer";
2660 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
2661 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
2662 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
2663 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
2664 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
2665 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
2668 Pass *createSLPVectorizerPass() { return new SLPVectorizer(); }