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 \p I after propagating metadata from \p VL.
167 static Instruction *propagateMetadata(Instruction *I, ArrayRef<Value *> VL) {
168 Instruction *I0 = cast<Instruction>(VL[0]);
169 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
170 I0->getAllMetadataOtherThanDebugLoc(Metadata);
172 for (unsigned i = 0, n = Metadata.size(); i != n; ++i) {
173 unsigned Kind = Metadata[i].first;
174 MDNode *MD = Metadata[i].second;
176 for (int i = 1, e = VL.size(); MD && i != e; i++) {
177 Instruction *I = cast<Instruction>(VL[i]);
178 MDNode *IMD = I->getMetadata(Kind);
182 MD = 0; // Remove unknown metadata
184 case LLVMContext::MD_tbaa:
185 MD = MDNode::getMostGenericTBAA(MD, IMD);
187 case LLVMContext::MD_fpmath:
188 MD = MDNode::getMostGenericFPMath(MD, IMD);
192 I->setMetadata(Kind, MD);
197 /// \returns The type that all of the values in \p VL have or null if there
198 /// are different types.
199 static Type* getSameType(ArrayRef<Value *> VL) {
200 Type *Ty = VL[0]->getType();
201 for (int i = 1, e = VL.size(); i < e; i++)
202 if (VL[i]->getType() != Ty)
208 /// \returns True if the ExtractElement instructions in VL can be vectorized
209 /// to use the original vector.
210 static bool CanReuseExtract(ArrayRef<Value *> VL) {
211 assert(Instruction::ExtractElement == getSameOpcode(VL) && "Invalid opcode");
212 // Check if all of the extracts come from the same vector and from the
215 ExtractElementInst *E0 = cast<ExtractElementInst>(VL0);
216 Value *Vec = E0->getOperand(0);
218 // We have to extract from the same vector type.
219 unsigned NElts = Vec->getType()->getVectorNumElements();
221 if (NElts != VL.size())
224 // Check that all of the indices extract from the correct offset.
225 ConstantInt *CI = dyn_cast<ConstantInt>(E0->getOperand(1));
226 if (!CI || CI->getZExtValue())
229 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
230 ExtractElementInst *E = cast<ExtractElementInst>(VL[i]);
231 ConstantInt *CI = dyn_cast<ConstantInt>(E->getOperand(1));
233 if (!CI || CI->getZExtValue() != i || E->getOperand(0) != Vec)
240 static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
241 SmallVectorImpl<Value *> &Left,
242 SmallVectorImpl<Value *> &Right) {
244 SmallVector<Value *, 16> OrigLeft, OrigRight;
246 bool AllSameOpcodeLeft = true;
247 bool AllSameOpcodeRight = true;
248 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
249 Instruction *I = cast<Instruction>(VL[i]);
250 Value *V0 = I->getOperand(0);
251 Value *V1 = I->getOperand(1);
253 OrigLeft.push_back(V0);
254 OrigRight.push_back(V1);
256 Instruction *I0 = dyn_cast<Instruction>(V0);
257 Instruction *I1 = dyn_cast<Instruction>(V1);
259 // Check whether all operands on one side have the same opcode. In this case
260 // we want to preserve the original order and not make things worse by
262 AllSameOpcodeLeft = I0;
263 AllSameOpcodeRight = I1;
265 if (i && AllSameOpcodeLeft) {
266 if(Instruction *P0 = dyn_cast<Instruction>(OrigLeft[i-1])) {
267 if(P0->getOpcode() != I0->getOpcode())
268 AllSameOpcodeLeft = false;
270 AllSameOpcodeLeft = false;
272 if (i && AllSameOpcodeRight) {
273 if(Instruction *P1 = dyn_cast<Instruction>(OrigRight[i-1])) {
274 if(P1->getOpcode() != I1->getOpcode())
275 AllSameOpcodeRight = false;
277 AllSameOpcodeRight = false;
280 // Sort two opcodes. In the code below we try to preserve the ability to use
281 // broadcast of values instead of individual inserts.
288 // If we just sorted according to opcode we would leave the first line in
289 // tact but we would swap vl2 with vr2 because opcode(phi) > opcode(load).
292 // Because vr2 and vr1 are from the same load we loose the opportunity of a
293 // broadcast for the packed right side in the backend: we have [vr1, vl2]
294 // instead of [vr1, vr2=vr1].
296 if(!i && I0->getOpcode() > I1->getOpcode()) {
299 } else if (i && I0->getOpcode() > I1->getOpcode() && Right[i-1] != I1) {
300 // Try not to destroy a broad cast for no apparent benefit.
303 } else if (i && I0->getOpcode() == I1->getOpcode() && Right[i-1] == I0) {
304 // Try preserve broadcasts.
307 } else if (i && I0->getOpcode() == I1->getOpcode() && Left[i-1] == I1) {
308 // Try preserve broadcasts.
317 // One opcode, put the instruction on the right.
327 bool LeftBroadcast = isSplat(Left);
328 bool RightBroadcast = isSplat(Right);
330 // Don't reorder if the operands where good to begin with.
331 if (!(LeftBroadcast || RightBroadcast) &&
332 (AllSameOpcodeRight || AllSameOpcodeLeft)) {
338 /// Bottom Up SLP Vectorizer.
341 typedef SmallVector<Value *, 8> ValueList;
342 typedef SmallVector<Instruction *, 16> InstrList;
343 typedef SmallPtrSet<Value *, 16> ValueSet;
344 typedef SmallVector<StoreInst *, 8> StoreList;
346 BoUpSLP(Function *Func, ScalarEvolution *Se, DataLayout *Dl,
347 TargetTransformInfo *Tti, AliasAnalysis *Aa, LoopInfo *Li,
349 F(Func), SE(Se), DL(Dl), TTI(Tti), AA(Aa), LI(Li), DT(Dt),
350 Builder(Se->getContext()) {
351 // Setup the block numbering utility for all of the blocks in the
353 for (Function::iterator it = F->begin(), e = F->end(); it != e; ++it) {
355 BlocksNumbers[BB] = BlockNumbering(BB);
359 /// \brief Vectorize the tree that starts with the elements in \p VL.
360 /// Returns the vectorized root.
361 Value *vectorizeTree();
363 /// \returns the vectorization cost of the subtree that starts at \p VL.
364 /// A negative number means that this is profitable.
367 /// Construct a vectorizable tree that starts at \p Roots and is possibly
368 /// used by a reduction of \p RdxOps.
369 void buildTree(ArrayRef<Value *> Roots, ValueSet *RdxOps = 0);
371 /// Clear the internal data structures that are created by 'buildTree'.
374 VectorizableTree.clear();
375 ScalarToTreeEntry.clear();
377 ExternalUses.clear();
378 MemBarrierIgnoreList.clear();
381 /// \returns true if the memory operations A and B are consecutive.
382 bool isConsecutiveAccess(Value *A, Value *B);
384 /// \brief Perform LICM and CSE on the newly generated gather sequences.
385 void optimizeGatherSequence();
389 /// \returns the cost of the vectorizable entry.
390 int getEntryCost(TreeEntry *E);
392 /// This is the recursive part of buildTree.
393 void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth);
395 /// Vectorize a single entry in the tree.
396 Value *vectorizeTree(TreeEntry *E);
398 /// Vectorize a single entry in the tree, starting in \p VL.
399 Value *vectorizeTree(ArrayRef<Value *> VL);
401 /// \returns the pointer to the vectorized value if \p VL is already
402 /// vectorized, or NULL. They may happen in cycles.
403 Value *alreadyVectorized(ArrayRef<Value *> VL) const;
405 /// \brief Take the pointer operand from the Load/Store instruction.
406 /// \returns NULL if this is not a valid Load/Store instruction.
407 static Value *getPointerOperand(Value *I);
409 /// \brief Take the address space operand from the Load/Store instruction.
410 /// \returns -1 if this is not a valid Load/Store instruction.
411 static unsigned getAddressSpaceOperand(Value *I);
413 /// \returns the scalarization cost for this type. Scalarization in this
414 /// context means the creation of vectors from a group of scalars.
415 int getGatherCost(Type *Ty);
417 /// \returns the scalarization cost for this list of values. Assuming that
418 /// this subtree gets vectorized, we may need to extract the values from the
419 /// roots. This method calculates the cost of extracting the values.
420 int getGatherCost(ArrayRef<Value *> VL);
422 /// \returns the AA location that is being access by the instruction.
423 AliasAnalysis::Location getLocation(Instruction *I);
425 /// \brief Checks if it is possible to sink an instruction from
426 /// \p Src to \p Dst.
427 /// \returns the pointer to the barrier instruction if we can't sink.
428 Value *getSinkBarrier(Instruction *Src, Instruction *Dst);
430 /// \returns the index of the last instruction in the BB from \p VL.
431 int getLastIndex(ArrayRef<Value *> VL);
433 /// \returns the Instruction in the bundle \p VL.
434 Instruction *getLastInstruction(ArrayRef<Value *> VL);
436 /// \brief Set the Builder insert point to one after the last instruction in
438 void setInsertPointAfterBundle(ArrayRef<Value *> VL);
440 /// \returns a vector from a collection of scalars in \p VL.
441 Value *Gather(ArrayRef<Value *> VL, VectorType *Ty);
443 /// \returns whether the VectorizableTree is fully vectoriable and will
444 /// be beneficial even the tree height is tiny.
445 bool isFullyVectorizableTinyTree();
448 TreeEntry() : Scalars(), VectorizedValue(0), LastScalarIndex(0),
451 /// \returns true if the scalars in VL are equal to this entry.
452 bool isSame(ArrayRef<Value *> VL) const {
453 assert(VL.size() == Scalars.size() && "Invalid size");
454 return std::equal(VL.begin(), VL.end(), Scalars.begin());
457 /// A vector of scalars.
460 /// The Scalars are vectorized into this value. It is initialized to Null.
461 Value *VectorizedValue;
463 /// The index in the basic block of the last scalar.
466 /// Do we need to gather this sequence ?
470 /// Create a new VectorizableTree entry.
471 TreeEntry *newTreeEntry(ArrayRef<Value *> VL, bool Vectorized) {
472 VectorizableTree.push_back(TreeEntry());
473 int idx = VectorizableTree.size() - 1;
474 TreeEntry *Last = &VectorizableTree[idx];
475 Last->Scalars.insert(Last->Scalars.begin(), VL.begin(), VL.end());
476 Last->NeedToGather = !Vectorized;
478 Last->LastScalarIndex = getLastIndex(VL);
479 for (int i = 0, e = VL.size(); i != e; ++i) {
480 assert(!ScalarToTreeEntry.count(VL[i]) && "Scalar already in tree!");
481 ScalarToTreeEntry[VL[i]] = idx;
484 Last->LastScalarIndex = 0;
485 MustGather.insert(VL.begin(), VL.end());
490 /// -- Vectorization State --
491 /// Holds all of the tree entries.
492 std::vector<TreeEntry> VectorizableTree;
494 /// Maps a specific scalar to its tree entry.
495 SmallDenseMap<Value*, int> ScalarToTreeEntry;
497 /// A list of scalars that we found that we need to keep as scalars.
500 /// This POD struct describes one external user in the vectorized tree.
501 struct ExternalUser {
502 ExternalUser (Value *S, llvm::User *U, int L) :
503 Scalar(S), User(U), Lane(L){};
504 // Which scalar in our function.
506 // Which user that uses the scalar.
508 // Which lane does the scalar belong to.
511 typedef SmallVector<ExternalUser, 16> UserList;
513 /// A list of values that need to extracted out of the tree.
514 /// This list holds pairs of (Internal Scalar : External User).
515 UserList ExternalUses;
517 /// A list of instructions to ignore while sinking
518 /// memory instructions. This map must be reset between runs of getCost.
519 ValueSet MemBarrierIgnoreList;
521 /// Holds all of the instructions that we gathered.
522 SetVector<Instruction *> GatherSeq;
523 /// A list of blocks that we are going to CSE.
524 SmallSet<BasicBlock *, 8> CSEBlocks;
526 /// Numbers instructions in different blocks.
527 DenseMap<BasicBlock *, BlockNumbering> BlocksNumbers;
529 /// Reduction operators.
532 // Analysis and block reference.
536 TargetTransformInfo *TTI;
540 /// Instruction builder to construct the vectorized tree.
544 void BoUpSLP::buildTree(ArrayRef<Value *> Roots, ValueSet *Rdx) {
547 if (!getSameType(Roots))
549 buildTree_rec(Roots, 0);
551 // Collect the values that we need to extract from the tree.
552 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
553 TreeEntry *Entry = &VectorizableTree[EIdx];
556 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
557 Value *Scalar = Entry->Scalars[Lane];
559 // No need to handle users of gathered values.
560 if (Entry->NeedToGather)
563 for (Value::use_iterator User = Scalar->use_begin(),
564 UE = Scalar->use_end(); User != UE; ++User) {
565 DEBUG(dbgs() << "SLP: Checking user:" << **User << ".\n");
567 bool Gathered = MustGather.count(*User);
569 // Skip in-tree scalars that become vectors.
570 if (ScalarToTreeEntry.count(*User) && !Gathered) {
571 DEBUG(dbgs() << "SLP: \tInternal user will be removed:" <<
573 int Idx = ScalarToTreeEntry[*User]; (void) Idx;
574 assert(!VectorizableTree[Idx].NeedToGather && "Bad state");
577 Instruction *UserInst = dyn_cast<Instruction>(*User);
581 // Ignore uses that are part of the reduction.
582 if (Rdx && std::find(Rdx->begin(), Rdx->end(), UserInst) != Rdx->end())
585 DEBUG(dbgs() << "SLP: Need to extract:" << **User << " from lane " <<
586 Lane << " from " << *Scalar << ".\n");
587 ExternalUses.push_back(ExternalUser(Scalar, *User, Lane));
594 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth) {
595 bool SameTy = getSameType(VL); (void)SameTy;
596 assert(SameTy && "Invalid types!");
598 if (Depth == RecursionMaxDepth) {
599 DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
600 newTreeEntry(VL, false);
604 // Don't handle vectors.
605 if (VL[0]->getType()->isVectorTy()) {
606 DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
607 newTreeEntry(VL, false);
611 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
612 if (SI->getValueOperand()->getType()->isVectorTy()) {
613 DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
614 newTreeEntry(VL, false);
618 // If all of the operands are identical or constant we have a simple solution.
619 if (allConstant(VL) || isSplat(VL) || !getSameBlock(VL) ||
620 !getSameOpcode(VL)) {
621 DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
622 newTreeEntry(VL, false);
626 // We now know that this is a vector of instructions of the same type from
629 // Check if this is a duplicate of another entry.
630 if (ScalarToTreeEntry.count(VL[0])) {
631 int Idx = ScalarToTreeEntry[VL[0]];
632 TreeEntry *E = &VectorizableTree[Idx];
633 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
634 DEBUG(dbgs() << "SLP: \tChecking bundle: " << *VL[i] << ".\n");
635 if (E->Scalars[i] != VL[i]) {
636 DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
637 newTreeEntry(VL, false);
641 DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *VL[0] << ".\n");
645 // Check that none of the instructions in the bundle are already in the tree.
646 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
647 if (ScalarToTreeEntry.count(VL[i])) {
648 DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
649 ") is already in tree.\n");
650 newTreeEntry(VL, false);
655 // If any of the scalars appears in the table OR it is marked as a value that
656 // needs to stat scalar then we need to gather the scalars.
657 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
658 if (ScalarToTreeEntry.count(VL[i]) || MustGather.count(VL[i])) {
659 DEBUG(dbgs() << "SLP: Gathering due to gathered scalar. \n");
660 newTreeEntry(VL, false);
665 // Check that all of the users of the scalars that we want to vectorize are
667 Instruction *VL0 = cast<Instruction>(VL[0]);
668 int MyLastIndex = getLastIndex(VL);
669 BasicBlock *BB = cast<Instruction>(VL0)->getParent();
671 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
672 Instruction *Scalar = cast<Instruction>(VL[i]);
673 DEBUG(dbgs() << "SLP: Checking users of " << *Scalar << ". \n");
674 for (Value::use_iterator U = Scalar->use_begin(), UE = Scalar->use_end();
676 DEBUG(dbgs() << "SLP: \tUser " << **U << ". \n");
677 Instruction *User = dyn_cast<Instruction>(*U);
679 DEBUG(dbgs() << "SLP: Gathering due unknown user. \n");
680 newTreeEntry(VL, false);
684 // We don't care if the user is in a different basic block.
685 BasicBlock *UserBlock = User->getParent();
686 if (UserBlock != BB) {
687 DEBUG(dbgs() << "SLP: User from a different basic block "
692 // If this is a PHINode within this basic block then we can place the
693 // extract wherever we want.
694 if (isa<PHINode>(*User)) {
695 DEBUG(dbgs() << "SLP: \tWe can schedule PHIs:" << *User << ". \n");
699 // Check if this is a safe in-tree user.
700 if (ScalarToTreeEntry.count(User)) {
701 int Idx = ScalarToTreeEntry[User];
702 int VecLocation = VectorizableTree[Idx].LastScalarIndex;
703 if (VecLocation <= MyLastIndex) {
704 DEBUG(dbgs() << "SLP: Gathering due to unschedulable vector. \n");
705 newTreeEntry(VL, false);
708 DEBUG(dbgs() << "SLP: In-tree user (" << *User << ") at #" <<
709 VecLocation << " vector value (" << *Scalar << ") at #"
710 << MyLastIndex << ".\n");
714 // This user is part of the reduction.
715 if (RdxOps && RdxOps->count(User))
718 // Make sure that we can schedule this unknown user.
719 BlockNumbering &BN = BlocksNumbers[BB];
720 int UserIndex = BN.getIndex(User);
721 if (UserIndex < MyLastIndex) {
723 DEBUG(dbgs() << "SLP: Can't schedule extractelement for "
725 newTreeEntry(VL, false);
731 // Check that every instructions appears once in this bundle.
732 for (unsigned i = 0, e = VL.size(); i < e; ++i)
733 for (unsigned j = i+1; j < e; ++j)
734 if (VL[i] == VL[j]) {
735 DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
736 newTreeEntry(VL, false);
740 // Check that instructions in this bundle don't reference other instructions.
741 // The runtime of this check is O(N * N-1 * uses(N)) and a typical N is 4.
742 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
743 for (Value::use_iterator U = VL[i]->use_begin(), UE = VL[i]->use_end();
745 for (unsigned j = 0; j < e; ++j) {
746 if (i != j && *U == VL[j]) {
747 DEBUG(dbgs() << "SLP: Intra-bundle dependencies!" << **U << ". \n");
748 newTreeEntry(VL, false);
755 DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
757 unsigned Opcode = getSameOpcode(VL);
759 // Check if it is safe to sink the loads or the stores.
760 if (Opcode == Instruction::Load || Opcode == Instruction::Store) {
761 Instruction *Last = getLastInstruction(VL);
763 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
766 Value *Barrier = getSinkBarrier(cast<Instruction>(VL[i]), Last);
768 DEBUG(dbgs() << "SLP: Can't sink " << *VL[i] << "\n down to " << *Last
769 << "\n because of " << *Barrier << ". Gathering.\n");
770 newTreeEntry(VL, false);
777 case Instruction::PHI: {
778 PHINode *PH = dyn_cast<PHINode>(VL0);
780 // Check for terminator values (e.g. invoke).
781 for (unsigned j = 0; j < VL.size(); ++j)
782 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
783 TerminatorInst *Term = dyn_cast<TerminatorInst>(cast<PHINode>(VL[j])->getIncomingValue(i));
785 DEBUG(dbgs() << "SLP: Need to swizzle PHINodes (TerminatorInst use).\n");
786 newTreeEntry(VL, false);
791 newTreeEntry(VL, true);
792 DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
794 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
796 // Prepare the operand vector.
797 for (unsigned j = 0; j < VL.size(); ++j)
798 Operands.push_back(cast<PHINode>(VL[j])->getIncomingValue(i));
800 buildTree_rec(Operands, Depth + 1);
804 case Instruction::ExtractElement: {
805 bool Reuse = CanReuseExtract(VL);
807 DEBUG(dbgs() << "SLP: Reusing extract sequence.\n");
809 newTreeEntry(VL, Reuse);
812 case Instruction::Load: {
813 // Check if the loads are consecutive or of we need to swizzle them.
814 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i) {
815 LoadInst *L = cast<LoadInst>(VL[i]);
816 if (!L->isSimple() || !isConsecutiveAccess(VL[i], VL[i + 1])) {
817 newTreeEntry(VL, false);
818 DEBUG(dbgs() << "SLP: Need to swizzle loads.\n");
822 newTreeEntry(VL, true);
823 DEBUG(dbgs() << "SLP: added a vector of loads.\n");
826 case Instruction::ZExt:
827 case Instruction::SExt:
828 case Instruction::FPToUI:
829 case Instruction::FPToSI:
830 case Instruction::FPExt:
831 case Instruction::PtrToInt:
832 case Instruction::IntToPtr:
833 case Instruction::SIToFP:
834 case Instruction::UIToFP:
835 case Instruction::Trunc:
836 case Instruction::FPTrunc:
837 case Instruction::BitCast: {
838 Type *SrcTy = VL0->getOperand(0)->getType();
839 for (unsigned i = 0; i < VL.size(); ++i) {
840 Type *Ty = cast<Instruction>(VL[i])->getOperand(0)->getType();
841 if (Ty != SrcTy || Ty->isAggregateType() || Ty->isVectorTy()) {
842 newTreeEntry(VL, false);
843 DEBUG(dbgs() << "SLP: Gathering casts with different src types.\n");
847 newTreeEntry(VL, true);
848 DEBUG(dbgs() << "SLP: added a vector of casts.\n");
850 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
852 // Prepare the operand vector.
853 for (unsigned j = 0; j < VL.size(); ++j)
854 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
856 buildTree_rec(Operands, Depth+1);
860 case Instruction::ICmp:
861 case Instruction::FCmp: {
862 // Check that all of the compares have the same predicate.
863 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
864 Type *ComparedTy = cast<Instruction>(VL[0])->getOperand(0)->getType();
865 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
866 CmpInst *Cmp = cast<CmpInst>(VL[i]);
867 if (Cmp->getPredicate() != P0 ||
868 Cmp->getOperand(0)->getType() != ComparedTy) {
869 newTreeEntry(VL, false);
870 DEBUG(dbgs() << "SLP: Gathering cmp with different predicate.\n");
875 newTreeEntry(VL, true);
876 DEBUG(dbgs() << "SLP: added a vector of compares.\n");
878 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
880 // Prepare the operand vector.
881 for (unsigned j = 0; j < VL.size(); ++j)
882 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
884 buildTree_rec(Operands, Depth+1);
888 case Instruction::Select:
889 case Instruction::Add:
890 case Instruction::FAdd:
891 case Instruction::Sub:
892 case Instruction::FSub:
893 case Instruction::Mul:
894 case Instruction::FMul:
895 case Instruction::UDiv:
896 case Instruction::SDiv:
897 case Instruction::FDiv:
898 case Instruction::URem:
899 case Instruction::SRem:
900 case Instruction::FRem:
901 case Instruction::Shl:
902 case Instruction::LShr:
903 case Instruction::AShr:
904 case Instruction::And:
905 case Instruction::Or:
906 case Instruction::Xor: {
907 newTreeEntry(VL, true);
908 DEBUG(dbgs() << "SLP: added a vector of bin op.\n");
910 // Sort operands of the instructions so that each side is more likely to
911 // have the same opcode.
912 if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
913 ValueList Left, Right;
914 reorderInputsAccordingToOpcode(VL, Left, Right);
915 buildTree_rec(Left, Depth + 1);
916 buildTree_rec(Right, Depth + 1);
920 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
922 // Prepare the operand vector.
923 for (unsigned j = 0; j < VL.size(); ++j)
924 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
926 buildTree_rec(Operands, Depth+1);
930 case Instruction::Store: {
931 // Check if the stores are consecutive or of we need to swizzle them.
932 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
933 if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
934 newTreeEntry(VL, false);
935 DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
939 newTreeEntry(VL, true);
940 DEBUG(dbgs() << "SLP: added a vector of stores.\n");
943 for (unsigned j = 0; j < VL.size(); ++j)
944 Operands.push_back(cast<Instruction>(VL[j])->getOperand(0));
946 // We can ignore these values because we are sinking them down.
947 MemBarrierIgnoreList.insert(VL.begin(), VL.end());
948 buildTree_rec(Operands, Depth + 1);
952 newTreeEntry(VL, false);
953 DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
958 int BoUpSLP::getEntryCost(TreeEntry *E) {
959 ArrayRef<Value*> VL = E->Scalars;
961 Type *ScalarTy = VL[0]->getType();
962 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
963 ScalarTy = SI->getValueOperand()->getType();
964 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
966 if (E->NeedToGather) {
970 return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
972 return getGatherCost(E->Scalars);
975 assert(getSameOpcode(VL) && getSameType(VL) && getSameBlock(VL) &&
977 Instruction *VL0 = cast<Instruction>(VL[0]);
978 unsigned Opcode = VL0->getOpcode();
980 case Instruction::PHI: {
983 case Instruction::ExtractElement: {
984 if (CanReuseExtract(VL))
986 return getGatherCost(VecTy);
988 case Instruction::ZExt:
989 case Instruction::SExt:
990 case Instruction::FPToUI:
991 case Instruction::FPToSI:
992 case Instruction::FPExt:
993 case Instruction::PtrToInt:
994 case Instruction::IntToPtr:
995 case Instruction::SIToFP:
996 case Instruction::UIToFP:
997 case Instruction::Trunc:
998 case Instruction::FPTrunc:
999 case Instruction::BitCast: {
1000 Type *SrcTy = VL0->getOperand(0)->getType();
1002 // Calculate the cost of this instruction.
1003 int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(),
1004 VL0->getType(), SrcTy);
1006 VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
1007 int VecCost = TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy);
1008 return VecCost - ScalarCost;
1010 case Instruction::FCmp:
1011 case Instruction::ICmp:
1012 case Instruction::Select:
1013 case Instruction::Add:
1014 case Instruction::FAdd:
1015 case Instruction::Sub:
1016 case Instruction::FSub:
1017 case Instruction::Mul:
1018 case Instruction::FMul:
1019 case Instruction::UDiv:
1020 case Instruction::SDiv:
1021 case Instruction::FDiv:
1022 case Instruction::URem:
1023 case Instruction::SRem:
1024 case Instruction::FRem:
1025 case Instruction::Shl:
1026 case Instruction::LShr:
1027 case Instruction::AShr:
1028 case Instruction::And:
1029 case Instruction::Or:
1030 case Instruction::Xor: {
1031 // Calculate the cost of this instruction.
1034 if (Opcode == Instruction::FCmp || Opcode == Instruction::ICmp ||
1035 Opcode == Instruction::Select) {
1036 VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
1037 ScalarCost = VecTy->getNumElements() *
1038 TTI->getCmpSelInstrCost(Opcode, ScalarTy, Builder.getInt1Ty());
1039 VecCost = TTI->getCmpSelInstrCost(Opcode, VecTy, MaskTy);
1041 // Certain instructions can be cheaper to vectorize if they have a
1042 // constant second vector operand.
1043 TargetTransformInfo::OperandValueKind Op1VK =
1044 TargetTransformInfo::OK_AnyValue;
1045 TargetTransformInfo::OperandValueKind Op2VK =
1046 TargetTransformInfo::OK_UniformConstantValue;
1048 // Check whether all second operands are constant.
1049 for (unsigned i = 0; i < VL.size(); ++i)
1050 if (!isa<ConstantInt>(cast<Instruction>(VL[i])->getOperand(1))) {
1051 Op2VK = TargetTransformInfo::OK_AnyValue;
1056 VecTy->getNumElements() *
1057 TTI->getArithmeticInstrCost(Opcode, ScalarTy, Op1VK, Op2VK);
1058 VecCost = TTI->getArithmeticInstrCost(Opcode, VecTy, Op1VK, Op2VK);
1060 return VecCost - ScalarCost;
1062 case Instruction::Load: {
1063 // Cost of wide load - cost of scalar loads.
1064 int ScalarLdCost = VecTy->getNumElements() *
1065 TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
1066 int VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, 1, 0);
1067 return VecLdCost - ScalarLdCost;
1069 case Instruction::Store: {
1070 // We know that we can merge the stores. Calculate the cost.
1071 int ScalarStCost = VecTy->getNumElements() *
1072 TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
1073 int VecStCost = TTI->getMemoryOpCost(Instruction::Store, VecTy, 1, 0);
1074 return VecStCost - ScalarStCost;
1077 llvm_unreachable("Unknown instruction");
1081 bool BoUpSLP::isFullyVectorizableTinyTree() {
1082 DEBUG(dbgs() << "SLP: Check whether the tree with height " <<
1083 VectorizableTree.size() << " is fully vectorizable .\n");
1085 // We only handle trees of height 2.
1086 if (VectorizableTree.size() != 2)
1089 // Gathering cost would be too much for tiny trees.
1090 if (VectorizableTree[0].NeedToGather || VectorizableTree[1].NeedToGather)
1096 int BoUpSLP::getTreeCost() {
1098 DEBUG(dbgs() << "SLP: Calculating cost for tree of size " <<
1099 VectorizableTree.size() << ".\n");
1101 // We only vectorize tiny trees if it is fully vectorizable.
1102 if (VectorizableTree.size() < 3 && !isFullyVectorizableTinyTree()) {
1103 if (!VectorizableTree.size()) {
1104 assert(!ExternalUses.size() && "We should not have any external users");
1109 unsigned BundleWidth = VectorizableTree[0].Scalars.size();
1111 for (unsigned i = 0, e = VectorizableTree.size(); i != e; ++i) {
1112 int C = getEntryCost(&VectorizableTree[i]);
1113 DEBUG(dbgs() << "SLP: Adding cost " << C << " for bundle that starts with "
1114 << *VectorizableTree[i].Scalars[0] << " .\n");
1118 SmallSet<Value *, 16> ExtractCostCalculated;
1119 int ExtractCost = 0;
1120 for (UserList::iterator I = ExternalUses.begin(), E = ExternalUses.end();
1122 // We only add extract cost once for the same scalar.
1123 if (!ExtractCostCalculated.insert(I->Scalar))
1126 VectorType *VecTy = VectorType::get(I->Scalar->getType(), BundleWidth);
1127 ExtractCost += TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy,
1131 DEBUG(dbgs() << "SLP: Total Cost " << Cost + ExtractCost<< ".\n");
1132 return Cost + ExtractCost;
1135 int BoUpSLP::getGatherCost(Type *Ty) {
1137 for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
1138 Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
1142 int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) {
1143 // Find the type of the operands in VL.
1144 Type *ScalarTy = VL[0]->getType();
1145 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1146 ScalarTy = SI->getValueOperand()->getType();
1147 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1148 // Find the cost of inserting/extracting values from the vector.
1149 return getGatherCost(VecTy);
1152 AliasAnalysis::Location BoUpSLP::getLocation(Instruction *I) {
1153 if (StoreInst *SI = dyn_cast<StoreInst>(I))
1154 return AA->getLocation(SI);
1155 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1156 return AA->getLocation(LI);
1157 return AliasAnalysis::Location();
1160 Value *BoUpSLP::getPointerOperand(Value *I) {
1161 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1162 return LI->getPointerOperand();
1163 if (StoreInst *SI = dyn_cast<StoreInst>(I))
1164 return SI->getPointerOperand();
1168 unsigned BoUpSLP::getAddressSpaceOperand(Value *I) {
1169 if (LoadInst *L = dyn_cast<LoadInst>(I))
1170 return L->getPointerAddressSpace();
1171 if (StoreInst *S = dyn_cast<StoreInst>(I))
1172 return S->getPointerAddressSpace();
1176 bool BoUpSLP::isConsecutiveAccess(Value *A, Value *B) {
1177 Value *PtrA = getPointerOperand(A);
1178 Value *PtrB = getPointerOperand(B);
1179 unsigned ASA = getAddressSpaceOperand(A);
1180 unsigned ASB = getAddressSpaceOperand(B);
1182 // Check that the address spaces match and that the pointers are valid.
1183 if (!PtrA || !PtrB || (ASA != ASB))
1186 // Make sure that A and B are different pointers of the same type.
1187 if (PtrA == PtrB || PtrA->getType() != PtrB->getType())
1190 unsigned PtrBitWidth = DL->getPointerSizeInBits(ASA);
1191 Type *Ty = cast<PointerType>(PtrA->getType())->getElementType();
1192 APInt Size(PtrBitWidth, DL->getTypeStoreSize(Ty));
1194 APInt OffsetA(PtrBitWidth, 0), OffsetB(PtrBitWidth, 0);
1195 PtrA = PtrA->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetA);
1196 PtrB = PtrB->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetB);
1198 APInt OffsetDelta = OffsetB - OffsetA;
1200 // Check if they are based on the same pointer. That makes the offsets
1203 return OffsetDelta == Size;
1205 // Compute the necessary base pointer delta to have the necessary final delta
1206 // equal to the size.
1207 APInt BaseDelta = Size - OffsetDelta;
1209 // Otherwise compute the distance with SCEV between the base pointers.
1210 const SCEV *PtrSCEVA = SE->getSCEV(PtrA);
1211 const SCEV *PtrSCEVB = SE->getSCEV(PtrB);
1212 const SCEV *C = SE->getConstant(BaseDelta);
1213 const SCEV *X = SE->getAddExpr(PtrSCEVA, C);
1214 return X == PtrSCEVB;
1217 Value *BoUpSLP::getSinkBarrier(Instruction *Src, Instruction *Dst) {
1218 assert(Src->getParent() == Dst->getParent() && "Not the same BB");
1219 BasicBlock::iterator I = Src, E = Dst;
1220 /// Scan all of the instruction from SRC to DST and check if
1221 /// the source may alias.
1222 for (++I; I != E; ++I) {
1223 // Ignore store instructions that are marked as 'ignore'.
1224 if (MemBarrierIgnoreList.count(I))
1226 if (Src->mayWriteToMemory()) /* Write */ {
1227 if (!I->mayReadOrWriteMemory())
1230 if (!I->mayWriteToMemory())
1233 AliasAnalysis::Location A = getLocation(&*I);
1234 AliasAnalysis::Location B = getLocation(Src);
1236 if (!A.Ptr || !B.Ptr || AA->alias(A, B))
1242 int BoUpSLP::getLastIndex(ArrayRef<Value *> VL) {
1243 BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
1244 assert(BB == getSameBlock(VL) && BlocksNumbers.count(BB) && "Invalid block");
1245 BlockNumbering &BN = BlocksNumbers[BB];
1247 int MaxIdx = BN.getIndex(BB->getFirstNonPHI());
1248 for (unsigned i = 0, e = VL.size(); i < e; ++i)
1249 MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
1253 Instruction *BoUpSLP::getLastInstruction(ArrayRef<Value *> VL) {
1254 BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
1255 assert(BB == getSameBlock(VL) && BlocksNumbers.count(BB) && "Invalid block");
1256 BlockNumbering &BN = BlocksNumbers[BB];
1258 int MaxIdx = BN.getIndex(cast<Instruction>(VL[0]));
1259 for (unsigned i = 1, e = VL.size(); i < e; ++i)
1260 MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
1261 Instruction *I = BN.getInstruction(MaxIdx);
1262 assert(I && "bad location");
1266 void BoUpSLP::setInsertPointAfterBundle(ArrayRef<Value *> VL) {
1267 Instruction *VL0 = cast<Instruction>(VL[0]);
1268 Instruction *LastInst = getLastInstruction(VL);
1269 BasicBlock::iterator NextInst = LastInst;
1271 Builder.SetInsertPoint(VL0->getParent(), NextInst);
1272 Builder.SetCurrentDebugLocation(VL0->getDebugLoc());
1275 Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
1276 Value *Vec = UndefValue::get(Ty);
1277 // Generate the 'InsertElement' instruction.
1278 for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
1279 Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
1280 if (Instruction *Insrt = dyn_cast<Instruction>(Vec)) {
1281 GatherSeq.insert(Insrt);
1282 CSEBlocks.insert(Insrt->getParent());
1284 // Add to our 'need-to-extract' list.
1285 if (ScalarToTreeEntry.count(VL[i])) {
1286 int Idx = ScalarToTreeEntry[VL[i]];
1287 TreeEntry *E = &VectorizableTree[Idx];
1288 // Find which lane we need to extract.
1290 for (unsigned Lane = 0, LE = VL.size(); Lane != LE; ++Lane) {
1291 // Is this the lane of the scalar that we are looking for ?
1292 if (E->Scalars[Lane] == VL[i]) {
1297 assert(FoundLane >= 0 && "Could not find the correct lane");
1298 ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
1306 Value *BoUpSLP::alreadyVectorized(ArrayRef<Value *> VL) const {
1307 SmallDenseMap<Value*, int>::const_iterator Entry
1308 = ScalarToTreeEntry.find(VL[0]);
1309 if (Entry != ScalarToTreeEntry.end()) {
1310 int Idx = Entry->second;
1311 const TreeEntry *En = &VectorizableTree[Idx];
1312 if (En->isSame(VL) && En->VectorizedValue)
1313 return En->VectorizedValue;
1318 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
1319 if (ScalarToTreeEntry.count(VL[0])) {
1320 int Idx = ScalarToTreeEntry[VL[0]];
1321 TreeEntry *E = &VectorizableTree[Idx];
1323 return vectorizeTree(E);
1326 Type *ScalarTy = VL[0]->getType();
1327 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1328 ScalarTy = SI->getValueOperand()->getType();
1329 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1331 return Gather(VL, VecTy);
1334 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
1335 IRBuilder<>::InsertPointGuard Guard(Builder);
1337 if (E->VectorizedValue) {
1338 DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
1339 return E->VectorizedValue;
1342 Instruction *VL0 = cast<Instruction>(E->Scalars[0]);
1343 Type *ScalarTy = VL0->getType();
1344 if (StoreInst *SI = dyn_cast<StoreInst>(VL0))
1345 ScalarTy = SI->getValueOperand()->getType();
1346 VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size());
1348 if (E->NeedToGather) {
1349 setInsertPointAfterBundle(E->Scalars);
1350 return Gather(E->Scalars, VecTy);
1353 unsigned Opcode = VL0->getOpcode();
1354 assert(Opcode == getSameOpcode(E->Scalars) && "Invalid opcode");
1357 case Instruction::PHI: {
1358 PHINode *PH = dyn_cast<PHINode>(VL0);
1359 Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
1360 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1361 PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
1362 E->VectorizedValue = NewPhi;
1364 // PHINodes may have multiple entries from the same block. We want to
1365 // visit every block once.
1366 SmallSet<BasicBlock*, 4> VisitedBBs;
1368 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1370 BasicBlock *IBB = PH->getIncomingBlock(i);
1372 if (!VisitedBBs.insert(IBB)) {
1373 NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
1377 // Prepare the operand vector.
1378 for (unsigned j = 0; j < E->Scalars.size(); ++j)
1379 Operands.push_back(cast<PHINode>(E->Scalars[j])->
1380 getIncomingValueForBlock(IBB));
1382 Builder.SetInsertPoint(IBB->getTerminator());
1383 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1384 Value *Vec = vectorizeTree(Operands);
1385 NewPhi->addIncoming(Vec, IBB);
1388 assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
1389 "Invalid number of incoming values");
1393 case Instruction::ExtractElement: {
1394 if (CanReuseExtract(E->Scalars)) {
1395 Value *V = VL0->getOperand(0);
1396 E->VectorizedValue = V;
1399 return Gather(E->Scalars, VecTy);
1401 case Instruction::ZExt:
1402 case Instruction::SExt:
1403 case Instruction::FPToUI:
1404 case Instruction::FPToSI:
1405 case Instruction::FPExt:
1406 case Instruction::PtrToInt:
1407 case Instruction::IntToPtr:
1408 case Instruction::SIToFP:
1409 case Instruction::UIToFP:
1410 case Instruction::Trunc:
1411 case Instruction::FPTrunc:
1412 case Instruction::BitCast: {
1414 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1415 INVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1417 setInsertPointAfterBundle(E->Scalars);
1419 Value *InVec = vectorizeTree(INVL);
1421 if (Value *V = alreadyVectorized(E->Scalars))
1424 CastInst *CI = dyn_cast<CastInst>(VL0);
1425 Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
1426 E->VectorizedValue = V;
1429 case Instruction::FCmp:
1430 case Instruction::ICmp: {
1431 ValueList LHSV, RHSV;
1432 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1433 LHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1434 RHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1437 setInsertPointAfterBundle(E->Scalars);
1439 Value *L = vectorizeTree(LHSV);
1440 Value *R = vectorizeTree(RHSV);
1442 if (Value *V = alreadyVectorized(E->Scalars))
1445 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
1447 if (Opcode == Instruction::FCmp)
1448 V = Builder.CreateFCmp(P0, L, R);
1450 V = Builder.CreateICmp(P0, L, R);
1452 E->VectorizedValue = V;
1455 case Instruction::Select: {
1456 ValueList TrueVec, FalseVec, CondVec;
1457 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1458 CondVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1459 TrueVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1460 FalseVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(2));
1463 setInsertPointAfterBundle(E->Scalars);
1465 Value *Cond = vectorizeTree(CondVec);
1466 Value *True = vectorizeTree(TrueVec);
1467 Value *False = vectorizeTree(FalseVec);
1469 if (Value *V = alreadyVectorized(E->Scalars))
1472 Value *V = Builder.CreateSelect(Cond, True, False);
1473 E->VectorizedValue = V;
1476 case Instruction::Add:
1477 case Instruction::FAdd:
1478 case Instruction::Sub:
1479 case Instruction::FSub:
1480 case Instruction::Mul:
1481 case Instruction::FMul:
1482 case Instruction::UDiv:
1483 case Instruction::SDiv:
1484 case Instruction::FDiv:
1485 case Instruction::URem:
1486 case Instruction::SRem:
1487 case Instruction::FRem:
1488 case Instruction::Shl:
1489 case Instruction::LShr:
1490 case Instruction::AShr:
1491 case Instruction::And:
1492 case Instruction::Or:
1493 case Instruction::Xor: {
1494 ValueList LHSVL, RHSVL;
1495 if (isa<BinaryOperator>(VL0) && VL0->isCommutative())
1496 reorderInputsAccordingToOpcode(E->Scalars, LHSVL, RHSVL);
1498 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1499 LHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1500 RHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1503 setInsertPointAfterBundle(E->Scalars);
1505 Value *LHS = vectorizeTree(LHSVL);
1506 Value *RHS = vectorizeTree(RHSVL);
1508 if (LHS == RHS && isa<Instruction>(LHS)) {
1509 assert((VL0->getOperand(0) == VL0->getOperand(1)) && "Invalid order");
1512 if (Value *V = alreadyVectorized(E->Scalars))
1515 BinaryOperator *BinOp = cast<BinaryOperator>(VL0);
1516 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), LHS, RHS);
1517 E->VectorizedValue = V;
1519 if (Instruction *I = dyn_cast<Instruction>(V))
1520 return propagateMetadata(I, E->Scalars);
1524 case Instruction::Load: {
1525 // Loads are inserted at the head of the tree because we don't want to
1526 // sink them all the way down past store instructions.
1527 setInsertPointAfterBundle(E->Scalars);
1529 LoadInst *LI = cast<LoadInst>(VL0);
1530 unsigned AS = LI->getPointerAddressSpace();
1532 Value *VecPtr = Builder.CreateBitCast(LI->getPointerOperand(),
1533 VecTy->getPointerTo(AS));
1534 unsigned Alignment = LI->getAlignment();
1535 LI = Builder.CreateLoad(VecPtr);
1536 LI->setAlignment(Alignment);
1537 E->VectorizedValue = LI;
1538 return propagateMetadata(LI, E->Scalars);
1540 case Instruction::Store: {
1541 StoreInst *SI = cast<StoreInst>(VL0);
1542 unsigned Alignment = SI->getAlignment();
1543 unsigned AS = SI->getPointerAddressSpace();
1546 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1547 ValueOp.push_back(cast<StoreInst>(E->Scalars[i])->getValueOperand());
1549 setInsertPointAfterBundle(E->Scalars);
1551 Value *VecValue = vectorizeTree(ValueOp);
1552 Value *VecPtr = Builder.CreateBitCast(SI->getPointerOperand(),
1553 VecTy->getPointerTo(AS));
1554 StoreInst *S = Builder.CreateStore(VecValue, VecPtr);
1555 S->setAlignment(Alignment);
1556 E->VectorizedValue = S;
1557 return propagateMetadata(S, E->Scalars);
1560 llvm_unreachable("unknown inst");
1565 Value *BoUpSLP::vectorizeTree() {
1566 Builder.SetInsertPoint(F->getEntryBlock().begin());
1567 vectorizeTree(&VectorizableTree[0]);
1569 DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() << " values .\n");
1571 // Extract all of the elements with the external uses.
1572 for (UserList::iterator it = ExternalUses.begin(), e = ExternalUses.end();
1574 Value *Scalar = it->Scalar;
1575 llvm::User *User = it->User;
1577 // Skip users that we already RAUW. This happens when one instruction
1578 // has multiple uses of the same value.
1579 if (std::find(Scalar->use_begin(), Scalar->use_end(), User) ==
1582 assert(ScalarToTreeEntry.count(Scalar) && "Invalid scalar");
1584 int Idx = ScalarToTreeEntry[Scalar];
1585 TreeEntry *E = &VectorizableTree[Idx];
1586 assert(!E->NeedToGather && "Extracting from a gather list");
1588 Value *Vec = E->VectorizedValue;
1589 assert(Vec && "Can't find vectorizable value");
1591 Value *Lane = Builder.getInt32(it->Lane);
1592 // Generate extracts for out-of-tree users.
1593 // Find the insertion point for the extractelement lane.
1594 if (PHINode *PN = dyn_cast<PHINode>(Vec)) {
1595 Builder.SetInsertPoint(PN->getParent()->getFirstInsertionPt());
1596 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1597 CSEBlocks.insert(PN->getParent());
1598 User->replaceUsesOfWith(Scalar, Ex);
1599 } else if (isa<Instruction>(Vec)){
1600 if (PHINode *PH = dyn_cast<PHINode>(User)) {
1601 for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
1602 if (PH->getIncomingValue(i) == Scalar) {
1603 Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
1604 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1605 CSEBlocks.insert(PH->getIncomingBlock(i));
1606 PH->setOperand(i, Ex);
1610 Builder.SetInsertPoint(cast<Instruction>(User));
1611 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1612 CSEBlocks.insert(cast<Instruction>(User)->getParent());
1613 User->replaceUsesOfWith(Scalar, Ex);
1616 Builder.SetInsertPoint(F->getEntryBlock().begin());
1617 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1618 CSEBlocks.insert(&F->getEntryBlock());
1619 User->replaceUsesOfWith(Scalar, Ex);
1622 DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
1625 // For each vectorized value:
1626 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
1627 TreeEntry *Entry = &VectorizableTree[EIdx];
1630 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
1631 Value *Scalar = Entry->Scalars[Lane];
1633 // No need to handle users of gathered values.
1634 if (Entry->NeedToGather)
1637 assert(Entry->VectorizedValue && "Can't find vectorizable value");
1639 Type *Ty = Scalar->getType();
1640 if (!Ty->isVoidTy()) {
1641 for (Value::use_iterator User = Scalar->use_begin(),
1642 UE = Scalar->use_end(); User != UE; ++User) {
1643 DEBUG(dbgs() << "SLP: \tvalidating user:" << **User << ".\n");
1644 assert(!MustGather.count(*User) &&
1645 "Replacing gathered value with undef");
1647 assert((ScalarToTreeEntry.count(*User) ||
1648 // It is legal to replace the reduction users by undef.
1649 (RdxOps && RdxOps->count(*User))) &&
1650 "Replacing out-of-tree value with undef");
1652 Value *Undef = UndefValue::get(Ty);
1653 Scalar->replaceAllUsesWith(Undef);
1655 DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
1656 cast<Instruction>(Scalar)->eraseFromParent();
1660 for (Function::iterator it = F->begin(), e = F->end(); it != e; ++it) {
1661 BlocksNumbers[it].forget();
1663 Builder.ClearInsertionPoint();
1665 return VectorizableTree[0].VectorizedValue;
1669 const DominatorTree *DT;
1672 DTCmp(const DominatorTree *DT) : DT(DT) {}
1673 bool operator()(const BasicBlock *A, const BasicBlock *B) const {
1674 return DT->properlyDominates(A, B);
1678 void BoUpSLP::optimizeGatherSequence() {
1679 DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
1680 << " gather sequences instructions.\n");
1681 // LICM InsertElementInst sequences.
1682 for (SetVector<Instruction *>::iterator it = GatherSeq.begin(),
1683 e = GatherSeq.end(); it != e; ++it) {
1684 InsertElementInst *Insert = dyn_cast<InsertElementInst>(*it);
1689 // Check if this block is inside a loop.
1690 Loop *L = LI->getLoopFor(Insert->getParent());
1694 // Check if it has a preheader.
1695 BasicBlock *PreHeader = L->getLoopPreheader();
1699 // If the vector or the element that we insert into it are
1700 // instructions that are defined in this basic block then we can't
1701 // hoist this instruction.
1702 Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
1703 Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
1704 if (CurrVec && L->contains(CurrVec))
1706 if (NewElem && L->contains(NewElem))
1709 // We can hoist this instruction. Move it to the pre-header.
1710 Insert->moveBefore(PreHeader->getTerminator());
1713 // Sort blocks by domination. This ensures we visit a block after all blocks
1714 // dominating it are visited.
1715 SmallVector<BasicBlock *, 8> CSEWorkList(CSEBlocks.begin(), CSEBlocks.end());
1716 std::stable_sort(CSEWorkList.begin(), CSEWorkList.end(), DTCmp(DT));
1718 // Perform O(N^2) search over the gather sequences and merge identical
1719 // instructions. TODO: We can further optimize this scan if we split the
1720 // instructions into different buckets based on the insert lane.
1721 SmallVector<Instruction *, 16> Visited;
1722 for (SmallVectorImpl<BasicBlock *>::iterator I = CSEWorkList.begin(),
1723 E = CSEWorkList.end();
1725 assert((I == CSEWorkList.begin() || !DT->dominates(*I, *llvm::prior(I))) &&
1726 "Worklist not sorted properly!");
1727 BasicBlock *BB = *I;
1728 // For all instructions in blocks containing gather sequences:
1729 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) {
1730 Instruction *In = it++;
1731 if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In))
1734 // Check if we can replace this instruction with any of the
1735 // visited instructions.
1736 for (SmallVectorImpl<Instruction *>::iterator v = Visited.begin(),
1739 if (In->isIdenticalTo(*v) &&
1740 DT->dominates((*v)->getParent(), In->getParent())) {
1741 In->replaceAllUsesWith(*v);
1742 In->eraseFromParent();
1748 assert(std::find(Visited.begin(), Visited.end(), In) == Visited.end());
1749 Visited.push_back(In);
1757 /// The SLPVectorizer Pass.
1758 struct SLPVectorizer : public FunctionPass {
1759 typedef SmallVector<StoreInst *, 8> StoreList;
1760 typedef MapVector<Value *, StoreList> StoreListMap;
1762 /// Pass identification, replacement for typeid
1765 explicit SLPVectorizer() : FunctionPass(ID) {
1766 initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
1769 ScalarEvolution *SE;
1771 TargetTransformInfo *TTI;
1776 virtual bool runOnFunction(Function &F) {
1777 SE = &getAnalysis<ScalarEvolution>();
1778 DL = getAnalysisIfAvailable<DataLayout>();
1779 TTI = &getAnalysis<TargetTransformInfo>();
1780 AA = &getAnalysis<AliasAnalysis>();
1781 LI = &getAnalysis<LoopInfo>();
1782 DT = &getAnalysis<DominatorTree>();
1785 bool Changed = false;
1787 // If the target claims to have no vector registers don't attempt
1789 if (!TTI->getNumberOfRegisters(true))
1792 // Must have DataLayout. We can't require it because some tests run w/o
1797 // Don't vectorize when the attribute NoImplicitFloat is used.
1798 if (F.hasFnAttribute(Attribute::NoImplicitFloat))
1801 DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
1803 // Use the bollom up slp vectorizer to construct chains that start with
1804 // he store instructions.
1805 BoUpSLP R(&F, SE, DL, TTI, AA, LI, DT);
1807 // Scan the blocks in the function in post order.
1808 for (po_iterator<BasicBlock*> it = po_begin(&F.getEntryBlock()),
1809 e = po_end(&F.getEntryBlock()); it != e; ++it) {
1810 BasicBlock *BB = *it;
1812 // Vectorize trees that end at stores.
1813 if (unsigned count = collectStores(BB, R)) {
1815 DEBUG(dbgs() << "SLP: Found " << count << " stores to vectorize.\n");
1816 Changed |= vectorizeStoreChains(R);
1819 // Vectorize trees that end at reductions.
1820 Changed |= vectorizeChainsInBlock(BB, R);
1824 R.optimizeGatherSequence();
1825 DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
1826 DEBUG(verifyFunction(F));
1831 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1832 FunctionPass::getAnalysisUsage(AU);
1833 AU.addRequired<ScalarEvolution>();
1834 AU.addRequired<AliasAnalysis>();
1835 AU.addRequired<TargetTransformInfo>();
1836 AU.addRequired<LoopInfo>();
1837 AU.addRequired<DominatorTree>();
1838 AU.addPreserved<LoopInfo>();
1839 AU.addPreserved<DominatorTree>();
1840 AU.setPreservesCFG();
1845 /// \brief Collect memory references and sort them according to their base
1846 /// object. We sort the stores to their base objects to reduce the cost of the
1847 /// quadratic search on the stores. TODO: We can further reduce this cost
1848 /// if we flush the chain creation every time we run into a memory barrier.
1849 unsigned collectStores(BasicBlock *BB, BoUpSLP &R);
1851 /// \brief Try to vectorize a chain that starts at two arithmetic instrs.
1852 bool tryToVectorizePair(Value *A, Value *B, BoUpSLP &R);
1854 /// \brief Try to vectorize a list of operands.
1855 /// \returns true if a value was vectorized.
1856 bool tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R);
1858 /// \brief Try to vectorize a chain that may start at the operands of \V;
1859 bool tryToVectorize(BinaryOperator *V, BoUpSLP &R);
1861 /// \brief Vectorize the stores that were collected in StoreRefs.
1862 bool vectorizeStoreChains(BoUpSLP &R);
1864 /// \brief Scan the basic block and look for patterns that are likely to start
1865 /// a vectorization chain.
1866 bool vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R);
1868 bool vectorizeStoreChain(ArrayRef<Value *> Chain, int CostThreshold,
1871 bool vectorizeStores(ArrayRef<StoreInst *> Stores, int costThreshold,
1874 StoreListMap StoreRefs;
1877 /// \brief Check that the Values in the slice in VL array are still existant in
1878 /// the WeakVH array.
1879 /// Vectorization of part of the VL array may cause later values in the VL array
1880 /// to become invalid. We track when this has happened in the WeakVH array.
1881 static bool hasValueBeenRAUWed(ArrayRef<Value *> &VL,
1882 SmallVectorImpl<WeakVH> &VH,
1883 unsigned SliceBegin,
1884 unsigned SliceSize) {
1885 for (unsigned i = SliceBegin; i < SliceBegin + SliceSize; ++i)
1892 bool SLPVectorizer::vectorizeStoreChain(ArrayRef<Value *> Chain,
1893 int CostThreshold, BoUpSLP &R) {
1894 unsigned ChainLen = Chain.size();
1895 DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
1897 Type *StoreTy = cast<StoreInst>(Chain[0])->getValueOperand()->getType();
1898 unsigned Sz = DL->getTypeSizeInBits(StoreTy);
1899 unsigned VF = MinVecRegSize / Sz;
1901 if (!isPowerOf2_32(Sz) || VF < 2)
1904 // Keep track of values that were delete by vectorizing in the loop below.
1905 SmallVector<WeakVH, 8> TrackValues(Chain.begin(), Chain.end());
1907 bool Changed = false;
1908 // Look for profitable vectorizable trees at all offsets, starting at zero.
1909 for (unsigned i = 0, e = ChainLen; i < e; ++i) {
1913 // Check that a previous iteration of this loop did not delete the Value.
1914 if (hasValueBeenRAUWed(Chain, TrackValues, i, VF))
1917 DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
1919 ArrayRef<Value *> Operands = Chain.slice(i, VF);
1921 R.buildTree(Operands);
1923 int Cost = R.getTreeCost();
1925 DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
1926 if (Cost < CostThreshold) {
1927 DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
1930 // Move to the next bundle.
1939 bool SLPVectorizer::vectorizeStores(ArrayRef<StoreInst *> Stores,
1940 int costThreshold, BoUpSLP &R) {
1941 SetVector<Value *> Heads, Tails;
1942 SmallDenseMap<Value *, Value *> ConsecutiveChain;
1944 // We may run into multiple chains that merge into a single chain. We mark the
1945 // stores that we vectorized so that we don't visit the same store twice.
1946 BoUpSLP::ValueSet VectorizedStores;
1947 bool Changed = false;
1949 // Do a quadratic search on all of the given stores and find
1950 // all of the pairs of stores that follow each other.
1951 for (unsigned i = 0, e = Stores.size(); i < e; ++i) {
1952 for (unsigned j = 0; j < e; ++j) {
1956 if (R.isConsecutiveAccess(Stores[i], Stores[j])) {
1957 Tails.insert(Stores[j]);
1958 Heads.insert(Stores[i]);
1959 ConsecutiveChain[Stores[i]] = Stores[j];
1964 // For stores that start but don't end a link in the chain:
1965 for (SetVector<Value *>::iterator it = Heads.begin(), e = Heads.end();
1967 if (Tails.count(*it))
1970 // We found a store instr that starts a chain. Now follow the chain and try
1972 BoUpSLP::ValueList Operands;
1974 // Collect the chain into a list.
1975 while (Tails.count(I) || Heads.count(I)) {
1976 if (VectorizedStores.count(I))
1978 Operands.push_back(I);
1979 // Move to the next value in the chain.
1980 I = ConsecutiveChain[I];
1983 bool Vectorized = vectorizeStoreChain(Operands, costThreshold, R);
1985 // Mark the vectorized stores so that we don't vectorize them again.
1987 VectorizedStores.insert(Operands.begin(), Operands.end());
1988 Changed |= Vectorized;
1995 unsigned SLPVectorizer::collectStores(BasicBlock *BB, BoUpSLP &R) {
1998 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1999 StoreInst *SI = dyn_cast<StoreInst>(it);
2003 // Don't touch volatile stores.
2004 if (!SI->isSimple())
2007 // Check that the pointer points to scalars.
2008 Type *Ty = SI->getValueOperand()->getType();
2009 if (Ty->isAggregateType() || Ty->isVectorTy())
2012 // Find the base pointer.
2013 Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), DL);
2015 // Save the store locations.
2016 StoreRefs[Ptr].push_back(SI);
2022 bool SLPVectorizer::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
2025 Value *VL[] = { A, B };
2026 return tryToVectorizeList(VL, R);
2029 bool SLPVectorizer::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R) {
2033 DEBUG(dbgs() << "SLP: Vectorizing a list of length = " << VL.size() << ".\n");
2035 // Check that all of the parts are scalar instructions of the same type.
2036 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
2040 unsigned Opcode0 = I0->getOpcode();
2042 Type *Ty0 = I0->getType();
2043 unsigned Sz = DL->getTypeSizeInBits(Ty0);
2044 unsigned VF = MinVecRegSize / Sz;
2046 for (int i = 0, e = VL.size(); i < e; ++i) {
2047 Type *Ty = VL[i]->getType();
2048 if (Ty->isAggregateType() || Ty->isVectorTy())
2050 Instruction *Inst = dyn_cast<Instruction>(VL[i]);
2051 if (!Inst || Inst->getOpcode() != Opcode0)
2055 bool Changed = false;
2057 // Keep track of values that were delete by vectorizing in the loop below.
2058 SmallVector<WeakVH, 8> TrackValues(VL.begin(), VL.end());
2060 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
2061 unsigned OpsWidth = 0;
2068 if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
2071 // Check that a previous iteration of this loop did not delete the Value.
2072 if (hasValueBeenRAUWed(VL, TrackValues, i, OpsWidth))
2075 DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
2077 ArrayRef<Value *> Ops = VL.slice(i, OpsWidth);
2080 int Cost = R.getTreeCost();
2082 if (Cost < -SLPCostThreshold) {
2083 DEBUG(dbgs() << "SLP: Vectorizing pair at cost:" << Cost << ".\n");
2086 // Move to the next bundle.
2095 bool SLPVectorizer::tryToVectorize(BinaryOperator *V, BoUpSLP &R) {
2099 // Try to vectorize V.
2100 if (tryToVectorizePair(V->getOperand(0), V->getOperand(1), R))
2103 BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0));
2104 BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1));
2106 if (B && B->hasOneUse()) {
2107 BinaryOperator *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
2108 BinaryOperator *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
2109 if (tryToVectorizePair(A, B0, R)) {
2113 if (tryToVectorizePair(A, B1, R)) {
2120 if (A && A->hasOneUse()) {
2121 BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
2122 BinaryOperator *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
2123 if (tryToVectorizePair(A0, B, R)) {
2127 if (tryToVectorizePair(A1, B, R)) {
2135 /// \brief Generate a shuffle mask to be used in a reduction tree.
2137 /// \param VecLen The length of the vector to be reduced.
2138 /// \param NumEltsToRdx The number of elements that should be reduced in the
2140 /// \param IsPairwise Whether the reduction is a pairwise or splitting
2141 /// reduction. A pairwise reduction will generate a mask of
2142 /// <0,2,...> or <1,3,..> while a splitting reduction will generate
2143 /// <2,3, undef,undef> for a vector of 4 and NumElts = 2.
2144 /// \param IsLeft True will generate a mask of even elements, odd otherwise.
2145 static Value *createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx,
2146 bool IsPairwise, bool IsLeft,
2147 IRBuilder<> &Builder) {
2148 assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask");
2150 SmallVector<Constant *, 32> ShuffleMask(
2151 VecLen, UndefValue::get(Builder.getInt32Ty()));
2154 // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
2155 for (unsigned i = 0; i != NumEltsToRdx; ++i)
2156 ShuffleMask[i] = Builder.getInt32(2 * i + !IsLeft);
2158 // Move the upper half of the vector to the lower half.
2159 for (unsigned i = 0; i != NumEltsToRdx; ++i)
2160 ShuffleMask[i] = Builder.getInt32(NumEltsToRdx + i);
2162 return ConstantVector::get(ShuffleMask);
2166 /// Model horizontal reductions.
2168 /// A horizontal reduction is a tree of reduction operations (currently add and
2169 /// fadd) that has operations that can be put into a vector as its leaf.
2170 /// For example, this tree:
2177 /// This tree has "mul" as its reduced values and "+" as its reduction
2178 /// operations. A reduction might be feeding into a store or a binary operation
2193 class HorizontalReduction {
2194 SmallPtrSet<Value *, 16> ReductionOps;
2195 SmallVector<Value *, 32> ReducedVals;
2197 BinaryOperator *ReductionRoot;
2198 PHINode *ReductionPHI;
2200 /// The opcode of the reduction.
2201 unsigned ReductionOpcode;
2202 /// The opcode of the values we perform a reduction on.
2203 unsigned ReducedValueOpcode;
2204 /// The width of one full horizontal reduction operation.
2205 unsigned ReduxWidth;
2206 /// Should we model this reduction as a pairwise reduction tree or a tree that
2207 /// splits the vector in halves and adds those halves.
2208 bool IsPairwiseReduction;
2211 HorizontalReduction()
2212 : ReductionRoot(0), ReductionPHI(0), ReductionOpcode(0),
2213 ReducedValueOpcode(0), ReduxWidth(0), IsPairwiseReduction(false) {}
2215 /// \brief Try to find a reduction tree.
2216 bool matchAssociativeReduction(PHINode *Phi, BinaryOperator *B,
2219 std::find(Phi->op_begin(), Phi->op_end(), B) != Phi->op_end()) &&
2220 "Thi phi needs to use the binary operator");
2222 // We could have a initial reductions that is not an add.
2223 // r *= v1 + v2 + v3 + v4
2224 // In such a case start looking for a tree rooted in the first '+'.
2226 if (B->getOperand(0) == Phi) {
2228 B = dyn_cast<BinaryOperator>(B->getOperand(1));
2229 } else if (B->getOperand(1) == Phi) {
2231 B = dyn_cast<BinaryOperator>(B->getOperand(0));
2238 Type *Ty = B->getType();
2239 if (Ty->isVectorTy())
2242 ReductionOpcode = B->getOpcode();
2243 ReducedValueOpcode = 0;
2244 ReduxWidth = MinVecRegSize / DL->getTypeSizeInBits(Ty);
2251 // We currently only support adds.
2252 if (ReductionOpcode != Instruction::Add &&
2253 ReductionOpcode != Instruction::FAdd)
2256 // Post order traverse the reduction tree starting at B. We only handle true
2257 // trees containing only binary operators.
2258 SmallVector<std::pair<BinaryOperator *, unsigned>, 32> Stack;
2259 Stack.push_back(std::make_pair(B, 0));
2260 while (!Stack.empty()) {
2261 BinaryOperator *TreeN = Stack.back().first;
2262 unsigned EdgeToVist = Stack.back().second++;
2263 bool IsReducedValue = TreeN->getOpcode() != ReductionOpcode;
2265 // Only handle trees in the current basic block.
2266 if (TreeN->getParent() != B->getParent())
2269 // Each tree node needs to have one user except for the ultimate
2271 if (!TreeN->hasOneUse() && TreeN != B)
2275 if (EdgeToVist == 2 || IsReducedValue) {
2276 if (IsReducedValue) {
2277 // Make sure that the opcodes of the operations that we are going to
2279 if (!ReducedValueOpcode)
2280 ReducedValueOpcode = TreeN->getOpcode();
2281 else if (ReducedValueOpcode != TreeN->getOpcode())
2283 ReducedVals.push_back(TreeN);
2285 // We need to be able to reassociate the adds.
2286 if (!TreeN->isAssociative())
2288 ReductionOps.insert(TreeN);
2295 // Visit left or right.
2296 Value *NextV = TreeN->getOperand(EdgeToVist);
2297 BinaryOperator *Next = dyn_cast<BinaryOperator>(NextV);
2299 Stack.push_back(std::make_pair(Next, 0));
2300 else if (NextV != Phi)
2306 /// \brief Attempt to vectorize the tree found by
2307 /// matchAssociativeReduction.
2308 bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
2309 if (ReducedVals.empty())
2312 unsigned NumReducedVals = ReducedVals.size();
2313 if (NumReducedVals < ReduxWidth)
2316 Value *VectorizedTree = 0;
2317 IRBuilder<> Builder(ReductionRoot);
2318 FastMathFlags Unsafe;
2319 Unsafe.setUnsafeAlgebra();
2320 Builder.SetFastMathFlags(Unsafe);
2323 for (; i < NumReducedVals - ReduxWidth + 1; i += ReduxWidth) {
2324 ArrayRef<Value *> ValsToReduce(&ReducedVals[i], ReduxWidth);
2325 V.buildTree(ValsToReduce, &ReductionOps);
2328 int Cost = V.getTreeCost() + getReductionCost(TTI, ReducedVals[i]);
2329 if (Cost >= -SLPCostThreshold)
2332 DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" << Cost
2335 // Vectorize a tree.
2336 DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
2337 Value *VectorizedRoot = V.vectorizeTree();
2339 // Emit a reduction.
2340 Value *ReducedSubTree = emitReduction(VectorizedRoot, Builder);
2341 if (VectorizedTree) {
2342 Builder.SetCurrentDebugLocation(Loc);
2343 VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
2344 ReducedSubTree, "bin.rdx");
2346 VectorizedTree = ReducedSubTree;
2349 if (VectorizedTree) {
2350 // Finish the reduction.
2351 for (; i < NumReducedVals; ++i) {
2352 Builder.SetCurrentDebugLocation(
2353 cast<Instruction>(ReducedVals[i])->getDebugLoc());
2354 VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
2359 assert(ReductionRoot != NULL && "Need a reduction operation");
2360 ReductionRoot->setOperand(0, VectorizedTree);
2361 ReductionRoot->setOperand(1, ReductionPHI);
2363 ReductionRoot->replaceAllUsesWith(VectorizedTree);
2365 return VectorizedTree != 0;
2370 /// \brief Calcuate the cost of a reduction.
2371 int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal) {
2372 Type *ScalarTy = FirstReducedVal->getType();
2373 Type *VecTy = VectorType::get(ScalarTy, ReduxWidth);
2375 int PairwiseRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, true);
2376 int SplittingRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, false);
2378 IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
2379 int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
2381 int ScalarReduxCost =
2382 ReduxWidth * TTI->getArithmeticInstrCost(ReductionOpcode, VecTy);
2384 DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost
2385 << " for reduction that starts with " << *FirstReducedVal
2387 << (IsPairwiseReduction ? "pairwise" : "splitting")
2388 << " reduction)\n");
2390 return VecReduxCost - ScalarReduxCost;
2393 static Value *createBinOp(IRBuilder<> &Builder, unsigned Opcode, Value *L,
2394 Value *R, const Twine &Name = "") {
2395 if (Opcode == Instruction::FAdd)
2396 return Builder.CreateFAdd(L, R, Name);
2397 return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, L, R, Name);
2400 /// \brief Emit a horizontal reduction of the vectorized value.
2401 Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder) {
2402 assert(VectorizedValue && "Need to have a vectorized tree node");
2403 Instruction *ValToReduce = dyn_cast<Instruction>(VectorizedValue);
2404 assert(isPowerOf2_32(ReduxWidth) &&
2405 "We only handle power-of-two reductions for now");
2407 Value *TmpVec = ValToReduce;
2408 for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
2409 if (IsPairwiseReduction) {
2411 createRdxShuffleMask(ReduxWidth, i, true, true, Builder);
2413 createRdxShuffleMask(ReduxWidth, i, true, false, Builder);
2415 Value *LeftShuf = Builder.CreateShuffleVector(
2416 TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l");
2417 Value *RightShuf = Builder.CreateShuffleVector(
2418 TmpVec, UndefValue::get(TmpVec->getType()), (RightMask),
2420 TmpVec = createBinOp(Builder, ReductionOpcode, LeftShuf, RightShuf,
2424 createRdxShuffleMask(ReduxWidth, i, false, false, Builder);
2425 Value *Shuf = Builder.CreateShuffleVector(
2426 TmpVec, UndefValue::get(TmpVec->getType()), UpperHalf, "rdx.shuf");
2427 TmpVec = createBinOp(Builder, ReductionOpcode, TmpVec, Shuf, "bin.rdx");
2431 // The result is in the first element of the vector.
2432 return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
2436 /// \brief Recognize construction of vectors like
2437 /// %ra = insertelement <4 x float> undef, float %s0, i32 0
2438 /// %rb = insertelement <4 x float> %ra, float %s1, i32 1
2439 /// %rc = insertelement <4 x float> %rb, float %s2, i32 2
2440 /// %rd = insertelement <4 x float> %rc, float %s3, i32 3
2442 /// Returns true if it matches
2444 static bool findBuildVector(InsertElementInst *IE,
2445 SmallVectorImpl<Value *> &Ops) {
2446 if (!isa<UndefValue>(IE->getOperand(0)))
2450 Ops.push_back(IE->getOperand(1));
2452 if (IE->use_empty())
2455 InsertElementInst *NextUse = dyn_cast<InsertElementInst>(IE->use_back());
2459 // If this isn't the final use, make sure the next insertelement is the only
2460 // use. It's OK if the final constructed vector is used multiple times
2461 if (!IE->hasOneUse())
2470 static bool PhiTypeSorterFunc(Value *V, Value *V2) {
2471 return V->getType() < V2->getType();
2474 bool SLPVectorizer::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
2475 bool Changed = false;
2476 SmallVector<Value *, 4> Incoming;
2477 SmallSet<Value *, 16> VisitedInstrs;
2479 bool HaveVectorizedPhiNodes = true;
2480 while (HaveVectorizedPhiNodes) {
2481 HaveVectorizedPhiNodes = false;
2483 // Collect the incoming values from the PHIs.
2485 for (BasicBlock::iterator instr = BB->begin(), ie = BB->end(); instr != ie;
2487 PHINode *P = dyn_cast<PHINode>(instr);
2491 if (!VisitedInstrs.count(P))
2492 Incoming.push_back(P);
2496 std::stable_sort(Incoming.begin(), Incoming.end(), PhiTypeSorterFunc);
2498 // Try to vectorize elements base on their type.
2499 for (SmallVector<Value *, 4>::iterator IncIt = Incoming.begin(),
2503 // Look for the next elements with the same type.
2504 SmallVector<Value *, 4>::iterator SameTypeIt = IncIt;
2505 while (SameTypeIt != E &&
2506 (*SameTypeIt)->getType() == (*IncIt)->getType()) {
2507 VisitedInstrs.insert(*SameTypeIt);
2511 // Try to vectorize them.
2512 unsigned NumElts = (SameTypeIt - IncIt);
2513 DEBUG(errs() << "SLP: Trying to vectorize starting at PHIs (" << NumElts << ")\n");
2515 tryToVectorizeList(ArrayRef<Value *>(IncIt, NumElts), R)) {
2516 // Success start over because instructions might have been changed.
2517 HaveVectorizedPhiNodes = true;
2522 // Start over at the next instruction of a differnt type (or the end).
2527 VisitedInstrs.clear();
2529 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) {
2530 // We may go through BB multiple times so skip the one we have checked.
2531 if (!VisitedInstrs.insert(it))
2534 if (isa<DbgInfoIntrinsic>(it))
2537 // Try to vectorize reductions that use PHINodes.
2538 if (PHINode *P = dyn_cast<PHINode>(it)) {
2539 // Check that the PHI is a reduction PHI.
2540 if (P->getNumIncomingValues() != 2)
2543 (P->getIncomingBlock(0) == BB
2544 ? (P->getIncomingValue(0))
2545 : (P->getIncomingBlock(1) == BB ? P->getIncomingValue(1) : 0));
2546 // Check if this is a Binary Operator.
2547 BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx);
2551 // Try to match and vectorize a horizontal reduction.
2552 HorizontalReduction HorRdx;
2553 if (ShouldVectorizeHor &&
2554 HorRdx.matchAssociativeReduction(P, BI, DL) &&
2555 HorRdx.tryToReduce(R, TTI)) {
2562 Value *Inst = BI->getOperand(0);
2564 Inst = BI->getOperand(1);
2566 if (tryToVectorize(dyn_cast<BinaryOperator>(Inst), R)) {
2567 // We would like to start over since some instructions are deleted
2568 // and the iterator may become invalid value.
2578 // Try to vectorize horizontal reductions feeding into a store.
2579 if (ShouldStartVectorizeHorAtStore)
2580 if (StoreInst *SI = dyn_cast<StoreInst>(it))
2581 if (BinaryOperator *BinOp =
2582 dyn_cast<BinaryOperator>(SI->getValueOperand())) {
2583 HorizontalReduction HorRdx;
2584 if (((HorRdx.matchAssociativeReduction(0, BinOp, DL) &&
2585 HorRdx.tryToReduce(R, TTI)) ||
2586 tryToVectorize(BinOp, R))) {
2594 // Try to vectorize trees that start at compare instructions.
2595 if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
2596 if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) {
2598 // We would like to start over since some instructions are deleted
2599 // and the iterator may become invalid value.
2605 for (int i = 0; i < 2; ++i) {
2606 if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i))) {
2607 if (tryToVectorizePair(BI->getOperand(0), BI->getOperand(1), R)) {
2609 // We would like to start over since some instructions are deleted
2610 // and the iterator may become invalid value.
2619 // Try to vectorize trees that start at insertelement instructions.
2620 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(it)) {
2621 SmallVector<Value *, 8> Ops;
2622 if (!findBuildVector(IE, Ops))
2625 if (tryToVectorizeList(Ops, R)) {
2638 bool SLPVectorizer::vectorizeStoreChains(BoUpSLP &R) {
2639 bool Changed = false;
2640 // Attempt to sort and vectorize each of the store-groups.
2641 for (StoreListMap::iterator it = StoreRefs.begin(), e = StoreRefs.end();
2643 if (it->second.size() < 2)
2646 DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
2647 << it->second.size() << ".\n");
2649 // Process the stores in chunks of 16.
2650 for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI+=16) {
2651 unsigned Len = std::min<unsigned>(CE - CI, 16);
2652 ArrayRef<StoreInst *> Chunk(&it->second[CI], Len);
2653 Changed |= vectorizeStores(Chunk, -SLPCostThreshold, R);
2659 } // end anonymous namespace
2661 char SLPVectorizer::ID = 0;
2662 static const char lv_name[] = "SLP Vectorizer";
2663 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
2664 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
2665 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
2666 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
2667 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
2668 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
2671 Pass *createSLPVectorizerPass() { return new SLPVectorizer(); }