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/ADT/Statistic.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/Analysis/LoopInfo.h"
25 #include "llvm/Analysis/ScalarEvolution.h"
26 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
27 #include "llvm/Analysis/TargetTransformInfo.h"
28 #include "llvm/Analysis/ValueTracking.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/Dominators.h"
31 #include "llvm/IR/IRBuilder.h"
32 #include "llvm/IR/Instructions.h"
33 #include "llvm/IR/IntrinsicInst.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/IR/NoFolder.h"
36 #include "llvm/IR/Type.h"
37 #include "llvm/IR/Value.h"
38 #include "llvm/IR/Verifier.h"
39 #include "llvm/Pass.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include "llvm/Transforms/Utils/VectorUtils.h"
50 #define SV_NAME "slp-vectorizer"
51 #define DEBUG_TYPE "SLP"
53 STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
56 SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
57 cl::desc("Only vectorize if you gain more than this "
61 ShouldVectorizeHor("slp-vectorize-hor", cl::init(false), cl::Hidden,
62 cl::desc("Attempt to vectorize horizontal reductions"));
64 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
65 "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
67 "Attempt to vectorize horizontal reductions feeding into a store"));
71 static const unsigned MinVecRegSize = 128;
73 static const unsigned RecursionMaxDepth = 12;
75 /// \returns the parent basic block if all of the instructions in \p VL
76 /// are in the same block or null otherwise.
77 static BasicBlock *getSameBlock(ArrayRef<Value *> VL) {
78 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
81 BasicBlock *BB = I0->getParent();
82 for (int i = 1, e = VL.size(); i < e; i++) {
83 Instruction *I = dyn_cast<Instruction>(VL[i]);
87 if (BB != I->getParent())
93 /// \returns True if all of the values in \p VL are constants.
94 static bool allConstant(ArrayRef<Value *> VL) {
95 for (unsigned i = 0, e = VL.size(); i < e; ++i)
96 if (!isa<Constant>(VL[i]))
101 /// \returns True if all of the values in \p VL are identical.
102 static bool isSplat(ArrayRef<Value *> VL) {
103 for (unsigned i = 1, e = VL.size(); i < e; ++i)
109 ///\returns Opcode that can be clubbed with \p Op to create an alternate
110 /// sequence which can later be merged as a ShuffleVector instruction.
111 static unsigned getAltOpcode(unsigned Op) {
113 case Instruction::FAdd:
114 return Instruction::FSub;
115 case Instruction::FSub:
116 return Instruction::FAdd;
117 case Instruction::Add:
118 return Instruction::Sub;
119 case Instruction::Sub:
120 return Instruction::Add;
126 ///\returns bool representing if Opcode \p Op can be part
127 /// of an alternate sequence which can later be merged as
128 /// a ShuffleVector instruction.
129 static bool canCombineAsAltInst(unsigned Op) {
130 if (Op == Instruction::FAdd || Op == Instruction::FSub ||
131 Op == Instruction::Sub || Op == Instruction::Add)
136 /// \returns ShuffleVector instruction if intructions in \p VL have
137 /// alternate fadd,fsub / fsub,fadd/add,sub/sub,add sequence.
138 /// (i.e. e.g. opcodes of fadd,fsub,fadd,fsub...)
139 static unsigned isAltInst(ArrayRef<Value *> VL) {
140 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
141 unsigned Opcode = I0->getOpcode();
142 unsigned AltOpcode = getAltOpcode(Opcode);
143 for (int i = 1, e = VL.size(); i < e; i++) {
144 Instruction *I = dyn_cast<Instruction>(VL[i]);
145 if (!I || I->getOpcode() != ((i & 1) ? AltOpcode : Opcode))
148 return Instruction::ShuffleVector;
151 /// \returns The opcode if all of the Instructions in \p VL have the same
153 static unsigned getSameOpcode(ArrayRef<Value *> VL) {
154 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
157 unsigned Opcode = I0->getOpcode();
158 for (int i = 1, e = VL.size(); i < e; i++) {
159 Instruction *I = dyn_cast<Instruction>(VL[i]);
160 if (!I || Opcode != I->getOpcode()) {
161 if (canCombineAsAltInst(Opcode) && i == 1)
162 return isAltInst(VL);
169 /// \returns \p I after propagating metadata from \p VL.
170 static Instruction *propagateMetadata(Instruction *I, ArrayRef<Value *> VL) {
171 Instruction *I0 = cast<Instruction>(VL[0]);
172 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
173 I0->getAllMetadataOtherThanDebugLoc(Metadata);
175 for (unsigned i = 0, n = Metadata.size(); i != n; ++i) {
176 unsigned Kind = Metadata[i].first;
177 MDNode *MD = Metadata[i].second;
179 for (int i = 1, e = VL.size(); MD && i != e; i++) {
180 Instruction *I = cast<Instruction>(VL[i]);
181 MDNode *IMD = I->getMetadata(Kind);
185 MD = nullptr; // Remove unknown metadata
187 case LLVMContext::MD_tbaa:
188 MD = MDNode::getMostGenericTBAA(MD, IMD);
190 case LLVMContext::MD_alias_scope:
191 case LLVMContext::MD_noalias:
192 MD = MDNode::intersect(MD, IMD);
194 case LLVMContext::MD_fpmath:
195 MD = MDNode::getMostGenericFPMath(MD, IMD);
199 I->setMetadata(Kind, MD);
204 /// \returns The type that all of the values in \p VL have or null if there
205 /// are different types.
206 static Type* getSameType(ArrayRef<Value *> VL) {
207 Type *Ty = VL[0]->getType();
208 for (int i = 1, e = VL.size(); i < e; i++)
209 if (VL[i]->getType() != Ty)
215 /// \returns True if the ExtractElement instructions in VL can be vectorized
216 /// to use the original vector.
217 static bool CanReuseExtract(ArrayRef<Value *> VL) {
218 assert(Instruction::ExtractElement == getSameOpcode(VL) && "Invalid opcode");
219 // Check if all of the extracts come from the same vector and from the
222 ExtractElementInst *E0 = cast<ExtractElementInst>(VL0);
223 Value *Vec = E0->getOperand(0);
225 // We have to extract from the same vector type.
226 unsigned NElts = Vec->getType()->getVectorNumElements();
228 if (NElts != VL.size())
231 // Check that all of the indices extract from the correct offset.
232 ConstantInt *CI = dyn_cast<ConstantInt>(E0->getOperand(1));
233 if (!CI || CI->getZExtValue())
236 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
237 ExtractElementInst *E = cast<ExtractElementInst>(VL[i]);
238 ConstantInt *CI = dyn_cast<ConstantInt>(E->getOperand(1));
240 if (!CI || CI->getZExtValue() != i || E->getOperand(0) != Vec)
247 static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
248 SmallVectorImpl<Value *> &Left,
249 SmallVectorImpl<Value *> &Right) {
251 SmallVector<Value *, 16> OrigLeft, OrigRight;
253 bool AllSameOpcodeLeft = true;
254 bool AllSameOpcodeRight = true;
255 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
256 Instruction *I = cast<Instruction>(VL[i]);
257 Value *V0 = I->getOperand(0);
258 Value *V1 = I->getOperand(1);
260 OrigLeft.push_back(V0);
261 OrigRight.push_back(V1);
263 Instruction *I0 = dyn_cast<Instruction>(V0);
264 Instruction *I1 = dyn_cast<Instruction>(V1);
266 // Check whether all operands on one side have the same opcode. In this case
267 // we want to preserve the original order and not make things worse by
269 AllSameOpcodeLeft = I0;
270 AllSameOpcodeRight = I1;
272 if (i && AllSameOpcodeLeft) {
273 if(Instruction *P0 = dyn_cast<Instruction>(OrigLeft[i-1])) {
274 if(P0->getOpcode() != I0->getOpcode())
275 AllSameOpcodeLeft = false;
277 AllSameOpcodeLeft = false;
279 if (i && AllSameOpcodeRight) {
280 if(Instruction *P1 = dyn_cast<Instruction>(OrigRight[i-1])) {
281 if(P1->getOpcode() != I1->getOpcode())
282 AllSameOpcodeRight = false;
284 AllSameOpcodeRight = false;
287 // Sort two opcodes. In the code below we try to preserve the ability to use
288 // broadcast of values instead of individual inserts.
295 // If we just sorted according to opcode we would leave the first line in
296 // tact but we would swap vl2 with vr2 because opcode(phi) > opcode(load).
299 // Because vr2 and vr1 are from the same load we loose the opportunity of a
300 // broadcast for the packed right side in the backend: we have [vr1, vl2]
301 // instead of [vr1, vr2=vr1].
303 if(!i && I0->getOpcode() > I1->getOpcode()) {
306 } else if (i && I0->getOpcode() > I1->getOpcode() && Right[i-1] != I1) {
307 // Try not to destroy a broad cast for no apparent benefit.
310 } else if (i && I0->getOpcode() == I1->getOpcode() && Right[i-1] == I0) {
311 // Try preserve broadcasts.
314 } else if (i && I0->getOpcode() == I1->getOpcode() && Left[i-1] == I1) {
315 // Try preserve broadcasts.
324 // One opcode, put the instruction on the right.
334 bool LeftBroadcast = isSplat(Left);
335 bool RightBroadcast = isSplat(Right);
337 // Don't reorder if the operands where good to begin with.
338 if (!(LeftBroadcast || RightBroadcast) &&
339 (AllSameOpcodeRight || AllSameOpcodeLeft)) {
345 /// Bottom Up SLP Vectorizer.
348 typedef SmallVector<Value *, 8> ValueList;
349 typedef SmallVector<Instruction *, 16> InstrList;
350 typedef SmallPtrSet<Value *, 16> ValueSet;
351 typedef SmallVector<StoreInst *, 8> StoreList;
353 BoUpSLP(Function *Func, ScalarEvolution *Se, const DataLayout *Dl,
354 TargetTransformInfo *Tti, TargetLibraryInfo *TLi, AliasAnalysis *Aa,
355 LoopInfo *Li, DominatorTree *Dt)
356 : NumLoadsWantToKeepOrder(0), NumLoadsWantToChangeOrder(0),
357 F(Func), SE(Se), DL(Dl), TTI(Tti), TLI(TLi), AA(Aa), LI(Li), DT(Dt),
358 Builder(Se->getContext()) {}
360 /// \brief Vectorize the tree that starts with the elements in \p VL.
361 /// Returns the vectorized root.
362 Value *vectorizeTree();
364 /// \returns the cost incurred by unwanted spills and fills, caused by
365 /// holding live values over call sites.
368 /// \returns the vectorization cost of the subtree that starts at \p VL.
369 /// A negative number means that this is profitable.
372 /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
373 /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
374 void buildTree(ArrayRef<Value *> Roots,
375 ArrayRef<Value *> UserIgnoreLst = None);
377 /// Clear the internal data structures that are created by 'buildTree'.
379 VectorizableTree.clear();
380 ScalarToTreeEntry.clear();
382 ExternalUses.clear();
383 NumLoadsWantToKeepOrder = 0;
384 NumLoadsWantToChangeOrder = 0;
385 for (auto &Iter : BlocksSchedules) {
386 BlockScheduling *BS = Iter.second.get();
391 /// \returns true if the memory operations A and B are consecutive.
392 bool isConsecutiveAccess(Value *A, Value *B);
394 /// \brief Perform LICM and CSE on the newly generated gather sequences.
395 void optimizeGatherSequence();
397 /// \returns true if it is benefitial to reverse the vector order.
398 bool shouldReorder() const {
399 return NumLoadsWantToChangeOrder > NumLoadsWantToKeepOrder;
405 /// \returns the cost of the vectorizable entry.
406 int getEntryCost(TreeEntry *E);
408 /// This is the recursive part of buildTree.
409 void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth);
411 /// Vectorize a single entry in the tree.
412 Value *vectorizeTree(TreeEntry *E);
414 /// Vectorize a single entry in the tree, starting in \p VL.
415 Value *vectorizeTree(ArrayRef<Value *> VL);
417 /// \returns the pointer to the vectorized value if \p VL is already
418 /// vectorized, or NULL. They may happen in cycles.
419 Value *alreadyVectorized(ArrayRef<Value *> VL) const;
421 /// \brief Take the pointer operand from the Load/Store instruction.
422 /// \returns NULL if this is not a valid Load/Store instruction.
423 static Value *getPointerOperand(Value *I);
425 /// \brief Take the address space operand from the Load/Store instruction.
426 /// \returns -1 if this is not a valid Load/Store instruction.
427 static unsigned getAddressSpaceOperand(Value *I);
429 /// \returns the scalarization cost for this type. Scalarization in this
430 /// context means the creation of vectors from a group of scalars.
431 int getGatherCost(Type *Ty);
433 /// \returns the scalarization cost for this list of values. Assuming that
434 /// this subtree gets vectorized, we may need to extract the values from the
435 /// roots. This method calculates the cost of extracting the values.
436 int getGatherCost(ArrayRef<Value *> VL);
438 /// \brief Set the Builder insert point to one after the last instruction in
440 void setInsertPointAfterBundle(ArrayRef<Value *> VL);
442 /// \returns a vector from a collection of scalars in \p VL.
443 Value *Gather(ArrayRef<Value *> VL, VectorType *Ty);
445 /// \returns whether the VectorizableTree is fully vectoriable and will
446 /// be beneficial even the tree height is tiny.
447 bool isFullyVectorizableTinyTree();
450 TreeEntry() : Scalars(), VectorizedValue(nullptr),
453 /// \returns true if the scalars in VL are equal to this entry.
454 bool isSame(ArrayRef<Value *> VL) const {
455 assert(VL.size() == Scalars.size() && "Invalid size");
456 return std::equal(VL.begin(), VL.end(), Scalars.begin());
459 /// A vector of scalars.
462 /// The Scalars are vectorized into this value. It is initialized to Null.
463 Value *VectorizedValue;
465 /// Do we need to gather this sequence ?
469 /// Create a new VectorizableTree entry.
470 TreeEntry *newTreeEntry(ArrayRef<Value *> VL, bool Vectorized) {
471 VectorizableTree.push_back(TreeEntry());
472 int idx = VectorizableTree.size() - 1;
473 TreeEntry *Last = &VectorizableTree[idx];
474 Last->Scalars.insert(Last->Scalars.begin(), VL.begin(), VL.end());
475 Last->NeedToGather = !Vectorized;
477 for (int i = 0, e = VL.size(); i != e; ++i) {
478 assert(!ScalarToTreeEntry.count(VL[i]) && "Scalar already in tree!");
479 ScalarToTreeEntry[VL[i]] = idx;
482 MustGather.insert(VL.begin(), VL.end());
487 /// -- Vectorization State --
488 /// Holds all of the tree entries.
489 std::vector<TreeEntry> VectorizableTree;
491 /// Maps a specific scalar to its tree entry.
492 SmallDenseMap<Value*, int> ScalarToTreeEntry;
494 /// A list of scalars that we found that we need to keep as scalars.
497 /// This POD struct describes one external user in the vectorized tree.
498 struct ExternalUser {
499 ExternalUser (Value *S, llvm::User *U, int L) :
500 Scalar(S), User(U), Lane(L){};
501 // Which scalar in our function.
503 // Which user that uses the scalar.
505 // Which lane does the scalar belong to.
508 typedef SmallVector<ExternalUser, 16> UserList;
510 /// A list of values that need to extracted out of the tree.
511 /// This list holds pairs of (Internal Scalar : External User).
512 UserList ExternalUses;
514 /// Holds all of the instructions that we gathered.
515 SetVector<Instruction *> GatherSeq;
516 /// A list of blocks that we are going to CSE.
517 SetVector<BasicBlock *> CSEBlocks;
519 /// Contains all scheduling relevant data for an instruction.
520 /// A ScheduleData either represents a single instruction or a member of an
521 /// instruction bundle (= a group of instructions which is combined into a
522 /// vector instruction).
523 struct ScheduleData {
525 // The initial value for the dependency counters. It means that the
526 // dependencies are not calculated yet.
527 enum { InvalidDeps = -1 };
530 : Inst(nullptr), FirstInBundle(nullptr), NextInBundle(nullptr),
531 NextLoadStore(nullptr), SchedulingRegionID(0), SchedulingPriority(0),
532 Dependencies(InvalidDeps), UnscheduledDeps(InvalidDeps),
533 UnscheduledDepsInBundle(InvalidDeps), IsScheduled(false) {}
535 void init(int BlockSchedulingRegionID) {
536 FirstInBundle = this;
537 NextInBundle = nullptr;
538 NextLoadStore = nullptr;
540 SchedulingRegionID = BlockSchedulingRegionID;
541 UnscheduledDepsInBundle = UnscheduledDeps;
545 /// Returns true if the dependency information has been calculated.
546 bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
548 /// Returns true for single instructions and for bundle representatives
549 /// (= the head of a bundle).
550 bool isSchedulingEntity() const { return FirstInBundle == this; }
552 /// Returns true if it represents an instruction bundle and not only a
553 /// single instruction.
554 bool isPartOfBundle() const {
555 return NextInBundle != nullptr || FirstInBundle != this;
558 /// Returns true if it is ready for scheduling, i.e. it has no more
559 /// unscheduled depending instructions/bundles.
560 bool isReady() const {
561 assert(isSchedulingEntity() &&
562 "can't consider non-scheduling entity for ready list");
563 return UnscheduledDepsInBundle == 0 && !IsScheduled;
566 /// Modifies the number of unscheduled dependencies, also updating it for
567 /// the whole bundle.
568 int incrementUnscheduledDeps(int Incr) {
569 UnscheduledDeps += Incr;
570 return FirstInBundle->UnscheduledDepsInBundle += Incr;
573 /// Sets the number of unscheduled dependencies to the number of
575 void resetUnscheduledDeps() {
576 incrementUnscheduledDeps(Dependencies - UnscheduledDeps);
579 /// Clears all dependency information.
580 void clearDependencies() {
581 Dependencies = InvalidDeps;
582 resetUnscheduledDeps();
583 MemoryDependencies.clear();
586 void dump(raw_ostream &os) const {
587 if (!isSchedulingEntity()) {
589 } else if (NextInBundle) {
591 ScheduleData *SD = NextInBundle;
593 os << ';' << *SD->Inst;
594 SD = SD->NextInBundle;
604 /// Points to the head in an instruction bundle (and always to this for
605 /// single instructions).
606 ScheduleData *FirstInBundle;
608 /// Single linked list of all instructions in a bundle. Null if it is a
609 /// single instruction.
610 ScheduleData *NextInBundle;
612 /// Single linked list of all memory instructions (e.g. load, store, call)
613 /// in the block - until the end of the scheduling region.
614 ScheduleData *NextLoadStore;
616 /// The dependent memory instructions.
617 /// This list is derived on demand in calculateDependencies().
618 SmallVector<ScheduleData *, 4> MemoryDependencies;
620 /// This ScheduleData is in the current scheduling region if this matches
621 /// the current SchedulingRegionID of BlockScheduling.
622 int SchedulingRegionID;
624 /// Used for getting a "good" final ordering of instructions.
625 int SchedulingPriority;
627 /// The number of dependencies. Constitutes of the number of users of the
628 /// instruction plus the number of dependent memory instructions (if any).
629 /// This value is calculated on demand.
630 /// If InvalidDeps, the number of dependencies is not calculated yet.
634 /// The number of dependencies minus the number of dependencies of scheduled
635 /// instructions. As soon as this is zero, the instruction/bundle gets ready
637 /// Note that this is negative as long as Dependencies is not calculated.
640 /// The sum of UnscheduledDeps in a bundle. Equals to UnscheduledDeps for
641 /// single instructions.
642 int UnscheduledDepsInBundle;
644 /// True if this instruction is scheduled (or considered as scheduled in the
650 friend raw_ostream &operator<<(raw_ostream &os,
651 const BoUpSLP::ScheduleData &SD);
654 /// Contains all scheduling data for a basic block.
656 struct BlockScheduling {
658 BlockScheduling(BasicBlock *BB)
659 : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize),
660 ScheduleStart(nullptr), ScheduleEnd(nullptr),
661 FirstLoadStoreInRegion(nullptr), LastLoadStoreInRegion(nullptr),
662 // Make sure that the initial SchedulingRegionID is greater than the
663 // initial SchedulingRegionID in ScheduleData (which is 0).
664 SchedulingRegionID(1) {}
668 ScheduleStart = nullptr;
669 ScheduleEnd = nullptr;
670 FirstLoadStoreInRegion = nullptr;
671 LastLoadStoreInRegion = nullptr;
673 // Make a new scheduling region, i.e. all existing ScheduleData is not
674 // in the new region yet.
675 ++SchedulingRegionID;
678 ScheduleData *getScheduleData(Value *V) {
679 ScheduleData *SD = ScheduleDataMap[V];
680 if (SD && SD->SchedulingRegionID == SchedulingRegionID)
685 bool isInSchedulingRegion(ScheduleData *SD) {
686 return SD->SchedulingRegionID == SchedulingRegionID;
689 /// Marks an instruction as scheduled and puts all dependent ready
690 /// instructions into the ready-list.
691 template <typename ReadyListType>
692 void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
693 SD->IsScheduled = true;
694 DEBUG(dbgs() << "SLP: schedule " << *SD << "\n");
696 ScheduleData *BundleMember = SD;
697 while (BundleMember) {
698 // Handle the def-use chain dependencies.
699 for (Use &U : BundleMember->Inst->operands()) {
700 ScheduleData *OpDef = getScheduleData(U.get());
701 if (OpDef && OpDef->hasValidDependencies() &&
702 OpDef->incrementUnscheduledDeps(-1) == 0) {
703 // There are no more unscheduled dependencies after decrementing,
704 // so we can put the dependent instruction into the ready list.
705 ScheduleData *DepBundle = OpDef->FirstInBundle;
706 assert(!DepBundle->IsScheduled &&
707 "already scheduled bundle gets ready");
708 ReadyList.insert(DepBundle);
709 DEBUG(dbgs() << "SLP: gets ready (def): " << *DepBundle << "\n");
712 // Handle the memory dependencies.
713 for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
714 if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
715 // There are no more unscheduled dependencies after decrementing,
716 // so we can put the dependent instruction into the ready list.
717 ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
718 assert(!DepBundle->IsScheduled &&
719 "already scheduled bundle gets ready");
720 ReadyList.insert(DepBundle);
721 DEBUG(dbgs() << "SLP: gets ready (mem): " << *DepBundle << "\n");
724 BundleMember = BundleMember->NextInBundle;
728 /// Put all instructions into the ReadyList which are ready for scheduling.
729 template <typename ReadyListType>
730 void initialFillReadyList(ReadyListType &ReadyList) {
731 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
732 ScheduleData *SD = getScheduleData(I);
733 if (SD->isSchedulingEntity() && SD->isReady()) {
734 ReadyList.insert(SD);
735 DEBUG(dbgs() << "SLP: initially in ready list: " << *I << "\n");
740 /// Checks if a bundle of instructions can be scheduled, i.e. has no
741 /// cyclic dependencies. This is only a dry-run, no instructions are
742 /// actually moved at this stage.
743 bool tryScheduleBundle(ArrayRef<Value *> VL, AliasAnalysis *AA);
745 /// Un-bundles a group of instructions.
746 void cancelScheduling(ArrayRef<Value *> VL);
748 /// Extends the scheduling region so that V is inside the region.
749 void extendSchedulingRegion(Value *V);
751 /// Initialize the ScheduleData structures for new instructions in the
752 /// scheduling region.
753 void initScheduleData(Instruction *FromI, Instruction *ToI,
754 ScheduleData *PrevLoadStore,
755 ScheduleData *NextLoadStore);
757 /// Updates the dependency information of a bundle and of all instructions/
758 /// bundles which depend on the original bundle.
759 void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
762 /// Sets all instruction in the scheduling region to un-scheduled.
763 void resetSchedule();
767 /// Simple memory allocation for ScheduleData.
768 std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
770 /// The size of a ScheduleData array in ScheduleDataChunks.
773 /// The allocator position in the current chunk, which is the last entry
774 /// of ScheduleDataChunks.
777 /// Attaches ScheduleData to Instruction.
778 /// Note that the mapping survives during all vectorization iterations, i.e.
779 /// ScheduleData structures are recycled.
780 DenseMap<Value *, ScheduleData *> ScheduleDataMap;
782 struct ReadyList : SmallVector<ScheduleData *, 8> {
783 void insert(ScheduleData *SD) { push_back(SD); }
786 /// The ready-list for scheduling (only used for the dry-run).
787 ReadyList ReadyInsts;
789 /// The first instruction of the scheduling region.
790 Instruction *ScheduleStart;
792 /// The first instruction _after_ the scheduling region.
793 Instruction *ScheduleEnd;
795 /// The first memory accessing instruction in the scheduling region
797 ScheduleData *FirstLoadStoreInRegion;
799 /// The last memory accessing instruction in the scheduling region
801 ScheduleData *LastLoadStoreInRegion;
803 /// The ID of the scheduling region. For a new vectorization iteration this
804 /// is incremented which "removes" all ScheduleData from the region.
805 int SchedulingRegionID;
808 /// Attaches the BlockScheduling structures to basic blocks.
809 DenseMap<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
811 /// Performs the "real" scheduling. Done before vectorization is actually
812 /// performed in a basic block.
813 void scheduleBlock(BlockScheduling *BS);
815 /// List of users to ignore during scheduling and that don't need extracting.
816 ArrayRef<Value *> UserIgnoreList;
818 // Number of load-bundles, which contain consecutive loads.
819 int NumLoadsWantToKeepOrder;
821 // Number of load-bundles of size 2, which are consecutive loads if reversed.
822 int NumLoadsWantToChangeOrder;
824 // Analysis and block reference.
827 const DataLayout *DL;
828 TargetTransformInfo *TTI;
829 TargetLibraryInfo *TLI;
833 /// Instruction builder to construct the vectorized tree.
838 raw_ostream &operator<<(raw_ostream &os, const BoUpSLP::ScheduleData &SD) {
844 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
845 ArrayRef<Value *> UserIgnoreLst) {
847 UserIgnoreList = UserIgnoreLst;
848 if (!getSameType(Roots))
850 buildTree_rec(Roots, 0);
852 // Collect the values that we need to extract from the tree.
853 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
854 TreeEntry *Entry = &VectorizableTree[EIdx];
857 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
858 Value *Scalar = Entry->Scalars[Lane];
860 // No need to handle users of gathered values.
861 if (Entry->NeedToGather)
864 for (User *U : Scalar->users()) {
865 DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
867 // Skip in-tree scalars that become vectors.
868 if (ScalarToTreeEntry.count(U)) {
869 DEBUG(dbgs() << "SLP: \tInternal user will be removed:" <<
871 int Idx = ScalarToTreeEntry[U]; (void) Idx;
872 assert(!VectorizableTree[Idx].NeedToGather && "Bad state");
875 Instruction *UserInst = dyn_cast<Instruction>(U);
879 // Ignore users in the user ignore list.
880 if (std::find(UserIgnoreList.begin(), UserIgnoreList.end(), UserInst) !=
881 UserIgnoreList.end())
884 DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane " <<
885 Lane << " from " << *Scalar << ".\n");
886 ExternalUses.push_back(ExternalUser(Scalar, U, Lane));
893 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth) {
894 bool SameTy = getSameType(VL); (void)SameTy;
895 bool isAltShuffle = false;
896 assert(SameTy && "Invalid types!");
898 if (Depth == RecursionMaxDepth) {
899 DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
900 newTreeEntry(VL, false);
904 // Don't handle vectors.
905 if (VL[0]->getType()->isVectorTy()) {
906 DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
907 newTreeEntry(VL, false);
911 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
912 if (SI->getValueOperand()->getType()->isVectorTy()) {
913 DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
914 newTreeEntry(VL, false);
917 unsigned Opcode = getSameOpcode(VL);
919 // Check that this shuffle vector refers to the alternate
920 // sequence of opcodes.
921 if (Opcode == Instruction::ShuffleVector) {
922 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
923 unsigned Op = I0->getOpcode();
924 if (Op != Instruction::ShuffleVector)
928 // If all of the operands are identical or constant we have a simple solution.
929 if (allConstant(VL) || isSplat(VL) || !getSameBlock(VL) || !Opcode) {
930 DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
931 newTreeEntry(VL, false);
935 // We now know that this is a vector of instructions of the same type from
938 // Check if this is a duplicate of another entry.
939 if (ScalarToTreeEntry.count(VL[0])) {
940 int Idx = ScalarToTreeEntry[VL[0]];
941 TreeEntry *E = &VectorizableTree[Idx];
942 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
943 DEBUG(dbgs() << "SLP: \tChecking bundle: " << *VL[i] << ".\n");
944 if (E->Scalars[i] != VL[i]) {
945 DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
946 newTreeEntry(VL, false);
950 DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *VL[0] << ".\n");
954 // Check that none of the instructions in the bundle are already in the tree.
955 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
956 if (ScalarToTreeEntry.count(VL[i])) {
957 DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
958 ") is already in tree.\n");
959 newTreeEntry(VL, false);
964 // If any of the scalars appears in the table OR it is marked as a value that
965 // needs to stat scalar then we need to gather the scalars.
966 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
967 if (ScalarToTreeEntry.count(VL[i]) || MustGather.count(VL[i])) {
968 DEBUG(dbgs() << "SLP: Gathering due to gathered scalar. \n");
969 newTreeEntry(VL, false);
974 // Check that all of the users of the scalars that we want to vectorize are
976 Instruction *VL0 = cast<Instruction>(VL[0]);
977 BasicBlock *BB = cast<Instruction>(VL0)->getParent();
979 if (!DT->isReachableFromEntry(BB)) {
980 // Don't go into unreachable blocks. They may contain instructions with
981 // dependency cycles which confuse the final scheduling.
982 DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
983 newTreeEntry(VL, false);
987 // Check that every instructions appears once in this bundle.
988 for (unsigned i = 0, e = VL.size(); i < e; ++i)
989 for (unsigned j = i+1; j < e; ++j)
990 if (VL[i] == VL[j]) {
991 DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
992 newTreeEntry(VL, false);
996 auto &BSRef = BlocksSchedules[BB];
998 BSRef = llvm::make_unique<BlockScheduling>(BB);
1000 BlockScheduling &BS = *BSRef.get();
1002 if (!BS.tryScheduleBundle(VL, AA)) {
1003 DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
1004 BS.cancelScheduling(VL);
1005 newTreeEntry(VL, false);
1008 DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
1011 case Instruction::PHI: {
1012 PHINode *PH = dyn_cast<PHINode>(VL0);
1014 // Check for terminator values (e.g. invoke).
1015 for (unsigned j = 0; j < VL.size(); ++j)
1016 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1017 TerminatorInst *Term = dyn_cast<TerminatorInst>(
1018 cast<PHINode>(VL[j])->getIncomingValueForBlock(PH->getIncomingBlock(i)));
1020 DEBUG(dbgs() << "SLP: Need to swizzle PHINodes (TerminatorInst use).\n");
1021 BS.cancelScheduling(VL);
1022 newTreeEntry(VL, false);
1027 newTreeEntry(VL, true);
1028 DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
1030 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1032 // Prepare the operand vector.
1033 for (unsigned j = 0; j < VL.size(); ++j)
1034 Operands.push_back(cast<PHINode>(VL[j])->getIncomingValueForBlock(
1035 PH->getIncomingBlock(i)));
1037 buildTree_rec(Operands, Depth + 1);
1041 case Instruction::ExtractElement: {
1042 bool Reuse = CanReuseExtract(VL);
1044 DEBUG(dbgs() << "SLP: Reusing extract sequence.\n");
1046 BS.cancelScheduling(VL);
1048 newTreeEntry(VL, Reuse);
1051 case Instruction::Load: {
1052 // Check if the loads are consecutive or of we need to swizzle them.
1053 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i) {
1054 LoadInst *L = cast<LoadInst>(VL[i]);
1055 if (!L->isSimple()) {
1056 BS.cancelScheduling(VL);
1057 newTreeEntry(VL, false);
1058 DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
1061 if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
1062 if (VL.size() == 2 && isConsecutiveAccess(VL[1], VL[0])) {
1063 ++NumLoadsWantToChangeOrder;
1065 BS.cancelScheduling(VL);
1066 newTreeEntry(VL, false);
1067 DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
1071 ++NumLoadsWantToKeepOrder;
1072 newTreeEntry(VL, true);
1073 DEBUG(dbgs() << "SLP: added a vector of loads.\n");
1076 case Instruction::ZExt:
1077 case Instruction::SExt:
1078 case Instruction::FPToUI:
1079 case Instruction::FPToSI:
1080 case Instruction::FPExt:
1081 case Instruction::PtrToInt:
1082 case Instruction::IntToPtr:
1083 case Instruction::SIToFP:
1084 case Instruction::UIToFP:
1085 case Instruction::Trunc:
1086 case Instruction::FPTrunc:
1087 case Instruction::BitCast: {
1088 Type *SrcTy = VL0->getOperand(0)->getType();
1089 for (unsigned i = 0; i < VL.size(); ++i) {
1090 Type *Ty = cast<Instruction>(VL[i])->getOperand(0)->getType();
1091 if (Ty != SrcTy || Ty->isAggregateType() || Ty->isVectorTy()) {
1092 BS.cancelScheduling(VL);
1093 newTreeEntry(VL, false);
1094 DEBUG(dbgs() << "SLP: Gathering casts with different src types.\n");
1098 newTreeEntry(VL, true);
1099 DEBUG(dbgs() << "SLP: added a vector of casts.\n");
1101 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1103 // Prepare the operand vector.
1104 for (unsigned j = 0; j < VL.size(); ++j)
1105 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1107 buildTree_rec(Operands, Depth+1);
1111 case Instruction::ICmp:
1112 case Instruction::FCmp: {
1113 // Check that all of the compares have the same predicate.
1114 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
1115 Type *ComparedTy = cast<Instruction>(VL[0])->getOperand(0)->getType();
1116 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
1117 CmpInst *Cmp = cast<CmpInst>(VL[i]);
1118 if (Cmp->getPredicate() != P0 ||
1119 Cmp->getOperand(0)->getType() != ComparedTy) {
1120 BS.cancelScheduling(VL);
1121 newTreeEntry(VL, false);
1122 DEBUG(dbgs() << "SLP: Gathering cmp with different predicate.\n");
1127 newTreeEntry(VL, true);
1128 DEBUG(dbgs() << "SLP: added a vector of compares.\n");
1130 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1132 // Prepare the operand vector.
1133 for (unsigned j = 0; j < VL.size(); ++j)
1134 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1136 buildTree_rec(Operands, Depth+1);
1140 case Instruction::Select:
1141 case Instruction::Add:
1142 case Instruction::FAdd:
1143 case Instruction::Sub:
1144 case Instruction::FSub:
1145 case Instruction::Mul:
1146 case Instruction::FMul:
1147 case Instruction::UDiv:
1148 case Instruction::SDiv:
1149 case Instruction::FDiv:
1150 case Instruction::URem:
1151 case Instruction::SRem:
1152 case Instruction::FRem:
1153 case Instruction::Shl:
1154 case Instruction::LShr:
1155 case Instruction::AShr:
1156 case Instruction::And:
1157 case Instruction::Or:
1158 case Instruction::Xor: {
1159 newTreeEntry(VL, true);
1160 DEBUG(dbgs() << "SLP: added a vector of bin op.\n");
1162 // Sort operands of the instructions so that each side is more likely to
1163 // have the same opcode.
1164 if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
1165 ValueList Left, Right;
1166 reorderInputsAccordingToOpcode(VL, Left, Right);
1167 buildTree_rec(Left, Depth + 1);
1168 buildTree_rec(Right, Depth + 1);
1172 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1174 // Prepare the operand vector.
1175 for (unsigned j = 0; j < VL.size(); ++j)
1176 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1178 buildTree_rec(Operands, Depth+1);
1182 case Instruction::Store: {
1183 // Check if the stores are consecutive or of we need to swizzle them.
1184 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
1185 if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
1186 BS.cancelScheduling(VL);
1187 newTreeEntry(VL, false);
1188 DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
1192 newTreeEntry(VL, true);
1193 DEBUG(dbgs() << "SLP: added a vector of stores.\n");
1196 for (unsigned j = 0; j < VL.size(); ++j)
1197 Operands.push_back(cast<Instruction>(VL[j])->getOperand(0));
1199 buildTree_rec(Operands, Depth + 1);
1202 case Instruction::Call: {
1203 // Check if the calls are all to the same vectorizable intrinsic.
1204 CallInst *CI = cast<CallInst>(VL[0]);
1205 // Check if this is an Intrinsic call or something that can be
1206 // represented by an intrinsic call
1207 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
1208 if (!isTriviallyVectorizable(ID)) {
1209 BS.cancelScheduling(VL);
1210 newTreeEntry(VL, false);
1211 DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
1214 Function *Int = CI->getCalledFunction();
1215 Value *A1I = nullptr;
1216 if (hasVectorInstrinsicScalarOpd(ID, 1))
1217 A1I = CI->getArgOperand(1);
1218 for (unsigned i = 1, e = VL.size(); i != e; ++i) {
1219 CallInst *CI2 = dyn_cast<CallInst>(VL[i]);
1220 if (!CI2 || CI2->getCalledFunction() != Int ||
1221 getIntrinsicIDForCall(CI2, TLI) != ID) {
1222 BS.cancelScheduling(VL);
1223 newTreeEntry(VL, false);
1224 DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *VL[i]
1228 // ctlz,cttz and powi are special intrinsics whose second argument
1229 // should be same in order for them to be vectorized.
1230 if (hasVectorInstrinsicScalarOpd(ID, 1)) {
1231 Value *A1J = CI2->getArgOperand(1);
1233 BS.cancelScheduling(VL);
1234 newTreeEntry(VL, false);
1235 DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
1236 << " argument "<< A1I<<"!=" << A1J
1243 newTreeEntry(VL, true);
1244 for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i) {
1246 // Prepare the operand vector.
1247 for (unsigned j = 0; j < VL.size(); ++j) {
1248 CallInst *CI2 = dyn_cast<CallInst>(VL[j]);
1249 Operands.push_back(CI2->getArgOperand(i));
1251 buildTree_rec(Operands, Depth + 1);
1255 case Instruction::ShuffleVector: {
1256 // If this is not an alternate sequence of opcode like add-sub
1257 // then do not vectorize this instruction.
1258 if (!isAltShuffle) {
1259 BS.cancelScheduling(VL);
1260 newTreeEntry(VL, false);
1261 DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
1264 newTreeEntry(VL, true);
1265 DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
1266 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1268 // Prepare the operand vector.
1269 for (unsigned j = 0; j < VL.size(); ++j)
1270 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1272 buildTree_rec(Operands, Depth + 1);
1277 BS.cancelScheduling(VL);
1278 newTreeEntry(VL, false);
1279 DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
1284 int BoUpSLP::getEntryCost(TreeEntry *E) {
1285 ArrayRef<Value*> VL = E->Scalars;
1287 Type *ScalarTy = VL[0]->getType();
1288 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1289 ScalarTy = SI->getValueOperand()->getType();
1290 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1292 if (E->NeedToGather) {
1293 if (allConstant(VL))
1296 return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
1298 return getGatherCost(E->Scalars);
1300 unsigned Opcode = getSameOpcode(VL);
1301 assert(Opcode && getSameType(VL) && getSameBlock(VL) && "Invalid VL");
1302 Instruction *VL0 = cast<Instruction>(VL[0]);
1304 case Instruction::PHI: {
1307 case Instruction::ExtractElement: {
1308 if (CanReuseExtract(VL)) {
1310 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
1311 ExtractElementInst *E = cast<ExtractElementInst>(VL[i]);
1313 // Take credit for instruction that will become dead.
1315 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, i);
1319 return getGatherCost(VecTy);
1321 case Instruction::ZExt:
1322 case Instruction::SExt:
1323 case Instruction::FPToUI:
1324 case Instruction::FPToSI:
1325 case Instruction::FPExt:
1326 case Instruction::PtrToInt:
1327 case Instruction::IntToPtr:
1328 case Instruction::SIToFP:
1329 case Instruction::UIToFP:
1330 case Instruction::Trunc:
1331 case Instruction::FPTrunc:
1332 case Instruction::BitCast: {
1333 Type *SrcTy = VL0->getOperand(0)->getType();
1335 // Calculate the cost of this instruction.
1336 int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(),
1337 VL0->getType(), SrcTy);
1339 VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
1340 int VecCost = TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy);
1341 return VecCost - ScalarCost;
1343 case Instruction::FCmp:
1344 case Instruction::ICmp:
1345 case Instruction::Select:
1346 case Instruction::Add:
1347 case Instruction::FAdd:
1348 case Instruction::Sub:
1349 case Instruction::FSub:
1350 case Instruction::Mul:
1351 case Instruction::FMul:
1352 case Instruction::UDiv:
1353 case Instruction::SDiv:
1354 case Instruction::FDiv:
1355 case Instruction::URem:
1356 case Instruction::SRem:
1357 case Instruction::FRem:
1358 case Instruction::Shl:
1359 case Instruction::LShr:
1360 case Instruction::AShr:
1361 case Instruction::And:
1362 case Instruction::Or:
1363 case Instruction::Xor: {
1364 // Calculate the cost of this instruction.
1367 if (Opcode == Instruction::FCmp || Opcode == Instruction::ICmp ||
1368 Opcode == Instruction::Select) {
1369 VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
1370 ScalarCost = VecTy->getNumElements() *
1371 TTI->getCmpSelInstrCost(Opcode, ScalarTy, Builder.getInt1Ty());
1372 VecCost = TTI->getCmpSelInstrCost(Opcode, VecTy, MaskTy);
1374 // Certain instructions can be cheaper to vectorize if they have a
1375 // constant second vector operand.
1376 TargetTransformInfo::OperandValueKind Op1VK =
1377 TargetTransformInfo::OK_AnyValue;
1378 TargetTransformInfo::OperandValueKind Op2VK =
1379 TargetTransformInfo::OK_UniformConstantValue;
1380 TargetTransformInfo::OperandValueProperties Op1VP =
1381 TargetTransformInfo::OP_None;
1382 TargetTransformInfo::OperandValueProperties Op2VP =
1383 TargetTransformInfo::OP_None;
1385 // If all operands are exactly the same ConstantInt then set the
1386 // operand kind to OK_UniformConstantValue.
1387 // If instead not all operands are constants, then set the operand kind
1388 // to OK_AnyValue. If all operands are constants but not the same,
1389 // then set the operand kind to OK_NonUniformConstantValue.
1390 ConstantInt *CInt = nullptr;
1391 for (unsigned i = 0; i < VL.size(); ++i) {
1392 const Instruction *I = cast<Instruction>(VL[i]);
1393 if (!isa<ConstantInt>(I->getOperand(1))) {
1394 Op2VK = TargetTransformInfo::OK_AnyValue;
1398 CInt = cast<ConstantInt>(I->getOperand(1));
1401 if (Op2VK == TargetTransformInfo::OK_UniformConstantValue &&
1402 CInt != cast<ConstantInt>(I->getOperand(1)))
1403 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
1405 // FIXME: Currently cost of model modification for division by
1406 // power of 2 is handled only for X86. Add support for other targets.
1407 if (Op2VK == TargetTransformInfo::OK_UniformConstantValue && CInt &&
1408 CInt->getValue().isPowerOf2())
1409 Op2VP = TargetTransformInfo::OP_PowerOf2;
1411 ScalarCost = VecTy->getNumElements() *
1412 TTI->getArithmeticInstrCost(Opcode, ScalarTy, Op1VK, Op2VK,
1414 VecCost = TTI->getArithmeticInstrCost(Opcode, VecTy, Op1VK, Op2VK,
1417 return VecCost - ScalarCost;
1419 case Instruction::Load: {
1420 // Cost of wide load - cost of scalar loads.
1421 int ScalarLdCost = VecTy->getNumElements() *
1422 TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
1423 int VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, 1, 0);
1424 return VecLdCost - ScalarLdCost;
1426 case Instruction::Store: {
1427 // We know that we can merge the stores. Calculate the cost.
1428 int ScalarStCost = VecTy->getNumElements() *
1429 TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
1430 int VecStCost = TTI->getMemoryOpCost(Instruction::Store, VecTy, 1, 0);
1431 return VecStCost - ScalarStCost;
1433 case Instruction::Call: {
1434 CallInst *CI = cast<CallInst>(VL0);
1435 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
1437 // Calculate the cost of the scalar and vector calls.
1438 SmallVector<Type*, 4> ScalarTys, VecTys;
1439 for (unsigned op = 0, opc = CI->getNumArgOperands(); op!= opc; ++op) {
1440 ScalarTys.push_back(CI->getArgOperand(op)->getType());
1441 VecTys.push_back(VectorType::get(CI->getArgOperand(op)->getType(),
1442 VecTy->getNumElements()));
1445 int ScalarCallCost = VecTy->getNumElements() *
1446 TTI->getIntrinsicInstrCost(ID, ScalarTy, ScalarTys);
1448 int VecCallCost = TTI->getIntrinsicInstrCost(ID, VecTy, VecTys);
1450 DEBUG(dbgs() << "SLP: Call cost "<< VecCallCost - ScalarCallCost
1451 << " (" << VecCallCost << "-" << ScalarCallCost << ")"
1452 << " for " << *CI << "\n");
1454 return VecCallCost - ScalarCallCost;
1456 case Instruction::ShuffleVector: {
1457 TargetTransformInfo::OperandValueKind Op1VK =
1458 TargetTransformInfo::OK_AnyValue;
1459 TargetTransformInfo::OperandValueKind Op2VK =
1460 TargetTransformInfo::OK_AnyValue;
1463 for (unsigned i = 0; i < VL.size(); ++i) {
1464 Instruction *I = cast<Instruction>(VL[i]);
1468 TTI->getArithmeticInstrCost(I->getOpcode(), ScalarTy, Op1VK, Op2VK);
1470 // VecCost is equal to sum of the cost of creating 2 vectors
1471 // and the cost of creating shuffle.
1472 Instruction *I0 = cast<Instruction>(VL[0]);
1474 TTI->getArithmeticInstrCost(I0->getOpcode(), VecTy, Op1VK, Op2VK);
1475 Instruction *I1 = cast<Instruction>(VL[1]);
1477 TTI->getArithmeticInstrCost(I1->getOpcode(), VecTy, Op1VK, Op2VK);
1479 TTI->getShuffleCost(TargetTransformInfo::SK_Alternate, VecTy, 0);
1480 return VecCost - ScalarCost;
1483 llvm_unreachable("Unknown instruction");
1487 bool BoUpSLP::isFullyVectorizableTinyTree() {
1488 DEBUG(dbgs() << "SLP: Check whether the tree with height " <<
1489 VectorizableTree.size() << " is fully vectorizable .\n");
1491 // We only handle trees of height 2.
1492 if (VectorizableTree.size() != 2)
1495 // Handle splat stores.
1496 if (!VectorizableTree[0].NeedToGather && isSplat(VectorizableTree[1].Scalars))
1499 // Gathering cost would be too much for tiny trees.
1500 if (VectorizableTree[0].NeedToGather || VectorizableTree[1].NeedToGather)
1506 int BoUpSLP::getSpillCost() {
1507 // Walk from the bottom of the tree to the top, tracking which values are
1508 // live. When we see a call instruction that is not part of our tree,
1509 // query TTI to see if there is a cost to keeping values live over it
1510 // (for example, if spills and fills are required).
1511 unsigned BundleWidth = VectorizableTree.front().Scalars.size();
1514 SmallPtrSet<Instruction*, 4> LiveValues;
1515 Instruction *PrevInst = nullptr;
1517 for (unsigned N = 0; N < VectorizableTree.size(); ++N) {
1518 Instruction *Inst = dyn_cast<Instruction>(VectorizableTree[N].Scalars[0]);
1528 dbgs() << "SLP: #LV: " << LiveValues.size();
1529 for (auto *X : LiveValues)
1530 dbgs() << " " << X->getName();
1531 dbgs() << ", Looking at ";
1535 // Update LiveValues.
1536 LiveValues.erase(PrevInst);
1537 for (auto &J : PrevInst->operands()) {
1538 if (isa<Instruction>(&*J) && ScalarToTreeEntry.count(&*J))
1539 LiveValues.insert(cast<Instruction>(&*J));
1542 // Now find the sequence of instructions between PrevInst and Inst.
1543 BasicBlock::reverse_iterator InstIt(Inst), PrevInstIt(PrevInst);
1545 while (InstIt != PrevInstIt) {
1546 if (PrevInstIt == PrevInst->getParent()->rend()) {
1547 PrevInstIt = Inst->getParent()->rbegin();
1551 if (isa<CallInst>(&*PrevInstIt) && &*PrevInstIt != PrevInst) {
1552 SmallVector<Type*, 4> V;
1553 for (auto *II : LiveValues)
1554 V.push_back(VectorType::get(II->getType(), BundleWidth));
1555 Cost += TTI->getCostOfKeepingLiveOverCall(V);
1564 DEBUG(dbgs() << "SLP: SpillCost=" << Cost << "\n");
1568 int BoUpSLP::getTreeCost() {
1570 DEBUG(dbgs() << "SLP: Calculating cost for tree of size " <<
1571 VectorizableTree.size() << ".\n");
1573 // We only vectorize tiny trees if it is fully vectorizable.
1574 if (VectorizableTree.size() < 3 && !isFullyVectorizableTinyTree()) {
1575 if (!VectorizableTree.size()) {
1576 assert(!ExternalUses.size() && "We should not have any external users");
1581 unsigned BundleWidth = VectorizableTree[0].Scalars.size();
1583 for (unsigned i = 0, e = VectorizableTree.size(); i != e; ++i) {
1584 int C = getEntryCost(&VectorizableTree[i]);
1585 DEBUG(dbgs() << "SLP: Adding cost " << C << " for bundle that starts with "
1586 << *VectorizableTree[i].Scalars[0] << " .\n");
1590 SmallSet<Value *, 16> ExtractCostCalculated;
1591 int ExtractCost = 0;
1592 for (UserList::iterator I = ExternalUses.begin(), E = ExternalUses.end();
1594 // We only add extract cost once for the same scalar.
1595 if (!ExtractCostCalculated.insert(I->Scalar))
1598 VectorType *VecTy = VectorType::get(I->Scalar->getType(), BundleWidth);
1599 ExtractCost += TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy,
1603 Cost += getSpillCost();
1605 DEBUG(dbgs() << "SLP: Total Cost " << Cost + ExtractCost<< ".\n");
1606 return Cost + ExtractCost;
1609 int BoUpSLP::getGatherCost(Type *Ty) {
1611 for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
1612 Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
1616 int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) {
1617 // Find the type of the operands in VL.
1618 Type *ScalarTy = VL[0]->getType();
1619 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1620 ScalarTy = SI->getValueOperand()->getType();
1621 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1622 // Find the cost of inserting/extracting values from the vector.
1623 return getGatherCost(VecTy);
1626 Value *BoUpSLP::getPointerOperand(Value *I) {
1627 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1628 return LI->getPointerOperand();
1629 if (StoreInst *SI = dyn_cast<StoreInst>(I))
1630 return SI->getPointerOperand();
1634 unsigned BoUpSLP::getAddressSpaceOperand(Value *I) {
1635 if (LoadInst *L = dyn_cast<LoadInst>(I))
1636 return L->getPointerAddressSpace();
1637 if (StoreInst *S = dyn_cast<StoreInst>(I))
1638 return S->getPointerAddressSpace();
1642 bool BoUpSLP::isConsecutiveAccess(Value *A, Value *B) {
1643 Value *PtrA = getPointerOperand(A);
1644 Value *PtrB = getPointerOperand(B);
1645 unsigned ASA = getAddressSpaceOperand(A);
1646 unsigned ASB = getAddressSpaceOperand(B);
1648 // Check that the address spaces match and that the pointers are valid.
1649 if (!PtrA || !PtrB || (ASA != ASB))
1652 // Make sure that A and B are different pointers of the same type.
1653 if (PtrA == PtrB || PtrA->getType() != PtrB->getType())
1656 unsigned PtrBitWidth = DL->getPointerSizeInBits(ASA);
1657 Type *Ty = cast<PointerType>(PtrA->getType())->getElementType();
1658 APInt Size(PtrBitWidth, DL->getTypeStoreSize(Ty));
1660 APInt OffsetA(PtrBitWidth, 0), OffsetB(PtrBitWidth, 0);
1661 PtrA = PtrA->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetA);
1662 PtrB = PtrB->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetB);
1664 APInt OffsetDelta = OffsetB - OffsetA;
1666 // Check if they are based on the same pointer. That makes the offsets
1669 return OffsetDelta == Size;
1671 // Compute the necessary base pointer delta to have the necessary final delta
1672 // equal to the size.
1673 APInt BaseDelta = Size - OffsetDelta;
1675 // Otherwise compute the distance with SCEV between the base pointers.
1676 const SCEV *PtrSCEVA = SE->getSCEV(PtrA);
1677 const SCEV *PtrSCEVB = SE->getSCEV(PtrB);
1678 const SCEV *C = SE->getConstant(BaseDelta);
1679 const SCEV *X = SE->getAddExpr(PtrSCEVA, C);
1680 return X == PtrSCEVB;
1683 void BoUpSLP::setInsertPointAfterBundle(ArrayRef<Value *> VL) {
1684 Instruction *VL0 = cast<Instruction>(VL[0]);
1685 BasicBlock::iterator NextInst = VL0;
1687 Builder.SetInsertPoint(VL0->getParent(), NextInst);
1688 Builder.SetCurrentDebugLocation(VL0->getDebugLoc());
1691 Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
1692 Value *Vec = UndefValue::get(Ty);
1693 // Generate the 'InsertElement' instruction.
1694 for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
1695 Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
1696 if (Instruction *Insrt = dyn_cast<Instruction>(Vec)) {
1697 GatherSeq.insert(Insrt);
1698 CSEBlocks.insert(Insrt->getParent());
1700 // Add to our 'need-to-extract' list.
1701 if (ScalarToTreeEntry.count(VL[i])) {
1702 int Idx = ScalarToTreeEntry[VL[i]];
1703 TreeEntry *E = &VectorizableTree[Idx];
1704 // Find which lane we need to extract.
1706 for (unsigned Lane = 0, LE = VL.size(); Lane != LE; ++Lane) {
1707 // Is this the lane of the scalar that we are looking for ?
1708 if (E->Scalars[Lane] == VL[i]) {
1713 assert(FoundLane >= 0 && "Could not find the correct lane");
1714 ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
1722 Value *BoUpSLP::alreadyVectorized(ArrayRef<Value *> VL) const {
1723 SmallDenseMap<Value*, int>::const_iterator Entry
1724 = ScalarToTreeEntry.find(VL[0]);
1725 if (Entry != ScalarToTreeEntry.end()) {
1726 int Idx = Entry->second;
1727 const TreeEntry *En = &VectorizableTree[Idx];
1728 if (En->isSame(VL) && En->VectorizedValue)
1729 return En->VectorizedValue;
1734 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
1735 if (ScalarToTreeEntry.count(VL[0])) {
1736 int Idx = ScalarToTreeEntry[VL[0]];
1737 TreeEntry *E = &VectorizableTree[Idx];
1739 return vectorizeTree(E);
1742 Type *ScalarTy = VL[0]->getType();
1743 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1744 ScalarTy = SI->getValueOperand()->getType();
1745 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1747 return Gather(VL, VecTy);
1750 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
1751 IRBuilder<>::InsertPointGuard Guard(Builder);
1753 if (E->VectorizedValue) {
1754 DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
1755 return E->VectorizedValue;
1758 Instruction *VL0 = cast<Instruction>(E->Scalars[0]);
1759 Type *ScalarTy = VL0->getType();
1760 if (StoreInst *SI = dyn_cast<StoreInst>(VL0))
1761 ScalarTy = SI->getValueOperand()->getType();
1762 VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size());
1764 if (E->NeedToGather) {
1765 setInsertPointAfterBundle(E->Scalars);
1766 return Gather(E->Scalars, VecTy);
1769 unsigned Opcode = getSameOpcode(E->Scalars);
1772 case Instruction::PHI: {
1773 PHINode *PH = dyn_cast<PHINode>(VL0);
1774 Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
1775 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1776 PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
1777 E->VectorizedValue = NewPhi;
1779 // PHINodes may have multiple entries from the same block. We want to
1780 // visit every block once.
1781 SmallSet<BasicBlock*, 4> VisitedBBs;
1783 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1785 BasicBlock *IBB = PH->getIncomingBlock(i);
1787 if (!VisitedBBs.insert(IBB)) {
1788 NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
1792 // Prepare the operand vector.
1793 for (unsigned j = 0; j < E->Scalars.size(); ++j)
1794 Operands.push_back(cast<PHINode>(E->Scalars[j])->
1795 getIncomingValueForBlock(IBB));
1797 Builder.SetInsertPoint(IBB->getTerminator());
1798 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1799 Value *Vec = vectorizeTree(Operands);
1800 NewPhi->addIncoming(Vec, IBB);
1803 assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
1804 "Invalid number of incoming values");
1808 case Instruction::ExtractElement: {
1809 if (CanReuseExtract(E->Scalars)) {
1810 Value *V = VL0->getOperand(0);
1811 E->VectorizedValue = V;
1814 return Gather(E->Scalars, VecTy);
1816 case Instruction::ZExt:
1817 case Instruction::SExt:
1818 case Instruction::FPToUI:
1819 case Instruction::FPToSI:
1820 case Instruction::FPExt:
1821 case Instruction::PtrToInt:
1822 case Instruction::IntToPtr:
1823 case Instruction::SIToFP:
1824 case Instruction::UIToFP:
1825 case Instruction::Trunc:
1826 case Instruction::FPTrunc:
1827 case Instruction::BitCast: {
1829 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1830 INVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1832 setInsertPointAfterBundle(E->Scalars);
1834 Value *InVec = vectorizeTree(INVL);
1836 if (Value *V = alreadyVectorized(E->Scalars))
1839 CastInst *CI = dyn_cast<CastInst>(VL0);
1840 Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
1841 E->VectorizedValue = V;
1842 ++NumVectorInstructions;
1845 case Instruction::FCmp:
1846 case Instruction::ICmp: {
1847 ValueList LHSV, RHSV;
1848 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1849 LHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1850 RHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1853 setInsertPointAfterBundle(E->Scalars);
1855 Value *L = vectorizeTree(LHSV);
1856 Value *R = vectorizeTree(RHSV);
1858 if (Value *V = alreadyVectorized(E->Scalars))
1861 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
1863 if (Opcode == Instruction::FCmp)
1864 V = Builder.CreateFCmp(P0, L, R);
1866 V = Builder.CreateICmp(P0, L, R);
1868 E->VectorizedValue = V;
1869 ++NumVectorInstructions;
1872 case Instruction::Select: {
1873 ValueList TrueVec, FalseVec, CondVec;
1874 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1875 CondVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1876 TrueVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1877 FalseVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(2));
1880 setInsertPointAfterBundle(E->Scalars);
1882 Value *Cond = vectorizeTree(CondVec);
1883 Value *True = vectorizeTree(TrueVec);
1884 Value *False = vectorizeTree(FalseVec);
1886 if (Value *V = alreadyVectorized(E->Scalars))
1889 Value *V = Builder.CreateSelect(Cond, True, False);
1890 E->VectorizedValue = V;
1891 ++NumVectorInstructions;
1894 case Instruction::Add:
1895 case Instruction::FAdd:
1896 case Instruction::Sub:
1897 case Instruction::FSub:
1898 case Instruction::Mul:
1899 case Instruction::FMul:
1900 case Instruction::UDiv:
1901 case Instruction::SDiv:
1902 case Instruction::FDiv:
1903 case Instruction::URem:
1904 case Instruction::SRem:
1905 case Instruction::FRem:
1906 case Instruction::Shl:
1907 case Instruction::LShr:
1908 case Instruction::AShr:
1909 case Instruction::And:
1910 case Instruction::Or:
1911 case Instruction::Xor: {
1912 ValueList LHSVL, RHSVL;
1913 if (isa<BinaryOperator>(VL0) && VL0->isCommutative())
1914 reorderInputsAccordingToOpcode(E->Scalars, LHSVL, RHSVL);
1916 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1917 LHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1918 RHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1921 setInsertPointAfterBundle(E->Scalars);
1923 Value *LHS = vectorizeTree(LHSVL);
1924 Value *RHS = vectorizeTree(RHSVL);
1926 if (LHS == RHS && isa<Instruction>(LHS)) {
1927 assert((VL0->getOperand(0) == VL0->getOperand(1)) && "Invalid order");
1930 if (Value *V = alreadyVectorized(E->Scalars))
1933 BinaryOperator *BinOp = cast<BinaryOperator>(VL0);
1934 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), LHS, RHS);
1935 E->VectorizedValue = V;
1936 ++NumVectorInstructions;
1938 if (Instruction *I = dyn_cast<Instruction>(V))
1939 return propagateMetadata(I, E->Scalars);
1943 case Instruction::Load: {
1944 // Loads are inserted at the head of the tree because we don't want to
1945 // sink them all the way down past store instructions.
1946 setInsertPointAfterBundle(E->Scalars);
1948 LoadInst *LI = cast<LoadInst>(VL0);
1949 Type *ScalarLoadTy = LI->getType();
1950 unsigned AS = LI->getPointerAddressSpace();
1952 Value *VecPtr = Builder.CreateBitCast(LI->getPointerOperand(),
1953 VecTy->getPointerTo(AS));
1954 unsigned Alignment = LI->getAlignment();
1955 LI = Builder.CreateLoad(VecPtr);
1957 Alignment = DL->getABITypeAlignment(ScalarLoadTy);
1958 LI->setAlignment(Alignment);
1959 E->VectorizedValue = LI;
1960 ++NumVectorInstructions;
1961 return propagateMetadata(LI, E->Scalars);
1963 case Instruction::Store: {
1964 StoreInst *SI = cast<StoreInst>(VL0);
1965 unsigned Alignment = SI->getAlignment();
1966 unsigned AS = SI->getPointerAddressSpace();
1969 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1970 ValueOp.push_back(cast<StoreInst>(E->Scalars[i])->getValueOperand());
1972 setInsertPointAfterBundle(E->Scalars);
1974 Value *VecValue = vectorizeTree(ValueOp);
1975 Value *VecPtr = Builder.CreateBitCast(SI->getPointerOperand(),
1976 VecTy->getPointerTo(AS));
1977 StoreInst *S = Builder.CreateStore(VecValue, VecPtr);
1979 Alignment = DL->getABITypeAlignment(SI->getValueOperand()->getType());
1980 S->setAlignment(Alignment);
1981 E->VectorizedValue = S;
1982 ++NumVectorInstructions;
1983 return propagateMetadata(S, E->Scalars);
1985 case Instruction::Call: {
1986 CallInst *CI = cast<CallInst>(VL0);
1987 setInsertPointAfterBundle(E->Scalars);
1989 Intrinsic::ID IID = Intrinsic::not_intrinsic;
1990 if (CI && (FI = CI->getCalledFunction())) {
1991 IID = (Intrinsic::ID) FI->getIntrinsicID();
1993 std::vector<Value *> OpVecs;
1994 for (int j = 0, e = CI->getNumArgOperands(); j < e; ++j) {
1996 // ctlz,cttz and powi are special intrinsics whose second argument is
1997 // a scalar. This argument should not be vectorized.
1998 if (hasVectorInstrinsicScalarOpd(IID, 1) && j == 1) {
1999 CallInst *CEI = cast<CallInst>(E->Scalars[0]);
2000 OpVecs.push_back(CEI->getArgOperand(j));
2003 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
2004 CallInst *CEI = cast<CallInst>(E->Scalars[i]);
2005 OpVL.push_back(CEI->getArgOperand(j));
2008 Value *OpVec = vectorizeTree(OpVL);
2009 DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
2010 OpVecs.push_back(OpVec);
2013 Module *M = F->getParent();
2014 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
2015 Type *Tys[] = { VectorType::get(CI->getType(), E->Scalars.size()) };
2016 Function *CF = Intrinsic::getDeclaration(M, ID, Tys);
2017 Value *V = Builder.CreateCall(CF, OpVecs);
2018 E->VectorizedValue = V;
2019 ++NumVectorInstructions;
2022 case Instruction::ShuffleVector: {
2023 ValueList LHSVL, RHSVL;
2024 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
2025 LHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
2026 RHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
2028 setInsertPointAfterBundle(E->Scalars);
2030 Value *LHS = vectorizeTree(LHSVL);
2031 Value *RHS = vectorizeTree(RHSVL);
2033 if (Value *V = alreadyVectorized(E->Scalars))
2036 // Create a vector of LHS op1 RHS
2037 BinaryOperator *BinOp0 = cast<BinaryOperator>(VL0);
2038 Value *V0 = Builder.CreateBinOp(BinOp0->getOpcode(), LHS, RHS);
2040 // Create a vector of LHS op2 RHS
2041 Instruction *VL1 = cast<Instruction>(E->Scalars[1]);
2042 BinaryOperator *BinOp1 = cast<BinaryOperator>(VL1);
2043 Value *V1 = Builder.CreateBinOp(BinOp1->getOpcode(), LHS, RHS);
2045 // Create appropriate shuffle to take alternative operations from
2047 std::vector<Constant *> Mask(E->Scalars.size());
2048 unsigned e = E->Scalars.size();
2049 for (unsigned i = 0; i < e; ++i) {
2051 Mask[i] = Builder.getInt32(e + i);
2053 Mask[i] = Builder.getInt32(i);
2056 Value *ShuffleMask = ConstantVector::get(Mask);
2058 Value *V = Builder.CreateShuffleVector(V0, V1, ShuffleMask);
2059 E->VectorizedValue = V;
2060 ++NumVectorInstructions;
2061 if (Instruction *I = dyn_cast<Instruction>(V))
2062 return propagateMetadata(I, E->Scalars);
2067 llvm_unreachable("unknown inst");
2072 Value *BoUpSLP::vectorizeTree() {
2074 // All blocks must be scheduled before any instructions are inserted.
2075 for (auto &BSIter : BlocksSchedules) {
2076 scheduleBlock(BSIter.second.get());
2079 Builder.SetInsertPoint(F->getEntryBlock().begin());
2080 vectorizeTree(&VectorizableTree[0]);
2082 DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() << " values .\n");
2084 // Extract all of the elements with the external uses.
2085 for (UserList::iterator it = ExternalUses.begin(), e = ExternalUses.end();
2087 Value *Scalar = it->Scalar;
2088 llvm::User *User = it->User;
2090 // Skip users that we already RAUW. This happens when one instruction
2091 // has multiple uses of the same value.
2092 if (std::find(Scalar->user_begin(), Scalar->user_end(), User) ==
2095 assert(ScalarToTreeEntry.count(Scalar) && "Invalid scalar");
2097 int Idx = ScalarToTreeEntry[Scalar];
2098 TreeEntry *E = &VectorizableTree[Idx];
2099 assert(!E->NeedToGather && "Extracting from a gather list");
2101 Value *Vec = E->VectorizedValue;
2102 assert(Vec && "Can't find vectorizable value");
2104 Value *Lane = Builder.getInt32(it->Lane);
2105 // Generate extracts for out-of-tree users.
2106 // Find the insertion point for the extractelement lane.
2107 if (isa<Instruction>(Vec)){
2108 if (PHINode *PH = dyn_cast<PHINode>(User)) {
2109 for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
2110 if (PH->getIncomingValue(i) == Scalar) {
2111 Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
2112 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2113 CSEBlocks.insert(PH->getIncomingBlock(i));
2114 PH->setOperand(i, Ex);
2118 Builder.SetInsertPoint(cast<Instruction>(User));
2119 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2120 CSEBlocks.insert(cast<Instruction>(User)->getParent());
2121 User->replaceUsesOfWith(Scalar, Ex);
2124 Builder.SetInsertPoint(F->getEntryBlock().begin());
2125 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2126 CSEBlocks.insert(&F->getEntryBlock());
2127 User->replaceUsesOfWith(Scalar, Ex);
2130 DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
2133 // For each vectorized value:
2134 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
2135 TreeEntry *Entry = &VectorizableTree[EIdx];
2138 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
2139 Value *Scalar = Entry->Scalars[Lane];
2140 // No need to handle users of gathered values.
2141 if (Entry->NeedToGather)
2144 assert(Entry->VectorizedValue && "Can't find vectorizable value");
2146 Type *Ty = Scalar->getType();
2147 if (!Ty->isVoidTy()) {
2149 for (User *U : Scalar->users()) {
2150 DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
2152 assert((ScalarToTreeEntry.count(U) ||
2153 // It is legal to replace users in the ignorelist by undef.
2154 (std::find(UserIgnoreList.begin(), UserIgnoreList.end(), U) !=
2155 UserIgnoreList.end())) &&
2156 "Replacing out-of-tree value with undef");
2159 Value *Undef = UndefValue::get(Ty);
2160 Scalar->replaceAllUsesWith(Undef);
2162 DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
2163 cast<Instruction>(Scalar)->eraseFromParent();
2167 Builder.ClearInsertionPoint();
2169 return VectorizableTree[0].VectorizedValue;
2172 void BoUpSLP::optimizeGatherSequence() {
2173 DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
2174 << " gather sequences instructions.\n");
2175 // LICM InsertElementInst sequences.
2176 for (SetVector<Instruction *>::iterator it = GatherSeq.begin(),
2177 e = GatherSeq.end(); it != e; ++it) {
2178 InsertElementInst *Insert = dyn_cast<InsertElementInst>(*it);
2183 // Check if this block is inside a loop.
2184 Loop *L = LI->getLoopFor(Insert->getParent());
2188 // Check if it has a preheader.
2189 BasicBlock *PreHeader = L->getLoopPreheader();
2193 // If the vector or the element that we insert into it are
2194 // instructions that are defined in this basic block then we can't
2195 // hoist this instruction.
2196 Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
2197 Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
2198 if (CurrVec && L->contains(CurrVec))
2200 if (NewElem && L->contains(NewElem))
2203 // We can hoist this instruction. Move it to the pre-header.
2204 Insert->moveBefore(PreHeader->getTerminator());
2207 // Make a list of all reachable blocks in our CSE queue.
2208 SmallVector<const DomTreeNode *, 8> CSEWorkList;
2209 CSEWorkList.reserve(CSEBlocks.size());
2210 for (BasicBlock *BB : CSEBlocks)
2211 if (DomTreeNode *N = DT->getNode(BB)) {
2212 assert(DT->isReachableFromEntry(N));
2213 CSEWorkList.push_back(N);
2216 // Sort blocks by domination. This ensures we visit a block after all blocks
2217 // dominating it are visited.
2218 std::stable_sort(CSEWorkList.begin(), CSEWorkList.end(),
2219 [this](const DomTreeNode *A, const DomTreeNode *B) {
2220 return DT->properlyDominates(A, B);
2223 // Perform O(N^2) search over the gather sequences and merge identical
2224 // instructions. TODO: We can further optimize this scan if we split the
2225 // instructions into different buckets based on the insert lane.
2226 SmallVector<Instruction *, 16> Visited;
2227 for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
2228 assert((I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
2229 "Worklist not sorted properly!");
2230 BasicBlock *BB = (*I)->getBlock();
2231 // For all instructions in blocks containing gather sequences:
2232 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) {
2233 Instruction *In = it++;
2234 if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In))
2237 // Check if we can replace this instruction with any of the
2238 // visited instructions.
2239 for (SmallVectorImpl<Instruction *>::iterator v = Visited.begin(),
2242 if (In->isIdenticalTo(*v) &&
2243 DT->dominates((*v)->getParent(), In->getParent())) {
2244 In->replaceAllUsesWith(*v);
2245 In->eraseFromParent();
2251 assert(std::find(Visited.begin(), Visited.end(), In) == Visited.end());
2252 Visited.push_back(In);
2260 // Groups the instructions to a bundle (which is then a single scheduling entity)
2261 // and schedules instructions until the bundle gets ready.
2262 bool BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL,
2263 AliasAnalysis *AA) {
2264 if (isa<PHINode>(VL[0]))
2267 // Initialize the instruction bundle.
2268 Instruction *OldScheduleEnd = ScheduleEnd;
2269 ScheduleData *PrevInBundle = nullptr;
2270 ScheduleData *Bundle = nullptr;
2271 bool ReSchedule = false;
2272 DEBUG(dbgs() << "SLP: bundle: " << *VL[0] << "\n");
2273 for (Value *V : VL) {
2274 extendSchedulingRegion(V);
2275 ScheduleData *BundleMember = getScheduleData(V);
2276 assert(BundleMember &&
2277 "no ScheduleData for bundle member (maybe not in same basic block)");
2278 if (BundleMember->IsScheduled) {
2279 // A bundle member was scheduled as single instruction before and now
2280 // needs to be scheduled as part of the bundle. We just get rid of the
2281 // existing schedule.
2282 DEBUG(dbgs() << "SLP: reset schedule because " << *BundleMember
2283 << " was already scheduled\n");
2286 assert(BundleMember->isSchedulingEntity() &&
2287 "bundle member already part of other bundle");
2289 PrevInBundle->NextInBundle = BundleMember;
2291 Bundle = BundleMember;
2293 BundleMember->UnscheduledDepsInBundle = 0;
2294 Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps;
2296 // Group the instructions to a bundle.
2297 BundleMember->FirstInBundle = Bundle;
2298 PrevInBundle = BundleMember;
2300 if (ScheduleEnd != OldScheduleEnd) {
2301 // The scheduling region got new instructions at the lower end (or it is a
2302 // new region for the first bundle). This makes it necessary to
2303 // recalculate all dependencies.
2304 // It is seldom that this needs to be done a second time after adding the
2305 // initial bundle to the region.
2306 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2307 ScheduleData *SD = getScheduleData(I);
2308 SD->clearDependencies();
2314 initialFillReadyList(ReadyInsts);
2317 DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle << " in block "
2318 << BB->getName() << "\n");
2320 calculateDependencies(Bundle, true, AA);
2322 // Now try to schedule the new bundle. As soon as the bundle is "ready" it
2323 // means that there are no cyclic dependencies and we can schedule it.
2324 // Note that's important that we don't "schedule" the bundle yet (see
2325 // cancelScheduling).
2326 while (!Bundle->isReady() && !ReadyInsts.empty()) {
2328 ScheduleData *pickedSD = ReadyInsts.back();
2329 ReadyInsts.pop_back();
2331 if (pickedSD->isSchedulingEntity() && pickedSD->isReady()) {
2332 schedule(pickedSD, ReadyInsts);
2335 return Bundle->isReady();
2338 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL) {
2339 if (isa<PHINode>(VL[0]))
2342 ScheduleData *Bundle = getScheduleData(VL[0]);
2343 DEBUG(dbgs() << "SLP: cancel scheduling of " << *Bundle << "\n");
2344 assert(!Bundle->IsScheduled &&
2345 "Can't cancel bundle which is already scheduled");
2346 assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
2347 "tried to unbundle something which is not a bundle");
2349 // Un-bundle: make single instructions out of the bundle.
2350 ScheduleData *BundleMember = Bundle;
2351 while (BundleMember) {
2352 assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
2353 BundleMember->FirstInBundle = BundleMember;
2354 ScheduleData *Next = BundleMember->NextInBundle;
2355 BundleMember->NextInBundle = nullptr;
2356 BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps;
2357 if (BundleMember->UnscheduledDepsInBundle == 0) {
2358 ReadyInsts.insert(BundleMember);
2360 BundleMember = Next;
2364 void BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V) {
2365 if (getScheduleData(V))
2367 Instruction *I = dyn_cast<Instruction>(V);
2368 assert(I && "bundle member must be an instruction");
2369 assert(!isa<PHINode>(I) && "phi nodes don't need to be scheduled");
2370 if (!ScheduleStart) {
2371 // It's the first instruction in the new region.
2372 initScheduleData(I, I->getNextNode(), nullptr, nullptr);
2374 ScheduleEnd = I->getNextNode();
2375 assert(ScheduleEnd && "tried to vectorize a TerminatorInst?");
2376 DEBUG(dbgs() << "SLP: initialize schedule region to " << *I << "\n");
2379 // Search up and down at the same time, because we don't know if the new
2380 // instruction is above or below the existing scheduling region.
2381 BasicBlock::reverse_iterator UpIter(ScheduleStart);
2382 BasicBlock::reverse_iterator UpperEnd = BB->rend();
2383 BasicBlock::iterator DownIter(ScheduleEnd);
2384 BasicBlock::iterator LowerEnd = BB->end();
2386 if (UpIter != UpperEnd) {
2387 if (&*UpIter == I) {
2388 initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
2390 DEBUG(dbgs() << "SLP: extend schedule region start to " << *I << "\n");
2395 if (DownIter != LowerEnd) {
2396 if (&*DownIter == I) {
2397 initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
2399 ScheduleEnd = I->getNextNode();
2400 assert(ScheduleEnd && "tried to vectorize a TerminatorInst?");
2401 DEBUG(dbgs() << "SLP: extend schedule region end to " << *I << "\n");
2406 assert((UpIter != UpperEnd || DownIter != LowerEnd) &&
2407 "instruction not found in block");
2411 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
2413 ScheduleData *PrevLoadStore,
2414 ScheduleData *NextLoadStore) {
2415 ScheduleData *CurrentLoadStore = PrevLoadStore;
2416 for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
2417 ScheduleData *SD = ScheduleDataMap[I];
2419 // Allocate a new ScheduleData for the instruction.
2420 if (ChunkPos >= ChunkSize) {
2421 ScheduleDataChunks.push_back(
2422 llvm::make_unique<ScheduleData[]>(ChunkSize));
2425 SD = &(ScheduleDataChunks.back()[ChunkPos++]);
2426 ScheduleDataMap[I] = SD;
2429 assert(!isInSchedulingRegion(SD) &&
2430 "new ScheduleData already in scheduling region");
2431 SD->init(SchedulingRegionID);
2433 if (I->mayReadOrWriteMemory()) {
2434 // Update the linked list of memory accessing instructions.
2435 if (CurrentLoadStore) {
2436 CurrentLoadStore->NextLoadStore = SD;
2438 FirstLoadStoreInRegion = SD;
2440 CurrentLoadStore = SD;
2443 if (NextLoadStore) {
2444 if (CurrentLoadStore)
2445 CurrentLoadStore->NextLoadStore = NextLoadStore;
2447 LastLoadStoreInRegion = CurrentLoadStore;
2451 /// \returns the AA location that is being access by the instruction.
2452 static AliasAnalysis::Location getLocation(Instruction *I, AliasAnalysis *AA) {
2453 if (StoreInst *SI = dyn_cast<StoreInst>(I))
2454 return AA->getLocation(SI);
2455 if (LoadInst *LI = dyn_cast<LoadInst>(I))
2456 return AA->getLocation(LI);
2457 return AliasAnalysis::Location();
2460 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
2461 bool InsertInReadyList,
2462 AliasAnalysis *AA) {
2463 assert(SD->isSchedulingEntity());
2465 SmallVector<ScheduleData *, 10> WorkList;
2466 WorkList.push_back(SD);
2468 while (!WorkList.empty()) {
2469 ScheduleData *SD = WorkList.back();
2470 WorkList.pop_back();
2472 ScheduleData *BundleMember = SD;
2473 while (BundleMember) {
2474 assert(isInSchedulingRegion(BundleMember));
2475 if (!BundleMember->hasValidDependencies()) {
2477 DEBUG(dbgs() << "SLP: update deps of " << *BundleMember << "\n");
2478 BundleMember->Dependencies = 0;
2479 BundleMember->resetUnscheduledDeps();
2481 // Handle def-use chain dependencies.
2482 for (User *U : BundleMember->Inst->users()) {
2483 if (isa<Instruction>(U)) {
2484 ScheduleData *UseSD = getScheduleData(U);
2485 if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
2486 BundleMember->Dependencies++;
2487 ScheduleData *DestBundle = UseSD->FirstInBundle;
2488 if (!DestBundle->IsScheduled) {
2489 BundleMember->incrementUnscheduledDeps(1);
2491 if (!DestBundle->hasValidDependencies()) {
2492 WorkList.push_back(DestBundle);
2496 // I'm not sure if this can ever happen. But we need to be safe.
2497 // This lets the instruction/bundle never be scheduled and eventally
2498 // disable vectorization.
2499 BundleMember->Dependencies++;
2500 BundleMember->incrementUnscheduledDeps(1);
2504 // Handle the memory dependencies.
2505 ScheduleData *DepDest = BundleMember->NextLoadStore;
2507 AliasAnalysis::Location SrcLoc = getLocation(BundleMember->Inst, AA);
2508 bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
2511 assert(isInSchedulingRegion(DepDest));
2512 if (SrcMayWrite || DepDest->Inst->mayWriteToMemory()) {
2513 AliasAnalysis::Location DstLoc = getLocation(DepDest->Inst, AA);
2514 if (!SrcLoc.Ptr || !DstLoc.Ptr || AA->alias(SrcLoc, DstLoc)) {
2515 DepDest->MemoryDependencies.push_back(BundleMember);
2516 BundleMember->Dependencies++;
2517 ScheduleData *DestBundle = DepDest->FirstInBundle;
2518 if (!DestBundle->IsScheduled) {
2519 BundleMember->incrementUnscheduledDeps(1);
2521 if (!DestBundle->hasValidDependencies()) {
2522 WorkList.push_back(DestBundle);
2526 DepDest = DepDest->NextLoadStore;
2530 BundleMember = BundleMember->NextInBundle;
2532 if (InsertInReadyList && SD->isReady()) {
2533 ReadyInsts.push_back(SD);
2534 DEBUG(dbgs() << "SLP: gets ready on update: " << *SD->Inst << "\n");
2539 void BoUpSLP::BlockScheduling::resetSchedule() {
2540 assert(ScheduleStart &&
2541 "tried to reset schedule on block which has not been scheduled");
2542 for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2543 ScheduleData *SD = getScheduleData(I);
2544 assert(isInSchedulingRegion(SD));
2545 SD->IsScheduled = false;
2546 SD->resetUnscheduledDeps();
2551 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
2553 if (!BS->ScheduleStart)
2556 DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
2558 BS->resetSchedule();
2560 // For the real scheduling we use a more sophisticated ready-list: it is
2561 // sorted by the original instruction location. This lets the final schedule
2562 // be as close as possible to the original instruction order.
2563 struct ScheduleDataCompare {
2564 bool operator()(ScheduleData *SD1, ScheduleData *SD2) {
2565 return SD2->SchedulingPriority < SD1->SchedulingPriority;
2568 std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
2570 // Ensure that all depencency data is updated and fill the ready-list with
2571 // initial instructions.
2573 int NumToSchedule = 0;
2574 for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
2575 I = I->getNextNode()) {
2576 ScheduleData *SD = BS->getScheduleData(I);
2578 SD->isPartOfBundle() == (ScalarToTreeEntry.count(SD->Inst) != 0) &&
2579 "scheduler and vectorizer have different opinion on what is a bundle");
2580 SD->FirstInBundle->SchedulingPriority = Idx++;
2581 if (SD->isSchedulingEntity()) {
2582 BS->calculateDependencies(SD, false, AA);
2586 BS->initialFillReadyList(ReadyInsts);
2588 Instruction *LastScheduledInst = BS->ScheduleEnd;
2590 // Do the "real" scheduling.
2591 while (!ReadyInsts.empty()) {
2592 ScheduleData *picked = *ReadyInsts.begin();
2593 ReadyInsts.erase(ReadyInsts.begin());
2595 // Move the scheduled instruction(s) to their dedicated places, if not
2597 ScheduleData *BundleMember = picked;
2598 while (BundleMember) {
2599 Instruction *pickedInst = BundleMember->Inst;
2600 if (LastScheduledInst->getNextNode() != pickedInst) {
2601 BS->BB->getInstList().remove(pickedInst);
2602 BS->BB->getInstList().insert(LastScheduledInst, pickedInst);
2604 LastScheduledInst = pickedInst;
2605 BundleMember = BundleMember->NextInBundle;
2608 BS->schedule(picked, ReadyInsts);
2611 assert(NumToSchedule == 0 && "could not schedule all instructions");
2613 // Avoid duplicate scheduling of the block.
2614 BS->ScheduleStart = nullptr;
2617 /// The SLPVectorizer Pass.
2618 struct SLPVectorizer : public FunctionPass {
2619 typedef SmallVector<StoreInst *, 8> StoreList;
2620 typedef MapVector<Value *, StoreList> StoreListMap;
2622 /// Pass identification, replacement for typeid
2625 explicit SLPVectorizer() : FunctionPass(ID) {
2626 initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
2629 ScalarEvolution *SE;
2630 const DataLayout *DL;
2631 TargetTransformInfo *TTI;
2632 TargetLibraryInfo *TLI;
2637 bool runOnFunction(Function &F) override {
2638 if (skipOptnoneFunction(F))
2641 SE = &getAnalysis<ScalarEvolution>();
2642 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
2643 DL = DLP ? &DLP->getDataLayout() : nullptr;
2644 TTI = &getAnalysis<TargetTransformInfo>();
2645 TLI = getAnalysisIfAvailable<TargetLibraryInfo>();
2646 AA = &getAnalysis<AliasAnalysis>();
2647 LI = &getAnalysis<LoopInfo>();
2648 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2651 bool Changed = false;
2653 // If the target claims to have no vector registers don't attempt
2655 if (!TTI->getNumberOfRegisters(true))
2658 // Must have DataLayout. We can't require it because some tests run w/o
2663 // Don't vectorize when the attribute NoImplicitFloat is used.
2664 if (F.hasFnAttribute(Attribute::NoImplicitFloat))
2667 DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
2669 // Use the bottom up slp vectorizer to construct chains that start with
2670 // store instructions.
2671 BoUpSLP R(&F, SE, DL, TTI, TLI, AA, LI, DT);
2673 // Scan the blocks in the function in post order.
2674 for (po_iterator<BasicBlock*> it = po_begin(&F.getEntryBlock()),
2675 e = po_end(&F.getEntryBlock()); it != e; ++it) {
2676 BasicBlock *BB = *it;
2677 // Vectorize trees that end at stores.
2678 if (unsigned count = collectStores(BB, R)) {
2680 DEBUG(dbgs() << "SLP: Found " << count << " stores to vectorize.\n");
2681 Changed |= vectorizeStoreChains(R);
2684 // Vectorize trees that end at reductions.
2685 Changed |= vectorizeChainsInBlock(BB, R);
2689 R.optimizeGatherSequence();
2690 DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
2691 DEBUG(verifyFunction(F));
2696 void getAnalysisUsage(AnalysisUsage &AU) const override {
2697 FunctionPass::getAnalysisUsage(AU);
2698 AU.addRequired<ScalarEvolution>();
2699 AU.addRequired<AliasAnalysis>();
2700 AU.addRequired<TargetTransformInfo>();
2701 AU.addRequired<LoopInfo>();
2702 AU.addRequired<DominatorTreeWrapperPass>();
2703 AU.addPreserved<LoopInfo>();
2704 AU.addPreserved<DominatorTreeWrapperPass>();
2705 AU.setPreservesCFG();
2710 /// \brief Collect memory references and sort them according to their base
2711 /// object. We sort the stores to their base objects to reduce the cost of the
2712 /// quadratic search on the stores. TODO: We can further reduce this cost
2713 /// if we flush the chain creation every time we run into a memory barrier.
2714 unsigned collectStores(BasicBlock *BB, BoUpSLP &R);
2716 /// \brief Try to vectorize a chain that starts at two arithmetic instrs.
2717 bool tryToVectorizePair(Value *A, Value *B, BoUpSLP &R);
2719 /// \brief Try to vectorize a list of operands.
2720 /// \@param BuildVector A list of users to ignore for the purpose of
2721 /// scheduling and that don't need extracting.
2722 /// \returns true if a value was vectorized.
2723 bool tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
2724 ArrayRef<Value *> BuildVector = None,
2725 bool allowReorder = false);
2727 /// \brief Try to vectorize a chain that may start at the operands of \V;
2728 bool tryToVectorize(BinaryOperator *V, BoUpSLP &R);
2730 /// \brief Vectorize the stores that were collected in StoreRefs.
2731 bool vectorizeStoreChains(BoUpSLP &R);
2733 /// \brief Scan the basic block and look for patterns that are likely to start
2734 /// a vectorization chain.
2735 bool vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R);
2737 bool vectorizeStoreChain(ArrayRef<Value *> Chain, int CostThreshold,
2740 bool vectorizeStores(ArrayRef<StoreInst *> Stores, int costThreshold,
2743 StoreListMap StoreRefs;
2746 /// \brief Check that the Values in the slice in VL array are still existent in
2747 /// the WeakVH array.
2748 /// Vectorization of part of the VL array may cause later values in the VL array
2749 /// to become invalid. We track when this has happened in the WeakVH array.
2750 static bool hasValueBeenRAUWed(ArrayRef<Value *> &VL,
2751 SmallVectorImpl<WeakVH> &VH,
2752 unsigned SliceBegin,
2753 unsigned SliceSize) {
2754 for (unsigned i = SliceBegin; i < SliceBegin + SliceSize; ++i)
2761 bool SLPVectorizer::vectorizeStoreChain(ArrayRef<Value *> Chain,
2762 int CostThreshold, BoUpSLP &R) {
2763 unsigned ChainLen = Chain.size();
2764 DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
2766 Type *StoreTy = cast<StoreInst>(Chain[0])->getValueOperand()->getType();
2767 unsigned Sz = DL->getTypeSizeInBits(StoreTy);
2768 unsigned VF = MinVecRegSize / Sz;
2770 if (!isPowerOf2_32(Sz) || VF < 2)
2773 // Keep track of values that were deleted by vectorizing in the loop below.
2774 SmallVector<WeakVH, 8> TrackValues(Chain.begin(), Chain.end());
2776 bool Changed = false;
2777 // Look for profitable vectorizable trees at all offsets, starting at zero.
2778 for (unsigned i = 0, e = ChainLen; i < e; ++i) {
2782 // Check that a previous iteration of this loop did not delete the Value.
2783 if (hasValueBeenRAUWed(Chain, TrackValues, i, VF))
2786 DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
2788 ArrayRef<Value *> Operands = Chain.slice(i, VF);
2790 R.buildTree(Operands);
2792 int Cost = R.getTreeCost();
2794 DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
2795 if (Cost < CostThreshold) {
2796 DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
2799 // Move to the next bundle.
2808 bool SLPVectorizer::vectorizeStores(ArrayRef<StoreInst *> Stores,
2809 int costThreshold, BoUpSLP &R) {
2810 SetVector<Value *> Heads, Tails;
2811 SmallDenseMap<Value *, Value *> ConsecutiveChain;
2813 // We may run into multiple chains that merge into a single chain. We mark the
2814 // stores that we vectorized so that we don't visit the same store twice.
2815 BoUpSLP::ValueSet VectorizedStores;
2816 bool Changed = false;
2818 // Do a quadratic search on all of the given stores and find
2819 // all of the pairs of stores that follow each other.
2820 for (unsigned i = 0, e = Stores.size(); i < e; ++i) {
2821 for (unsigned j = 0; j < e; ++j) {
2825 if (R.isConsecutiveAccess(Stores[i], Stores[j])) {
2826 Tails.insert(Stores[j]);
2827 Heads.insert(Stores[i]);
2828 ConsecutiveChain[Stores[i]] = Stores[j];
2833 // For stores that start but don't end a link in the chain:
2834 for (SetVector<Value *>::iterator it = Heads.begin(), e = Heads.end();
2836 if (Tails.count(*it))
2839 // We found a store instr that starts a chain. Now follow the chain and try
2841 BoUpSLP::ValueList Operands;
2843 // Collect the chain into a list.
2844 while (Tails.count(I) || Heads.count(I)) {
2845 if (VectorizedStores.count(I))
2847 Operands.push_back(I);
2848 // Move to the next value in the chain.
2849 I = ConsecutiveChain[I];
2852 bool Vectorized = vectorizeStoreChain(Operands, costThreshold, R);
2854 // Mark the vectorized stores so that we don't vectorize them again.
2856 VectorizedStores.insert(Operands.begin(), Operands.end());
2857 Changed |= Vectorized;
2864 unsigned SLPVectorizer::collectStores(BasicBlock *BB, BoUpSLP &R) {
2867 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2868 StoreInst *SI = dyn_cast<StoreInst>(it);
2872 // Don't touch volatile stores.
2873 if (!SI->isSimple())
2876 // Check that the pointer points to scalars.
2877 Type *Ty = SI->getValueOperand()->getType();
2878 if (Ty->isAggregateType() || Ty->isVectorTy())
2881 // Find the base pointer.
2882 Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), DL);
2884 // Save the store locations.
2885 StoreRefs[Ptr].push_back(SI);
2891 bool SLPVectorizer::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
2894 Value *VL[] = { A, B };
2895 return tryToVectorizeList(VL, R, None, true);
2898 bool SLPVectorizer::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
2899 ArrayRef<Value *> BuildVector,
2900 bool allowReorder) {
2904 DEBUG(dbgs() << "SLP: Vectorizing a list of length = " << VL.size() << ".\n");
2906 // Check that all of the parts are scalar instructions of the same type.
2907 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
2911 unsigned Opcode0 = I0->getOpcode();
2913 Type *Ty0 = I0->getType();
2914 unsigned Sz = DL->getTypeSizeInBits(Ty0);
2915 unsigned VF = MinVecRegSize / Sz;
2917 for (int i = 0, e = VL.size(); i < e; ++i) {
2918 Type *Ty = VL[i]->getType();
2919 if (Ty->isAggregateType() || Ty->isVectorTy())
2921 Instruction *Inst = dyn_cast<Instruction>(VL[i]);
2922 if (!Inst || Inst->getOpcode() != Opcode0)
2926 bool Changed = false;
2928 // Keep track of values that were deleted by vectorizing in the loop below.
2929 SmallVector<WeakVH, 8> TrackValues(VL.begin(), VL.end());
2931 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
2932 unsigned OpsWidth = 0;
2939 if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
2942 // Check that a previous iteration of this loop did not delete the Value.
2943 if (hasValueBeenRAUWed(VL, TrackValues, i, OpsWidth))
2946 DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
2948 ArrayRef<Value *> Ops = VL.slice(i, OpsWidth);
2950 ArrayRef<Value *> BuildVectorSlice;
2951 if (!BuildVector.empty())
2952 BuildVectorSlice = BuildVector.slice(i, OpsWidth);
2954 R.buildTree(Ops, BuildVectorSlice);
2955 // TODO: check if we can allow reordering also for other cases than
2956 // tryToVectorizePair()
2957 if (allowReorder && R.shouldReorder()) {
2958 assert(Ops.size() == 2);
2959 assert(BuildVectorSlice.empty());
2960 Value *ReorderedOps[] = { Ops[1], Ops[0] };
2961 R.buildTree(ReorderedOps, None);
2963 int Cost = R.getTreeCost();
2965 if (Cost < -SLPCostThreshold) {
2966 DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
2967 Value *VectorizedRoot = R.vectorizeTree();
2969 // Reconstruct the build vector by extracting the vectorized root. This
2970 // way we handle the case where some elements of the vector are undefined.
2971 // (return (inserelt <4 xi32> (insertelt undef (opd0) 0) (opd1) 2))
2972 if (!BuildVectorSlice.empty()) {
2973 // The insert point is the last build vector instruction. The vectorized
2974 // root will precede it. This guarantees that we get an instruction. The
2975 // vectorized tree could have been constant folded.
2976 Instruction *InsertAfter = cast<Instruction>(BuildVectorSlice.back());
2977 unsigned VecIdx = 0;
2978 for (auto &V : BuildVectorSlice) {
2979 IRBuilder<true, NoFolder> Builder(
2980 ++BasicBlock::iterator(InsertAfter));
2981 InsertElementInst *IE = cast<InsertElementInst>(V);
2982 Instruction *Extract = cast<Instruction>(Builder.CreateExtractElement(
2983 VectorizedRoot, Builder.getInt32(VecIdx++)));
2984 IE->setOperand(1, Extract);
2985 IE->removeFromParent();
2986 IE->insertAfter(Extract);
2990 // Move to the next bundle.
2999 bool SLPVectorizer::tryToVectorize(BinaryOperator *V, BoUpSLP &R) {
3003 // Try to vectorize V.
3004 if (tryToVectorizePair(V->getOperand(0), V->getOperand(1), R))
3007 BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0));
3008 BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1));
3010 if (B && B->hasOneUse()) {
3011 BinaryOperator *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
3012 BinaryOperator *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
3013 if (tryToVectorizePair(A, B0, R)) {
3017 if (tryToVectorizePair(A, B1, R)) {
3024 if (A && A->hasOneUse()) {
3025 BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
3026 BinaryOperator *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
3027 if (tryToVectorizePair(A0, B, R)) {
3031 if (tryToVectorizePair(A1, B, R)) {
3039 /// \brief Generate a shuffle mask to be used in a reduction tree.
3041 /// \param VecLen The length of the vector to be reduced.
3042 /// \param NumEltsToRdx The number of elements that should be reduced in the
3044 /// \param IsPairwise Whether the reduction is a pairwise or splitting
3045 /// reduction. A pairwise reduction will generate a mask of
3046 /// <0,2,...> or <1,3,..> while a splitting reduction will generate
3047 /// <2,3, undef,undef> for a vector of 4 and NumElts = 2.
3048 /// \param IsLeft True will generate a mask of even elements, odd otherwise.
3049 static Value *createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx,
3050 bool IsPairwise, bool IsLeft,
3051 IRBuilder<> &Builder) {
3052 assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask");
3054 SmallVector<Constant *, 32> ShuffleMask(
3055 VecLen, UndefValue::get(Builder.getInt32Ty()));
3058 // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
3059 for (unsigned i = 0; i != NumEltsToRdx; ++i)
3060 ShuffleMask[i] = Builder.getInt32(2 * i + !IsLeft);
3062 // Move the upper half of the vector to the lower half.
3063 for (unsigned i = 0; i != NumEltsToRdx; ++i)
3064 ShuffleMask[i] = Builder.getInt32(NumEltsToRdx + i);
3066 return ConstantVector::get(ShuffleMask);
3070 /// Model horizontal reductions.
3072 /// A horizontal reduction is a tree of reduction operations (currently add and
3073 /// fadd) that has operations that can be put into a vector as its leaf.
3074 /// For example, this tree:
3081 /// This tree has "mul" as its reduced values and "+" as its reduction
3082 /// operations. A reduction might be feeding into a store or a binary operation
3097 class HorizontalReduction {
3098 SmallVector<Value *, 16> ReductionOps;
3099 SmallVector<Value *, 32> ReducedVals;
3101 BinaryOperator *ReductionRoot;
3102 PHINode *ReductionPHI;
3104 /// The opcode of the reduction.
3105 unsigned ReductionOpcode;
3106 /// The opcode of the values we perform a reduction on.
3107 unsigned ReducedValueOpcode;
3108 /// The width of one full horizontal reduction operation.
3109 unsigned ReduxWidth;
3110 /// Should we model this reduction as a pairwise reduction tree or a tree that
3111 /// splits the vector in halves and adds those halves.
3112 bool IsPairwiseReduction;
3115 HorizontalReduction()
3116 : ReductionRoot(nullptr), ReductionPHI(nullptr), ReductionOpcode(0),
3117 ReducedValueOpcode(0), ReduxWidth(0), IsPairwiseReduction(false) {}
3119 /// \brief Try to find a reduction tree.
3120 bool matchAssociativeReduction(PHINode *Phi, BinaryOperator *B,
3121 const DataLayout *DL) {
3123 std::find(Phi->op_begin(), Phi->op_end(), B) != Phi->op_end()) &&
3124 "Thi phi needs to use the binary operator");
3126 // We could have a initial reductions that is not an add.
3127 // r *= v1 + v2 + v3 + v4
3128 // In such a case start looking for a tree rooted in the first '+'.
3130 if (B->getOperand(0) == Phi) {
3132 B = dyn_cast<BinaryOperator>(B->getOperand(1));
3133 } else if (B->getOperand(1) == Phi) {
3135 B = dyn_cast<BinaryOperator>(B->getOperand(0));
3142 Type *Ty = B->getType();
3143 if (Ty->isVectorTy())
3146 ReductionOpcode = B->getOpcode();
3147 ReducedValueOpcode = 0;
3148 ReduxWidth = MinVecRegSize / DL->getTypeSizeInBits(Ty);
3155 // We currently only support adds.
3156 if (ReductionOpcode != Instruction::Add &&
3157 ReductionOpcode != Instruction::FAdd)
3160 // Post order traverse the reduction tree starting at B. We only handle true
3161 // trees containing only binary operators.
3162 SmallVector<std::pair<BinaryOperator *, unsigned>, 32> Stack;
3163 Stack.push_back(std::make_pair(B, 0));
3164 while (!Stack.empty()) {
3165 BinaryOperator *TreeN = Stack.back().first;
3166 unsigned EdgeToVist = Stack.back().second++;
3167 bool IsReducedValue = TreeN->getOpcode() != ReductionOpcode;
3169 // Only handle trees in the current basic block.
3170 if (TreeN->getParent() != B->getParent())
3173 // Each tree node needs to have one user except for the ultimate
3175 if (!TreeN->hasOneUse() && TreeN != B)
3179 if (EdgeToVist == 2 || IsReducedValue) {
3180 if (IsReducedValue) {
3181 // Make sure that the opcodes of the operations that we are going to
3183 if (!ReducedValueOpcode)
3184 ReducedValueOpcode = TreeN->getOpcode();
3185 else if (ReducedValueOpcode != TreeN->getOpcode())
3187 ReducedVals.push_back(TreeN);
3189 // We need to be able to reassociate the adds.
3190 if (!TreeN->isAssociative())
3192 ReductionOps.push_back(TreeN);
3199 // Visit left or right.
3200 Value *NextV = TreeN->getOperand(EdgeToVist);
3201 BinaryOperator *Next = dyn_cast<BinaryOperator>(NextV);
3203 Stack.push_back(std::make_pair(Next, 0));
3204 else if (NextV != Phi)
3210 /// \brief Attempt to vectorize the tree found by
3211 /// matchAssociativeReduction.
3212 bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
3213 if (ReducedVals.empty())
3216 unsigned NumReducedVals = ReducedVals.size();
3217 if (NumReducedVals < ReduxWidth)
3220 Value *VectorizedTree = nullptr;
3221 IRBuilder<> Builder(ReductionRoot);
3222 FastMathFlags Unsafe;
3223 Unsafe.setUnsafeAlgebra();
3224 Builder.SetFastMathFlags(Unsafe);
3227 for (; i < NumReducedVals - ReduxWidth + 1; i += ReduxWidth) {
3228 V.buildTree(makeArrayRef(&ReducedVals[i], ReduxWidth), ReductionOps);
3231 int Cost = V.getTreeCost() + getReductionCost(TTI, ReducedVals[i]);
3232 if (Cost >= -SLPCostThreshold)
3235 DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" << Cost
3238 // Vectorize a tree.
3239 DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
3240 Value *VectorizedRoot = V.vectorizeTree();
3242 // Emit a reduction.
3243 Value *ReducedSubTree = emitReduction(VectorizedRoot, Builder);
3244 if (VectorizedTree) {
3245 Builder.SetCurrentDebugLocation(Loc);
3246 VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
3247 ReducedSubTree, "bin.rdx");
3249 VectorizedTree = ReducedSubTree;
3252 if (VectorizedTree) {
3253 // Finish the reduction.
3254 for (; i < NumReducedVals; ++i) {
3255 Builder.SetCurrentDebugLocation(
3256 cast<Instruction>(ReducedVals[i])->getDebugLoc());
3257 VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
3262 assert(ReductionRoot && "Need a reduction operation");
3263 ReductionRoot->setOperand(0, VectorizedTree);
3264 ReductionRoot->setOperand(1, ReductionPHI);
3266 ReductionRoot->replaceAllUsesWith(VectorizedTree);
3268 return VectorizedTree != nullptr;
3273 /// \brief Calcuate the cost of a reduction.
3274 int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal) {
3275 Type *ScalarTy = FirstReducedVal->getType();
3276 Type *VecTy = VectorType::get(ScalarTy, ReduxWidth);
3278 int PairwiseRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, true);
3279 int SplittingRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, false);
3281 IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
3282 int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
3284 int ScalarReduxCost =
3285 ReduxWidth * TTI->getArithmeticInstrCost(ReductionOpcode, VecTy);
3287 DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost
3288 << " for reduction that starts with " << *FirstReducedVal
3290 << (IsPairwiseReduction ? "pairwise" : "splitting")
3291 << " reduction)\n");
3293 return VecReduxCost - ScalarReduxCost;
3296 static Value *createBinOp(IRBuilder<> &Builder, unsigned Opcode, Value *L,
3297 Value *R, const Twine &Name = "") {
3298 if (Opcode == Instruction::FAdd)
3299 return Builder.CreateFAdd(L, R, Name);
3300 return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, L, R, Name);
3303 /// \brief Emit a horizontal reduction of the vectorized value.
3304 Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder) {
3305 assert(VectorizedValue && "Need to have a vectorized tree node");
3306 Instruction *ValToReduce = dyn_cast<Instruction>(VectorizedValue);
3307 assert(isPowerOf2_32(ReduxWidth) &&
3308 "We only handle power-of-two reductions for now");
3310 Value *TmpVec = ValToReduce;
3311 for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
3312 if (IsPairwiseReduction) {
3314 createRdxShuffleMask(ReduxWidth, i, true, true, Builder);
3316 createRdxShuffleMask(ReduxWidth, i, true, false, Builder);
3318 Value *LeftShuf = Builder.CreateShuffleVector(
3319 TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l");
3320 Value *RightShuf = Builder.CreateShuffleVector(
3321 TmpVec, UndefValue::get(TmpVec->getType()), (RightMask),
3323 TmpVec = createBinOp(Builder, ReductionOpcode, LeftShuf, RightShuf,
3327 createRdxShuffleMask(ReduxWidth, i, false, false, Builder);
3328 Value *Shuf = Builder.CreateShuffleVector(
3329 TmpVec, UndefValue::get(TmpVec->getType()), UpperHalf, "rdx.shuf");
3330 TmpVec = createBinOp(Builder, ReductionOpcode, TmpVec, Shuf, "bin.rdx");
3334 // The result is in the first element of the vector.
3335 return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
3339 /// \brief Recognize construction of vectors like
3340 /// %ra = insertelement <4 x float> undef, float %s0, i32 0
3341 /// %rb = insertelement <4 x float> %ra, float %s1, i32 1
3342 /// %rc = insertelement <4 x float> %rb, float %s2, i32 2
3343 /// %rd = insertelement <4 x float> %rc, float %s3, i32 3
3345 /// Returns true if it matches
3347 static bool findBuildVector(InsertElementInst *FirstInsertElem,
3348 SmallVectorImpl<Value *> &BuildVector,
3349 SmallVectorImpl<Value *> &BuildVectorOpds) {
3350 if (!isa<UndefValue>(FirstInsertElem->getOperand(0)))
3353 InsertElementInst *IE = FirstInsertElem;
3355 BuildVector.push_back(IE);
3356 BuildVectorOpds.push_back(IE->getOperand(1));
3358 if (IE->use_empty())
3361 InsertElementInst *NextUse = dyn_cast<InsertElementInst>(IE->user_back());
3365 // If this isn't the final use, make sure the next insertelement is the only
3366 // use. It's OK if the final constructed vector is used multiple times
3367 if (!IE->hasOneUse())
3376 static bool PhiTypeSorterFunc(Value *V, Value *V2) {
3377 return V->getType() < V2->getType();
3380 bool SLPVectorizer::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
3381 bool Changed = false;
3382 SmallVector<Value *, 4> Incoming;
3383 SmallSet<Value *, 16> VisitedInstrs;
3385 bool HaveVectorizedPhiNodes = true;
3386 while (HaveVectorizedPhiNodes) {
3387 HaveVectorizedPhiNodes = false;
3389 // Collect the incoming values from the PHIs.
3391 for (BasicBlock::iterator instr = BB->begin(), ie = BB->end(); instr != ie;
3393 PHINode *P = dyn_cast<PHINode>(instr);
3397 if (!VisitedInstrs.count(P))
3398 Incoming.push_back(P);
3402 std::stable_sort(Incoming.begin(), Incoming.end(), PhiTypeSorterFunc);
3404 // Try to vectorize elements base on their type.
3405 for (SmallVector<Value *, 4>::iterator IncIt = Incoming.begin(),
3409 // Look for the next elements with the same type.
3410 SmallVector<Value *, 4>::iterator SameTypeIt = IncIt;
3411 while (SameTypeIt != E &&
3412 (*SameTypeIt)->getType() == (*IncIt)->getType()) {
3413 VisitedInstrs.insert(*SameTypeIt);
3417 // Try to vectorize them.
3418 unsigned NumElts = (SameTypeIt - IncIt);
3419 DEBUG(errs() << "SLP: Trying to vectorize starting at PHIs (" << NumElts << ")\n");
3420 if (NumElts > 1 && tryToVectorizeList(makeArrayRef(IncIt, NumElts), R)) {
3421 // Success start over because instructions might have been changed.
3422 HaveVectorizedPhiNodes = true;
3427 // Start over at the next instruction of a different type (or the end).
3432 VisitedInstrs.clear();
3434 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) {
3435 // We may go through BB multiple times so skip the one we have checked.
3436 if (!VisitedInstrs.insert(it))
3439 if (isa<DbgInfoIntrinsic>(it))
3442 // Try to vectorize reductions that use PHINodes.
3443 if (PHINode *P = dyn_cast<PHINode>(it)) {
3444 // Check that the PHI is a reduction PHI.
3445 if (P->getNumIncomingValues() != 2)
3448 (P->getIncomingBlock(0) == BB
3449 ? (P->getIncomingValue(0))
3450 : (P->getIncomingBlock(1) == BB ? P->getIncomingValue(1)
3452 // Check if this is a Binary Operator.
3453 BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx);
3457 // Try to match and vectorize a horizontal reduction.
3458 HorizontalReduction HorRdx;
3459 if (ShouldVectorizeHor &&
3460 HorRdx.matchAssociativeReduction(P, BI, DL) &&
3461 HorRdx.tryToReduce(R, TTI)) {
3468 Value *Inst = BI->getOperand(0);
3470 Inst = BI->getOperand(1);
3472 if (tryToVectorize(dyn_cast<BinaryOperator>(Inst), R)) {
3473 // We would like to start over since some instructions are deleted
3474 // and the iterator may become invalid value.
3484 // Try to vectorize horizontal reductions feeding into a store.
3485 if (ShouldStartVectorizeHorAtStore)
3486 if (StoreInst *SI = dyn_cast<StoreInst>(it))
3487 if (BinaryOperator *BinOp =
3488 dyn_cast<BinaryOperator>(SI->getValueOperand())) {
3489 HorizontalReduction HorRdx;
3490 if (((HorRdx.matchAssociativeReduction(nullptr, BinOp, DL) &&
3491 HorRdx.tryToReduce(R, TTI)) ||
3492 tryToVectorize(BinOp, R))) {
3500 // Try to vectorize trees that start at compare instructions.
3501 if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
3502 if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) {
3504 // We would like to start over since some instructions are deleted
3505 // and the iterator may become invalid value.
3511 for (int i = 0; i < 2; ++i) {
3512 if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i))) {
3513 if (tryToVectorizePair(BI->getOperand(0), BI->getOperand(1), R)) {
3515 // We would like to start over since some instructions are deleted
3516 // and the iterator may become invalid value.
3525 // Try to vectorize trees that start at insertelement instructions.
3526 if (InsertElementInst *FirstInsertElem = dyn_cast<InsertElementInst>(it)) {
3527 SmallVector<Value *, 16> BuildVector;
3528 SmallVector<Value *, 16> BuildVectorOpds;
3529 if (!findBuildVector(FirstInsertElem, BuildVector, BuildVectorOpds))
3532 // Vectorize starting with the build vector operands ignoring the
3533 // BuildVector instructions for the purpose of scheduling and user
3535 if (tryToVectorizeList(BuildVectorOpds, R, BuildVector)) {
3548 bool SLPVectorizer::vectorizeStoreChains(BoUpSLP &R) {
3549 bool Changed = false;
3550 // Attempt to sort and vectorize each of the store-groups.
3551 for (StoreListMap::iterator it = StoreRefs.begin(), e = StoreRefs.end();
3553 if (it->second.size() < 2)
3556 DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
3557 << it->second.size() << ".\n");
3559 // Process the stores in chunks of 16.
3560 for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI+=16) {
3561 unsigned Len = std::min<unsigned>(CE - CI, 16);
3562 Changed |= vectorizeStores(makeArrayRef(&it->second[CI], Len),
3563 -SLPCostThreshold, R);
3569 } // end anonymous namespace
3571 char SLPVectorizer::ID = 0;
3572 static const char lv_name[] = "SLP Vectorizer";
3573 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
3574 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3575 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
3576 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
3577 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
3578 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
3581 Pass *createSLPVectorizerPass() { return new SLPVectorizer(); }