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 #include "llvm/Transforms/Vectorize.h"
19 #include "llvm/ADT/MapVector.h"
20 #include "llvm/ADT/PostOrderIterator.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
23 #include "llvm/Analysis/LoopInfo.h"
24 #include "llvm/Analysis/ScalarEvolution.h"
25 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
26 #include "llvm/Analysis/TargetTransformInfo.h"
27 #include "llvm/Analysis/ValueTracking.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/Dominators.h"
30 #include "llvm/IR/IRBuilder.h"
31 #include "llvm/IR/Instructions.h"
32 #include "llvm/IR/IntrinsicInst.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/NoFolder.h"
35 #include "llvm/IR/Type.h"
36 #include "llvm/IR/Value.h"
37 #include "llvm/IR/Verifier.h"
38 #include "llvm/Pass.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/Transforms/Utils/VectorUtils.h"
48 #define SV_NAME "slp-vectorizer"
49 #define DEBUG_TYPE "SLP"
52 SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
53 cl::desc("Only vectorize if you gain more than this "
57 ShouldVectorizeHor("slp-vectorize-hor", cl::init(false), cl::Hidden,
58 cl::desc("Attempt to vectorize horizontal reductions"));
60 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
61 "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
63 "Attempt to vectorize horizontal reductions feeding into a store"));
67 static const unsigned MinVecRegSize = 128;
69 static const unsigned RecursionMaxDepth = 12;
71 /// A helper class for numbering instructions in multiple blocks.
72 /// Numbers start at zero for each basic block.
73 struct BlockNumbering {
75 BlockNumbering(BasicBlock *Bb) : BB(Bb), 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 Opcode that can be clubbed with \p Op to create an alternate
153 /// sequence which can later be merged as a ShuffleVector instruction.
154 static unsigned getAltOpcode(unsigned Op) {
156 case Instruction::FAdd:
157 return Instruction::FSub;
158 case Instruction::FSub:
159 return Instruction::FAdd;
160 case Instruction::Add:
161 return Instruction::Sub;
162 case Instruction::Sub:
163 return Instruction::Add;
169 ///\returns bool representing if Opcode \p Op can be part
170 /// of an alternate sequence which can later be merged as
171 /// a ShuffleVector instruction.
172 static bool canCombineAsAltInst(unsigned Op) {
173 if (Op == Instruction::FAdd || Op == Instruction::FSub ||
174 Op == Instruction::Sub || Op == Instruction::Add)
179 /// \returns ShuffleVector instruction if intructions in \p VL have
180 /// alternate fadd,fsub / fsub,fadd/add,sub/sub,add sequence.
181 /// (i.e. e.g. opcodes of fadd,fsub,fadd,fsub...)
182 static unsigned isAltInst(ArrayRef<Value *> VL) {
183 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
184 unsigned Opcode = I0->getOpcode();
185 unsigned AltOpcode = getAltOpcode(Opcode);
186 for (int i = 1, e = VL.size(); i < e; i++) {
187 Instruction *I = dyn_cast<Instruction>(VL[i]);
188 if (!I || I->getOpcode() != ((i & 1) ? AltOpcode : Opcode))
191 return Instruction::ShuffleVector;
194 /// \returns The opcode if all of the Instructions in \p VL have the same
196 static unsigned getSameOpcode(ArrayRef<Value *> VL) {
197 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
200 unsigned Opcode = I0->getOpcode();
201 for (int i = 1, e = VL.size(); i < e; i++) {
202 Instruction *I = dyn_cast<Instruction>(VL[i]);
203 if (!I || Opcode != I->getOpcode()) {
204 if (canCombineAsAltInst(Opcode) && i == 1)
205 return isAltInst(VL);
212 /// \returns \p I after propagating metadata from \p VL.
213 static Instruction *propagateMetadata(Instruction *I, ArrayRef<Value *> VL) {
214 Instruction *I0 = cast<Instruction>(VL[0]);
215 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
216 I0->getAllMetadataOtherThanDebugLoc(Metadata);
218 for (unsigned i = 0, n = Metadata.size(); i != n; ++i) {
219 unsigned Kind = Metadata[i].first;
220 MDNode *MD = Metadata[i].second;
222 for (int i = 1, e = VL.size(); MD && i != e; i++) {
223 Instruction *I = cast<Instruction>(VL[i]);
224 MDNode *IMD = I->getMetadata(Kind);
228 MD = nullptr; // Remove unknown metadata
230 case LLVMContext::MD_tbaa:
231 MD = MDNode::getMostGenericTBAA(MD, IMD);
233 case LLVMContext::MD_alias_scope:
234 case LLVMContext::MD_noalias:
235 MD = MDNode::intersect(MD, IMD);
237 case LLVMContext::MD_fpmath:
238 MD = MDNode::getMostGenericFPMath(MD, IMD);
242 I->setMetadata(Kind, MD);
247 /// \returns The type that all of the values in \p VL have or null if there
248 /// are different types.
249 static Type* getSameType(ArrayRef<Value *> VL) {
250 Type *Ty = VL[0]->getType();
251 for (int i = 1, e = VL.size(); i < e; i++)
252 if (VL[i]->getType() != Ty)
258 /// \returns True if the ExtractElement instructions in VL can be vectorized
259 /// to use the original vector.
260 static bool CanReuseExtract(ArrayRef<Value *> VL) {
261 assert(Instruction::ExtractElement == getSameOpcode(VL) && "Invalid opcode");
262 // Check if all of the extracts come from the same vector and from the
265 ExtractElementInst *E0 = cast<ExtractElementInst>(VL0);
266 Value *Vec = E0->getOperand(0);
268 // We have to extract from the same vector type.
269 unsigned NElts = Vec->getType()->getVectorNumElements();
271 if (NElts != VL.size())
274 // Check that all of the indices extract from the correct offset.
275 ConstantInt *CI = dyn_cast<ConstantInt>(E0->getOperand(1));
276 if (!CI || CI->getZExtValue())
279 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
280 ExtractElementInst *E = cast<ExtractElementInst>(VL[i]);
281 ConstantInt *CI = dyn_cast<ConstantInt>(E->getOperand(1));
283 if (!CI || CI->getZExtValue() != i || E->getOperand(0) != Vec)
290 static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
291 SmallVectorImpl<Value *> &Left,
292 SmallVectorImpl<Value *> &Right) {
294 SmallVector<Value *, 16> OrigLeft, OrigRight;
296 bool AllSameOpcodeLeft = true;
297 bool AllSameOpcodeRight = true;
298 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
299 Instruction *I = cast<Instruction>(VL[i]);
300 Value *V0 = I->getOperand(0);
301 Value *V1 = I->getOperand(1);
303 OrigLeft.push_back(V0);
304 OrigRight.push_back(V1);
306 Instruction *I0 = dyn_cast<Instruction>(V0);
307 Instruction *I1 = dyn_cast<Instruction>(V1);
309 // Check whether all operands on one side have the same opcode. In this case
310 // we want to preserve the original order and not make things worse by
312 AllSameOpcodeLeft = I0;
313 AllSameOpcodeRight = I1;
315 if (i && AllSameOpcodeLeft) {
316 if(Instruction *P0 = dyn_cast<Instruction>(OrigLeft[i-1])) {
317 if(P0->getOpcode() != I0->getOpcode())
318 AllSameOpcodeLeft = false;
320 AllSameOpcodeLeft = false;
322 if (i && AllSameOpcodeRight) {
323 if(Instruction *P1 = dyn_cast<Instruction>(OrigRight[i-1])) {
324 if(P1->getOpcode() != I1->getOpcode())
325 AllSameOpcodeRight = false;
327 AllSameOpcodeRight = false;
330 // Sort two opcodes. In the code below we try to preserve the ability to use
331 // broadcast of values instead of individual inserts.
338 // If we just sorted according to opcode we would leave the first line in
339 // tact but we would swap vl2 with vr2 because opcode(phi) > opcode(load).
342 // Because vr2 and vr1 are from the same load we loose the opportunity of a
343 // broadcast for the packed right side in the backend: we have [vr1, vl2]
344 // instead of [vr1, vr2=vr1].
346 if(!i && I0->getOpcode() > I1->getOpcode()) {
349 } else if (i && I0->getOpcode() > I1->getOpcode() && Right[i-1] != I1) {
350 // Try not to destroy a broad cast for no apparent benefit.
353 } else if (i && I0->getOpcode() == I1->getOpcode() && Right[i-1] == I0) {
354 // Try preserve broadcasts.
357 } else if (i && I0->getOpcode() == I1->getOpcode() && Left[i-1] == I1) {
358 // Try preserve broadcasts.
367 // One opcode, put the instruction on the right.
377 bool LeftBroadcast = isSplat(Left);
378 bool RightBroadcast = isSplat(Right);
380 // Don't reorder if the operands where good to begin with.
381 if (!(LeftBroadcast || RightBroadcast) &&
382 (AllSameOpcodeRight || AllSameOpcodeLeft)) {
388 /// Bottom Up SLP Vectorizer.
391 typedef SmallVector<Value *, 8> ValueList;
392 typedef SmallVector<Instruction *, 16> InstrList;
393 typedef SmallPtrSet<Value *, 16> ValueSet;
394 typedef SmallVector<StoreInst *, 8> StoreList;
396 BoUpSLP(Function *Func, ScalarEvolution *Se, const DataLayout *Dl,
397 TargetTransformInfo *Tti, TargetLibraryInfo *TLi, AliasAnalysis *Aa,
398 LoopInfo *Li, DominatorTree *Dt)
399 : NumLoadsWantToKeepOrder(0), NumLoadsWantToChangeOrder(0),
400 F(Func), SE(Se), DL(Dl), TTI(Tti), TLI(TLi), AA(Aa), LI(Li), DT(Dt),
401 Builder(Se->getContext()) {}
403 /// \brief Vectorize the tree that starts with the elements in \p VL.
404 /// Returns the vectorized root.
405 Value *vectorizeTree();
407 /// \returns the vectorization cost of the subtree that starts at \p VL.
408 /// A negative number means that this is profitable.
411 /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
412 /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
413 void buildTree(ArrayRef<Value *> Roots,
414 ArrayRef<Value *> UserIgnoreLst = None);
416 /// Clear the internal data structures that are created by 'buildTree'.
418 VectorizableTree.clear();
419 ScalarToTreeEntry.clear();
421 ExternalUses.clear();
422 MemBarrierIgnoreList.clear();
423 NumLoadsWantToKeepOrder = 0;
424 NumLoadsWantToChangeOrder = 0;
427 /// \returns true if the memory operations A and B are consecutive.
428 bool isConsecutiveAccess(Value *A, Value *B);
430 /// \brief Perform LICM and CSE on the newly generated gather sequences.
431 void optimizeGatherSequence();
433 /// \returns true if it is benefitial to reverse the vector order.
434 bool shouldReorder() const {
435 return NumLoadsWantToChangeOrder > NumLoadsWantToKeepOrder;
441 /// \returns the cost of the vectorizable entry.
442 int getEntryCost(TreeEntry *E);
444 /// This is the recursive part of buildTree.
445 void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth);
447 /// Vectorize a single entry in the tree.
448 Value *vectorizeTree(TreeEntry *E);
450 /// Vectorize a single entry in the tree, starting in \p VL.
451 Value *vectorizeTree(ArrayRef<Value *> VL);
453 /// \returns the pointer to the vectorized value if \p VL is already
454 /// vectorized, or NULL. They may happen in cycles.
455 Value *alreadyVectorized(ArrayRef<Value *> VL) const;
457 /// \brief Take the pointer operand from the Load/Store instruction.
458 /// \returns NULL if this is not a valid Load/Store instruction.
459 static Value *getPointerOperand(Value *I);
461 /// \brief Take the address space operand from the Load/Store instruction.
462 /// \returns -1 if this is not a valid Load/Store instruction.
463 static unsigned getAddressSpaceOperand(Value *I);
465 /// \returns the scalarization cost for this type. Scalarization in this
466 /// context means the creation of vectors from a group of scalars.
467 int getGatherCost(Type *Ty);
469 /// \returns the scalarization cost for this list of values. Assuming that
470 /// this subtree gets vectorized, we may need to extract the values from the
471 /// roots. This method calculates the cost of extracting the values.
472 int getGatherCost(ArrayRef<Value *> VL);
474 /// \returns the AA location that is being access by the instruction.
475 AliasAnalysis::Location getLocation(Instruction *I);
477 /// \brief Checks if it is possible to sink an instruction from
478 /// \p Src to \p Dst.
479 /// \returns the pointer to the barrier instruction if we can't sink.
480 Value *getSinkBarrier(Instruction *Src, Instruction *Dst);
482 /// \returns the index of the last instruction in the BB from \p VL.
483 int getLastIndex(ArrayRef<Value *> VL);
485 /// \returns the Instruction in the bundle \p VL.
486 Instruction *getLastInstruction(ArrayRef<Value *> VL);
488 /// \brief Set the Builder insert point to one after the last instruction in
490 void setInsertPointAfterBundle(ArrayRef<Value *> VL);
492 /// \returns a vector from a collection of scalars in \p VL.
493 Value *Gather(ArrayRef<Value *> VL, VectorType *Ty);
495 /// \returns whether the VectorizableTree is fully vectoriable and will
496 /// be beneficial even the tree height is tiny.
497 bool isFullyVectorizableTinyTree();
500 TreeEntry() : Scalars(), VectorizedValue(nullptr), LastScalarIndex(0),
503 /// \returns true if the scalars in VL are equal to this entry.
504 bool isSame(ArrayRef<Value *> VL) const {
505 assert(VL.size() == Scalars.size() && "Invalid size");
506 return std::equal(VL.begin(), VL.end(), Scalars.begin());
509 /// A vector of scalars.
512 /// The Scalars are vectorized into this value. It is initialized to Null.
513 Value *VectorizedValue;
515 /// The index in the basic block of the last scalar.
518 /// Do we need to gather this sequence ?
522 /// Create a new VectorizableTree entry.
523 TreeEntry *newTreeEntry(ArrayRef<Value *> VL, bool Vectorized) {
524 VectorizableTree.push_back(TreeEntry());
525 int idx = VectorizableTree.size() - 1;
526 TreeEntry *Last = &VectorizableTree[idx];
527 Last->Scalars.insert(Last->Scalars.begin(), VL.begin(), VL.end());
528 Last->NeedToGather = !Vectorized;
530 Last->LastScalarIndex = getLastIndex(VL);
531 for (int i = 0, e = VL.size(); i != e; ++i) {
532 assert(!ScalarToTreeEntry.count(VL[i]) && "Scalar already in tree!");
533 ScalarToTreeEntry[VL[i]] = idx;
536 Last->LastScalarIndex = 0;
537 MustGather.insert(VL.begin(), VL.end());
542 /// -- Vectorization State --
543 /// Holds all of the tree entries.
544 std::vector<TreeEntry> VectorizableTree;
546 /// Maps a specific scalar to its tree entry.
547 SmallDenseMap<Value*, int> ScalarToTreeEntry;
549 /// A list of scalars that we found that we need to keep as scalars.
552 /// This POD struct describes one external user in the vectorized tree.
553 struct ExternalUser {
554 ExternalUser (Value *S, llvm::User *U, int L) :
555 Scalar(S), User(U), Lane(L){};
556 // Which scalar in our function.
558 // Which user that uses the scalar.
560 // Which lane does the scalar belong to.
563 typedef SmallVector<ExternalUser, 16> UserList;
565 /// A list of values that need to extracted out of the tree.
566 /// This list holds pairs of (Internal Scalar : External User).
567 UserList ExternalUses;
569 /// A list of instructions to ignore while sinking
570 /// memory instructions. This map must be reset between runs of getCost.
571 ValueSet MemBarrierIgnoreList;
573 /// Holds all of the instructions that we gathered.
574 SetVector<Instruction *> GatherSeq;
575 /// A list of blocks that we are going to CSE.
576 SetVector<BasicBlock *> CSEBlocks;
578 /// Numbers instructions in different blocks.
579 DenseMap<BasicBlock *, BlockNumbering> BlocksNumbers;
581 /// \brief Get the corresponding instruction numbering list for a given
582 /// BasicBlock. The list is allocated lazily.
583 BlockNumbering &getBlockNumbering(BasicBlock *BB) {
584 auto I = BlocksNumbers.insert(std::make_pair(BB, BlockNumbering(BB)));
585 return I.first->second;
588 /// List of users to ignore during scheduling and that don't need extracting.
589 ArrayRef<Value *> UserIgnoreList;
591 // Number of load-bundles, which contain consecutive loads.
592 int NumLoadsWantToKeepOrder;
594 // Number of load-bundles of size 2, which are consecutive loads if reversed.
595 int NumLoadsWantToChangeOrder;
597 // Analysis and block reference.
600 const DataLayout *DL;
601 TargetTransformInfo *TTI;
602 TargetLibraryInfo *TLI;
606 /// Instruction builder to construct the vectorized tree.
610 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
611 ArrayRef<Value *> UserIgnoreLst) {
613 UserIgnoreList = UserIgnoreLst;
614 if (!getSameType(Roots))
616 buildTree_rec(Roots, 0);
618 // Collect the values that we need to extract from the tree.
619 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
620 TreeEntry *Entry = &VectorizableTree[EIdx];
623 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
624 Value *Scalar = Entry->Scalars[Lane];
626 // No need to handle users of gathered values.
627 if (Entry->NeedToGather)
630 for (User *U : Scalar->users()) {
631 DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
633 // Skip in-tree scalars that become vectors.
634 if (ScalarToTreeEntry.count(U)) {
635 DEBUG(dbgs() << "SLP: \tInternal user will be removed:" <<
637 int Idx = ScalarToTreeEntry[U]; (void) Idx;
638 assert(!VectorizableTree[Idx].NeedToGather && "Bad state");
641 Instruction *UserInst = dyn_cast<Instruction>(U);
645 // Ignore users in the user ignore list.
646 if (std::find(UserIgnoreList.begin(), UserIgnoreList.end(), UserInst) !=
647 UserIgnoreList.end())
650 DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane " <<
651 Lane << " from " << *Scalar << ".\n");
652 ExternalUses.push_back(ExternalUser(Scalar, U, Lane));
659 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth) {
660 bool SameTy = getSameType(VL); (void)SameTy;
661 bool isAltShuffle = false;
662 assert(SameTy && "Invalid types!");
664 if (Depth == RecursionMaxDepth) {
665 DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
666 newTreeEntry(VL, false);
670 // Don't handle vectors.
671 if (VL[0]->getType()->isVectorTy()) {
672 DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
673 newTreeEntry(VL, false);
677 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
678 if (SI->getValueOperand()->getType()->isVectorTy()) {
679 DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
680 newTreeEntry(VL, false);
683 unsigned Opcode = getSameOpcode(VL);
685 // Check that this shuffle vector refers to the alternate
686 // sequence of opcodes.
687 if (Opcode == Instruction::ShuffleVector) {
688 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
689 unsigned Op = I0->getOpcode();
690 if (Op != Instruction::ShuffleVector)
694 // If all of the operands are identical or constant we have a simple solution.
695 if (allConstant(VL) || isSplat(VL) || !getSameBlock(VL) || !Opcode) {
696 DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
697 newTreeEntry(VL, false);
701 // We now know that this is a vector of instructions of the same type from
704 // Check if this is a duplicate of another entry.
705 if (ScalarToTreeEntry.count(VL[0])) {
706 int Idx = ScalarToTreeEntry[VL[0]];
707 TreeEntry *E = &VectorizableTree[Idx];
708 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
709 DEBUG(dbgs() << "SLP: \tChecking bundle: " << *VL[i] << ".\n");
710 if (E->Scalars[i] != VL[i]) {
711 DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
712 newTreeEntry(VL, false);
716 DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *VL[0] << ".\n");
720 // Check that none of the instructions in the bundle are already in the tree.
721 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
722 if (ScalarToTreeEntry.count(VL[i])) {
723 DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
724 ") is already in tree.\n");
725 newTreeEntry(VL, false);
730 // If any of the scalars appears in the table OR it is marked as a value that
731 // needs to stat scalar then we need to gather the scalars.
732 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
733 if (ScalarToTreeEntry.count(VL[i]) || MustGather.count(VL[i])) {
734 DEBUG(dbgs() << "SLP: Gathering due to gathered scalar. \n");
735 newTreeEntry(VL, false);
740 // Check that all of the users of the scalars that we want to vectorize are
742 Instruction *VL0 = cast<Instruction>(VL[0]);
743 int MyLastIndex = getLastIndex(VL);
744 BasicBlock *BB = cast<Instruction>(VL0)->getParent();
746 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
747 Instruction *Scalar = cast<Instruction>(VL[i]);
748 DEBUG(dbgs() << "SLP: Checking users of " << *Scalar << ". \n");
749 for (User *U : Scalar->users()) {
750 DEBUG(dbgs() << "SLP: \tUser " << *U << ". \n");
751 Instruction *UI = dyn_cast<Instruction>(U);
753 DEBUG(dbgs() << "SLP: Gathering due unknown user. \n");
754 newTreeEntry(VL, false);
758 // We don't care if the user is in a different basic block.
759 BasicBlock *UserBlock = UI->getParent();
760 if (UserBlock != BB) {
761 DEBUG(dbgs() << "SLP: User from a different basic block "
766 // If this is a PHINode within this basic block then we can place the
767 // extract wherever we want.
768 if (isa<PHINode>(*UI)) {
769 DEBUG(dbgs() << "SLP: \tWe can schedule PHIs:" << *UI << ". \n");
773 // Check if this is a safe in-tree user.
774 if (ScalarToTreeEntry.count(UI)) {
775 int Idx = ScalarToTreeEntry[UI];
776 int VecLocation = VectorizableTree[Idx].LastScalarIndex;
777 if (VecLocation <= MyLastIndex) {
778 DEBUG(dbgs() << "SLP: Gathering due to unschedulable vector. \n");
779 newTreeEntry(VL, false);
782 DEBUG(dbgs() << "SLP: In-tree user (" << *UI << ") at #" <<
783 VecLocation << " vector value (" << *Scalar << ") at #"
784 << MyLastIndex << ".\n");
788 // Ignore users in the user ignore list.
789 if (std::find(UserIgnoreList.begin(), UserIgnoreList.end(), UI) !=
790 UserIgnoreList.end())
793 // Make sure that we can schedule this unknown user.
794 BlockNumbering &BN = getBlockNumbering(BB);
795 int UserIndex = BN.getIndex(UI);
796 if (UserIndex < MyLastIndex) {
798 DEBUG(dbgs() << "SLP: Can't schedule extractelement for "
800 newTreeEntry(VL, false);
806 // Check that every instructions appears once in this bundle.
807 for (unsigned i = 0, e = VL.size(); i < e; ++i)
808 for (unsigned j = i+1; j < e; ++j)
809 if (VL[i] == VL[j]) {
810 DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
811 newTreeEntry(VL, false);
815 // Check that instructions in this bundle don't reference other instructions.
816 // The runtime of this check is O(N * N-1 * uses(N)) and a typical N is 4.
817 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
818 for (User *U : VL[i]->users()) {
819 for (unsigned j = 0; j < e; ++j) {
820 if (i != j && U == VL[j]) {
821 DEBUG(dbgs() << "SLP: Intra-bundle dependencies!" << *U << ". \n");
822 newTreeEntry(VL, false);
829 DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
831 // Check if it is safe to sink the loads or the stores.
832 if (Opcode == Instruction::Load || Opcode == Instruction::Store) {
833 Instruction *Last = getLastInstruction(VL);
835 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
838 Value *Barrier = getSinkBarrier(cast<Instruction>(VL[i]), Last);
840 DEBUG(dbgs() << "SLP: Can't sink " << *VL[i] << "\n down to " << *Last
841 << "\n because of " << *Barrier << ". Gathering.\n");
842 newTreeEntry(VL, false);
849 case Instruction::PHI: {
850 PHINode *PH = dyn_cast<PHINode>(VL0);
852 // Check for terminator values (e.g. invoke).
853 for (unsigned j = 0; j < VL.size(); ++j)
854 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
855 TerminatorInst *Term = dyn_cast<TerminatorInst>(
856 cast<PHINode>(VL[j])->getIncomingValueForBlock(PH->getIncomingBlock(i)));
858 DEBUG(dbgs() << "SLP: Need to swizzle PHINodes (TerminatorInst use).\n");
859 newTreeEntry(VL, false);
864 newTreeEntry(VL, true);
865 DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
867 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
869 // Prepare the operand vector.
870 for (unsigned j = 0; j < VL.size(); ++j)
871 Operands.push_back(cast<PHINode>(VL[j])->getIncomingValueForBlock(
872 PH->getIncomingBlock(i)));
874 buildTree_rec(Operands, Depth + 1);
878 case Instruction::ExtractElement: {
879 bool Reuse = CanReuseExtract(VL);
881 DEBUG(dbgs() << "SLP: Reusing extract sequence.\n");
883 newTreeEntry(VL, Reuse);
886 case Instruction::Load: {
887 // Check if the loads are consecutive or of we need to swizzle them.
888 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i) {
889 LoadInst *L = cast<LoadInst>(VL[i]);
890 if (!L->isSimple()) {
891 newTreeEntry(VL, false);
892 DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
895 if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
896 if (VL.size() == 2 && isConsecutiveAccess(VL[1], VL[0])) {
897 ++NumLoadsWantToChangeOrder;
899 newTreeEntry(VL, false);
900 DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
904 ++NumLoadsWantToKeepOrder;
905 newTreeEntry(VL, true);
906 DEBUG(dbgs() << "SLP: added a vector of loads.\n");
909 case Instruction::ZExt:
910 case Instruction::SExt:
911 case Instruction::FPToUI:
912 case Instruction::FPToSI:
913 case Instruction::FPExt:
914 case Instruction::PtrToInt:
915 case Instruction::IntToPtr:
916 case Instruction::SIToFP:
917 case Instruction::UIToFP:
918 case Instruction::Trunc:
919 case Instruction::FPTrunc:
920 case Instruction::BitCast: {
921 Type *SrcTy = VL0->getOperand(0)->getType();
922 for (unsigned i = 0; i < VL.size(); ++i) {
923 Type *Ty = cast<Instruction>(VL[i])->getOperand(0)->getType();
924 if (Ty != SrcTy || Ty->isAggregateType() || Ty->isVectorTy()) {
925 newTreeEntry(VL, false);
926 DEBUG(dbgs() << "SLP: Gathering casts with different src types.\n");
930 newTreeEntry(VL, true);
931 DEBUG(dbgs() << "SLP: added a vector of casts.\n");
933 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
935 // Prepare the operand vector.
936 for (unsigned j = 0; j < VL.size(); ++j)
937 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
939 buildTree_rec(Operands, Depth+1);
943 case Instruction::ICmp:
944 case Instruction::FCmp: {
945 // Check that all of the compares have the same predicate.
946 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
947 Type *ComparedTy = cast<Instruction>(VL[0])->getOperand(0)->getType();
948 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
949 CmpInst *Cmp = cast<CmpInst>(VL[i]);
950 if (Cmp->getPredicate() != P0 ||
951 Cmp->getOperand(0)->getType() != ComparedTy) {
952 newTreeEntry(VL, false);
953 DEBUG(dbgs() << "SLP: Gathering cmp with different predicate.\n");
958 newTreeEntry(VL, true);
959 DEBUG(dbgs() << "SLP: added a vector of compares.\n");
961 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
963 // Prepare the operand vector.
964 for (unsigned j = 0; j < VL.size(); ++j)
965 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
967 buildTree_rec(Operands, Depth+1);
971 case Instruction::Select:
972 case Instruction::Add:
973 case Instruction::FAdd:
974 case Instruction::Sub:
975 case Instruction::FSub:
976 case Instruction::Mul:
977 case Instruction::FMul:
978 case Instruction::UDiv:
979 case Instruction::SDiv:
980 case Instruction::FDiv:
981 case Instruction::URem:
982 case Instruction::SRem:
983 case Instruction::FRem:
984 case Instruction::Shl:
985 case Instruction::LShr:
986 case Instruction::AShr:
987 case Instruction::And:
988 case Instruction::Or:
989 case Instruction::Xor: {
990 newTreeEntry(VL, true);
991 DEBUG(dbgs() << "SLP: added a vector of bin op.\n");
993 // Sort operands of the instructions so that each side is more likely to
994 // have the same opcode.
995 if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
996 ValueList Left, Right;
997 reorderInputsAccordingToOpcode(VL, Left, Right);
998 BasicBlock *LeftBB = getSameBlock(Left);
999 BasicBlock *RightBB = getSameBlock(Right);
1000 // If we have common uses on separate paths in the tree make sure we
1001 // process the one with greater common depth first.
1002 // We can use block numbering to determine the subtree traversal as
1003 // earler user has to come in between the common use and the later user.
1004 if (LeftBB && RightBB && LeftBB == RightBB &&
1005 getLastIndex(Right) > getLastIndex(Left)) {
1006 buildTree_rec(Right, Depth + 1);
1007 buildTree_rec(Left, Depth + 1);
1009 buildTree_rec(Left, Depth + 1);
1010 buildTree_rec(Right, Depth + 1);
1015 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1017 // Prepare the operand vector.
1018 for (unsigned j = 0; j < VL.size(); ++j)
1019 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1021 buildTree_rec(Operands, Depth+1);
1025 case Instruction::GetElementPtr: {
1026 // We don't combine GEPs with complicated (nested) indexing.
1027 for (unsigned j = 0; j < VL.size(); ++j) {
1028 if (cast<Instruction>(VL[j])->getNumOperands() != 2) {
1029 DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
1030 newTreeEntry(VL, false);
1035 // We can't combine several GEPs into one vector if they operate on
1037 Type *Ty0 = cast<Instruction>(VL0)->getOperand(0)->getType();
1038 for (unsigned j = 0; j < VL.size(); ++j) {
1039 Type *CurTy = cast<Instruction>(VL[j])->getOperand(0)->getType();
1041 DEBUG(dbgs() << "SLP: not-vectorizable GEP (different types).\n");
1042 newTreeEntry(VL, false);
1047 // We don't combine GEPs with non-constant indexes.
1048 for (unsigned j = 0; j < VL.size(); ++j) {
1049 auto Op = cast<Instruction>(VL[j])->getOperand(1);
1050 if (!isa<ConstantInt>(Op)) {
1052 dbgs() << "SLP: not-vectorizable GEP (non-constant indexes).\n");
1053 newTreeEntry(VL, false);
1058 newTreeEntry(VL, true);
1059 DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
1060 for (unsigned i = 0, e = 2; i < e; ++i) {
1062 // Prepare the operand vector.
1063 for (unsigned j = 0; j < VL.size(); ++j)
1064 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1066 buildTree_rec(Operands, Depth + 1);
1070 case Instruction::Store: {
1071 // Check if the stores are consecutive or of we need to swizzle them.
1072 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
1073 if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
1074 newTreeEntry(VL, false);
1075 DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
1079 newTreeEntry(VL, true);
1080 DEBUG(dbgs() << "SLP: added a vector of stores.\n");
1083 for (unsigned j = 0; j < VL.size(); ++j)
1084 Operands.push_back(cast<Instruction>(VL[j])->getOperand(0));
1086 // We can ignore these values because we are sinking them down.
1087 MemBarrierIgnoreList.insert(VL.begin(), VL.end());
1088 buildTree_rec(Operands, Depth + 1);
1091 case Instruction::Call: {
1092 // Check if the calls are all to the same vectorizable intrinsic.
1093 CallInst *CI = cast<CallInst>(VL[0]);
1094 // Check if this is an Intrinsic call or something that can be
1095 // represented by an intrinsic call
1096 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
1097 if (!isTriviallyVectorizable(ID)) {
1098 newTreeEntry(VL, false);
1099 DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
1102 Function *Int = CI->getCalledFunction();
1103 Value *A1I = nullptr;
1104 if (hasVectorInstrinsicScalarOpd(ID, 1))
1105 A1I = CI->getArgOperand(1);
1106 for (unsigned i = 1, e = VL.size(); i != e; ++i) {
1107 CallInst *CI2 = dyn_cast<CallInst>(VL[i]);
1108 if (!CI2 || CI2->getCalledFunction() != Int ||
1109 getIntrinsicIDForCall(CI2, TLI) != ID) {
1110 newTreeEntry(VL, false);
1111 DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *VL[i]
1115 // ctlz,cttz and powi are special intrinsics whose second argument
1116 // should be same in order for them to be vectorized.
1117 if (hasVectorInstrinsicScalarOpd(ID, 1)) {
1118 Value *A1J = CI2->getArgOperand(1);
1120 newTreeEntry(VL, false);
1121 DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
1122 << " argument "<< A1I<<"!=" << A1J
1129 newTreeEntry(VL, true);
1130 for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i) {
1132 // Prepare the operand vector.
1133 for (unsigned j = 0; j < VL.size(); ++j) {
1134 CallInst *CI2 = dyn_cast<CallInst>(VL[j]);
1135 Operands.push_back(CI2->getArgOperand(i));
1137 buildTree_rec(Operands, Depth + 1);
1141 case Instruction::ShuffleVector: {
1142 // If this is not an alternate sequence of opcode like add-sub
1143 // then do not vectorize this instruction.
1144 if (!isAltShuffle) {
1145 newTreeEntry(VL, false);
1146 DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
1149 newTreeEntry(VL, true);
1150 DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
1151 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1153 // Prepare the operand vector.
1154 for (unsigned j = 0; j < VL.size(); ++j)
1155 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1157 buildTree_rec(Operands, Depth + 1);
1162 newTreeEntry(VL, false);
1163 DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
1168 int BoUpSLP::getEntryCost(TreeEntry *E) {
1169 ArrayRef<Value*> VL = E->Scalars;
1171 Type *ScalarTy = VL[0]->getType();
1172 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1173 ScalarTy = SI->getValueOperand()->getType();
1174 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1176 if (E->NeedToGather) {
1177 if (allConstant(VL))
1180 return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
1182 return getGatherCost(E->Scalars);
1184 unsigned Opcode = getSameOpcode(VL);
1185 assert(Opcode && getSameType(VL) && getSameBlock(VL) && "Invalid VL");
1186 Instruction *VL0 = cast<Instruction>(VL[0]);
1188 case Instruction::PHI: {
1191 case Instruction::ExtractElement: {
1192 if (CanReuseExtract(VL)) {
1194 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
1195 ExtractElementInst *E = cast<ExtractElementInst>(VL[i]);
1197 // Take credit for instruction that will become dead.
1199 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, i);
1203 return getGatherCost(VecTy);
1205 case Instruction::ZExt:
1206 case Instruction::SExt:
1207 case Instruction::FPToUI:
1208 case Instruction::FPToSI:
1209 case Instruction::FPExt:
1210 case Instruction::PtrToInt:
1211 case Instruction::IntToPtr:
1212 case Instruction::SIToFP:
1213 case Instruction::UIToFP:
1214 case Instruction::Trunc:
1215 case Instruction::FPTrunc:
1216 case Instruction::BitCast: {
1217 Type *SrcTy = VL0->getOperand(0)->getType();
1219 // Calculate the cost of this instruction.
1220 int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(),
1221 VL0->getType(), SrcTy);
1223 VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
1224 int VecCost = TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy);
1225 return VecCost - ScalarCost;
1227 case Instruction::FCmp:
1228 case Instruction::ICmp:
1229 case Instruction::Select:
1230 case Instruction::Add:
1231 case Instruction::FAdd:
1232 case Instruction::Sub:
1233 case Instruction::FSub:
1234 case Instruction::Mul:
1235 case Instruction::FMul:
1236 case Instruction::UDiv:
1237 case Instruction::SDiv:
1238 case Instruction::FDiv:
1239 case Instruction::URem:
1240 case Instruction::SRem:
1241 case Instruction::FRem:
1242 case Instruction::Shl:
1243 case Instruction::LShr:
1244 case Instruction::AShr:
1245 case Instruction::And:
1246 case Instruction::Or:
1247 case Instruction::Xor: {
1248 // Calculate the cost of this instruction.
1251 if (Opcode == Instruction::FCmp || Opcode == Instruction::ICmp ||
1252 Opcode == Instruction::Select) {
1253 VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
1254 ScalarCost = VecTy->getNumElements() *
1255 TTI->getCmpSelInstrCost(Opcode, ScalarTy, Builder.getInt1Ty());
1256 VecCost = TTI->getCmpSelInstrCost(Opcode, VecTy, MaskTy);
1258 // Certain instructions can be cheaper to vectorize if they have a
1259 // constant second vector operand.
1260 TargetTransformInfo::OperandValueKind Op1VK =
1261 TargetTransformInfo::OK_AnyValue;
1262 TargetTransformInfo::OperandValueKind Op2VK =
1263 TargetTransformInfo::OK_UniformConstantValue;
1265 // If all operands are exactly the same ConstantInt then set the
1266 // operand kind to OK_UniformConstantValue.
1267 // If instead not all operands are constants, then set the operand kind
1268 // to OK_AnyValue. If all operands are constants but not the same,
1269 // then set the operand kind to OK_NonUniformConstantValue.
1270 ConstantInt *CInt = nullptr;
1271 for (unsigned i = 0; i < VL.size(); ++i) {
1272 const Instruction *I = cast<Instruction>(VL[i]);
1273 if (!isa<ConstantInt>(I->getOperand(1))) {
1274 Op2VK = TargetTransformInfo::OK_AnyValue;
1278 CInt = cast<ConstantInt>(I->getOperand(1));
1281 if (Op2VK == TargetTransformInfo::OK_UniformConstantValue &&
1282 CInt != cast<ConstantInt>(I->getOperand(1)))
1283 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
1287 VecTy->getNumElements() *
1288 TTI->getArithmeticInstrCost(Opcode, ScalarTy, Op1VK, Op2VK);
1289 VecCost = TTI->getArithmeticInstrCost(Opcode, VecTy, Op1VK, Op2VK);
1291 return VecCost - ScalarCost;
1293 case Instruction::GetElementPtr: {
1294 TargetTransformInfo::OperandValueKind Op1VK =
1295 TargetTransformInfo::OK_AnyValue;
1296 TargetTransformInfo::OperandValueKind Op2VK =
1297 TargetTransformInfo::OK_UniformConstantValue;
1300 VecTy->getNumElements() *
1301 TTI->getArithmeticInstrCost(Instruction::Add, ScalarTy, Op1VK, Op2VK);
1303 TTI->getArithmeticInstrCost(Instruction::Add, VecTy, Op1VK, Op2VK);
1305 return VecCost - ScalarCost;
1307 case Instruction::Load: {
1308 // Cost of wide load - cost of scalar loads.
1309 int ScalarLdCost = VecTy->getNumElements() *
1310 TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
1311 int VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, 1, 0);
1312 return VecLdCost - ScalarLdCost;
1314 case Instruction::Store: {
1315 // We know that we can merge the stores. Calculate the cost.
1316 int ScalarStCost = VecTy->getNumElements() *
1317 TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
1318 int VecStCost = TTI->getMemoryOpCost(Instruction::Store, VecTy, 1, 0);
1319 return VecStCost - ScalarStCost;
1321 case Instruction::Call: {
1322 CallInst *CI = cast<CallInst>(VL0);
1323 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
1325 // Calculate the cost of the scalar and vector calls.
1326 SmallVector<Type*, 4> ScalarTys, VecTys;
1327 for (unsigned op = 0, opc = CI->getNumArgOperands(); op!= opc; ++op) {
1328 ScalarTys.push_back(CI->getArgOperand(op)->getType());
1329 VecTys.push_back(VectorType::get(CI->getArgOperand(op)->getType(),
1330 VecTy->getNumElements()));
1333 int ScalarCallCost = VecTy->getNumElements() *
1334 TTI->getIntrinsicInstrCost(ID, ScalarTy, ScalarTys);
1336 int VecCallCost = TTI->getIntrinsicInstrCost(ID, VecTy, VecTys);
1338 DEBUG(dbgs() << "SLP: Call cost "<< VecCallCost - ScalarCallCost
1339 << " (" << VecCallCost << "-" << ScalarCallCost << ")"
1340 << " for " << *CI << "\n");
1342 return VecCallCost - ScalarCallCost;
1344 case Instruction::ShuffleVector: {
1345 TargetTransformInfo::OperandValueKind Op1VK =
1346 TargetTransformInfo::OK_AnyValue;
1347 TargetTransformInfo::OperandValueKind Op2VK =
1348 TargetTransformInfo::OK_AnyValue;
1351 for (unsigned i = 0; i < VL.size(); ++i) {
1352 Instruction *I = cast<Instruction>(VL[i]);
1356 TTI->getArithmeticInstrCost(I->getOpcode(), ScalarTy, Op1VK, Op2VK);
1358 // VecCost is equal to sum of the cost of creating 2 vectors
1359 // and the cost of creating shuffle.
1360 Instruction *I0 = cast<Instruction>(VL[0]);
1362 TTI->getArithmeticInstrCost(I0->getOpcode(), VecTy, Op1VK, Op2VK);
1363 Instruction *I1 = cast<Instruction>(VL[1]);
1365 TTI->getArithmeticInstrCost(I1->getOpcode(), VecTy, Op1VK, Op2VK);
1367 TTI->getShuffleCost(TargetTransformInfo::SK_Alternate, VecTy, 0);
1368 return VecCost - ScalarCost;
1371 llvm_unreachable("Unknown instruction");
1375 bool BoUpSLP::isFullyVectorizableTinyTree() {
1376 DEBUG(dbgs() << "SLP: Check whether the tree with height " <<
1377 VectorizableTree.size() << " is fully vectorizable .\n");
1379 // We only handle trees of height 2.
1380 if (VectorizableTree.size() != 2)
1383 // Handle splat stores.
1384 if (!VectorizableTree[0].NeedToGather && isSplat(VectorizableTree[1].Scalars))
1387 // Gathering cost would be too much for tiny trees.
1388 if (VectorizableTree[0].NeedToGather || VectorizableTree[1].NeedToGather)
1394 int BoUpSLP::getTreeCost() {
1396 DEBUG(dbgs() << "SLP: Calculating cost for tree of size " <<
1397 VectorizableTree.size() << ".\n");
1399 // We only vectorize tiny trees if it is fully vectorizable.
1400 if (VectorizableTree.size() < 3 && !isFullyVectorizableTinyTree()) {
1401 if (!VectorizableTree.size()) {
1402 assert(!ExternalUses.size() && "We should not have any external users");
1407 unsigned BundleWidth = VectorizableTree[0].Scalars.size();
1409 for (unsigned i = 0, e = VectorizableTree.size(); i != e; ++i) {
1410 int C = getEntryCost(&VectorizableTree[i]);
1411 DEBUG(dbgs() << "SLP: Adding cost " << C << " for bundle that starts with "
1412 << *VectorizableTree[i].Scalars[0] << " .\n");
1416 SmallSet<Value *, 16> ExtractCostCalculated;
1417 int ExtractCost = 0;
1418 for (UserList::iterator I = ExternalUses.begin(), E = ExternalUses.end();
1420 // We only add extract cost once for the same scalar.
1421 if (!ExtractCostCalculated.insert(I->Scalar))
1424 VectorType *VecTy = VectorType::get(I->Scalar->getType(), BundleWidth);
1425 ExtractCost += TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy,
1429 DEBUG(dbgs() << "SLP: Total Cost " << Cost + ExtractCost<< ".\n");
1430 return Cost + ExtractCost;
1433 int BoUpSLP::getGatherCost(Type *Ty) {
1435 for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
1436 Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
1440 int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) {
1441 // Find the type of the operands in VL.
1442 Type *ScalarTy = VL[0]->getType();
1443 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1444 ScalarTy = SI->getValueOperand()->getType();
1445 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1446 // Find the cost of inserting/extracting values from the vector.
1447 return getGatherCost(VecTy);
1450 AliasAnalysis::Location BoUpSLP::getLocation(Instruction *I) {
1451 if (StoreInst *SI = dyn_cast<StoreInst>(I))
1452 return AA->getLocation(SI);
1453 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1454 return AA->getLocation(LI);
1455 return AliasAnalysis::Location();
1458 Value *BoUpSLP::getPointerOperand(Value *I) {
1459 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1460 return LI->getPointerOperand();
1461 if (StoreInst *SI = dyn_cast<StoreInst>(I))
1462 return SI->getPointerOperand();
1466 unsigned BoUpSLP::getAddressSpaceOperand(Value *I) {
1467 if (LoadInst *L = dyn_cast<LoadInst>(I))
1468 return L->getPointerAddressSpace();
1469 if (StoreInst *S = dyn_cast<StoreInst>(I))
1470 return S->getPointerAddressSpace();
1474 bool BoUpSLP::isConsecutiveAccess(Value *A, Value *B) {
1475 Value *PtrA = getPointerOperand(A);
1476 Value *PtrB = getPointerOperand(B);
1477 unsigned ASA = getAddressSpaceOperand(A);
1478 unsigned ASB = getAddressSpaceOperand(B);
1480 // Check that the address spaces match and that the pointers are valid.
1481 if (!PtrA || !PtrB || (ASA != ASB))
1484 // Make sure that A and B are different pointers of the same type.
1485 if (PtrA == PtrB || PtrA->getType() != PtrB->getType())
1488 unsigned PtrBitWidth = DL->getPointerSizeInBits(ASA);
1489 Type *Ty = cast<PointerType>(PtrA->getType())->getElementType();
1490 APInt Size(PtrBitWidth, DL->getTypeStoreSize(Ty));
1492 APInt OffsetA(PtrBitWidth, 0), OffsetB(PtrBitWidth, 0);
1493 PtrA = PtrA->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetA);
1494 PtrB = PtrB->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetB);
1496 APInt OffsetDelta = OffsetB - OffsetA;
1498 // Check if they are based on the same pointer. That makes the offsets
1501 return OffsetDelta == Size;
1503 // Compute the necessary base pointer delta to have the necessary final delta
1504 // equal to the size.
1505 APInt BaseDelta = Size - OffsetDelta;
1507 // Otherwise compute the distance with SCEV between the base pointers.
1508 const SCEV *PtrSCEVA = SE->getSCEV(PtrA);
1509 const SCEV *PtrSCEVB = SE->getSCEV(PtrB);
1510 const SCEV *C = SE->getConstant(BaseDelta);
1511 const SCEV *X = SE->getAddExpr(PtrSCEVA, C);
1512 return X == PtrSCEVB;
1515 Value *BoUpSLP::getSinkBarrier(Instruction *Src, Instruction *Dst) {
1516 assert(Src->getParent() == Dst->getParent() && "Not the same BB");
1517 BasicBlock::iterator I = Src, E = Dst;
1518 /// Scan all of the instruction from SRC to DST and check if
1519 /// the source may alias.
1520 for (++I; I != E; ++I) {
1521 // Ignore store instructions that are marked as 'ignore'.
1522 if (MemBarrierIgnoreList.count(I))
1524 if (Src->mayWriteToMemory()) /* Write */ {
1525 if (!I->mayReadOrWriteMemory())
1528 if (!I->mayWriteToMemory())
1531 AliasAnalysis::Location A = getLocation(&*I);
1532 AliasAnalysis::Location B = getLocation(Src);
1534 if (!A.Ptr || !B.Ptr || AA->alias(A, B))
1540 int BoUpSLP::getLastIndex(ArrayRef<Value *> VL) {
1541 BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
1542 assert(BB == getSameBlock(VL) && "Invalid block");
1543 BlockNumbering &BN = getBlockNumbering(BB);
1545 int MaxIdx = BN.getIndex(BB->getFirstNonPHI());
1546 for (unsigned i = 0, e = VL.size(); i < e; ++i)
1547 MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
1551 Instruction *BoUpSLP::getLastInstruction(ArrayRef<Value *> VL) {
1552 BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
1553 assert(BB == getSameBlock(VL) && "Invalid block");
1554 BlockNumbering &BN = getBlockNumbering(BB);
1556 int MaxIdx = BN.getIndex(cast<Instruction>(VL[0]));
1557 for (unsigned i = 1, e = VL.size(); i < e; ++i)
1558 MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
1559 Instruction *I = BN.getInstruction(MaxIdx);
1560 assert(I && "bad location");
1564 void BoUpSLP::setInsertPointAfterBundle(ArrayRef<Value *> VL) {
1565 Instruction *VL0 = cast<Instruction>(VL[0]);
1566 Instruction *LastInst = getLastInstruction(VL);
1567 BasicBlock::iterator NextInst = LastInst;
1569 Builder.SetInsertPoint(VL0->getParent(), NextInst);
1570 Builder.SetCurrentDebugLocation(VL0->getDebugLoc());
1573 Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
1574 Value *Vec = UndefValue::get(Ty);
1575 // Generate the 'InsertElement' instruction.
1576 for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
1577 Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
1578 if (Instruction *Insrt = dyn_cast<Instruction>(Vec)) {
1579 GatherSeq.insert(Insrt);
1580 CSEBlocks.insert(Insrt->getParent());
1582 // Add to our 'need-to-extract' list.
1583 if (ScalarToTreeEntry.count(VL[i])) {
1584 int Idx = ScalarToTreeEntry[VL[i]];
1585 TreeEntry *E = &VectorizableTree[Idx];
1586 // Find which lane we need to extract.
1588 for (unsigned Lane = 0, LE = VL.size(); Lane != LE; ++Lane) {
1589 // Is this the lane of the scalar that we are looking for ?
1590 if (E->Scalars[Lane] == VL[i]) {
1595 assert(FoundLane >= 0 && "Could not find the correct lane");
1596 ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
1604 Value *BoUpSLP::alreadyVectorized(ArrayRef<Value *> VL) const {
1605 SmallDenseMap<Value*, int>::const_iterator Entry
1606 = ScalarToTreeEntry.find(VL[0]);
1607 if (Entry != ScalarToTreeEntry.end()) {
1608 int Idx = Entry->second;
1609 const TreeEntry *En = &VectorizableTree[Idx];
1610 if (En->isSame(VL) && En->VectorizedValue)
1611 return En->VectorizedValue;
1616 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
1617 if (ScalarToTreeEntry.count(VL[0])) {
1618 int Idx = ScalarToTreeEntry[VL[0]];
1619 TreeEntry *E = &VectorizableTree[Idx];
1621 return vectorizeTree(E);
1624 Type *ScalarTy = VL[0]->getType();
1625 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1626 ScalarTy = SI->getValueOperand()->getType();
1627 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1629 return Gather(VL, VecTy);
1632 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
1633 IRBuilder<>::InsertPointGuard Guard(Builder);
1635 if (E->VectorizedValue) {
1636 DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
1637 return E->VectorizedValue;
1640 Instruction *VL0 = cast<Instruction>(E->Scalars[0]);
1641 Type *ScalarTy = VL0->getType();
1642 if (StoreInst *SI = dyn_cast<StoreInst>(VL0))
1643 ScalarTy = SI->getValueOperand()->getType();
1644 VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size());
1646 if (E->NeedToGather) {
1647 setInsertPointAfterBundle(E->Scalars);
1648 return Gather(E->Scalars, VecTy);
1650 unsigned Opcode = getSameOpcode(E->Scalars);
1653 case Instruction::PHI: {
1654 PHINode *PH = dyn_cast<PHINode>(VL0);
1655 Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
1656 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1657 PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
1658 E->VectorizedValue = NewPhi;
1660 // PHINodes may have multiple entries from the same block. We want to
1661 // visit every block once.
1662 SmallSet<BasicBlock*, 4> VisitedBBs;
1664 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1666 BasicBlock *IBB = PH->getIncomingBlock(i);
1668 if (!VisitedBBs.insert(IBB)) {
1669 NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
1673 // Prepare the operand vector.
1674 for (unsigned j = 0; j < E->Scalars.size(); ++j)
1675 Operands.push_back(cast<PHINode>(E->Scalars[j])->
1676 getIncomingValueForBlock(IBB));
1678 Builder.SetInsertPoint(IBB->getTerminator());
1679 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1680 Value *Vec = vectorizeTree(Operands);
1681 NewPhi->addIncoming(Vec, IBB);
1684 assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
1685 "Invalid number of incoming values");
1689 case Instruction::ExtractElement: {
1690 if (CanReuseExtract(E->Scalars)) {
1691 Value *V = VL0->getOperand(0);
1692 E->VectorizedValue = V;
1695 return Gather(E->Scalars, VecTy);
1697 case Instruction::ZExt:
1698 case Instruction::SExt:
1699 case Instruction::FPToUI:
1700 case Instruction::FPToSI:
1701 case Instruction::FPExt:
1702 case Instruction::PtrToInt:
1703 case Instruction::IntToPtr:
1704 case Instruction::SIToFP:
1705 case Instruction::UIToFP:
1706 case Instruction::Trunc:
1707 case Instruction::FPTrunc:
1708 case Instruction::BitCast: {
1710 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1711 INVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1713 setInsertPointAfterBundle(E->Scalars);
1715 Value *InVec = vectorizeTree(INVL);
1717 if (Value *V = alreadyVectorized(E->Scalars))
1720 CastInst *CI = dyn_cast<CastInst>(VL0);
1721 Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
1722 E->VectorizedValue = V;
1725 case Instruction::FCmp:
1726 case Instruction::ICmp: {
1727 ValueList LHSV, RHSV;
1728 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1729 LHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1730 RHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1733 setInsertPointAfterBundle(E->Scalars);
1735 Value *L = vectorizeTree(LHSV);
1736 Value *R = vectorizeTree(RHSV);
1738 if (Value *V = alreadyVectorized(E->Scalars))
1741 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
1743 if (Opcode == Instruction::FCmp)
1744 V = Builder.CreateFCmp(P0, L, R);
1746 V = Builder.CreateICmp(P0, L, R);
1748 E->VectorizedValue = V;
1751 case Instruction::Select: {
1752 ValueList TrueVec, FalseVec, CondVec;
1753 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1754 CondVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1755 TrueVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1756 FalseVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(2));
1759 setInsertPointAfterBundle(E->Scalars);
1761 Value *Cond = vectorizeTree(CondVec);
1762 Value *True = vectorizeTree(TrueVec);
1763 Value *False = vectorizeTree(FalseVec);
1765 if (Value *V = alreadyVectorized(E->Scalars))
1768 Value *V = Builder.CreateSelect(Cond, True, False);
1769 E->VectorizedValue = V;
1772 case Instruction::Add:
1773 case Instruction::FAdd:
1774 case Instruction::Sub:
1775 case Instruction::FSub:
1776 case Instruction::Mul:
1777 case Instruction::FMul:
1778 case Instruction::UDiv:
1779 case Instruction::SDiv:
1780 case Instruction::FDiv:
1781 case Instruction::URem:
1782 case Instruction::SRem:
1783 case Instruction::FRem:
1784 case Instruction::Shl:
1785 case Instruction::LShr:
1786 case Instruction::AShr:
1787 case Instruction::And:
1788 case Instruction::Or:
1789 case Instruction::Xor: {
1790 ValueList LHSVL, RHSVL;
1791 if (isa<BinaryOperator>(VL0) && VL0->isCommutative())
1792 reorderInputsAccordingToOpcode(E->Scalars, LHSVL, RHSVL);
1794 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1795 LHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1796 RHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1799 setInsertPointAfterBundle(E->Scalars);
1801 Value *LHS = vectorizeTree(LHSVL);
1802 Value *RHS = vectorizeTree(RHSVL);
1804 if (LHS == RHS && isa<Instruction>(LHS)) {
1805 assert((VL0->getOperand(0) == VL0->getOperand(1)) && "Invalid order");
1808 if (Value *V = alreadyVectorized(E->Scalars))
1811 BinaryOperator *BinOp = cast<BinaryOperator>(VL0);
1812 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), LHS, RHS);
1813 E->VectorizedValue = V;
1815 if (Instruction *I = dyn_cast<Instruction>(V))
1816 return propagateMetadata(I, E->Scalars);
1820 case Instruction::Load: {
1821 // Loads are inserted at the head of the tree because we don't want to
1822 // sink them all the way down past store instructions.
1823 setInsertPointAfterBundle(E->Scalars);
1825 LoadInst *LI = cast<LoadInst>(VL0);
1826 unsigned AS = LI->getPointerAddressSpace();
1828 Value *VecPtr = Builder.CreateBitCast(LI->getPointerOperand(),
1829 VecTy->getPointerTo(AS));
1830 unsigned Alignment = LI->getAlignment();
1831 LI = Builder.CreateLoad(VecPtr);
1833 Alignment = DL->getABITypeAlignment(LI->getPointerOperand()->getType());
1834 LI->setAlignment(Alignment);
1835 E->VectorizedValue = LI;
1836 return propagateMetadata(LI, E->Scalars);
1838 case Instruction::Store: {
1839 StoreInst *SI = cast<StoreInst>(VL0);
1840 unsigned Alignment = SI->getAlignment();
1841 unsigned AS = SI->getPointerAddressSpace();
1844 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1845 ValueOp.push_back(cast<StoreInst>(E->Scalars[i])->getValueOperand());
1847 setInsertPointAfterBundle(E->Scalars);
1849 Value *VecValue = vectorizeTree(ValueOp);
1850 Value *VecPtr = Builder.CreateBitCast(SI->getPointerOperand(),
1851 VecTy->getPointerTo(AS));
1852 StoreInst *S = Builder.CreateStore(VecValue, VecPtr);
1854 Alignment = DL->getABITypeAlignment(SI->getPointerOperand()->getType());
1855 S->setAlignment(Alignment);
1856 E->VectorizedValue = S;
1857 return propagateMetadata(S, E->Scalars);
1859 case Instruction::GetElementPtr: {
1860 setInsertPointAfterBundle(E->Scalars);
1863 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1864 Op0VL.push_back(cast<GetElementPtrInst>(E->Scalars[i])->getOperand(0));
1866 Value *Op0 = vectorizeTree(Op0VL);
1868 std::vector<Value *> OpVecs;
1869 for (int j = 1, e = cast<GetElementPtrInst>(VL0)->getNumOperands(); j < e;
1872 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1873 OpVL.push_back(cast<GetElementPtrInst>(E->Scalars[i])->getOperand(j));
1875 Value *OpVec = vectorizeTree(OpVL);
1876 OpVecs.push_back(OpVec);
1879 Value *V = Builder.CreateGEP(Op0, OpVecs);
1880 E->VectorizedValue = V;
1882 if (Instruction *I = dyn_cast<Instruction>(V))
1883 return propagateMetadata(I, E->Scalars);
1887 case Instruction::Call: {
1888 CallInst *CI = cast<CallInst>(VL0);
1889 setInsertPointAfterBundle(E->Scalars);
1891 Intrinsic::ID IID = Intrinsic::not_intrinsic;
1892 if (CI && (FI = CI->getCalledFunction())) {
1893 IID = (Intrinsic::ID) FI->getIntrinsicID();
1895 std::vector<Value *> OpVecs;
1896 for (int j = 0, e = CI->getNumArgOperands(); j < e; ++j) {
1898 // ctlz,cttz and powi are special intrinsics whose second argument is
1899 // a scalar. This argument should not be vectorized.
1900 if (hasVectorInstrinsicScalarOpd(IID, 1) && j == 1) {
1901 CallInst *CEI = cast<CallInst>(E->Scalars[0]);
1902 OpVecs.push_back(CEI->getArgOperand(j));
1905 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1906 CallInst *CEI = cast<CallInst>(E->Scalars[i]);
1907 OpVL.push_back(CEI->getArgOperand(j));
1910 Value *OpVec = vectorizeTree(OpVL);
1911 DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
1912 OpVecs.push_back(OpVec);
1915 Module *M = F->getParent();
1916 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
1917 Type *Tys[] = { VectorType::get(CI->getType(), E->Scalars.size()) };
1918 Function *CF = Intrinsic::getDeclaration(M, ID, Tys);
1919 Value *V = Builder.CreateCall(CF, OpVecs);
1920 E->VectorizedValue = V;
1923 case Instruction::ShuffleVector: {
1924 ValueList LHSVL, RHSVL;
1925 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1926 LHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1927 RHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1929 setInsertPointAfterBundle(E->Scalars);
1931 Value *LHS = vectorizeTree(LHSVL);
1932 Value *RHS = vectorizeTree(RHSVL);
1934 if (Value *V = alreadyVectorized(E->Scalars))
1937 // Create a vector of LHS op1 RHS
1938 BinaryOperator *BinOp0 = cast<BinaryOperator>(VL0);
1939 Value *V0 = Builder.CreateBinOp(BinOp0->getOpcode(), LHS, RHS);
1941 // Create a vector of LHS op2 RHS
1942 Instruction *VL1 = cast<Instruction>(E->Scalars[1]);
1943 BinaryOperator *BinOp1 = cast<BinaryOperator>(VL1);
1944 Value *V1 = Builder.CreateBinOp(BinOp1->getOpcode(), LHS, RHS);
1946 // Create appropriate shuffle to take alternative operations from
1948 std::vector<Constant *> Mask(E->Scalars.size());
1949 unsigned e = E->Scalars.size();
1950 for (unsigned i = 0; i < e; ++i) {
1952 Mask[i] = Builder.getInt32(e + i);
1954 Mask[i] = Builder.getInt32(i);
1957 Value *ShuffleMask = ConstantVector::get(Mask);
1959 Value *V = Builder.CreateShuffleVector(V0, V1, ShuffleMask);
1960 E->VectorizedValue = V;
1961 if (Instruction *I = dyn_cast<Instruction>(V))
1962 return propagateMetadata(I, E->Scalars);
1967 llvm_unreachable("unknown inst");
1972 Value *BoUpSLP::vectorizeTree() {
1973 Builder.SetInsertPoint(F->getEntryBlock().begin());
1974 vectorizeTree(&VectorizableTree[0]);
1976 DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() << " values .\n");
1978 // Extract all of the elements with the external uses.
1979 for (UserList::iterator it = ExternalUses.begin(), e = ExternalUses.end();
1981 Value *Scalar = it->Scalar;
1982 llvm::User *User = it->User;
1984 // Skip users that we already RAUW. This happens when one instruction
1985 // has multiple uses of the same value.
1986 if (std::find(Scalar->user_begin(), Scalar->user_end(), User) ==
1989 assert(ScalarToTreeEntry.count(Scalar) && "Invalid scalar");
1991 int Idx = ScalarToTreeEntry[Scalar];
1992 TreeEntry *E = &VectorizableTree[Idx];
1993 assert(!E->NeedToGather && "Extracting from a gather list");
1995 Value *Vec = E->VectorizedValue;
1996 assert(Vec && "Can't find vectorizable value");
1998 Value *Lane = Builder.getInt32(it->Lane);
1999 // Generate extracts for out-of-tree users.
2000 // Find the insertion point for the extractelement lane.
2001 if (isa<Instruction>(Vec)){
2002 if (PHINode *PH = dyn_cast<PHINode>(User)) {
2003 for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
2004 if (PH->getIncomingValue(i) == Scalar) {
2005 Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
2006 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2007 CSEBlocks.insert(PH->getIncomingBlock(i));
2008 PH->setOperand(i, Ex);
2012 Builder.SetInsertPoint(cast<Instruction>(User));
2013 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2014 CSEBlocks.insert(cast<Instruction>(User)->getParent());
2015 User->replaceUsesOfWith(Scalar, Ex);
2018 Builder.SetInsertPoint(F->getEntryBlock().begin());
2019 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2020 CSEBlocks.insert(&F->getEntryBlock());
2021 User->replaceUsesOfWith(Scalar, Ex);
2024 DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
2027 // For each vectorized value:
2028 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
2029 TreeEntry *Entry = &VectorizableTree[EIdx];
2032 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
2033 Value *Scalar = Entry->Scalars[Lane];
2034 // No need to handle users of gathered values.
2035 if (Entry->NeedToGather)
2038 assert(Entry->VectorizedValue && "Can't find vectorizable value");
2040 Type *Ty = Scalar->getType();
2041 if (!Ty->isVoidTy()) {
2043 for (User *U : Scalar->users()) {
2044 DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
2046 assert((ScalarToTreeEntry.count(U) ||
2047 // It is legal to replace users in the ignorelist by undef.
2048 (std::find(UserIgnoreList.begin(), UserIgnoreList.end(), U) !=
2049 UserIgnoreList.end())) &&
2050 "Replacing out-of-tree value with undef");
2053 Value *Undef = UndefValue::get(Ty);
2054 Scalar->replaceAllUsesWith(Undef);
2056 DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
2057 cast<Instruction>(Scalar)->eraseFromParent();
2061 for (auto &BN : BlocksNumbers)
2064 Builder.ClearInsertionPoint();
2066 return VectorizableTree[0].VectorizedValue;
2069 void BoUpSLP::optimizeGatherSequence() {
2070 DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
2071 << " gather sequences instructions.\n");
2072 // LICM InsertElementInst sequences.
2073 for (SetVector<Instruction *>::iterator it = GatherSeq.begin(),
2074 e = GatherSeq.end(); it != e; ++it) {
2075 InsertElementInst *Insert = dyn_cast<InsertElementInst>(*it);
2080 // Check if this block is inside a loop.
2081 Loop *L = LI->getLoopFor(Insert->getParent());
2085 // Check if it has a preheader.
2086 BasicBlock *PreHeader = L->getLoopPreheader();
2090 // If the vector or the element that we insert into it are
2091 // instructions that are defined in this basic block then we can't
2092 // hoist this instruction.
2093 Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
2094 Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
2095 if (CurrVec && L->contains(CurrVec))
2097 if (NewElem && L->contains(NewElem))
2100 // We can hoist this instruction. Move it to the pre-header.
2101 Insert->moveBefore(PreHeader->getTerminator());
2104 // Make a list of all reachable blocks in our CSE queue.
2105 SmallVector<const DomTreeNode *, 8> CSEWorkList;
2106 CSEWorkList.reserve(CSEBlocks.size());
2107 for (BasicBlock *BB : CSEBlocks)
2108 if (DomTreeNode *N = DT->getNode(BB)) {
2109 assert(DT->isReachableFromEntry(N));
2110 CSEWorkList.push_back(N);
2113 // Sort blocks by domination. This ensures we visit a block after all blocks
2114 // dominating it are visited.
2115 std::stable_sort(CSEWorkList.begin(), CSEWorkList.end(),
2116 [this](const DomTreeNode *A, const DomTreeNode *B) {
2117 return DT->properlyDominates(A, B);
2120 // Perform O(N^2) search over the gather sequences and merge identical
2121 // instructions. TODO: We can further optimize this scan if we split the
2122 // instructions into different buckets based on the insert lane.
2123 SmallVector<Instruction *, 16> Visited;
2124 for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
2125 assert((I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
2126 "Worklist not sorted properly!");
2127 BasicBlock *BB = (*I)->getBlock();
2128 // For all instructions in blocks containing gather sequences:
2129 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) {
2130 Instruction *In = it++;
2131 if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In))
2134 // Check if we can replace this instruction with any of the
2135 // visited instructions.
2136 for (SmallVectorImpl<Instruction *>::iterator v = Visited.begin(),
2139 if (In->isIdenticalTo(*v) &&
2140 DT->dominates((*v)->getParent(), In->getParent())) {
2141 In->replaceAllUsesWith(*v);
2142 In->eraseFromParent();
2148 assert(std::find(Visited.begin(), Visited.end(), In) == Visited.end());
2149 Visited.push_back(In);
2157 /// The SLPVectorizer Pass.
2158 struct SLPVectorizer : public FunctionPass {
2159 typedef SmallVector<StoreInst *, 8> StoreList;
2160 typedef MapVector<Value *, StoreList> StoreListMap;
2162 /// Pass identification, replacement for typeid
2165 explicit SLPVectorizer() : FunctionPass(ID) {
2166 initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
2169 ScalarEvolution *SE;
2170 const DataLayout *DL;
2171 TargetTransformInfo *TTI;
2172 TargetLibraryInfo *TLI;
2177 bool runOnFunction(Function &F) override {
2178 if (skipOptnoneFunction(F))
2181 SE = &getAnalysis<ScalarEvolution>();
2182 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
2183 DL = DLP ? &DLP->getDataLayout() : nullptr;
2184 TTI = &getAnalysis<TargetTransformInfo>();
2185 TLI = getAnalysisIfAvailable<TargetLibraryInfo>();
2186 AA = &getAnalysis<AliasAnalysis>();
2187 LI = &getAnalysis<LoopInfo>();
2188 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2191 bool Changed = false;
2193 // If the target claims to have no vector registers don't attempt
2195 if (!TTI->getNumberOfRegisters(true))
2198 // Must have DataLayout. We can't require it because some tests run w/o
2203 // Don't vectorize when the attribute NoImplicitFloat is used.
2204 if (F.hasFnAttribute(Attribute::NoImplicitFloat))
2207 DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
2209 // Use the bottom up slp vectorizer to construct chains that start with
2210 // store instructions.
2211 BoUpSLP R(&F, SE, DL, TTI, TLI, AA, LI, DT);
2213 // Scan the blocks in the function in post order.
2214 for (po_iterator<BasicBlock*> it = po_begin(&F.getEntryBlock()),
2215 e = po_end(&F.getEntryBlock()); it != e; ++it) {
2216 BasicBlock *BB = *it;
2217 // Vectorize trees that end at stores.
2218 if (unsigned count = collectStores(BB, R)) {
2220 DEBUG(dbgs() << "SLP: Found " << count << " stores to vectorize.\n");
2221 Changed |= vectorizeStoreChains(R);
2224 // Vectorize trees that end at reductions.
2225 Changed |= vectorizeChainsInBlock(BB, R);
2229 R.optimizeGatherSequence();
2230 DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
2231 DEBUG(verifyFunction(F));
2236 void getAnalysisUsage(AnalysisUsage &AU) const override {
2237 FunctionPass::getAnalysisUsage(AU);
2238 AU.addRequired<ScalarEvolution>();
2239 AU.addRequired<AliasAnalysis>();
2240 AU.addRequired<TargetTransformInfo>();
2241 AU.addRequired<LoopInfo>();
2242 AU.addRequired<DominatorTreeWrapperPass>();
2243 AU.addPreserved<LoopInfo>();
2244 AU.addPreserved<DominatorTreeWrapperPass>();
2245 AU.setPreservesCFG();
2250 /// \brief Collect memory references and sort them according to their base
2251 /// object. We sort the stores to their base objects to reduce the cost of the
2252 /// quadratic search on the stores. TODO: We can further reduce this cost
2253 /// if we flush the chain creation every time we run into a memory barrier.
2254 unsigned collectStores(BasicBlock *BB, BoUpSLP &R);
2256 /// \brief Try to vectorize a chain that starts at two arithmetic instrs.
2257 bool tryToVectorizePair(Value *A, Value *B, BoUpSLP &R);
2259 /// \brief Try to vectorize a list of operands.
2260 /// \@param BuildVector A list of users to ignore for the purpose of
2261 /// scheduling and that don't need extracting.
2262 /// \returns true if a value was vectorized.
2263 bool tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
2264 ArrayRef<Value *> BuildVector = None,
2265 bool allowReorder = false);
2267 /// \brief Try to vectorize a chain that may start at the operands of \V;
2268 bool tryToVectorize(BinaryOperator *V, BoUpSLP &R);
2270 /// \brief Vectorize the stores that were collected in StoreRefs.
2271 bool vectorizeStoreChains(BoUpSLP &R);
2273 /// \brief Scan the basic block and look for patterns that are likely to start
2274 /// a vectorization chain.
2275 bool vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R);
2277 bool vectorizeStoreChain(ArrayRef<Value *> Chain, int CostThreshold,
2280 bool vectorizeStores(ArrayRef<StoreInst *> Stores, int costThreshold,
2283 StoreListMap StoreRefs;
2286 /// \brief Check that the Values in the slice in VL array are still existent in
2287 /// the WeakVH array.
2288 /// Vectorization of part of the VL array may cause later values in the VL array
2289 /// to become invalid. We track when this has happened in the WeakVH array.
2290 static bool hasValueBeenRAUWed(ArrayRef<Value *> &VL,
2291 SmallVectorImpl<WeakVH> &VH,
2292 unsigned SliceBegin,
2293 unsigned SliceSize) {
2294 for (unsigned i = SliceBegin; i < SliceBegin + SliceSize; ++i)
2301 bool SLPVectorizer::vectorizeStoreChain(ArrayRef<Value *> Chain,
2302 int CostThreshold, BoUpSLP &R) {
2303 unsigned ChainLen = Chain.size();
2304 DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
2306 Type *StoreTy = cast<StoreInst>(Chain[0])->getValueOperand()->getType();
2307 unsigned Sz = DL->getTypeSizeInBits(StoreTy);
2308 unsigned VF = MinVecRegSize / Sz;
2310 if (!isPowerOf2_32(Sz) || VF < 2)
2313 // Keep track of values that were deleted by vectorizing in the loop below.
2314 SmallVector<WeakVH, 8> TrackValues(Chain.begin(), Chain.end());
2316 bool Changed = false;
2317 // Look for profitable vectorizable trees at all offsets, starting at zero.
2318 for (unsigned i = 0, e = ChainLen; i < e; ++i) {
2322 // Check that a previous iteration of this loop did not delete the Value.
2323 if (hasValueBeenRAUWed(Chain, TrackValues, i, VF))
2326 DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
2328 ArrayRef<Value *> Operands = Chain.slice(i, VF);
2330 R.buildTree(Operands);
2332 int Cost = R.getTreeCost();
2334 DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
2335 if (Cost < CostThreshold) {
2336 DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
2339 // Move to the next bundle.
2348 bool SLPVectorizer::vectorizeStores(ArrayRef<StoreInst *> Stores,
2349 int costThreshold, BoUpSLP &R) {
2350 SetVector<Value *> Heads, Tails;
2351 SmallDenseMap<Value *, Value *> ConsecutiveChain;
2353 // We may run into multiple chains that merge into a single chain. We mark the
2354 // stores that we vectorized so that we don't visit the same store twice.
2355 BoUpSLP::ValueSet VectorizedStores;
2356 bool Changed = false;
2358 // Do a quadratic search on all of the given stores and find
2359 // all of the pairs of stores that follow each other.
2360 for (unsigned i = 0, e = Stores.size(); i < e; ++i) {
2361 for (unsigned j = 0; j < e; ++j) {
2365 if (R.isConsecutiveAccess(Stores[i], Stores[j])) {
2366 Tails.insert(Stores[j]);
2367 Heads.insert(Stores[i]);
2368 ConsecutiveChain[Stores[i]] = Stores[j];
2373 // For stores that start but don't end a link in the chain:
2374 for (SetVector<Value *>::iterator it = Heads.begin(), e = Heads.end();
2376 if (Tails.count(*it))
2379 // We found a store instr that starts a chain. Now follow the chain and try
2381 BoUpSLP::ValueList Operands;
2383 // Collect the chain into a list.
2384 while (Tails.count(I) || Heads.count(I)) {
2385 if (VectorizedStores.count(I))
2387 Operands.push_back(I);
2388 // Move to the next value in the chain.
2389 I = ConsecutiveChain[I];
2392 bool Vectorized = vectorizeStoreChain(Operands, costThreshold, R);
2394 // Mark the vectorized stores so that we don't vectorize them again.
2396 VectorizedStores.insert(Operands.begin(), Operands.end());
2397 Changed |= Vectorized;
2404 unsigned SLPVectorizer::collectStores(BasicBlock *BB, BoUpSLP &R) {
2407 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2408 StoreInst *SI = dyn_cast<StoreInst>(it);
2412 // Don't touch volatile stores.
2413 if (!SI->isSimple())
2416 // Check that the pointer points to scalars.
2417 Type *Ty = SI->getValueOperand()->getType();
2418 if (Ty->isAggregateType() || Ty->isVectorTy())
2421 // Find the base pointer.
2422 Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), DL);
2424 // Save the store locations.
2425 StoreRefs[Ptr].push_back(SI);
2431 bool SLPVectorizer::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
2434 Value *VL[] = { A, B };
2435 return tryToVectorizeList(VL, R, None, true);
2438 bool SLPVectorizer::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
2439 ArrayRef<Value *> BuildVector,
2440 bool allowReorder) {
2444 DEBUG(dbgs() << "SLP: Vectorizing a list of length = " << VL.size() << ".\n");
2446 // Check that all of the parts are scalar instructions of the same type.
2447 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
2451 unsigned Opcode0 = I0->getOpcode();
2453 Type *Ty0 = I0->getType();
2454 unsigned Sz = DL->getTypeSizeInBits(Ty0);
2455 unsigned VF = MinVecRegSize / Sz;
2457 for (int i = 0, e = VL.size(); i < e; ++i) {
2458 Type *Ty = VL[i]->getType();
2459 if (Ty->isAggregateType() || Ty->isVectorTy())
2461 Instruction *Inst = dyn_cast<Instruction>(VL[i]);
2462 if (!Inst || Inst->getOpcode() != Opcode0)
2466 bool Changed = false;
2468 // Keep track of values that were deleted by vectorizing in the loop below.
2469 SmallVector<WeakVH, 8> TrackValues(VL.begin(), VL.end());
2471 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
2472 unsigned OpsWidth = 0;
2479 if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
2482 // Check that a previous iteration of this loop did not delete the Value.
2483 if (hasValueBeenRAUWed(VL, TrackValues, i, OpsWidth))
2486 DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
2488 ArrayRef<Value *> Ops = VL.slice(i, OpsWidth);
2490 ArrayRef<Value *> BuildVectorSlice;
2491 if (!BuildVector.empty())
2492 BuildVectorSlice = BuildVector.slice(i, OpsWidth);
2494 R.buildTree(Ops, BuildVectorSlice);
2495 // TODO: check if we can allow reordering also for other cases than
2496 // tryToVectorizePair()
2497 if (allowReorder && R.shouldReorder()) {
2498 assert(Ops.size() == 2);
2499 assert(BuildVectorSlice.empty());
2500 Value *ReorderedOps[] = { Ops[1], Ops[0] };
2501 R.buildTree(ReorderedOps, None);
2503 int Cost = R.getTreeCost();
2505 if (Cost < -SLPCostThreshold) {
2506 DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
2507 Value *VectorizedRoot = R.vectorizeTree();
2509 // Reconstruct the build vector by extracting the vectorized root. This
2510 // way we handle the case where some elements of the vector are undefined.
2511 // (return (inserelt <4 xi32> (insertelt undef (opd0) 0) (opd1) 2))
2512 if (!BuildVectorSlice.empty()) {
2513 // The insert point is the last build vector instruction. The vectorized
2514 // root will precede it. This guarantees that we get an instruction. The
2515 // vectorized tree could have been constant folded.
2516 Instruction *InsertAfter = cast<Instruction>(BuildVectorSlice.back());
2517 unsigned VecIdx = 0;
2518 for (auto &V : BuildVectorSlice) {
2519 IRBuilder<true, NoFolder> Builder(
2520 ++BasicBlock::iterator(InsertAfter));
2521 InsertElementInst *IE = cast<InsertElementInst>(V);
2522 Instruction *Extract = cast<Instruction>(Builder.CreateExtractElement(
2523 VectorizedRoot, Builder.getInt32(VecIdx++)));
2524 IE->setOperand(1, Extract);
2525 IE->removeFromParent();
2526 IE->insertAfter(Extract);
2530 // Move to the next bundle.
2539 bool SLPVectorizer::tryToVectorize(BinaryOperator *V, BoUpSLP &R) {
2543 // Try to vectorize V.
2544 if (tryToVectorizePair(V->getOperand(0), V->getOperand(1), R))
2547 BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0));
2548 BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1));
2550 if (B && B->hasOneUse()) {
2551 BinaryOperator *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
2552 BinaryOperator *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
2553 if (tryToVectorizePair(A, B0, R)) {
2557 if (tryToVectorizePair(A, B1, R)) {
2564 if (A && A->hasOneUse()) {
2565 BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
2566 BinaryOperator *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
2567 if (tryToVectorizePair(A0, B, R)) {
2571 if (tryToVectorizePair(A1, B, R)) {
2579 /// \brief Generate a shuffle mask to be used in a reduction tree.
2581 /// \param VecLen The length of the vector to be reduced.
2582 /// \param NumEltsToRdx The number of elements that should be reduced in the
2584 /// \param IsPairwise Whether the reduction is a pairwise or splitting
2585 /// reduction. A pairwise reduction will generate a mask of
2586 /// <0,2,...> or <1,3,..> while a splitting reduction will generate
2587 /// <2,3, undef,undef> for a vector of 4 and NumElts = 2.
2588 /// \param IsLeft True will generate a mask of even elements, odd otherwise.
2589 static Value *createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx,
2590 bool IsPairwise, bool IsLeft,
2591 IRBuilder<> &Builder) {
2592 assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask");
2594 SmallVector<Constant *, 32> ShuffleMask(
2595 VecLen, UndefValue::get(Builder.getInt32Ty()));
2598 // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
2599 for (unsigned i = 0; i != NumEltsToRdx; ++i)
2600 ShuffleMask[i] = Builder.getInt32(2 * i + !IsLeft);
2602 // Move the upper half of the vector to the lower half.
2603 for (unsigned i = 0; i != NumEltsToRdx; ++i)
2604 ShuffleMask[i] = Builder.getInt32(NumEltsToRdx + i);
2606 return ConstantVector::get(ShuffleMask);
2610 /// Model horizontal reductions.
2612 /// A horizontal reduction is a tree of reduction operations (currently add and
2613 /// fadd) that has operations that can be put into a vector as its leaf.
2614 /// For example, this tree:
2621 /// This tree has "mul" as its reduced values and "+" as its reduction
2622 /// operations. A reduction might be feeding into a store or a binary operation
2637 class HorizontalReduction {
2638 SmallVector<Value *, 16> ReductionOps;
2639 SmallVector<Value *, 32> ReducedVals;
2641 BinaryOperator *ReductionRoot;
2642 PHINode *ReductionPHI;
2644 /// The opcode of the reduction.
2645 unsigned ReductionOpcode;
2646 /// The opcode of the values we perform a reduction on.
2647 unsigned ReducedValueOpcode;
2648 /// The width of one full horizontal reduction operation.
2649 unsigned ReduxWidth;
2650 /// Should we model this reduction as a pairwise reduction tree or a tree that
2651 /// splits the vector in halves and adds those halves.
2652 bool IsPairwiseReduction;
2655 HorizontalReduction()
2656 : ReductionRoot(nullptr), ReductionPHI(nullptr), ReductionOpcode(0),
2657 ReducedValueOpcode(0), ReduxWidth(0), IsPairwiseReduction(false) {}
2659 /// \brief Try to find a reduction tree.
2660 bool matchAssociativeReduction(PHINode *Phi, BinaryOperator *B,
2661 const DataLayout *DL) {
2663 std::find(Phi->op_begin(), Phi->op_end(), B) != Phi->op_end()) &&
2664 "Thi phi needs to use the binary operator");
2666 // We could have a initial reductions that is not an add.
2667 // r *= v1 + v2 + v3 + v4
2668 // In such a case start looking for a tree rooted in the first '+'.
2670 if (B->getOperand(0) == Phi) {
2672 B = dyn_cast<BinaryOperator>(B->getOperand(1));
2673 } else if (B->getOperand(1) == Phi) {
2675 B = dyn_cast<BinaryOperator>(B->getOperand(0));
2682 Type *Ty = B->getType();
2683 if (Ty->isVectorTy())
2686 ReductionOpcode = B->getOpcode();
2687 ReducedValueOpcode = 0;
2688 ReduxWidth = MinVecRegSize / DL->getTypeSizeInBits(Ty);
2695 // We currently only support adds.
2696 if (ReductionOpcode != Instruction::Add &&
2697 ReductionOpcode != Instruction::FAdd)
2700 // Post order traverse the reduction tree starting at B. We only handle true
2701 // trees containing only binary operators.
2702 SmallVector<std::pair<BinaryOperator *, unsigned>, 32> Stack;
2703 Stack.push_back(std::make_pair(B, 0));
2704 while (!Stack.empty()) {
2705 BinaryOperator *TreeN = Stack.back().first;
2706 unsigned EdgeToVist = Stack.back().second++;
2707 bool IsReducedValue = TreeN->getOpcode() != ReductionOpcode;
2709 // Only handle trees in the current basic block.
2710 if (TreeN->getParent() != B->getParent())
2713 // Each tree node needs to have one user except for the ultimate
2715 if (!TreeN->hasOneUse() && TreeN != B)
2719 if (EdgeToVist == 2 || IsReducedValue) {
2720 if (IsReducedValue) {
2721 // Make sure that the opcodes of the operations that we are going to
2723 if (!ReducedValueOpcode)
2724 ReducedValueOpcode = TreeN->getOpcode();
2725 else if (ReducedValueOpcode != TreeN->getOpcode())
2727 ReducedVals.push_back(TreeN);
2729 // We need to be able to reassociate the adds.
2730 if (!TreeN->isAssociative())
2732 ReductionOps.push_back(TreeN);
2739 // Visit left or right.
2740 Value *NextV = TreeN->getOperand(EdgeToVist);
2741 BinaryOperator *Next = dyn_cast<BinaryOperator>(NextV);
2743 Stack.push_back(std::make_pair(Next, 0));
2744 else if (NextV != Phi)
2750 /// \brief Attempt to vectorize the tree found by
2751 /// matchAssociativeReduction.
2752 bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
2753 if (ReducedVals.empty())
2756 unsigned NumReducedVals = ReducedVals.size();
2757 if (NumReducedVals < ReduxWidth)
2760 Value *VectorizedTree = nullptr;
2761 IRBuilder<> Builder(ReductionRoot);
2762 FastMathFlags Unsafe;
2763 Unsafe.setUnsafeAlgebra();
2764 Builder.SetFastMathFlags(Unsafe);
2767 for (; i < NumReducedVals - ReduxWidth + 1; i += ReduxWidth) {
2768 ArrayRef<Value *> ValsToReduce(&ReducedVals[i], ReduxWidth);
2769 V.buildTree(ValsToReduce, ReductionOps);
2772 int Cost = V.getTreeCost() + getReductionCost(TTI, ReducedVals[i]);
2773 if (Cost >= -SLPCostThreshold)
2776 DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" << Cost
2779 // Vectorize a tree.
2780 DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
2781 Value *VectorizedRoot = V.vectorizeTree();
2783 // Emit a reduction.
2784 Value *ReducedSubTree = emitReduction(VectorizedRoot, Builder);
2785 if (VectorizedTree) {
2786 Builder.SetCurrentDebugLocation(Loc);
2787 VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
2788 ReducedSubTree, "bin.rdx");
2790 VectorizedTree = ReducedSubTree;
2793 if (VectorizedTree) {
2794 // Finish the reduction.
2795 for (; i < NumReducedVals; ++i) {
2796 Builder.SetCurrentDebugLocation(
2797 cast<Instruction>(ReducedVals[i])->getDebugLoc());
2798 VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
2803 assert(ReductionRoot && "Need a reduction operation");
2804 ReductionRoot->setOperand(0, VectorizedTree);
2805 ReductionRoot->setOperand(1, ReductionPHI);
2807 ReductionRoot->replaceAllUsesWith(VectorizedTree);
2809 return VectorizedTree != nullptr;
2814 /// \brief Calcuate the cost of a reduction.
2815 int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal) {
2816 Type *ScalarTy = FirstReducedVal->getType();
2817 Type *VecTy = VectorType::get(ScalarTy, ReduxWidth);
2819 int PairwiseRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, true);
2820 int SplittingRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, false);
2822 IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
2823 int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
2825 int ScalarReduxCost =
2826 ReduxWidth * TTI->getArithmeticInstrCost(ReductionOpcode, VecTy);
2828 DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost
2829 << " for reduction that starts with " << *FirstReducedVal
2831 << (IsPairwiseReduction ? "pairwise" : "splitting")
2832 << " reduction)\n");
2834 return VecReduxCost - ScalarReduxCost;
2837 static Value *createBinOp(IRBuilder<> &Builder, unsigned Opcode, Value *L,
2838 Value *R, const Twine &Name = "") {
2839 if (Opcode == Instruction::FAdd)
2840 return Builder.CreateFAdd(L, R, Name);
2841 return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, L, R, Name);
2844 /// \brief Emit a horizontal reduction of the vectorized value.
2845 Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder) {
2846 assert(VectorizedValue && "Need to have a vectorized tree node");
2847 Instruction *ValToReduce = dyn_cast<Instruction>(VectorizedValue);
2848 assert(isPowerOf2_32(ReduxWidth) &&
2849 "We only handle power-of-two reductions for now");
2851 Value *TmpVec = ValToReduce;
2852 for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
2853 if (IsPairwiseReduction) {
2855 createRdxShuffleMask(ReduxWidth, i, true, true, Builder);
2857 createRdxShuffleMask(ReduxWidth, i, true, false, Builder);
2859 Value *LeftShuf = Builder.CreateShuffleVector(
2860 TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l");
2861 Value *RightShuf = Builder.CreateShuffleVector(
2862 TmpVec, UndefValue::get(TmpVec->getType()), (RightMask),
2864 TmpVec = createBinOp(Builder, ReductionOpcode, LeftShuf, RightShuf,
2868 createRdxShuffleMask(ReduxWidth, i, false, false, Builder);
2869 Value *Shuf = Builder.CreateShuffleVector(
2870 TmpVec, UndefValue::get(TmpVec->getType()), UpperHalf, "rdx.shuf");
2871 TmpVec = createBinOp(Builder, ReductionOpcode, TmpVec, Shuf, "bin.rdx");
2875 // The result is in the first element of the vector.
2876 return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
2880 /// \brief Recognize construction of vectors like
2881 /// %ra = insertelement <4 x float> undef, float %s0, i32 0
2882 /// %rb = insertelement <4 x float> %ra, float %s1, i32 1
2883 /// %rc = insertelement <4 x float> %rb, float %s2, i32 2
2884 /// %rd = insertelement <4 x float> %rc, float %s3, i32 3
2886 /// Returns true if it matches
2888 static bool findBuildVector(InsertElementInst *FirstInsertElem,
2889 SmallVectorImpl<Value *> &BuildVector,
2890 SmallVectorImpl<Value *> &BuildVectorOpds) {
2891 if (!isa<UndefValue>(FirstInsertElem->getOperand(0)))
2894 InsertElementInst *IE = FirstInsertElem;
2896 BuildVector.push_back(IE);
2897 BuildVectorOpds.push_back(IE->getOperand(1));
2899 if (IE->use_empty())
2902 InsertElementInst *NextUse = dyn_cast<InsertElementInst>(IE->user_back());
2906 // If this isn't the final use, make sure the next insertelement is the only
2907 // use. It's OK if the final constructed vector is used multiple times
2908 if (!IE->hasOneUse())
2917 static bool PhiTypeSorterFunc(Value *V, Value *V2) {
2918 return V->getType() < V2->getType();
2921 bool SLPVectorizer::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
2922 bool Changed = false;
2923 SmallVector<Value *, 4> Incoming;
2924 SmallSet<Value *, 16> VisitedInstrs;
2926 bool HaveVectorizedPhiNodes = true;
2927 while (HaveVectorizedPhiNodes) {
2928 HaveVectorizedPhiNodes = false;
2930 // Collect the incoming values from the PHIs.
2932 for (BasicBlock::iterator instr = BB->begin(), ie = BB->end(); instr != ie;
2934 PHINode *P = dyn_cast<PHINode>(instr);
2938 if (!VisitedInstrs.count(P))
2939 Incoming.push_back(P);
2943 std::stable_sort(Incoming.begin(), Incoming.end(), PhiTypeSorterFunc);
2945 // Try to vectorize elements base on their type.
2946 for (SmallVector<Value *, 4>::iterator IncIt = Incoming.begin(),
2950 // Look for the next elements with the same type.
2951 SmallVector<Value *, 4>::iterator SameTypeIt = IncIt;
2952 while (SameTypeIt != E &&
2953 (*SameTypeIt)->getType() == (*IncIt)->getType()) {
2954 VisitedInstrs.insert(*SameTypeIt);
2958 // Try to vectorize them.
2959 unsigned NumElts = (SameTypeIt - IncIt);
2960 DEBUG(errs() << "SLP: Trying to vectorize starting at PHIs (" << NumElts << ")\n");
2962 tryToVectorizeList(ArrayRef<Value *>(IncIt, NumElts), R)) {
2963 // Success start over because instructions might have been changed.
2964 HaveVectorizedPhiNodes = true;
2969 // Start over at the next instruction of a different type (or the end).
2974 VisitedInstrs.clear();
2976 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) {
2977 // We may go through BB multiple times so skip the one we have checked.
2978 if (!VisitedInstrs.insert(it))
2981 if (isa<DbgInfoIntrinsic>(it))
2984 // Try to vectorize reductions that use PHINodes.
2985 if (PHINode *P = dyn_cast<PHINode>(it)) {
2986 // Check that the PHI is a reduction PHI.
2987 if (P->getNumIncomingValues() != 2)
2990 (P->getIncomingBlock(0) == BB
2991 ? (P->getIncomingValue(0))
2992 : (P->getIncomingBlock(1) == BB ? P->getIncomingValue(1)
2994 // Check if this is a Binary Operator.
2995 BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx);
2999 // Try to match and vectorize a horizontal reduction.
3000 HorizontalReduction HorRdx;
3001 if (ShouldVectorizeHor &&
3002 HorRdx.matchAssociativeReduction(P, BI, DL) &&
3003 HorRdx.tryToReduce(R, TTI)) {
3010 Value *Inst = BI->getOperand(0);
3012 Inst = BI->getOperand(1);
3014 if (tryToVectorize(dyn_cast<BinaryOperator>(Inst), R)) {
3015 // We would like to start over since some instructions are deleted
3016 // and the iterator may become invalid value.
3026 // Try to vectorize horizontal reductions feeding into a store.
3027 if (ShouldStartVectorizeHorAtStore)
3028 if (StoreInst *SI = dyn_cast<StoreInst>(it))
3029 if (BinaryOperator *BinOp =
3030 dyn_cast<BinaryOperator>(SI->getValueOperand())) {
3031 HorizontalReduction HorRdx;
3032 if (((HorRdx.matchAssociativeReduction(nullptr, BinOp, DL) &&
3033 HorRdx.tryToReduce(R, TTI)) ||
3034 tryToVectorize(BinOp, R))) {
3042 // Try to vectorize trees that start at compare instructions.
3043 if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
3044 if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) {
3046 // We would like to start over since some instructions are deleted
3047 // and the iterator may become invalid value.
3053 for (int i = 0; i < 2; ++i) {
3054 if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i))) {
3055 if (tryToVectorizePair(BI->getOperand(0), BI->getOperand(1), R)) {
3057 // We would like to start over since some instructions are deleted
3058 // and the iterator may become invalid value.
3067 // Try to vectorize trees that start at insertelement instructions.
3068 if (InsertElementInst *FirstInsertElem = dyn_cast<InsertElementInst>(it)) {
3069 SmallVector<Value *, 16> BuildVector;
3070 SmallVector<Value *, 16> BuildVectorOpds;
3071 if (!findBuildVector(FirstInsertElem, BuildVector, BuildVectorOpds))
3074 // Vectorize starting with the build vector operands ignoring the
3075 // BuildVector instructions for the purpose of scheduling and user
3077 if (tryToVectorizeList(BuildVectorOpds, R, BuildVector)) {
3090 bool SLPVectorizer::vectorizeStoreChains(BoUpSLP &R) {
3091 bool Changed = false;
3092 // Attempt to sort and vectorize each of the store-groups.
3093 for (StoreListMap::iterator it = StoreRefs.begin(), e = StoreRefs.end();
3095 if (it->second.size() < 2)
3098 DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
3099 << it->second.size() << ".\n");
3101 // Process the stores in chunks of 16.
3102 for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI+=16) {
3103 unsigned Len = std::min<unsigned>(CE - CI, 16);
3104 ArrayRef<StoreInst *> Chunk(&it->second[CI], Len);
3105 Changed |= vectorizeStores(Chunk, -SLPCostThreshold, R);
3111 } // end anonymous namespace
3113 char SLPVectorizer::ID = 0;
3114 static const char lv_name[] = "SLP Vectorizer";
3115 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
3116 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3117 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
3118 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
3119 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
3120 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
3123 Pass *createSLPVectorizerPass() { return new SLPVectorizer(); }