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/Optional.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/Analysis/AssumptionCache.h"
26 #include "llvm/Analysis/CodeMetrics.h"
27 #include "llvm/Analysis/LoopInfo.h"
28 #include "llvm/Analysis/ScalarEvolution.h"
29 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
30 #include "llvm/Analysis/TargetTransformInfo.h"
31 #include "llvm/Analysis/ValueTracking.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/Dominators.h"
34 #include "llvm/IR/IRBuilder.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/IR/IntrinsicInst.h"
37 #include "llvm/IR/Module.h"
38 #include "llvm/IR/NoFolder.h"
39 #include "llvm/IR/Type.h"
40 #include "llvm/IR/Value.h"
41 #include "llvm/IR/Verifier.h"
42 #include "llvm/Pass.h"
43 #include "llvm/Support/CommandLine.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/Support/raw_ostream.h"
46 #include "llvm/Transforms/Utils/VectorUtils.h"
53 #define SV_NAME "slp-vectorizer"
54 #define DEBUG_TYPE "SLP"
56 STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
59 SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
60 cl::desc("Only vectorize if you gain more than this "
64 ShouldVectorizeHor("slp-vectorize-hor", cl::init(false), cl::Hidden,
65 cl::desc("Attempt to vectorize horizontal reductions"));
67 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
68 "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
70 "Attempt to vectorize horizontal reductions feeding into a store"));
74 static const unsigned MinVecRegSize = 128;
76 static const unsigned RecursionMaxDepth = 12;
78 /// \returns the parent basic block if all of the instructions in \p VL
79 /// are in the same block or null otherwise.
80 static BasicBlock *getSameBlock(ArrayRef<Value *> VL) {
81 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
84 BasicBlock *BB = I0->getParent();
85 for (int i = 1, e = VL.size(); i < e; i++) {
86 Instruction *I = dyn_cast<Instruction>(VL[i]);
90 if (BB != I->getParent())
96 /// \returns True if all of the values in \p VL are constants.
97 static bool allConstant(ArrayRef<Value *> VL) {
98 for (unsigned i = 0, e = VL.size(); i < e; ++i)
99 if (!isa<Constant>(VL[i]))
104 /// \returns True if all of the values in \p VL are identical.
105 static bool isSplat(ArrayRef<Value *> VL) {
106 for (unsigned i = 1, e = VL.size(); i < e; ++i)
112 ///\returns Opcode that can be clubbed with \p Op to create an alternate
113 /// sequence which can later be merged as a ShuffleVector instruction.
114 static unsigned getAltOpcode(unsigned Op) {
116 case Instruction::FAdd:
117 return Instruction::FSub;
118 case Instruction::FSub:
119 return Instruction::FAdd;
120 case Instruction::Add:
121 return Instruction::Sub;
122 case Instruction::Sub:
123 return Instruction::Add;
129 ///\returns bool representing if Opcode \p Op can be part
130 /// of an alternate sequence which can later be merged as
131 /// a ShuffleVector instruction.
132 static bool canCombineAsAltInst(unsigned Op) {
133 if (Op == Instruction::FAdd || Op == Instruction::FSub ||
134 Op == Instruction::Sub || Op == Instruction::Add)
139 /// \returns ShuffleVector instruction if intructions in \p VL have
140 /// alternate fadd,fsub / fsub,fadd/add,sub/sub,add sequence.
141 /// (i.e. e.g. opcodes of fadd,fsub,fadd,fsub...)
142 static unsigned isAltInst(ArrayRef<Value *> VL) {
143 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
144 unsigned Opcode = I0->getOpcode();
145 unsigned AltOpcode = getAltOpcode(Opcode);
146 for (int i = 1, e = VL.size(); i < e; i++) {
147 Instruction *I = dyn_cast<Instruction>(VL[i]);
148 if (!I || I->getOpcode() != ((i & 1) ? AltOpcode : Opcode))
151 return Instruction::ShuffleVector;
154 /// \returns The opcode if all of the Instructions in \p VL have the same
156 static unsigned getSameOpcode(ArrayRef<Value *> VL) {
157 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
160 unsigned Opcode = I0->getOpcode();
161 for (int i = 1, e = VL.size(); i < e; i++) {
162 Instruction *I = dyn_cast<Instruction>(VL[i]);
163 if (!I || Opcode != I->getOpcode()) {
164 if (canCombineAsAltInst(Opcode) && i == 1)
165 return isAltInst(VL);
172 /// Get the intersection (logical and) of all of the potential IR flags
173 /// of each scalar operation (VL) that will be converted into a vector (I).
174 /// Flag set: NSW, NUW, exact, and all of fast-math.
175 static void propagateIRFlags(Value *I, ArrayRef<Value *> VL) {
176 if (auto *VecOp = dyn_cast<BinaryOperator>(I)) {
177 if (auto *Intersection = dyn_cast<BinaryOperator>(VL[0])) {
178 // Intersection is initialized to the 0th scalar,
179 // so start counting from index '1'.
180 for (int i = 1, e = VL.size(); i < e; ++i) {
181 if (auto *Scalar = dyn_cast<BinaryOperator>(VL[i]))
182 Intersection->andIRFlags(Scalar);
184 VecOp->copyIRFlags(Intersection);
189 /// \returns \p I after propagating metadata from \p VL.
190 static Instruction *propagateMetadata(Instruction *I, ArrayRef<Value *> VL) {
191 Instruction *I0 = cast<Instruction>(VL[0]);
192 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
193 I0->getAllMetadataOtherThanDebugLoc(Metadata);
195 for (unsigned i = 0, n = Metadata.size(); i != n; ++i) {
196 unsigned Kind = Metadata[i].first;
197 MDNode *MD = Metadata[i].second;
199 for (int i = 1, e = VL.size(); MD && i != e; i++) {
200 Instruction *I = cast<Instruction>(VL[i]);
201 MDNode *IMD = I->getMetadata(Kind);
205 MD = nullptr; // Remove unknown metadata
207 case LLVMContext::MD_tbaa:
208 MD = MDNode::getMostGenericTBAA(MD, IMD);
210 case LLVMContext::MD_alias_scope:
211 case LLVMContext::MD_noalias:
212 MD = MDNode::intersect(MD, IMD);
214 case LLVMContext::MD_fpmath:
215 MD = MDNode::getMostGenericFPMath(MD, IMD);
219 I->setMetadata(Kind, MD);
224 /// \returns The type that all of the values in \p VL have or null if there
225 /// are different types.
226 static Type* getSameType(ArrayRef<Value *> VL) {
227 Type *Ty = VL[0]->getType();
228 for (int i = 1, e = VL.size(); i < e; i++)
229 if (VL[i]->getType() != Ty)
235 /// \returns True if the ExtractElement instructions in VL can be vectorized
236 /// to use the original vector.
237 static bool CanReuseExtract(ArrayRef<Value *> VL) {
238 assert(Instruction::ExtractElement == getSameOpcode(VL) && "Invalid opcode");
239 // Check if all of the extracts come from the same vector and from the
242 ExtractElementInst *E0 = cast<ExtractElementInst>(VL0);
243 Value *Vec = E0->getOperand(0);
245 // We have to extract from the same vector type.
246 unsigned NElts = Vec->getType()->getVectorNumElements();
248 if (NElts != VL.size())
251 // Check that all of the indices extract from the correct offset.
252 ConstantInt *CI = dyn_cast<ConstantInt>(E0->getOperand(1));
253 if (!CI || CI->getZExtValue())
256 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
257 ExtractElementInst *E = cast<ExtractElementInst>(VL[i]);
258 ConstantInt *CI = dyn_cast<ConstantInt>(E->getOperand(1));
260 if (!CI || CI->getZExtValue() != i || E->getOperand(0) != Vec)
267 static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
268 SmallVectorImpl<Value *> &Left,
269 SmallVectorImpl<Value *> &Right) {
271 SmallVector<Value *, 16> OrigLeft, OrigRight;
273 bool AllSameOpcodeLeft = true;
274 bool AllSameOpcodeRight = true;
275 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
276 Instruction *I = cast<Instruction>(VL[i]);
277 Value *V0 = I->getOperand(0);
278 Value *V1 = I->getOperand(1);
280 OrigLeft.push_back(V0);
281 OrigRight.push_back(V1);
283 Instruction *I0 = dyn_cast<Instruction>(V0);
284 Instruction *I1 = dyn_cast<Instruction>(V1);
286 // Check whether all operands on one side have the same opcode. In this case
287 // we want to preserve the original order and not make things worse by
289 AllSameOpcodeLeft = I0;
290 AllSameOpcodeRight = I1;
292 if (i && AllSameOpcodeLeft) {
293 if(Instruction *P0 = dyn_cast<Instruction>(OrigLeft[i-1])) {
294 if(P0->getOpcode() != I0->getOpcode())
295 AllSameOpcodeLeft = false;
297 AllSameOpcodeLeft = false;
299 if (i && AllSameOpcodeRight) {
300 if(Instruction *P1 = dyn_cast<Instruction>(OrigRight[i-1])) {
301 if(P1->getOpcode() != I1->getOpcode())
302 AllSameOpcodeRight = false;
304 AllSameOpcodeRight = false;
307 // Sort two opcodes. In the code below we try to preserve the ability to use
308 // broadcast of values instead of individual inserts.
315 // If we just sorted according to opcode we would leave the first line in
316 // tact but we would swap vl2 with vr2 because opcode(phi) > opcode(load).
319 // Because vr2 and vr1 are from the same load we loose the opportunity of a
320 // broadcast for the packed right side in the backend: we have [vr1, vl2]
321 // instead of [vr1, vr2=vr1].
323 if(!i && I0->getOpcode() > I1->getOpcode()) {
326 } else if (i && I0->getOpcode() > I1->getOpcode() && Right[i-1] != I1) {
327 // Try not to destroy a broad cast for no apparent benefit.
330 } else if (i && I0->getOpcode() == I1->getOpcode() && Right[i-1] == I0) {
331 // Try preserve broadcasts.
334 } else if (i && I0->getOpcode() == I1->getOpcode() && Left[i-1] == I1) {
335 // Try preserve broadcasts.
344 // One opcode, put the instruction on the right.
354 bool LeftBroadcast = isSplat(Left);
355 bool RightBroadcast = isSplat(Right);
357 // Don't reorder if the operands where good to begin with.
358 if (!(LeftBroadcast || RightBroadcast) &&
359 (AllSameOpcodeRight || AllSameOpcodeLeft)) {
365 /// \returns True if in-tree use also needs extract. This refers to
366 /// possible scalar operand in vectorized instruction.
367 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
368 TargetLibraryInfo *TLI) {
370 unsigned Opcode = UserInst->getOpcode();
372 case Instruction::Load: {
373 LoadInst *LI = cast<LoadInst>(UserInst);
374 return (LI->getPointerOperand() == Scalar);
376 case Instruction::Store: {
377 StoreInst *SI = cast<StoreInst>(UserInst);
378 return (SI->getPointerOperand() == Scalar);
380 case Instruction::Call: {
381 CallInst *CI = cast<CallInst>(UserInst);
382 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
383 if (hasVectorInstrinsicScalarOpd(ID, 1)) {
384 return (CI->getArgOperand(1) == Scalar);
392 /// \returns the AA location that is being access by the instruction.
393 static AliasAnalysis::Location getLocation(Instruction *I, AliasAnalysis *AA) {
394 if (StoreInst *SI = dyn_cast<StoreInst>(I))
395 return AA->getLocation(SI);
396 if (LoadInst *LI = dyn_cast<LoadInst>(I))
397 return AA->getLocation(LI);
398 return AliasAnalysis::Location();
401 /// Bottom Up SLP Vectorizer.
404 typedef SmallVector<Value *, 8> ValueList;
405 typedef SmallVector<Instruction *, 16> InstrList;
406 typedef SmallPtrSet<Value *, 16> ValueSet;
407 typedef SmallVector<StoreInst *, 8> StoreList;
409 BoUpSLP(Function *Func, ScalarEvolution *Se, const DataLayout *Dl,
410 TargetTransformInfo *Tti, TargetLibraryInfo *TLi, AliasAnalysis *Aa,
411 LoopInfo *Li, DominatorTree *Dt, AssumptionCache *AC)
412 : NumLoadsWantToKeepOrder(0), NumLoadsWantToChangeOrder(0), F(Func),
413 SE(Se), DL(Dl), TTI(Tti), TLI(TLi), AA(Aa), LI(Li), DT(Dt),
414 Builder(Se->getContext()) {
415 CodeMetrics::collectEphemeralValues(F, AC, EphValues);
418 /// \brief Vectorize the tree that starts with the elements in \p VL.
419 /// Returns the vectorized root.
420 Value *vectorizeTree();
422 /// \returns the cost incurred by unwanted spills and fills, caused by
423 /// holding live values over call sites.
426 /// \returns the vectorization cost of the subtree that starts at \p VL.
427 /// A negative number means that this is profitable.
430 /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
431 /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
432 void buildTree(ArrayRef<Value *> Roots,
433 ArrayRef<Value *> UserIgnoreLst = None);
435 /// Clear the internal data structures that are created by 'buildTree'.
437 VectorizableTree.clear();
438 ScalarToTreeEntry.clear();
440 ExternalUses.clear();
441 NumLoadsWantToKeepOrder = 0;
442 NumLoadsWantToChangeOrder = 0;
443 for (auto &Iter : BlocksSchedules) {
444 BlockScheduling *BS = Iter.second.get();
449 /// \returns true if the memory operations A and B are consecutive.
450 bool isConsecutiveAccess(Value *A, Value *B);
452 /// \brief Perform LICM and CSE on the newly generated gather sequences.
453 void optimizeGatherSequence();
455 /// \returns true if it is benefitial to reverse the vector order.
456 bool shouldReorder() const {
457 return NumLoadsWantToChangeOrder > NumLoadsWantToKeepOrder;
463 /// \returns the cost of the vectorizable entry.
464 int getEntryCost(TreeEntry *E);
466 /// This is the recursive part of buildTree.
467 void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth);
469 /// Vectorize a single entry in the tree.
470 Value *vectorizeTree(TreeEntry *E);
472 /// Vectorize a single entry in the tree, starting in \p VL.
473 Value *vectorizeTree(ArrayRef<Value *> VL);
475 /// \returns the pointer to the vectorized value if \p VL is already
476 /// vectorized, or NULL. They may happen in cycles.
477 Value *alreadyVectorized(ArrayRef<Value *> VL) const;
479 /// \brief Take the pointer operand from the Load/Store instruction.
480 /// \returns NULL if this is not a valid Load/Store instruction.
481 static Value *getPointerOperand(Value *I);
483 /// \brief Take the address space operand from the Load/Store instruction.
484 /// \returns -1 if this is not a valid Load/Store instruction.
485 static unsigned getAddressSpaceOperand(Value *I);
487 /// \returns the scalarization cost for this type. Scalarization in this
488 /// context means the creation of vectors from a group of scalars.
489 int getGatherCost(Type *Ty);
491 /// \returns the scalarization cost for this list of values. Assuming that
492 /// this subtree gets vectorized, we may need to extract the values from the
493 /// roots. This method calculates the cost of extracting the values.
494 int getGatherCost(ArrayRef<Value *> VL);
496 /// \brief Set the Builder insert point to one after the last instruction in
498 void setInsertPointAfterBundle(ArrayRef<Value *> VL);
500 /// \returns a vector from a collection of scalars in \p VL.
501 Value *Gather(ArrayRef<Value *> VL, VectorType *Ty);
503 /// \returns whether the VectorizableTree is fully vectoriable and will
504 /// be beneficial even the tree height is tiny.
505 bool isFullyVectorizableTinyTree();
508 TreeEntry() : Scalars(), VectorizedValue(nullptr),
511 /// \returns true if the scalars in VL are equal to this entry.
512 bool isSame(ArrayRef<Value *> VL) const {
513 assert(VL.size() == Scalars.size() && "Invalid size");
514 return std::equal(VL.begin(), VL.end(), Scalars.begin());
517 /// A vector of scalars.
520 /// The Scalars are vectorized into this value. It is initialized to Null.
521 Value *VectorizedValue;
523 /// Do we need to gather this sequence ?
527 /// Create a new VectorizableTree entry.
528 TreeEntry *newTreeEntry(ArrayRef<Value *> VL, bool Vectorized) {
529 VectorizableTree.push_back(TreeEntry());
530 int idx = VectorizableTree.size() - 1;
531 TreeEntry *Last = &VectorizableTree[idx];
532 Last->Scalars.insert(Last->Scalars.begin(), VL.begin(), VL.end());
533 Last->NeedToGather = !Vectorized;
535 for (int i = 0, e = VL.size(); i != e; ++i) {
536 assert(!ScalarToTreeEntry.count(VL[i]) && "Scalar already in tree!");
537 ScalarToTreeEntry[VL[i]] = idx;
540 MustGather.insert(VL.begin(), VL.end());
545 /// -- Vectorization State --
546 /// Holds all of the tree entries.
547 std::vector<TreeEntry> VectorizableTree;
549 /// Maps a specific scalar to its tree entry.
550 SmallDenseMap<Value*, int> ScalarToTreeEntry;
552 /// A list of scalars that we found that we need to keep as scalars.
555 /// This POD struct describes one external user in the vectorized tree.
556 struct ExternalUser {
557 ExternalUser (Value *S, llvm::User *U, int L) :
558 Scalar(S), User(U), Lane(L){};
559 // Which scalar in our function.
561 // Which user that uses the scalar.
563 // Which lane does the scalar belong to.
566 typedef SmallVector<ExternalUser, 16> UserList;
568 /// Checks if two instructions may access the same memory.
570 /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
571 /// is invariant in the calling loop.
572 bool isAliased(const AliasAnalysis::Location &Loc1, Instruction *Inst1,
573 Instruction *Inst2) {
575 // First check if the result is already in the cache.
576 AliasCacheKey key = std::make_pair(Inst1, Inst2);
577 Optional<bool> &result = AliasCache[key];
578 if (result.hasValue()) {
579 return result.getValue();
581 AliasAnalysis::Location Loc2 = getLocation(Inst2, AA);
583 if (Loc1.Ptr && Loc2.Ptr) {
584 // Do the alias check.
585 aliased = AA->alias(Loc1, Loc2);
587 // Store the result in the cache.
592 typedef std::pair<Instruction *, Instruction *> AliasCacheKey;
594 /// Cache for alias results.
595 /// TODO: consider moving this to the AliasAnalysis itself.
596 DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
598 /// Removes an instruction from its block and eventually deletes it.
599 /// It's like Instruction::eraseFromParent() except that the actual deletion
600 /// is delayed until BoUpSLP is destructed.
601 /// This is required to ensure that there are no incorrect collisions in the
602 /// AliasCache, which can happen if a new instruction is allocated at the
603 /// same address as a previously deleted instruction.
604 void eraseInstruction(Instruction *I) {
605 I->removeFromParent();
606 I->dropAllReferences();
607 DeletedInstructions.push_back(std::unique_ptr<Instruction>(I));
610 /// Temporary store for deleted instructions. Instructions will be deleted
611 /// eventually when the BoUpSLP is destructed.
612 SmallVector<std::unique_ptr<Instruction>, 8> DeletedInstructions;
614 /// A list of values that need to extracted out of the tree.
615 /// This list holds pairs of (Internal Scalar : External User).
616 UserList ExternalUses;
618 /// Values used only by @llvm.assume calls.
619 SmallPtrSet<const Value *, 32> EphValues;
621 /// Holds all of the instructions that we gathered.
622 SetVector<Instruction *> GatherSeq;
623 /// A list of blocks that we are going to CSE.
624 SetVector<BasicBlock *> CSEBlocks;
626 /// Contains all scheduling relevant data for an instruction.
627 /// A ScheduleData either represents a single instruction or a member of an
628 /// instruction bundle (= a group of instructions which is combined into a
629 /// vector instruction).
630 struct ScheduleData {
632 // The initial value for the dependency counters. It means that the
633 // dependencies are not calculated yet.
634 enum { InvalidDeps = -1 };
637 : Inst(nullptr), FirstInBundle(nullptr), NextInBundle(nullptr),
638 NextLoadStore(nullptr), SchedulingRegionID(0), SchedulingPriority(0),
639 Dependencies(InvalidDeps), UnscheduledDeps(InvalidDeps),
640 UnscheduledDepsInBundle(InvalidDeps), IsScheduled(false) {}
642 void init(int BlockSchedulingRegionID) {
643 FirstInBundle = this;
644 NextInBundle = nullptr;
645 NextLoadStore = nullptr;
647 SchedulingRegionID = BlockSchedulingRegionID;
648 UnscheduledDepsInBundle = UnscheduledDeps;
652 /// Returns true if the dependency information has been calculated.
653 bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
655 /// Returns true for single instructions and for bundle representatives
656 /// (= the head of a bundle).
657 bool isSchedulingEntity() const { return FirstInBundle == this; }
659 /// Returns true if it represents an instruction bundle and not only a
660 /// single instruction.
661 bool isPartOfBundle() const {
662 return NextInBundle != nullptr || FirstInBundle != this;
665 /// Returns true if it is ready for scheduling, i.e. it has no more
666 /// unscheduled depending instructions/bundles.
667 bool isReady() const {
668 assert(isSchedulingEntity() &&
669 "can't consider non-scheduling entity for ready list");
670 return UnscheduledDepsInBundle == 0 && !IsScheduled;
673 /// Modifies the number of unscheduled dependencies, also updating it for
674 /// the whole bundle.
675 int incrementUnscheduledDeps(int Incr) {
676 UnscheduledDeps += Incr;
677 return FirstInBundle->UnscheduledDepsInBundle += Incr;
680 /// Sets the number of unscheduled dependencies to the number of
682 void resetUnscheduledDeps() {
683 incrementUnscheduledDeps(Dependencies - UnscheduledDeps);
686 /// Clears all dependency information.
687 void clearDependencies() {
688 Dependencies = InvalidDeps;
689 resetUnscheduledDeps();
690 MemoryDependencies.clear();
693 void dump(raw_ostream &os) const {
694 if (!isSchedulingEntity()) {
696 } else if (NextInBundle) {
698 ScheduleData *SD = NextInBundle;
700 os << ';' << *SD->Inst;
701 SD = SD->NextInBundle;
711 /// Points to the head in an instruction bundle (and always to this for
712 /// single instructions).
713 ScheduleData *FirstInBundle;
715 /// Single linked list of all instructions in a bundle. Null if it is a
716 /// single instruction.
717 ScheduleData *NextInBundle;
719 /// Single linked list of all memory instructions (e.g. load, store, call)
720 /// in the block - until the end of the scheduling region.
721 ScheduleData *NextLoadStore;
723 /// The dependent memory instructions.
724 /// This list is derived on demand in calculateDependencies().
725 SmallVector<ScheduleData *, 4> MemoryDependencies;
727 /// This ScheduleData is in the current scheduling region if this matches
728 /// the current SchedulingRegionID of BlockScheduling.
729 int SchedulingRegionID;
731 /// Used for getting a "good" final ordering of instructions.
732 int SchedulingPriority;
734 /// The number of dependencies. Constitutes of the number of users of the
735 /// instruction plus the number of dependent memory instructions (if any).
736 /// This value is calculated on demand.
737 /// If InvalidDeps, the number of dependencies is not calculated yet.
741 /// The number of dependencies minus the number of dependencies of scheduled
742 /// instructions. As soon as this is zero, the instruction/bundle gets ready
744 /// Note that this is negative as long as Dependencies is not calculated.
747 /// The sum of UnscheduledDeps in a bundle. Equals to UnscheduledDeps for
748 /// single instructions.
749 int UnscheduledDepsInBundle;
751 /// True if this instruction is scheduled (or considered as scheduled in the
757 friend raw_ostream &operator<<(raw_ostream &os,
758 const BoUpSLP::ScheduleData &SD);
761 /// Contains all scheduling data for a basic block.
763 struct BlockScheduling {
765 BlockScheduling(BasicBlock *BB)
766 : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize),
767 ScheduleStart(nullptr), ScheduleEnd(nullptr),
768 FirstLoadStoreInRegion(nullptr), LastLoadStoreInRegion(nullptr),
769 // Make sure that the initial SchedulingRegionID is greater than the
770 // initial SchedulingRegionID in ScheduleData (which is 0).
771 SchedulingRegionID(1) {}
775 ScheduleStart = nullptr;
776 ScheduleEnd = nullptr;
777 FirstLoadStoreInRegion = nullptr;
778 LastLoadStoreInRegion = nullptr;
780 // Make a new scheduling region, i.e. all existing ScheduleData is not
781 // in the new region yet.
782 ++SchedulingRegionID;
785 ScheduleData *getScheduleData(Value *V) {
786 ScheduleData *SD = ScheduleDataMap[V];
787 if (SD && SD->SchedulingRegionID == SchedulingRegionID)
792 bool isInSchedulingRegion(ScheduleData *SD) {
793 return SD->SchedulingRegionID == SchedulingRegionID;
796 /// Marks an instruction as scheduled and puts all dependent ready
797 /// instructions into the ready-list.
798 template <typename ReadyListType>
799 void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
800 SD->IsScheduled = true;
801 DEBUG(dbgs() << "SLP: schedule " << *SD << "\n");
803 ScheduleData *BundleMember = SD;
804 while (BundleMember) {
805 // Handle the def-use chain dependencies.
806 for (Use &U : BundleMember->Inst->operands()) {
807 ScheduleData *OpDef = getScheduleData(U.get());
808 if (OpDef && OpDef->hasValidDependencies() &&
809 OpDef->incrementUnscheduledDeps(-1) == 0) {
810 // There are no more unscheduled dependencies after decrementing,
811 // so we can put the dependent instruction into the ready list.
812 ScheduleData *DepBundle = OpDef->FirstInBundle;
813 assert(!DepBundle->IsScheduled &&
814 "already scheduled bundle gets ready");
815 ReadyList.insert(DepBundle);
816 DEBUG(dbgs() << "SLP: gets ready (def): " << *DepBundle << "\n");
819 // Handle the memory dependencies.
820 for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
821 if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
822 // There are no more unscheduled dependencies after decrementing,
823 // so we can put the dependent instruction into the ready list.
824 ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
825 assert(!DepBundle->IsScheduled &&
826 "already scheduled bundle gets ready");
827 ReadyList.insert(DepBundle);
828 DEBUG(dbgs() << "SLP: gets ready (mem): " << *DepBundle << "\n");
831 BundleMember = BundleMember->NextInBundle;
835 /// Put all instructions into the ReadyList which are ready for scheduling.
836 template <typename ReadyListType>
837 void initialFillReadyList(ReadyListType &ReadyList) {
838 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
839 ScheduleData *SD = getScheduleData(I);
840 if (SD->isSchedulingEntity() && SD->isReady()) {
841 ReadyList.insert(SD);
842 DEBUG(dbgs() << "SLP: initially in ready list: " << *I << "\n");
847 /// Checks if a bundle of instructions can be scheduled, i.e. has no
848 /// cyclic dependencies. This is only a dry-run, no instructions are
849 /// actually moved at this stage.
850 bool tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP);
852 /// Un-bundles a group of instructions.
853 void cancelScheduling(ArrayRef<Value *> VL);
855 /// Extends the scheduling region so that V is inside the region.
856 void extendSchedulingRegion(Value *V);
858 /// Initialize the ScheduleData structures for new instructions in the
859 /// scheduling region.
860 void initScheduleData(Instruction *FromI, Instruction *ToI,
861 ScheduleData *PrevLoadStore,
862 ScheduleData *NextLoadStore);
864 /// Updates the dependency information of a bundle and of all instructions/
865 /// bundles which depend on the original bundle.
866 void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
869 /// Sets all instruction in the scheduling region to un-scheduled.
870 void resetSchedule();
874 /// Simple memory allocation for ScheduleData.
875 std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
877 /// The size of a ScheduleData array in ScheduleDataChunks.
880 /// The allocator position in the current chunk, which is the last entry
881 /// of ScheduleDataChunks.
884 /// Attaches ScheduleData to Instruction.
885 /// Note that the mapping survives during all vectorization iterations, i.e.
886 /// ScheduleData structures are recycled.
887 DenseMap<Value *, ScheduleData *> ScheduleDataMap;
889 struct ReadyList : SmallVector<ScheduleData *, 8> {
890 void insert(ScheduleData *SD) { push_back(SD); }
893 /// The ready-list for scheduling (only used for the dry-run).
894 ReadyList ReadyInsts;
896 /// The first instruction of the scheduling region.
897 Instruction *ScheduleStart;
899 /// The first instruction _after_ the scheduling region.
900 Instruction *ScheduleEnd;
902 /// The first memory accessing instruction in the scheduling region
904 ScheduleData *FirstLoadStoreInRegion;
906 /// The last memory accessing instruction in the scheduling region
908 ScheduleData *LastLoadStoreInRegion;
910 /// The ID of the scheduling region. For a new vectorization iteration this
911 /// is incremented which "removes" all ScheduleData from the region.
912 int SchedulingRegionID;
915 /// Attaches the BlockScheduling structures to basic blocks.
916 MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
918 /// Performs the "real" scheduling. Done before vectorization is actually
919 /// performed in a basic block.
920 void scheduleBlock(BlockScheduling *BS);
922 /// List of users to ignore during scheduling and that don't need extracting.
923 ArrayRef<Value *> UserIgnoreList;
925 // Number of load-bundles, which contain consecutive loads.
926 int NumLoadsWantToKeepOrder;
928 // Number of load-bundles of size 2, which are consecutive loads if reversed.
929 int NumLoadsWantToChangeOrder;
931 // Analysis and block reference.
934 const DataLayout *DL;
935 TargetTransformInfo *TTI;
936 TargetLibraryInfo *TLI;
940 /// Instruction builder to construct the vectorized tree.
945 raw_ostream &operator<<(raw_ostream &os, const BoUpSLP::ScheduleData &SD) {
951 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
952 ArrayRef<Value *> UserIgnoreLst) {
954 UserIgnoreList = UserIgnoreLst;
955 if (!getSameType(Roots))
957 buildTree_rec(Roots, 0);
959 // Collect the values that we need to extract from the tree.
960 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
961 TreeEntry *Entry = &VectorizableTree[EIdx];
964 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
965 Value *Scalar = Entry->Scalars[Lane];
967 // No need to handle users of gathered values.
968 if (Entry->NeedToGather)
971 for (User *U : Scalar->users()) {
972 DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
974 Instruction *UserInst = dyn_cast<Instruction>(U);
978 // Skip in-tree scalars that become vectors
979 if (ScalarToTreeEntry.count(U)) {
980 int Idx = ScalarToTreeEntry[U];
981 TreeEntry *UseEntry = &VectorizableTree[Idx];
982 Value *UseScalar = UseEntry->Scalars[0];
983 // Some in-tree scalars will remain as scalar in vectorized
984 // instructions. If that is the case, the one in Lane 0 will
986 if (UseScalar != U ||
987 !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
988 DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
990 assert(!VectorizableTree[Idx].NeedToGather && "Bad state");
995 // Ignore users in the user ignore list.
996 if (std::find(UserIgnoreList.begin(), UserIgnoreList.end(), UserInst) !=
997 UserIgnoreList.end())
1000 DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane " <<
1001 Lane << " from " << *Scalar << ".\n");
1002 ExternalUses.push_back(ExternalUser(Scalar, U, Lane));
1009 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth) {
1010 bool SameTy = getSameType(VL); (void)SameTy;
1011 bool isAltShuffle = false;
1012 assert(SameTy && "Invalid types!");
1014 if (Depth == RecursionMaxDepth) {
1015 DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
1016 newTreeEntry(VL, false);
1020 // Don't handle vectors.
1021 if (VL[0]->getType()->isVectorTy()) {
1022 DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
1023 newTreeEntry(VL, false);
1027 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1028 if (SI->getValueOperand()->getType()->isVectorTy()) {
1029 DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
1030 newTreeEntry(VL, false);
1033 unsigned Opcode = getSameOpcode(VL);
1035 // Check that this shuffle vector refers to the alternate
1036 // sequence of opcodes.
1037 if (Opcode == Instruction::ShuffleVector) {
1038 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
1039 unsigned Op = I0->getOpcode();
1040 if (Op != Instruction::ShuffleVector)
1041 isAltShuffle = true;
1044 // If all of the operands are identical or constant we have a simple solution.
1045 if (allConstant(VL) || isSplat(VL) || !getSameBlock(VL) || !Opcode) {
1046 DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
1047 newTreeEntry(VL, false);
1051 // We now know that this is a vector of instructions of the same type from
1054 // Don't vectorize ephemeral values.
1055 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1056 if (EphValues.count(VL[i])) {
1057 DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
1058 ") is ephemeral.\n");
1059 newTreeEntry(VL, false);
1064 // Check if this is a duplicate of another entry.
1065 if (ScalarToTreeEntry.count(VL[0])) {
1066 int Idx = ScalarToTreeEntry[VL[0]];
1067 TreeEntry *E = &VectorizableTree[Idx];
1068 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1069 DEBUG(dbgs() << "SLP: \tChecking bundle: " << *VL[i] << ".\n");
1070 if (E->Scalars[i] != VL[i]) {
1071 DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
1072 newTreeEntry(VL, false);
1076 DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *VL[0] << ".\n");
1080 // Check that none of the instructions in the bundle are already in the tree.
1081 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1082 if (ScalarToTreeEntry.count(VL[i])) {
1083 DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
1084 ") is already in tree.\n");
1085 newTreeEntry(VL, false);
1090 // If any of the scalars is marked as a value that needs to stay scalar then
1091 // we need to gather the scalars.
1092 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1093 if (MustGather.count(VL[i])) {
1094 DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
1095 newTreeEntry(VL, false);
1100 // Check that all of the users of the scalars that we want to vectorize are
1102 Instruction *VL0 = cast<Instruction>(VL[0]);
1103 BasicBlock *BB = cast<Instruction>(VL0)->getParent();
1105 if (!DT->isReachableFromEntry(BB)) {
1106 // Don't go into unreachable blocks. They may contain instructions with
1107 // dependency cycles which confuse the final scheduling.
1108 DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
1109 newTreeEntry(VL, false);
1113 // Check that every instructions appears once in this bundle.
1114 for (unsigned i = 0, e = VL.size(); i < e; ++i)
1115 for (unsigned j = i+1; j < e; ++j)
1116 if (VL[i] == VL[j]) {
1117 DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
1118 newTreeEntry(VL, false);
1122 auto &BSRef = BlocksSchedules[BB];
1124 BSRef = llvm::make_unique<BlockScheduling>(BB);
1126 BlockScheduling &BS = *BSRef.get();
1128 if (!BS.tryScheduleBundle(VL, this)) {
1129 DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
1130 BS.cancelScheduling(VL);
1131 newTreeEntry(VL, false);
1134 DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
1137 case Instruction::PHI: {
1138 PHINode *PH = dyn_cast<PHINode>(VL0);
1140 // Check for terminator values (e.g. invoke).
1141 for (unsigned j = 0; j < VL.size(); ++j)
1142 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1143 TerminatorInst *Term = dyn_cast<TerminatorInst>(
1144 cast<PHINode>(VL[j])->getIncomingValueForBlock(PH->getIncomingBlock(i)));
1146 DEBUG(dbgs() << "SLP: Need to swizzle PHINodes (TerminatorInst use).\n");
1147 BS.cancelScheduling(VL);
1148 newTreeEntry(VL, false);
1153 newTreeEntry(VL, true);
1154 DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
1156 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1158 // Prepare the operand vector.
1159 for (unsigned j = 0; j < VL.size(); ++j)
1160 Operands.push_back(cast<PHINode>(VL[j])->getIncomingValueForBlock(
1161 PH->getIncomingBlock(i)));
1163 buildTree_rec(Operands, Depth + 1);
1167 case Instruction::ExtractElement: {
1168 bool Reuse = CanReuseExtract(VL);
1170 DEBUG(dbgs() << "SLP: Reusing extract sequence.\n");
1172 BS.cancelScheduling(VL);
1174 newTreeEntry(VL, Reuse);
1177 case Instruction::Load: {
1178 // Check if the loads are consecutive or of we need to swizzle them.
1179 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i) {
1180 LoadInst *L = cast<LoadInst>(VL[i]);
1181 if (!L->isSimple()) {
1182 BS.cancelScheduling(VL);
1183 newTreeEntry(VL, false);
1184 DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
1187 if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
1188 if (VL.size() == 2 && isConsecutiveAccess(VL[1], VL[0])) {
1189 ++NumLoadsWantToChangeOrder;
1191 BS.cancelScheduling(VL);
1192 newTreeEntry(VL, false);
1193 DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
1197 ++NumLoadsWantToKeepOrder;
1198 newTreeEntry(VL, true);
1199 DEBUG(dbgs() << "SLP: added a vector of loads.\n");
1202 case Instruction::ZExt:
1203 case Instruction::SExt:
1204 case Instruction::FPToUI:
1205 case Instruction::FPToSI:
1206 case Instruction::FPExt:
1207 case Instruction::PtrToInt:
1208 case Instruction::IntToPtr:
1209 case Instruction::SIToFP:
1210 case Instruction::UIToFP:
1211 case Instruction::Trunc:
1212 case Instruction::FPTrunc:
1213 case Instruction::BitCast: {
1214 Type *SrcTy = VL0->getOperand(0)->getType();
1215 for (unsigned i = 0; i < VL.size(); ++i) {
1216 Type *Ty = cast<Instruction>(VL[i])->getOperand(0)->getType();
1217 if (Ty != SrcTy || Ty->isAggregateType() || Ty->isVectorTy()) {
1218 BS.cancelScheduling(VL);
1219 newTreeEntry(VL, false);
1220 DEBUG(dbgs() << "SLP: Gathering casts with different src types.\n");
1224 newTreeEntry(VL, true);
1225 DEBUG(dbgs() << "SLP: added a vector of casts.\n");
1227 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1229 // Prepare the operand vector.
1230 for (unsigned j = 0; j < VL.size(); ++j)
1231 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1233 buildTree_rec(Operands, Depth+1);
1237 case Instruction::ICmp:
1238 case Instruction::FCmp: {
1239 // Check that all of the compares have the same predicate.
1240 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
1241 Type *ComparedTy = cast<Instruction>(VL[0])->getOperand(0)->getType();
1242 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
1243 CmpInst *Cmp = cast<CmpInst>(VL[i]);
1244 if (Cmp->getPredicate() != P0 ||
1245 Cmp->getOperand(0)->getType() != ComparedTy) {
1246 BS.cancelScheduling(VL);
1247 newTreeEntry(VL, false);
1248 DEBUG(dbgs() << "SLP: Gathering cmp with different predicate.\n");
1253 newTreeEntry(VL, true);
1254 DEBUG(dbgs() << "SLP: added a vector of compares.\n");
1256 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1258 // Prepare the operand vector.
1259 for (unsigned j = 0; j < VL.size(); ++j)
1260 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1262 buildTree_rec(Operands, Depth+1);
1266 case Instruction::Select:
1267 case Instruction::Add:
1268 case Instruction::FAdd:
1269 case Instruction::Sub:
1270 case Instruction::FSub:
1271 case Instruction::Mul:
1272 case Instruction::FMul:
1273 case Instruction::UDiv:
1274 case Instruction::SDiv:
1275 case Instruction::FDiv:
1276 case Instruction::URem:
1277 case Instruction::SRem:
1278 case Instruction::FRem:
1279 case Instruction::Shl:
1280 case Instruction::LShr:
1281 case Instruction::AShr:
1282 case Instruction::And:
1283 case Instruction::Or:
1284 case Instruction::Xor: {
1285 newTreeEntry(VL, true);
1286 DEBUG(dbgs() << "SLP: added a vector of bin op.\n");
1288 // Sort operands of the instructions so that each side is more likely to
1289 // have the same opcode.
1290 if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
1291 ValueList Left, Right;
1292 reorderInputsAccordingToOpcode(VL, Left, Right);
1293 buildTree_rec(Left, Depth + 1);
1294 buildTree_rec(Right, Depth + 1);
1298 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1300 // Prepare the operand vector.
1301 for (unsigned j = 0; j < VL.size(); ++j)
1302 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1304 buildTree_rec(Operands, Depth+1);
1308 case Instruction::GetElementPtr: {
1309 // We don't combine GEPs with complicated (nested) indexing.
1310 for (unsigned j = 0; j < VL.size(); ++j) {
1311 if (cast<Instruction>(VL[j])->getNumOperands() != 2) {
1312 DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
1313 BS.cancelScheduling(VL);
1314 newTreeEntry(VL, false);
1319 // We can't combine several GEPs into one vector if they operate on
1321 Type *Ty0 = cast<Instruction>(VL0)->getOperand(0)->getType();
1322 for (unsigned j = 0; j < VL.size(); ++j) {
1323 Type *CurTy = cast<Instruction>(VL[j])->getOperand(0)->getType();
1325 DEBUG(dbgs() << "SLP: not-vectorizable GEP (different types).\n");
1326 BS.cancelScheduling(VL);
1327 newTreeEntry(VL, false);
1332 // We don't combine GEPs with non-constant indexes.
1333 for (unsigned j = 0; j < VL.size(); ++j) {
1334 auto Op = cast<Instruction>(VL[j])->getOperand(1);
1335 if (!isa<ConstantInt>(Op)) {
1337 dbgs() << "SLP: not-vectorizable GEP (non-constant indexes).\n");
1338 BS.cancelScheduling(VL);
1339 newTreeEntry(VL, false);
1344 newTreeEntry(VL, true);
1345 DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
1346 for (unsigned i = 0, e = 2; i < e; ++i) {
1348 // Prepare the operand vector.
1349 for (unsigned j = 0; j < VL.size(); ++j)
1350 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1352 buildTree_rec(Operands, Depth + 1);
1356 case Instruction::Store: {
1357 // Check if the stores are consecutive or of we need to swizzle them.
1358 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
1359 if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
1360 BS.cancelScheduling(VL);
1361 newTreeEntry(VL, false);
1362 DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
1366 newTreeEntry(VL, true);
1367 DEBUG(dbgs() << "SLP: added a vector of stores.\n");
1370 for (unsigned j = 0; j < VL.size(); ++j)
1371 Operands.push_back(cast<Instruction>(VL[j])->getOperand(0));
1373 buildTree_rec(Operands, Depth + 1);
1376 case Instruction::Call: {
1377 // Check if the calls are all to the same vectorizable intrinsic.
1378 CallInst *CI = cast<CallInst>(VL[0]);
1379 // Check if this is an Intrinsic call or something that can be
1380 // represented by an intrinsic call
1381 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
1382 if (!isTriviallyVectorizable(ID)) {
1383 BS.cancelScheduling(VL);
1384 newTreeEntry(VL, false);
1385 DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
1388 Function *Int = CI->getCalledFunction();
1389 Value *A1I = nullptr;
1390 if (hasVectorInstrinsicScalarOpd(ID, 1))
1391 A1I = CI->getArgOperand(1);
1392 for (unsigned i = 1, e = VL.size(); i != e; ++i) {
1393 CallInst *CI2 = dyn_cast<CallInst>(VL[i]);
1394 if (!CI2 || CI2->getCalledFunction() != Int ||
1395 getIntrinsicIDForCall(CI2, TLI) != ID) {
1396 BS.cancelScheduling(VL);
1397 newTreeEntry(VL, false);
1398 DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *VL[i]
1402 // ctlz,cttz and powi are special intrinsics whose second argument
1403 // should be same in order for them to be vectorized.
1404 if (hasVectorInstrinsicScalarOpd(ID, 1)) {
1405 Value *A1J = CI2->getArgOperand(1);
1407 BS.cancelScheduling(VL);
1408 newTreeEntry(VL, false);
1409 DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
1410 << " argument "<< A1I<<"!=" << A1J
1417 newTreeEntry(VL, true);
1418 for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i) {
1420 // Prepare the operand vector.
1421 for (unsigned j = 0; j < VL.size(); ++j) {
1422 CallInst *CI2 = dyn_cast<CallInst>(VL[j]);
1423 Operands.push_back(CI2->getArgOperand(i));
1425 buildTree_rec(Operands, Depth + 1);
1429 case Instruction::ShuffleVector: {
1430 // If this is not an alternate sequence of opcode like add-sub
1431 // then do not vectorize this instruction.
1432 if (!isAltShuffle) {
1433 BS.cancelScheduling(VL);
1434 newTreeEntry(VL, false);
1435 DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
1438 newTreeEntry(VL, true);
1439 DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
1440 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1442 // Prepare the operand vector.
1443 for (unsigned j = 0; j < VL.size(); ++j)
1444 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1446 buildTree_rec(Operands, Depth + 1);
1451 BS.cancelScheduling(VL);
1452 newTreeEntry(VL, false);
1453 DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
1458 int BoUpSLP::getEntryCost(TreeEntry *E) {
1459 ArrayRef<Value*> VL = E->Scalars;
1461 Type *ScalarTy = VL[0]->getType();
1462 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1463 ScalarTy = SI->getValueOperand()->getType();
1464 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1466 if (E->NeedToGather) {
1467 if (allConstant(VL))
1470 return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
1472 return getGatherCost(E->Scalars);
1474 unsigned Opcode = getSameOpcode(VL);
1475 assert(Opcode && getSameType(VL) && getSameBlock(VL) && "Invalid VL");
1476 Instruction *VL0 = cast<Instruction>(VL[0]);
1478 case Instruction::PHI: {
1481 case Instruction::ExtractElement: {
1482 if (CanReuseExtract(VL)) {
1484 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
1485 ExtractElementInst *E = cast<ExtractElementInst>(VL[i]);
1487 // Take credit for instruction that will become dead.
1489 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, i);
1493 return getGatherCost(VecTy);
1495 case Instruction::ZExt:
1496 case Instruction::SExt:
1497 case Instruction::FPToUI:
1498 case Instruction::FPToSI:
1499 case Instruction::FPExt:
1500 case Instruction::PtrToInt:
1501 case Instruction::IntToPtr:
1502 case Instruction::SIToFP:
1503 case Instruction::UIToFP:
1504 case Instruction::Trunc:
1505 case Instruction::FPTrunc:
1506 case Instruction::BitCast: {
1507 Type *SrcTy = VL0->getOperand(0)->getType();
1509 // Calculate the cost of this instruction.
1510 int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(),
1511 VL0->getType(), SrcTy);
1513 VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
1514 int VecCost = TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy);
1515 return VecCost - ScalarCost;
1517 case Instruction::FCmp:
1518 case Instruction::ICmp:
1519 case Instruction::Select:
1520 case Instruction::Add:
1521 case Instruction::FAdd:
1522 case Instruction::Sub:
1523 case Instruction::FSub:
1524 case Instruction::Mul:
1525 case Instruction::FMul:
1526 case Instruction::UDiv:
1527 case Instruction::SDiv:
1528 case Instruction::FDiv:
1529 case Instruction::URem:
1530 case Instruction::SRem:
1531 case Instruction::FRem:
1532 case Instruction::Shl:
1533 case Instruction::LShr:
1534 case Instruction::AShr:
1535 case Instruction::And:
1536 case Instruction::Or:
1537 case Instruction::Xor: {
1538 // Calculate the cost of this instruction.
1541 if (Opcode == Instruction::FCmp || Opcode == Instruction::ICmp ||
1542 Opcode == Instruction::Select) {
1543 VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
1544 ScalarCost = VecTy->getNumElements() *
1545 TTI->getCmpSelInstrCost(Opcode, ScalarTy, Builder.getInt1Ty());
1546 VecCost = TTI->getCmpSelInstrCost(Opcode, VecTy, MaskTy);
1548 // Certain instructions can be cheaper to vectorize if they have a
1549 // constant second vector operand.
1550 TargetTransformInfo::OperandValueKind Op1VK =
1551 TargetTransformInfo::OK_AnyValue;
1552 TargetTransformInfo::OperandValueKind Op2VK =
1553 TargetTransformInfo::OK_UniformConstantValue;
1554 TargetTransformInfo::OperandValueProperties Op1VP =
1555 TargetTransformInfo::OP_None;
1556 TargetTransformInfo::OperandValueProperties Op2VP =
1557 TargetTransformInfo::OP_None;
1559 // If all operands are exactly the same ConstantInt then set the
1560 // operand kind to OK_UniformConstantValue.
1561 // If instead not all operands are constants, then set the operand kind
1562 // to OK_AnyValue. If all operands are constants but not the same,
1563 // then set the operand kind to OK_NonUniformConstantValue.
1564 ConstantInt *CInt = nullptr;
1565 for (unsigned i = 0; i < VL.size(); ++i) {
1566 const Instruction *I = cast<Instruction>(VL[i]);
1567 if (!isa<ConstantInt>(I->getOperand(1))) {
1568 Op2VK = TargetTransformInfo::OK_AnyValue;
1572 CInt = cast<ConstantInt>(I->getOperand(1));
1575 if (Op2VK == TargetTransformInfo::OK_UniformConstantValue &&
1576 CInt != cast<ConstantInt>(I->getOperand(1)))
1577 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
1579 // FIXME: Currently cost of model modification for division by
1580 // power of 2 is handled only for X86. Add support for other targets.
1581 if (Op2VK == TargetTransformInfo::OK_UniformConstantValue && CInt &&
1582 CInt->getValue().isPowerOf2())
1583 Op2VP = TargetTransformInfo::OP_PowerOf2;
1585 ScalarCost = VecTy->getNumElements() *
1586 TTI->getArithmeticInstrCost(Opcode, ScalarTy, Op1VK, Op2VK,
1588 VecCost = TTI->getArithmeticInstrCost(Opcode, VecTy, Op1VK, Op2VK,
1591 return VecCost - ScalarCost;
1593 case Instruction::GetElementPtr: {
1594 TargetTransformInfo::OperandValueKind Op1VK =
1595 TargetTransformInfo::OK_AnyValue;
1596 TargetTransformInfo::OperandValueKind Op2VK =
1597 TargetTransformInfo::OK_UniformConstantValue;
1600 VecTy->getNumElements() *
1601 TTI->getArithmeticInstrCost(Instruction::Add, ScalarTy, Op1VK, Op2VK);
1603 TTI->getArithmeticInstrCost(Instruction::Add, VecTy, Op1VK, Op2VK);
1605 return VecCost - ScalarCost;
1607 case Instruction::Load: {
1608 // Cost of wide load - cost of scalar loads.
1609 int ScalarLdCost = VecTy->getNumElements() *
1610 TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
1611 int VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, 1, 0);
1612 return VecLdCost - ScalarLdCost;
1614 case Instruction::Store: {
1615 // We know that we can merge the stores. Calculate the cost.
1616 int ScalarStCost = VecTy->getNumElements() *
1617 TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
1618 int VecStCost = TTI->getMemoryOpCost(Instruction::Store, VecTy, 1, 0);
1619 return VecStCost - ScalarStCost;
1621 case Instruction::Call: {
1622 CallInst *CI = cast<CallInst>(VL0);
1623 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
1625 // Calculate the cost of the scalar and vector calls.
1626 SmallVector<Type*, 4> ScalarTys, VecTys;
1627 for (unsigned op = 0, opc = CI->getNumArgOperands(); op!= opc; ++op) {
1628 ScalarTys.push_back(CI->getArgOperand(op)->getType());
1629 VecTys.push_back(VectorType::get(CI->getArgOperand(op)->getType(),
1630 VecTy->getNumElements()));
1633 int ScalarCallCost = VecTy->getNumElements() *
1634 TTI->getIntrinsicInstrCost(ID, ScalarTy, ScalarTys);
1636 int VecCallCost = TTI->getIntrinsicInstrCost(ID, VecTy, VecTys);
1638 DEBUG(dbgs() << "SLP: Call cost "<< VecCallCost - ScalarCallCost
1639 << " (" << VecCallCost << "-" << ScalarCallCost << ")"
1640 << " for " << *CI << "\n");
1642 return VecCallCost - ScalarCallCost;
1644 case Instruction::ShuffleVector: {
1645 TargetTransformInfo::OperandValueKind Op1VK =
1646 TargetTransformInfo::OK_AnyValue;
1647 TargetTransformInfo::OperandValueKind Op2VK =
1648 TargetTransformInfo::OK_AnyValue;
1651 for (unsigned i = 0; i < VL.size(); ++i) {
1652 Instruction *I = cast<Instruction>(VL[i]);
1656 TTI->getArithmeticInstrCost(I->getOpcode(), ScalarTy, Op1VK, Op2VK);
1658 // VecCost is equal to sum of the cost of creating 2 vectors
1659 // and the cost of creating shuffle.
1660 Instruction *I0 = cast<Instruction>(VL[0]);
1662 TTI->getArithmeticInstrCost(I0->getOpcode(), VecTy, Op1VK, Op2VK);
1663 Instruction *I1 = cast<Instruction>(VL[1]);
1665 TTI->getArithmeticInstrCost(I1->getOpcode(), VecTy, Op1VK, Op2VK);
1667 TTI->getShuffleCost(TargetTransformInfo::SK_Alternate, VecTy, 0);
1668 return VecCost - ScalarCost;
1671 llvm_unreachable("Unknown instruction");
1675 bool BoUpSLP::isFullyVectorizableTinyTree() {
1676 DEBUG(dbgs() << "SLP: Check whether the tree with height " <<
1677 VectorizableTree.size() << " is fully vectorizable .\n");
1679 // We only handle trees of height 2.
1680 if (VectorizableTree.size() != 2)
1683 // Handle splat stores.
1684 if (!VectorizableTree[0].NeedToGather && isSplat(VectorizableTree[1].Scalars))
1687 // Gathering cost would be too much for tiny trees.
1688 if (VectorizableTree[0].NeedToGather || VectorizableTree[1].NeedToGather)
1694 int BoUpSLP::getSpillCost() {
1695 // Walk from the bottom of the tree to the top, tracking which values are
1696 // live. When we see a call instruction that is not part of our tree,
1697 // query TTI to see if there is a cost to keeping values live over it
1698 // (for example, if spills and fills are required).
1699 unsigned BundleWidth = VectorizableTree.front().Scalars.size();
1702 SmallPtrSet<Instruction*, 4> LiveValues;
1703 Instruction *PrevInst = nullptr;
1705 for (unsigned N = 0; N < VectorizableTree.size(); ++N) {
1706 Instruction *Inst = dyn_cast<Instruction>(VectorizableTree[N].Scalars[0]);
1716 dbgs() << "SLP: #LV: " << LiveValues.size();
1717 for (auto *X : LiveValues)
1718 dbgs() << " " << X->getName();
1719 dbgs() << ", Looking at ";
1723 // Update LiveValues.
1724 LiveValues.erase(PrevInst);
1725 for (auto &J : PrevInst->operands()) {
1726 if (isa<Instruction>(&*J) && ScalarToTreeEntry.count(&*J))
1727 LiveValues.insert(cast<Instruction>(&*J));
1730 // Now find the sequence of instructions between PrevInst and Inst.
1731 BasicBlock::reverse_iterator InstIt(Inst), PrevInstIt(PrevInst);
1733 while (InstIt != PrevInstIt) {
1734 if (PrevInstIt == PrevInst->getParent()->rend()) {
1735 PrevInstIt = Inst->getParent()->rbegin();
1739 if (isa<CallInst>(&*PrevInstIt) && &*PrevInstIt != PrevInst) {
1740 SmallVector<Type*, 4> V;
1741 for (auto *II : LiveValues)
1742 V.push_back(VectorType::get(II->getType(), BundleWidth));
1743 Cost += TTI->getCostOfKeepingLiveOverCall(V);
1752 DEBUG(dbgs() << "SLP: SpillCost=" << Cost << "\n");
1756 int BoUpSLP::getTreeCost() {
1758 DEBUG(dbgs() << "SLP: Calculating cost for tree of size " <<
1759 VectorizableTree.size() << ".\n");
1761 // We only vectorize tiny trees if it is fully vectorizable.
1762 if (VectorizableTree.size() < 3 && !isFullyVectorizableTinyTree()) {
1763 if (VectorizableTree.empty()) {
1764 assert(!ExternalUses.size() && "We should not have any external users");
1769 unsigned BundleWidth = VectorizableTree[0].Scalars.size();
1771 for (unsigned i = 0, e = VectorizableTree.size(); i != e; ++i) {
1772 int C = getEntryCost(&VectorizableTree[i]);
1773 DEBUG(dbgs() << "SLP: Adding cost " << C << " for bundle that starts with "
1774 << *VectorizableTree[i].Scalars[0] << " .\n");
1778 SmallSet<Value *, 16> ExtractCostCalculated;
1779 int ExtractCost = 0;
1780 for (UserList::iterator I = ExternalUses.begin(), E = ExternalUses.end();
1782 // We only add extract cost once for the same scalar.
1783 if (!ExtractCostCalculated.insert(I->Scalar).second)
1786 // Uses by ephemeral values are free (because the ephemeral value will be
1787 // removed prior to code generation, and so the extraction will be
1788 // removed as well).
1789 if (EphValues.count(I->User))
1792 VectorType *VecTy = VectorType::get(I->Scalar->getType(), BundleWidth);
1793 ExtractCost += TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy,
1797 Cost += getSpillCost();
1799 DEBUG(dbgs() << "SLP: Total Cost " << Cost + ExtractCost<< ".\n");
1800 return Cost + ExtractCost;
1803 int BoUpSLP::getGatherCost(Type *Ty) {
1805 for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
1806 Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
1810 int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) {
1811 // Find the type of the operands in VL.
1812 Type *ScalarTy = VL[0]->getType();
1813 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1814 ScalarTy = SI->getValueOperand()->getType();
1815 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1816 // Find the cost of inserting/extracting values from the vector.
1817 return getGatherCost(VecTy);
1820 Value *BoUpSLP::getPointerOperand(Value *I) {
1821 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1822 return LI->getPointerOperand();
1823 if (StoreInst *SI = dyn_cast<StoreInst>(I))
1824 return SI->getPointerOperand();
1828 unsigned BoUpSLP::getAddressSpaceOperand(Value *I) {
1829 if (LoadInst *L = dyn_cast<LoadInst>(I))
1830 return L->getPointerAddressSpace();
1831 if (StoreInst *S = dyn_cast<StoreInst>(I))
1832 return S->getPointerAddressSpace();
1836 bool BoUpSLP::isConsecutiveAccess(Value *A, Value *B) {
1837 Value *PtrA = getPointerOperand(A);
1838 Value *PtrB = getPointerOperand(B);
1839 unsigned ASA = getAddressSpaceOperand(A);
1840 unsigned ASB = getAddressSpaceOperand(B);
1842 // Check that the address spaces match and that the pointers are valid.
1843 if (!PtrA || !PtrB || (ASA != ASB))
1846 // Make sure that A and B are different pointers of the same type.
1847 if (PtrA == PtrB || PtrA->getType() != PtrB->getType())
1850 unsigned PtrBitWidth = DL->getPointerSizeInBits(ASA);
1851 Type *Ty = cast<PointerType>(PtrA->getType())->getElementType();
1852 APInt Size(PtrBitWidth, DL->getTypeStoreSize(Ty));
1854 APInt OffsetA(PtrBitWidth, 0), OffsetB(PtrBitWidth, 0);
1855 PtrA = PtrA->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetA);
1856 PtrB = PtrB->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetB);
1858 APInt OffsetDelta = OffsetB - OffsetA;
1860 // Check if they are based on the same pointer. That makes the offsets
1863 return OffsetDelta == Size;
1865 // Compute the necessary base pointer delta to have the necessary final delta
1866 // equal to the size.
1867 APInt BaseDelta = Size - OffsetDelta;
1869 // Otherwise compute the distance with SCEV between the base pointers.
1870 const SCEV *PtrSCEVA = SE->getSCEV(PtrA);
1871 const SCEV *PtrSCEVB = SE->getSCEV(PtrB);
1872 const SCEV *C = SE->getConstant(BaseDelta);
1873 const SCEV *X = SE->getAddExpr(PtrSCEVA, C);
1874 return X == PtrSCEVB;
1877 void BoUpSLP::setInsertPointAfterBundle(ArrayRef<Value *> VL) {
1878 Instruction *VL0 = cast<Instruction>(VL[0]);
1879 BasicBlock::iterator NextInst = VL0;
1881 Builder.SetInsertPoint(VL0->getParent(), NextInst);
1882 Builder.SetCurrentDebugLocation(VL0->getDebugLoc());
1885 Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
1886 Value *Vec = UndefValue::get(Ty);
1887 // Generate the 'InsertElement' instruction.
1888 for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
1889 Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
1890 if (Instruction *Insrt = dyn_cast<Instruction>(Vec)) {
1891 GatherSeq.insert(Insrt);
1892 CSEBlocks.insert(Insrt->getParent());
1894 // Add to our 'need-to-extract' list.
1895 if (ScalarToTreeEntry.count(VL[i])) {
1896 int Idx = ScalarToTreeEntry[VL[i]];
1897 TreeEntry *E = &VectorizableTree[Idx];
1898 // Find which lane we need to extract.
1900 for (unsigned Lane = 0, LE = VL.size(); Lane != LE; ++Lane) {
1901 // Is this the lane of the scalar that we are looking for ?
1902 if (E->Scalars[Lane] == VL[i]) {
1907 assert(FoundLane >= 0 && "Could not find the correct lane");
1908 ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
1916 Value *BoUpSLP::alreadyVectorized(ArrayRef<Value *> VL) const {
1917 SmallDenseMap<Value*, int>::const_iterator Entry
1918 = ScalarToTreeEntry.find(VL[0]);
1919 if (Entry != ScalarToTreeEntry.end()) {
1920 int Idx = Entry->second;
1921 const TreeEntry *En = &VectorizableTree[Idx];
1922 if (En->isSame(VL) && En->VectorizedValue)
1923 return En->VectorizedValue;
1928 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
1929 if (ScalarToTreeEntry.count(VL[0])) {
1930 int Idx = ScalarToTreeEntry[VL[0]];
1931 TreeEntry *E = &VectorizableTree[Idx];
1933 return vectorizeTree(E);
1936 Type *ScalarTy = VL[0]->getType();
1937 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1938 ScalarTy = SI->getValueOperand()->getType();
1939 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1941 return Gather(VL, VecTy);
1944 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
1945 IRBuilder<>::InsertPointGuard Guard(Builder);
1947 if (E->VectorizedValue) {
1948 DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
1949 return E->VectorizedValue;
1952 Instruction *VL0 = cast<Instruction>(E->Scalars[0]);
1953 Type *ScalarTy = VL0->getType();
1954 if (StoreInst *SI = dyn_cast<StoreInst>(VL0))
1955 ScalarTy = SI->getValueOperand()->getType();
1956 VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size());
1958 if (E->NeedToGather) {
1959 setInsertPointAfterBundle(E->Scalars);
1960 return Gather(E->Scalars, VecTy);
1963 unsigned Opcode = getSameOpcode(E->Scalars);
1966 case Instruction::PHI: {
1967 PHINode *PH = dyn_cast<PHINode>(VL0);
1968 Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
1969 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1970 PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
1971 E->VectorizedValue = NewPhi;
1973 // PHINodes may have multiple entries from the same block. We want to
1974 // visit every block once.
1975 SmallSet<BasicBlock*, 4> VisitedBBs;
1977 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1979 BasicBlock *IBB = PH->getIncomingBlock(i);
1981 if (!VisitedBBs.insert(IBB).second) {
1982 NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
1986 // Prepare the operand vector.
1987 for (unsigned j = 0; j < E->Scalars.size(); ++j)
1988 Operands.push_back(cast<PHINode>(E->Scalars[j])->
1989 getIncomingValueForBlock(IBB));
1991 Builder.SetInsertPoint(IBB->getTerminator());
1992 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1993 Value *Vec = vectorizeTree(Operands);
1994 NewPhi->addIncoming(Vec, IBB);
1997 assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
1998 "Invalid number of incoming values");
2002 case Instruction::ExtractElement: {
2003 if (CanReuseExtract(E->Scalars)) {
2004 Value *V = VL0->getOperand(0);
2005 E->VectorizedValue = V;
2008 return Gather(E->Scalars, VecTy);
2010 case Instruction::ZExt:
2011 case Instruction::SExt:
2012 case Instruction::FPToUI:
2013 case Instruction::FPToSI:
2014 case Instruction::FPExt:
2015 case Instruction::PtrToInt:
2016 case Instruction::IntToPtr:
2017 case Instruction::SIToFP:
2018 case Instruction::UIToFP:
2019 case Instruction::Trunc:
2020 case Instruction::FPTrunc:
2021 case Instruction::BitCast: {
2023 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
2024 INVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
2026 setInsertPointAfterBundle(E->Scalars);
2028 Value *InVec = vectorizeTree(INVL);
2030 if (Value *V = alreadyVectorized(E->Scalars))
2033 CastInst *CI = dyn_cast<CastInst>(VL0);
2034 Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
2035 E->VectorizedValue = V;
2036 ++NumVectorInstructions;
2039 case Instruction::FCmp:
2040 case Instruction::ICmp: {
2041 ValueList LHSV, RHSV;
2042 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
2043 LHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
2044 RHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
2047 setInsertPointAfterBundle(E->Scalars);
2049 Value *L = vectorizeTree(LHSV);
2050 Value *R = vectorizeTree(RHSV);
2052 if (Value *V = alreadyVectorized(E->Scalars))
2055 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
2057 if (Opcode == Instruction::FCmp)
2058 V = Builder.CreateFCmp(P0, L, R);
2060 V = Builder.CreateICmp(P0, L, R);
2062 E->VectorizedValue = V;
2063 ++NumVectorInstructions;
2066 case Instruction::Select: {
2067 ValueList TrueVec, FalseVec, CondVec;
2068 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
2069 CondVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
2070 TrueVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
2071 FalseVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(2));
2074 setInsertPointAfterBundle(E->Scalars);
2076 Value *Cond = vectorizeTree(CondVec);
2077 Value *True = vectorizeTree(TrueVec);
2078 Value *False = vectorizeTree(FalseVec);
2080 if (Value *V = alreadyVectorized(E->Scalars))
2083 Value *V = Builder.CreateSelect(Cond, True, False);
2084 E->VectorizedValue = V;
2085 ++NumVectorInstructions;
2088 case Instruction::Add:
2089 case Instruction::FAdd:
2090 case Instruction::Sub:
2091 case Instruction::FSub:
2092 case Instruction::Mul:
2093 case Instruction::FMul:
2094 case Instruction::UDiv:
2095 case Instruction::SDiv:
2096 case Instruction::FDiv:
2097 case Instruction::URem:
2098 case Instruction::SRem:
2099 case Instruction::FRem:
2100 case Instruction::Shl:
2101 case Instruction::LShr:
2102 case Instruction::AShr:
2103 case Instruction::And:
2104 case Instruction::Or:
2105 case Instruction::Xor: {
2106 ValueList LHSVL, RHSVL;
2107 if (isa<BinaryOperator>(VL0) && VL0->isCommutative())
2108 reorderInputsAccordingToOpcode(E->Scalars, LHSVL, RHSVL);
2110 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
2111 LHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
2112 RHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
2115 setInsertPointAfterBundle(E->Scalars);
2117 Value *LHS = vectorizeTree(LHSVL);
2118 Value *RHS = vectorizeTree(RHSVL);
2120 if (LHS == RHS && isa<Instruction>(LHS)) {
2121 assert((VL0->getOperand(0) == VL0->getOperand(1)) && "Invalid order");
2124 if (Value *V = alreadyVectorized(E->Scalars))
2127 BinaryOperator *BinOp = cast<BinaryOperator>(VL0);
2128 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), LHS, RHS);
2129 E->VectorizedValue = V;
2130 propagateIRFlags(E->VectorizedValue, E->Scalars);
2131 ++NumVectorInstructions;
2133 if (Instruction *I = dyn_cast<Instruction>(V))
2134 return propagateMetadata(I, E->Scalars);
2138 case Instruction::Load: {
2139 // Loads are inserted at the head of the tree because we don't want to
2140 // sink them all the way down past store instructions.
2141 setInsertPointAfterBundle(E->Scalars);
2143 LoadInst *LI = cast<LoadInst>(VL0);
2144 Type *ScalarLoadTy = LI->getType();
2145 unsigned AS = LI->getPointerAddressSpace();
2147 Value *VecPtr = Builder.CreateBitCast(LI->getPointerOperand(),
2148 VecTy->getPointerTo(AS));
2150 // The pointer operand uses an in-tree scalar so we add the new BitCast to
2151 // ExternalUses list to make sure that an extract will be generated in the
2153 if (ScalarToTreeEntry.count(LI->getPointerOperand()))
2154 ExternalUses.push_back(
2155 ExternalUser(LI->getPointerOperand(), cast<User>(VecPtr), 0));
2157 unsigned Alignment = LI->getAlignment();
2158 LI = Builder.CreateLoad(VecPtr);
2160 Alignment = DL->getABITypeAlignment(ScalarLoadTy);
2161 LI->setAlignment(Alignment);
2162 E->VectorizedValue = LI;
2163 ++NumVectorInstructions;
2164 return propagateMetadata(LI, E->Scalars);
2166 case Instruction::Store: {
2167 StoreInst *SI = cast<StoreInst>(VL0);
2168 unsigned Alignment = SI->getAlignment();
2169 unsigned AS = SI->getPointerAddressSpace();
2172 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
2173 ValueOp.push_back(cast<StoreInst>(E->Scalars[i])->getValueOperand());
2175 setInsertPointAfterBundle(E->Scalars);
2177 Value *VecValue = vectorizeTree(ValueOp);
2178 Value *VecPtr = Builder.CreateBitCast(SI->getPointerOperand(),
2179 VecTy->getPointerTo(AS));
2180 StoreInst *S = Builder.CreateStore(VecValue, VecPtr);
2182 // The pointer operand uses an in-tree scalar so we add the new BitCast to
2183 // ExternalUses list to make sure that an extract will be generated in the
2185 if (ScalarToTreeEntry.count(SI->getPointerOperand()))
2186 ExternalUses.push_back(
2187 ExternalUser(SI->getPointerOperand(), cast<User>(VecPtr), 0));
2190 Alignment = DL->getABITypeAlignment(SI->getValueOperand()->getType());
2191 S->setAlignment(Alignment);
2192 E->VectorizedValue = S;
2193 ++NumVectorInstructions;
2194 return propagateMetadata(S, E->Scalars);
2196 case Instruction::GetElementPtr: {
2197 setInsertPointAfterBundle(E->Scalars);
2200 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
2201 Op0VL.push_back(cast<GetElementPtrInst>(E->Scalars[i])->getOperand(0));
2203 Value *Op0 = vectorizeTree(Op0VL);
2205 std::vector<Value *> OpVecs;
2206 for (int j = 1, e = cast<GetElementPtrInst>(VL0)->getNumOperands(); j < e;
2209 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
2210 OpVL.push_back(cast<GetElementPtrInst>(E->Scalars[i])->getOperand(j));
2212 Value *OpVec = vectorizeTree(OpVL);
2213 OpVecs.push_back(OpVec);
2216 Value *V = Builder.CreateGEP(Op0, OpVecs);
2217 E->VectorizedValue = V;
2218 ++NumVectorInstructions;
2220 if (Instruction *I = dyn_cast<Instruction>(V))
2221 return propagateMetadata(I, E->Scalars);
2225 case Instruction::Call: {
2226 CallInst *CI = cast<CallInst>(VL0);
2227 setInsertPointAfterBundle(E->Scalars);
2229 Intrinsic::ID IID = Intrinsic::not_intrinsic;
2230 Value *ScalarArg = nullptr;
2231 if (CI && (FI = CI->getCalledFunction())) {
2232 IID = (Intrinsic::ID) FI->getIntrinsicID();
2234 std::vector<Value *> OpVecs;
2235 for (int j = 0, e = CI->getNumArgOperands(); j < e; ++j) {
2237 // ctlz,cttz and powi are special intrinsics whose second argument is
2238 // a scalar. This argument should not be vectorized.
2239 if (hasVectorInstrinsicScalarOpd(IID, 1) && j == 1) {
2240 CallInst *CEI = cast<CallInst>(E->Scalars[0]);
2241 ScalarArg = CEI->getArgOperand(j);
2242 OpVecs.push_back(CEI->getArgOperand(j));
2245 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
2246 CallInst *CEI = cast<CallInst>(E->Scalars[i]);
2247 OpVL.push_back(CEI->getArgOperand(j));
2250 Value *OpVec = vectorizeTree(OpVL);
2251 DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
2252 OpVecs.push_back(OpVec);
2255 Module *M = F->getParent();
2256 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
2257 Type *Tys[] = { VectorType::get(CI->getType(), E->Scalars.size()) };
2258 Function *CF = Intrinsic::getDeclaration(M, ID, Tys);
2259 Value *V = Builder.CreateCall(CF, OpVecs);
2261 // The scalar argument uses an in-tree scalar so we add the new vectorized
2262 // call to ExternalUses list to make sure that an extract will be
2263 // generated in the future.
2264 if (ScalarArg && ScalarToTreeEntry.count(ScalarArg))
2265 ExternalUses.push_back(ExternalUser(ScalarArg, cast<User>(V), 0));
2267 E->VectorizedValue = V;
2268 ++NumVectorInstructions;
2271 case Instruction::ShuffleVector: {
2272 ValueList LHSVL, RHSVL;
2273 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
2274 LHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
2275 RHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
2277 setInsertPointAfterBundle(E->Scalars);
2279 Value *LHS = vectorizeTree(LHSVL);
2280 Value *RHS = vectorizeTree(RHSVL);
2282 if (Value *V = alreadyVectorized(E->Scalars))
2285 // Create a vector of LHS op1 RHS
2286 BinaryOperator *BinOp0 = cast<BinaryOperator>(VL0);
2287 Value *V0 = Builder.CreateBinOp(BinOp0->getOpcode(), LHS, RHS);
2289 // Create a vector of LHS op2 RHS
2290 Instruction *VL1 = cast<Instruction>(E->Scalars[1]);
2291 BinaryOperator *BinOp1 = cast<BinaryOperator>(VL1);
2292 Value *V1 = Builder.CreateBinOp(BinOp1->getOpcode(), LHS, RHS);
2294 // Create shuffle to take alternate operations from the vector.
2295 // Also, gather up odd and even scalar ops to propagate IR flags to
2296 // each vector operation.
2297 ValueList OddScalars, EvenScalars;
2298 unsigned e = E->Scalars.size();
2299 SmallVector<Constant *, 8> Mask(e);
2300 for (unsigned i = 0; i < e; ++i) {
2302 Mask[i] = Builder.getInt32(e + i);
2303 OddScalars.push_back(E->Scalars[i]);
2305 Mask[i] = Builder.getInt32(i);
2306 EvenScalars.push_back(E->Scalars[i]);
2310 Value *ShuffleMask = ConstantVector::get(Mask);
2311 propagateIRFlags(V0, EvenScalars);
2312 propagateIRFlags(V1, OddScalars);
2314 Value *V = Builder.CreateShuffleVector(V0, V1, ShuffleMask);
2315 E->VectorizedValue = V;
2316 ++NumVectorInstructions;
2317 if (Instruction *I = dyn_cast<Instruction>(V))
2318 return propagateMetadata(I, E->Scalars);
2323 llvm_unreachable("unknown inst");
2328 Value *BoUpSLP::vectorizeTree() {
2330 // All blocks must be scheduled before any instructions are inserted.
2331 for (auto &BSIter : BlocksSchedules) {
2332 scheduleBlock(BSIter.second.get());
2335 Builder.SetInsertPoint(F->getEntryBlock().begin());
2336 vectorizeTree(&VectorizableTree[0]);
2338 DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() << " values .\n");
2340 // Extract all of the elements with the external uses.
2341 for (UserList::iterator it = ExternalUses.begin(), e = ExternalUses.end();
2343 Value *Scalar = it->Scalar;
2344 llvm::User *User = it->User;
2346 // Skip users that we already RAUW. This happens when one instruction
2347 // has multiple uses of the same value.
2348 if (std::find(Scalar->user_begin(), Scalar->user_end(), User) ==
2351 assert(ScalarToTreeEntry.count(Scalar) && "Invalid scalar");
2353 int Idx = ScalarToTreeEntry[Scalar];
2354 TreeEntry *E = &VectorizableTree[Idx];
2355 assert(!E->NeedToGather && "Extracting from a gather list");
2357 Value *Vec = E->VectorizedValue;
2358 assert(Vec && "Can't find vectorizable value");
2360 Value *Lane = Builder.getInt32(it->Lane);
2361 // Generate extracts for out-of-tree users.
2362 // Find the insertion point for the extractelement lane.
2363 if (isa<Instruction>(Vec)){
2364 if (PHINode *PH = dyn_cast<PHINode>(User)) {
2365 for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
2366 if (PH->getIncomingValue(i) == Scalar) {
2367 Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
2368 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2369 CSEBlocks.insert(PH->getIncomingBlock(i));
2370 PH->setOperand(i, Ex);
2374 Builder.SetInsertPoint(cast<Instruction>(User));
2375 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2376 CSEBlocks.insert(cast<Instruction>(User)->getParent());
2377 User->replaceUsesOfWith(Scalar, Ex);
2380 Builder.SetInsertPoint(F->getEntryBlock().begin());
2381 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2382 CSEBlocks.insert(&F->getEntryBlock());
2383 User->replaceUsesOfWith(Scalar, Ex);
2386 DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
2389 // For each vectorized value:
2390 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
2391 TreeEntry *Entry = &VectorizableTree[EIdx];
2394 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
2395 Value *Scalar = Entry->Scalars[Lane];
2396 // No need to handle users of gathered values.
2397 if (Entry->NeedToGather)
2400 assert(Entry->VectorizedValue && "Can't find vectorizable value");
2402 Type *Ty = Scalar->getType();
2403 if (!Ty->isVoidTy()) {
2405 for (User *U : Scalar->users()) {
2406 DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
2408 assert((ScalarToTreeEntry.count(U) ||
2409 // It is legal to replace users in the ignorelist by undef.
2410 (std::find(UserIgnoreList.begin(), UserIgnoreList.end(), U) !=
2411 UserIgnoreList.end())) &&
2412 "Replacing out-of-tree value with undef");
2415 Value *Undef = UndefValue::get(Ty);
2416 Scalar->replaceAllUsesWith(Undef);
2418 DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
2419 eraseInstruction(cast<Instruction>(Scalar));
2423 Builder.ClearInsertionPoint();
2425 return VectorizableTree[0].VectorizedValue;
2428 void BoUpSLP::optimizeGatherSequence() {
2429 DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
2430 << " gather sequences instructions.\n");
2431 // LICM InsertElementInst sequences.
2432 for (SetVector<Instruction *>::iterator it = GatherSeq.begin(),
2433 e = GatherSeq.end(); it != e; ++it) {
2434 InsertElementInst *Insert = dyn_cast<InsertElementInst>(*it);
2439 // Check if this block is inside a loop.
2440 Loop *L = LI->getLoopFor(Insert->getParent());
2444 // Check if it has a preheader.
2445 BasicBlock *PreHeader = L->getLoopPreheader();
2449 // If the vector or the element that we insert into it are
2450 // instructions that are defined in this basic block then we can't
2451 // hoist this instruction.
2452 Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
2453 Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
2454 if (CurrVec && L->contains(CurrVec))
2456 if (NewElem && L->contains(NewElem))
2459 // We can hoist this instruction. Move it to the pre-header.
2460 Insert->moveBefore(PreHeader->getTerminator());
2463 // Make a list of all reachable blocks in our CSE queue.
2464 SmallVector<const DomTreeNode *, 8> CSEWorkList;
2465 CSEWorkList.reserve(CSEBlocks.size());
2466 for (BasicBlock *BB : CSEBlocks)
2467 if (DomTreeNode *N = DT->getNode(BB)) {
2468 assert(DT->isReachableFromEntry(N));
2469 CSEWorkList.push_back(N);
2472 // Sort blocks by domination. This ensures we visit a block after all blocks
2473 // dominating it are visited.
2474 std::stable_sort(CSEWorkList.begin(), CSEWorkList.end(),
2475 [this](const DomTreeNode *A, const DomTreeNode *B) {
2476 return DT->properlyDominates(A, B);
2479 // Perform O(N^2) search over the gather sequences and merge identical
2480 // instructions. TODO: We can further optimize this scan if we split the
2481 // instructions into different buckets based on the insert lane.
2482 SmallVector<Instruction *, 16> Visited;
2483 for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
2484 assert((I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
2485 "Worklist not sorted properly!");
2486 BasicBlock *BB = (*I)->getBlock();
2487 // For all instructions in blocks containing gather sequences:
2488 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) {
2489 Instruction *In = it++;
2490 if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In))
2493 // Check if we can replace this instruction with any of the
2494 // visited instructions.
2495 for (SmallVectorImpl<Instruction *>::iterator v = Visited.begin(),
2498 if (In->isIdenticalTo(*v) &&
2499 DT->dominates((*v)->getParent(), In->getParent())) {
2500 In->replaceAllUsesWith(*v);
2501 eraseInstruction(In);
2507 assert(std::find(Visited.begin(), Visited.end(), In) == Visited.end());
2508 Visited.push_back(In);
2516 // Groups the instructions to a bundle (which is then a single scheduling entity)
2517 // and schedules instructions until the bundle gets ready.
2518 bool BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL,
2520 if (isa<PHINode>(VL[0]))
2523 // Initialize the instruction bundle.
2524 Instruction *OldScheduleEnd = ScheduleEnd;
2525 ScheduleData *PrevInBundle = nullptr;
2526 ScheduleData *Bundle = nullptr;
2527 bool ReSchedule = false;
2528 DEBUG(dbgs() << "SLP: bundle: " << *VL[0] << "\n");
2529 for (Value *V : VL) {
2530 extendSchedulingRegion(V);
2531 ScheduleData *BundleMember = getScheduleData(V);
2532 assert(BundleMember &&
2533 "no ScheduleData for bundle member (maybe not in same basic block)");
2534 if (BundleMember->IsScheduled) {
2535 // A bundle member was scheduled as single instruction before and now
2536 // needs to be scheduled as part of the bundle. We just get rid of the
2537 // existing schedule.
2538 DEBUG(dbgs() << "SLP: reset schedule because " << *BundleMember
2539 << " was already scheduled\n");
2542 assert(BundleMember->isSchedulingEntity() &&
2543 "bundle member already part of other bundle");
2545 PrevInBundle->NextInBundle = BundleMember;
2547 Bundle = BundleMember;
2549 BundleMember->UnscheduledDepsInBundle = 0;
2550 Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps;
2552 // Group the instructions to a bundle.
2553 BundleMember->FirstInBundle = Bundle;
2554 PrevInBundle = BundleMember;
2556 if (ScheduleEnd != OldScheduleEnd) {
2557 // The scheduling region got new instructions at the lower end (or it is a
2558 // new region for the first bundle). This makes it necessary to
2559 // recalculate all dependencies.
2560 // It is seldom that this needs to be done a second time after adding the
2561 // initial bundle to the region.
2562 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2563 ScheduleData *SD = getScheduleData(I);
2564 SD->clearDependencies();
2570 initialFillReadyList(ReadyInsts);
2573 DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle << " in block "
2574 << BB->getName() << "\n");
2576 calculateDependencies(Bundle, true, SLP);
2578 // Now try to schedule the new bundle. As soon as the bundle is "ready" it
2579 // means that there are no cyclic dependencies and we can schedule it.
2580 // Note that's important that we don't "schedule" the bundle yet (see
2581 // cancelScheduling).
2582 while (!Bundle->isReady() && !ReadyInsts.empty()) {
2584 ScheduleData *pickedSD = ReadyInsts.back();
2585 ReadyInsts.pop_back();
2587 if (pickedSD->isSchedulingEntity() && pickedSD->isReady()) {
2588 schedule(pickedSD, ReadyInsts);
2591 return Bundle->isReady();
2594 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL) {
2595 if (isa<PHINode>(VL[0]))
2598 ScheduleData *Bundle = getScheduleData(VL[0]);
2599 DEBUG(dbgs() << "SLP: cancel scheduling of " << *Bundle << "\n");
2600 assert(!Bundle->IsScheduled &&
2601 "Can't cancel bundle which is already scheduled");
2602 assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
2603 "tried to unbundle something which is not a bundle");
2605 // Un-bundle: make single instructions out of the bundle.
2606 ScheduleData *BundleMember = Bundle;
2607 while (BundleMember) {
2608 assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
2609 BundleMember->FirstInBundle = BundleMember;
2610 ScheduleData *Next = BundleMember->NextInBundle;
2611 BundleMember->NextInBundle = nullptr;
2612 BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps;
2613 if (BundleMember->UnscheduledDepsInBundle == 0) {
2614 ReadyInsts.insert(BundleMember);
2616 BundleMember = Next;
2620 void BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V) {
2621 if (getScheduleData(V))
2623 Instruction *I = dyn_cast<Instruction>(V);
2624 assert(I && "bundle member must be an instruction");
2625 assert(!isa<PHINode>(I) && "phi nodes don't need to be scheduled");
2626 if (!ScheduleStart) {
2627 // It's the first instruction in the new region.
2628 initScheduleData(I, I->getNextNode(), nullptr, nullptr);
2630 ScheduleEnd = I->getNextNode();
2631 assert(ScheduleEnd && "tried to vectorize a TerminatorInst?");
2632 DEBUG(dbgs() << "SLP: initialize schedule region to " << *I << "\n");
2635 // Search up and down at the same time, because we don't know if the new
2636 // instruction is above or below the existing scheduling region.
2637 BasicBlock::reverse_iterator UpIter(ScheduleStart);
2638 BasicBlock::reverse_iterator UpperEnd = BB->rend();
2639 BasicBlock::iterator DownIter(ScheduleEnd);
2640 BasicBlock::iterator LowerEnd = BB->end();
2642 if (UpIter != UpperEnd) {
2643 if (&*UpIter == I) {
2644 initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
2646 DEBUG(dbgs() << "SLP: extend schedule region start to " << *I << "\n");
2651 if (DownIter != LowerEnd) {
2652 if (&*DownIter == I) {
2653 initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
2655 ScheduleEnd = I->getNextNode();
2656 assert(ScheduleEnd && "tried to vectorize a TerminatorInst?");
2657 DEBUG(dbgs() << "SLP: extend schedule region end to " << *I << "\n");
2662 assert((UpIter != UpperEnd || DownIter != LowerEnd) &&
2663 "instruction not found in block");
2667 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
2669 ScheduleData *PrevLoadStore,
2670 ScheduleData *NextLoadStore) {
2671 ScheduleData *CurrentLoadStore = PrevLoadStore;
2672 for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
2673 ScheduleData *SD = ScheduleDataMap[I];
2675 // Allocate a new ScheduleData for the instruction.
2676 if (ChunkPos >= ChunkSize) {
2677 ScheduleDataChunks.push_back(
2678 llvm::make_unique<ScheduleData[]>(ChunkSize));
2681 SD = &(ScheduleDataChunks.back()[ChunkPos++]);
2682 ScheduleDataMap[I] = SD;
2685 assert(!isInSchedulingRegion(SD) &&
2686 "new ScheduleData already in scheduling region");
2687 SD->init(SchedulingRegionID);
2689 if (I->mayReadOrWriteMemory()) {
2690 // Update the linked list of memory accessing instructions.
2691 if (CurrentLoadStore) {
2692 CurrentLoadStore->NextLoadStore = SD;
2694 FirstLoadStoreInRegion = SD;
2696 CurrentLoadStore = SD;
2699 if (NextLoadStore) {
2700 if (CurrentLoadStore)
2701 CurrentLoadStore->NextLoadStore = NextLoadStore;
2703 LastLoadStoreInRegion = CurrentLoadStore;
2707 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
2708 bool InsertInReadyList,
2710 assert(SD->isSchedulingEntity());
2712 SmallVector<ScheduleData *, 10> WorkList;
2713 WorkList.push_back(SD);
2715 while (!WorkList.empty()) {
2716 ScheduleData *SD = WorkList.back();
2717 WorkList.pop_back();
2719 ScheduleData *BundleMember = SD;
2720 while (BundleMember) {
2721 assert(isInSchedulingRegion(BundleMember));
2722 if (!BundleMember->hasValidDependencies()) {
2724 DEBUG(dbgs() << "SLP: update deps of " << *BundleMember << "\n");
2725 BundleMember->Dependencies = 0;
2726 BundleMember->resetUnscheduledDeps();
2728 // Handle def-use chain dependencies.
2729 for (User *U : BundleMember->Inst->users()) {
2730 if (isa<Instruction>(U)) {
2731 ScheduleData *UseSD = getScheduleData(U);
2732 if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
2733 BundleMember->Dependencies++;
2734 ScheduleData *DestBundle = UseSD->FirstInBundle;
2735 if (!DestBundle->IsScheduled) {
2736 BundleMember->incrementUnscheduledDeps(1);
2738 if (!DestBundle->hasValidDependencies()) {
2739 WorkList.push_back(DestBundle);
2743 // I'm not sure if this can ever happen. But we need to be safe.
2744 // This lets the instruction/bundle never be scheduled and eventally
2745 // disable vectorization.
2746 BundleMember->Dependencies++;
2747 BundleMember->incrementUnscheduledDeps(1);
2751 // Handle the memory dependencies.
2752 ScheduleData *DepDest = BundleMember->NextLoadStore;
2754 Instruction *SrcInst = BundleMember->Inst;
2755 AliasAnalysis::Location SrcLoc = getLocation(SrcInst, SLP->AA);
2756 bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
2759 assert(isInSchedulingRegion(DepDest));
2760 if (SrcMayWrite || DepDest->Inst->mayWriteToMemory()) {
2761 if (SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)) {
2762 DepDest->MemoryDependencies.push_back(BundleMember);
2763 BundleMember->Dependencies++;
2764 ScheduleData *DestBundle = DepDest->FirstInBundle;
2765 if (!DestBundle->IsScheduled) {
2766 BundleMember->incrementUnscheduledDeps(1);
2768 if (!DestBundle->hasValidDependencies()) {
2769 WorkList.push_back(DestBundle);
2773 DepDest = DepDest->NextLoadStore;
2777 BundleMember = BundleMember->NextInBundle;
2779 if (InsertInReadyList && SD->isReady()) {
2780 ReadyInsts.push_back(SD);
2781 DEBUG(dbgs() << "SLP: gets ready on update: " << *SD->Inst << "\n");
2786 void BoUpSLP::BlockScheduling::resetSchedule() {
2787 assert(ScheduleStart &&
2788 "tried to reset schedule on block which has not been scheduled");
2789 for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2790 ScheduleData *SD = getScheduleData(I);
2791 assert(isInSchedulingRegion(SD));
2792 SD->IsScheduled = false;
2793 SD->resetUnscheduledDeps();
2798 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
2800 if (!BS->ScheduleStart)
2803 DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
2805 BS->resetSchedule();
2807 // For the real scheduling we use a more sophisticated ready-list: it is
2808 // sorted by the original instruction location. This lets the final schedule
2809 // be as close as possible to the original instruction order.
2810 struct ScheduleDataCompare {
2811 bool operator()(ScheduleData *SD1, ScheduleData *SD2) {
2812 return SD2->SchedulingPriority < SD1->SchedulingPriority;
2815 std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
2817 // Ensure that all depencency data is updated and fill the ready-list with
2818 // initial instructions.
2820 int NumToSchedule = 0;
2821 for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
2822 I = I->getNextNode()) {
2823 ScheduleData *SD = BS->getScheduleData(I);
2825 SD->isPartOfBundle() == (ScalarToTreeEntry.count(SD->Inst) != 0) &&
2826 "scheduler and vectorizer have different opinion on what is a bundle");
2827 SD->FirstInBundle->SchedulingPriority = Idx++;
2828 if (SD->isSchedulingEntity()) {
2829 BS->calculateDependencies(SD, false, this);
2833 BS->initialFillReadyList(ReadyInsts);
2835 Instruction *LastScheduledInst = BS->ScheduleEnd;
2837 // Do the "real" scheduling.
2838 while (!ReadyInsts.empty()) {
2839 ScheduleData *picked = *ReadyInsts.begin();
2840 ReadyInsts.erase(ReadyInsts.begin());
2842 // Move the scheduled instruction(s) to their dedicated places, if not
2844 ScheduleData *BundleMember = picked;
2845 while (BundleMember) {
2846 Instruction *pickedInst = BundleMember->Inst;
2847 if (LastScheduledInst->getNextNode() != pickedInst) {
2848 BS->BB->getInstList().remove(pickedInst);
2849 BS->BB->getInstList().insert(LastScheduledInst, pickedInst);
2851 LastScheduledInst = pickedInst;
2852 BundleMember = BundleMember->NextInBundle;
2855 BS->schedule(picked, ReadyInsts);
2858 assert(NumToSchedule == 0 && "could not schedule all instructions");
2860 // Avoid duplicate scheduling of the block.
2861 BS->ScheduleStart = nullptr;
2864 /// The SLPVectorizer Pass.
2865 struct SLPVectorizer : public FunctionPass {
2866 typedef SmallVector<StoreInst *, 8> StoreList;
2867 typedef MapVector<Value *, StoreList> StoreListMap;
2869 /// Pass identification, replacement for typeid
2872 explicit SLPVectorizer() : FunctionPass(ID) {
2873 initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
2876 ScalarEvolution *SE;
2877 const DataLayout *DL;
2878 TargetTransformInfo *TTI;
2879 TargetLibraryInfo *TLI;
2883 AssumptionCache *AC;
2885 bool runOnFunction(Function &F) override {
2886 if (skipOptnoneFunction(F))
2889 SE = &getAnalysis<ScalarEvolution>();
2890 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
2891 DL = DLP ? &DLP->getDataLayout() : nullptr;
2892 TTI = &getAnalysis<TargetTransformInfo>();
2893 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
2894 TLI = TLIP ? &TLIP->getTLI() : nullptr;
2895 AA = &getAnalysis<AliasAnalysis>();
2896 LI = &getAnalysis<LoopInfo>();
2897 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2898 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
2901 bool Changed = false;
2903 // If the target claims to have no vector registers don't attempt
2905 if (!TTI->getNumberOfRegisters(true))
2908 // Must have DataLayout. We can't require it because some tests run w/o
2913 // Don't vectorize when the attribute NoImplicitFloat is used.
2914 if (F.hasFnAttribute(Attribute::NoImplicitFloat))
2917 DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
2919 // Use the bottom up slp vectorizer to construct chains that start with
2920 // store instructions.
2921 BoUpSLP R(&F, SE, DL, TTI, TLI, AA, LI, DT, AC);
2923 // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
2924 // delete instructions.
2926 // Scan the blocks in the function in post order.
2927 for (po_iterator<BasicBlock*> it = po_begin(&F.getEntryBlock()),
2928 e = po_end(&F.getEntryBlock()); it != e; ++it) {
2929 BasicBlock *BB = *it;
2930 // Vectorize trees that end at stores.
2931 if (unsigned count = collectStores(BB, R)) {
2933 DEBUG(dbgs() << "SLP: Found " << count << " stores to vectorize.\n");
2934 Changed |= vectorizeStoreChains(R);
2937 // Vectorize trees that end at reductions.
2938 Changed |= vectorizeChainsInBlock(BB, R);
2942 R.optimizeGatherSequence();
2943 DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
2944 DEBUG(verifyFunction(F));
2949 void getAnalysisUsage(AnalysisUsage &AU) const override {
2950 FunctionPass::getAnalysisUsage(AU);
2951 AU.addRequired<AssumptionCacheTracker>();
2952 AU.addRequired<ScalarEvolution>();
2953 AU.addRequired<AliasAnalysis>();
2954 AU.addRequired<TargetTransformInfo>();
2955 AU.addRequired<LoopInfo>();
2956 AU.addRequired<DominatorTreeWrapperPass>();
2957 AU.addPreserved<LoopInfo>();
2958 AU.addPreserved<DominatorTreeWrapperPass>();
2959 AU.setPreservesCFG();
2964 /// \brief Collect memory references and sort them according to their base
2965 /// object. We sort the stores to their base objects to reduce the cost of the
2966 /// quadratic search on the stores. TODO: We can further reduce this cost
2967 /// if we flush the chain creation every time we run into a memory barrier.
2968 unsigned collectStores(BasicBlock *BB, BoUpSLP &R);
2970 /// \brief Try to vectorize a chain that starts at two arithmetic instrs.
2971 bool tryToVectorizePair(Value *A, Value *B, BoUpSLP &R);
2973 /// \brief Try to vectorize a list of operands.
2974 /// \@param BuildVector A list of users to ignore for the purpose of
2975 /// scheduling and that don't need extracting.
2976 /// \returns true if a value was vectorized.
2977 bool tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
2978 ArrayRef<Value *> BuildVector = None,
2979 bool allowReorder = false);
2981 /// \brief Try to vectorize a chain that may start at the operands of \V;
2982 bool tryToVectorize(BinaryOperator *V, BoUpSLP &R);
2984 /// \brief Vectorize the stores that were collected in StoreRefs.
2985 bool vectorizeStoreChains(BoUpSLP &R);
2987 /// \brief Scan the basic block and look for patterns that are likely to start
2988 /// a vectorization chain.
2989 bool vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R);
2991 bool vectorizeStoreChain(ArrayRef<Value *> Chain, int CostThreshold,
2994 bool vectorizeStores(ArrayRef<StoreInst *> Stores, int costThreshold,
2997 StoreListMap StoreRefs;
3000 /// \brief Check that the Values in the slice in VL array are still existent in
3001 /// the WeakVH array.
3002 /// Vectorization of part of the VL array may cause later values in the VL array
3003 /// to become invalid. We track when this has happened in the WeakVH array.
3004 static bool hasValueBeenRAUWed(ArrayRef<Value *> &VL,
3005 SmallVectorImpl<WeakVH> &VH,
3006 unsigned SliceBegin,
3007 unsigned SliceSize) {
3008 for (unsigned i = SliceBegin; i < SliceBegin + SliceSize; ++i)
3015 bool SLPVectorizer::vectorizeStoreChain(ArrayRef<Value *> Chain,
3016 int CostThreshold, BoUpSLP &R) {
3017 unsigned ChainLen = Chain.size();
3018 DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
3020 Type *StoreTy = cast<StoreInst>(Chain[0])->getValueOperand()->getType();
3021 unsigned Sz = DL->getTypeSizeInBits(StoreTy);
3022 unsigned VF = MinVecRegSize / Sz;
3024 if (!isPowerOf2_32(Sz) || VF < 2)
3027 // Keep track of values that were deleted by vectorizing in the loop below.
3028 SmallVector<WeakVH, 8> TrackValues(Chain.begin(), Chain.end());
3030 bool Changed = false;
3031 // Look for profitable vectorizable trees at all offsets, starting at zero.
3032 for (unsigned i = 0, e = ChainLen; i < e; ++i) {
3036 // Check that a previous iteration of this loop did not delete the Value.
3037 if (hasValueBeenRAUWed(Chain, TrackValues, i, VF))
3040 DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
3042 ArrayRef<Value *> Operands = Chain.slice(i, VF);
3044 R.buildTree(Operands);
3046 int Cost = R.getTreeCost();
3048 DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
3049 if (Cost < CostThreshold) {
3050 DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
3053 // Move to the next bundle.
3062 bool SLPVectorizer::vectorizeStores(ArrayRef<StoreInst *> Stores,
3063 int costThreshold, BoUpSLP &R) {
3064 SetVector<Value *> Heads, Tails;
3065 SmallDenseMap<Value *, Value *> ConsecutiveChain;
3067 // We may run into multiple chains that merge into a single chain. We mark the
3068 // stores that we vectorized so that we don't visit the same store twice.
3069 BoUpSLP::ValueSet VectorizedStores;
3070 bool Changed = false;
3072 // Do a quadratic search on all of the given stores and find
3073 // all of the pairs of stores that follow each other.
3074 for (unsigned i = 0, e = Stores.size(); i < e; ++i) {
3075 for (unsigned j = 0; j < e; ++j) {
3079 if (R.isConsecutiveAccess(Stores[i], Stores[j])) {
3080 Tails.insert(Stores[j]);
3081 Heads.insert(Stores[i]);
3082 ConsecutiveChain[Stores[i]] = Stores[j];
3087 // For stores that start but don't end a link in the chain:
3088 for (SetVector<Value *>::iterator it = Heads.begin(), e = Heads.end();
3090 if (Tails.count(*it))
3093 // We found a store instr that starts a chain. Now follow the chain and try
3095 BoUpSLP::ValueList Operands;
3097 // Collect the chain into a list.
3098 while (Tails.count(I) || Heads.count(I)) {
3099 if (VectorizedStores.count(I))
3101 Operands.push_back(I);
3102 // Move to the next value in the chain.
3103 I = ConsecutiveChain[I];
3106 bool Vectorized = vectorizeStoreChain(Operands, costThreshold, R);
3108 // Mark the vectorized stores so that we don't vectorize them again.
3110 VectorizedStores.insert(Operands.begin(), Operands.end());
3111 Changed |= Vectorized;
3118 unsigned SLPVectorizer::collectStores(BasicBlock *BB, BoUpSLP &R) {
3121 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
3122 StoreInst *SI = dyn_cast<StoreInst>(it);
3126 // Don't touch volatile stores.
3127 if (!SI->isSimple())
3130 // Check that the pointer points to scalars.
3131 Type *Ty = SI->getValueOperand()->getType();
3132 if (Ty->isAggregateType() || Ty->isVectorTy())
3135 // Find the base pointer.
3136 Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), DL);
3138 // Save the store locations.
3139 StoreRefs[Ptr].push_back(SI);
3145 bool SLPVectorizer::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
3148 Value *VL[] = { A, B };
3149 return tryToVectorizeList(VL, R, None, true);
3152 bool SLPVectorizer::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
3153 ArrayRef<Value *> BuildVector,
3154 bool allowReorder) {
3158 DEBUG(dbgs() << "SLP: Vectorizing a list of length = " << VL.size() << ".\n");
3160 // Check that all of the parts are scalar instructions of the same type.
3161 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
3165 unsigned Opcode0 = I0->getOpcode();
3167 Type *Ty0 = I0->getType();
3168 unsigned Sz = DL->getTypeSizeInBits(Ty0);
3169 unsigned VF = MinVecRegSize / Sz;
3171 for (int i = 0, e = VL.size(); i < e; ++i) {
3172 Type *Ty = VL[i]->getType();
3173 if (Ty->isAggregateType() || Ty->isVectorTy())
3175 Instruction *Inst = dyn_cast<Instruction>(VL[i]);
3176 if (!Inst || Inst->getOpcode() != Opcode0)
3180 bool Changed = false;
3182 // Keep track of values that were deleted by vectorizing in the loop below.
3183 SmallVector<WeakVH, 8> TrackValues(VL.begin(), VL.end());
3185 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
3186 unsigned OpsWidth = 0;
3193 if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
3196 // Check that a previous iteration of this loop did not delete the Value.
3197 if (hasValueBeenRAUWed(VL, TrackValues, i, OpsWidth))
3200 DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
3202 ArrayRef<Value *> Ops = VL.slice(i, OpsWidth);
3204 ArrayRef<Value *> BuildVectorSlice;
3205 if (!BuildVector.empty())
3206 BuildVectorSlice = BuildVector.slice(i, OpsWidth);
3208 R.buildTree(Ops, BuildVectorSlice);
3209 // TODO: check if we can allow reordering also for other cases than
3210 // tryToVectorizePair()
3211 if (allowReorder && R.shouldReorder()) {
3212 assert(Ops.size() == 2);
3213 assert(BuildVectorSlice.empty());
3214 Value *ReorderedOps[] = { Ops[1], Ops[0] };
3215 R.buildTree(ReorderedOps, None);
3217 int Cost = R.getTreeCost();
3219 if (Cost < -SLPCostThreshold) {
3220 DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
3221 Value *VectorizedRoot = R.vectorizeTree();
3223 // Reconstruct the build vector by extracting the vectorized root. This
3224 // way we handle the case where some elements of the vector are undefined.
3225 // (return (inserelt <4 xi32> (insertelt undef (opd0) 0) (opd1) 2))
3226 if (!BuildVectorSlice.empty()) {
3227 // The insert point is the last build vector instruction. The vectorized
3228 // root will precede it. This guarantees that we get an instruction. The
3229 // vectorized tree could have been constant folded.
3230 Instruction *InsertAfter = cast<Instruction>(BuildVectorSlice.back());
3231 unsigned VecIdx = 0;
3232 for (auto &V : BuildVectorSlice) {
3233 IRBuilder<true, NoFolder> Builder(
3234 ++BasicBlock::iterator(InsertAfter));
3235 InsertElementInst *IE = cast<InsertElementInst>(V);
3236 Instruction *Extract = cast<Instruction>(Builder.CreateExtractElement(
3237 VectorizedRoot, Builder.getInt32(VecIdx++)));
3238 IE->setOperand(1, Extract);
3239 IE->removeFromParent();
3240 IE->insertAfter(Extract);
3244 // Move to the next bundle.
3253 bool SLPVectorizer::tryToVectorize(BinaryOperator *V, BoUpSLP &R) {
3257 // Try to vectorize V.
3258 if (tryToVectorizePair(V->getOperand(0), V->getOperand(1), R))
3261 BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0));
3262 BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1));
3264 if (B && B->hasOneUse()) {
3265 BinaryOperator *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
3266 BinaryOperator *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
3267 if (tryToVectorizePair(A, B0, R)) {
3270 if (tryToVectorizePair(A, B1, R)) {
3276 if (A && A->hasOneUse()) {
3277 BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
3278 BinaryOperator *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
3279 if (tryToVectorizePair(A0, B, R)) {
3282 if (tryToVectorizePair(A1, B, R)) {
3289 /// \brief Generate a shuffle mask to be used in a reduction tree.
3291 /// \param VecLen The length of the vector to be reduced.
3292 /// \param NumEltsToRdx The number of elements that should be reduced in the
3294 /// \param IsPairwise Whether the reduction is a pairwise or splitting
3295 /// reduction. A pairwise reduction will generate a mask of
3296 /// <0,2,...> or <1,3,..> while a splitting reduction will generate
3297 /// <2,3, undef,undef> for a vector of 4 and NumElts = 2.
3298 /// \param IsLeft True will generate a mask of even elements, odd otherwise.
3299 static Value *createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx,
3300 bool IsPairwise, bool IsLeft,
3301 IRBuilder<> &Builder) {
3302 assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask");
3304 SmallVector<Constant *, 32> ShuffleMask(
3305 VecLen, UndefValue::get(Builder.getInt32Ty()));
3308 // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
3309 for (unsigned i = 0; i != NumEltsToRdx; ++i)
3310 ShuffleMask[i] = Builder.getInt32(2 * i + !IsLeft);
3312 // Move the upper half of the vector to the lower half.
3313 for (unsigned i = 0; i != NumEltsToRdx; ++i)
3314 ShuffleMask[i] = Builder.getInt32(NumEltsToRdx + i);
3316 return ConstantVector::get(ShuffleMask);
3320 /// Model horizontal reductions.
3322 /// A horizontal reduction is a tree of reduction operations (currently add and
3323 /// fadd) that has operations that can be put into a vector as its leaf.
3324 /// For example, this tree:
3331 /// This tree has "mul" as its reduced values and "+" as its reduction
3332 /// operations. A reduction might be feeding into a store or a binary operation
3347 class HorizontalReduction {
3348 SmallVector<Value *, 16> ReductionOps;
3349 SmallVector<Value *, 32> ReducedVals;
3351 BinaryOperator *ReductionRoot;
3352 PHINode *ReductionPHI;
3354 /// The opcode of the reduction.
3355 unsigned ReductionOpcode;
3356 /// The opcode of the values we perform a reduction on.
3357 unsigned ReducedValueOpcode;
3358 /// The width of one full horizontal reduction operation.
3359 unsigned ReduxWidth;
3360 /// Should we model this reduction as a pairwise reduction tree or a tree that
3361 /// splits the vector in halves and adds those halves.
3362 bool IsPairwiseReduction;
3365 HorizontalReduction()
3366 : ReductionRoot(nullptr), ReductionPHI(nullptr), ReductionOpcode(0),
3367 ReducedValueOpcode(0), ReduxWidth(0), IsPairwiseReduction(false) {}
3369 /// \brief Try to find a reduction tree.
3370 bool matchAssociativeReduction(PHINode *Phi, BinaryOperator *B,
3371 const DataLayout *DL) {
3373 std::find(Phi->op_begin(), Phi->op_end(), B) != Phi->op_end()) &&
3374 "Thi phi needs to use the binary operator");
3376 // We could have a initial reductions that is not an add.
3377 // r *= v1 + v2 + v3 + v4
3378 // In such a case start looking for a tree rooted in the first '+'.
3380 if (B->getOperand(0) == Phi) {
3382 B = dyn_cast<BinaryOperator>(B->getOperand(1));
3383 } else if (B->getOperand(1) == Phi) {
3385 B = dyn_cast<BinaryOperator>(B->getOperand(0));
3392 Type *Ty = B->getType();
3393 if (Ty->isVectorTy())
3396 ReductionOpcode = B->getOpcode();
3397 ReducedValueOpcode = 0;
3398 ReduxWidth = MinVecRegSize / DL->getTypeSizeInBits(Ty);
3405 // We currently only support adds.
3406 if (ReductionOpcode != Instruction::Add &&
3407 ReductionOpcode != Instruction::FAdd)
3410 // Post order traverse the reduction tree starting at B. We only handle true
3411 // trees containing only binary operators.
3412 SmallVector<std::pair<BinaryOperator *, unsigned>, 32> Stack;
3413 Stack.push_back(std::make_pair(B, 0));
3414 while (!Stack.empty()) {
3415 BinaryOperator *TreeN = Stack.back().first;
3416 unsigned EdgeToVist = Stack.back().second++;
3417 bool IsReducedValue = TreeN->getOpcode() != ReductionOpcode;
3419 // Only handle trees in the current basic block.
3420 if (TreeN->getParent() != B->getParent())
3423 // Each tree node needs to have one user except for the ultimate
3425 if (!TreeN->hasOneUse() && TreeN != B)
3429 if (EdgeToVist == 2 || IsReducedValue) {
3430 if (IsReducedValue) {
3431 // Make sure that the opcodes of the operations that we are going to
3433 if (!ReducedValueOpcode)
3434 ReducedValueOpcode = TreeN->getOpcode();
3435 else if (ReducedValueOpcode != TreeN->getOpcode())
3437 ReducedVals.push_back(TreeN);
3439 // We need to be able to reassociate the adds.
3440 if (!TreeN->isAssociative())
3442 ReductionOps.push_back(TreeN);
3449 // Visit left or right.
3450 Value *NextV = TreeN->getOperand(EdgeToVist);
3451 BinaryOperator *Next = dyn_cast<BinaryOperator>(NextV);
3453 Stack.push_back(std::make_pair(Next, 0));
3454 else if (NextV != Phi)
3460 /// \brief Attempt to vectorize the tree found by
3461 /// matchAssociativeReduction.
3462 bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
3463 if (ReducedVals.empty())
3466 unsigned NumReducedVals = ReducedVals.size();
3467 if (NumReducedVals < ReduxWidth)
3470 Value *VectorizedTree = nullptr;
3471 IRBuilder<> Builder(ReductionRoot);
3472 FastMathFlags Unsafe;
3473 Unsafe.setUnsafeAlgebra();
3474 Builder.SetFastMathFlags(Unsafe);
3477 for (; i < NumReducedVals - ReduxWidth + 1; i += ReduxWidth) {
3478 V.buildTree(makeArrayRef(&ReducedVals[i], ReduxWidth), ReductionOps);
3481 int Cost = V.getTreeCost() + getReductionCost(TTI, ReducedVals[i]);
3482 if (Cost >= -SLPCostThreshold)
3485 DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" << Cost
3488 // Vectorize a tree.
3489 DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
3490 Value *VectorizedRoot = V.vectorizeTree();
3492 // Emit a reduction.
3493 Value *ReducedSubTree = emitReduction(VectorizedRoot, Builder);
3494 if (VectorizedTree) {
3495 Builder.SetCurrentDebugLocation(Loc);
3496 VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
3497 ReducedSubTree, "bin.rdx");
3499 VectorizedTree = ReducedSubTree;
3502 if (VectorizedTree) {
3503 // Finish the reduction.
3504 for (; i < NumReducedVals; ++i) {
3505 Builder.SetCurrentDebugLocation(
3506 cast<Instruction>(ReducedVals[i])->getDebugLoc());
3507 VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
3512 assert(ReductionRoot && "Need a reduction operation");
3513 ReductionRoot->setOperand(0, VectorizedTree);
3514 ReductionRoot->setOperand(1, ReductionPHI);
3516 ReductionRoot->replaceAllUsesWith(VectorizedTree);
3518 return VectorizedTree != nullptr;
3523 /// \brief Calcuate the cost of a reduction.
3524 int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal) {
3525 Type *ScalarTy = FirstReducedVal->getType();
3526 Type *VecTy = VectorType::get(ScalarTy, ReduxWidth);
3528 int PairwiseRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, true);
3529 int SplittingRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, false);
3531 IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
3532 int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
3534 int ScalarReduxCost =
3535 ReduxWidth * TTI->getArithmeticInstrCost(ReductionOpcode, VecTy);
3537 DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost
3538 << " for reduction that starts with " << *FirstReducedVal
3540 << (IsPairwiseReduction ? "pairwise" : "splitting")
3541 << " reduction)\n");
3543 return VecReduxCost - ScalarReduxCost;
3546 static Value *createBinOp(IRBuilder<> &Builder, unsigned Opcode, Value *L,
3547 Value *R, const Twine &Name = "") {
3548 if (Opcode == Instruction::FAdd)
3549 return Builder.CreateFAdd(L, R, Name);
3550 return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, L, R, Name);
3553 /// \brief Emit a horizontal reduction of the vectorized value.
3554 Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder) {
3555 assert(VectorizedValue && "Need to have a vectorized tree node");
3556 assert(isPowerOf2_32(ReduxWidth) &&
3557 "We only handle power-of-two reductions for now");
3559 Value *TmpVec = VectorizedValue;
3560 for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
3561 if (IsPairwiseReduction) {
3563 createRdxShuffleMask(ReduxWidth, i, true, true, Builder);
3565 createRdxShuffleMask(ReduxWidth, i, true, false, Builder);
3567 Value *LeftShuf = Builder.CreateShuffleVector(
3568 TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l");
3569 Value *RightShuf = Builder.CreateShuffleVector(
3570 TmpVec, UndefValue::get(TmpVec->getType()), (RightMask),
3572 TmpVec = createBinOp(Builder, ReductionOpcode, LeftShuf, RightShuf,
3576 createRdxShuffleMask(ReduxWidth, i, false, false, Builder);
3577 Value *Shuf = Builder.CreateShuffleVector(
3578 TmpVec, UndefValue::get(TmpVec->getType()), UpperHalf, "rdx.shuf");
3579 TmpVec = createBinOp(Builder, ReductionOpcode, TmpVec, Shuf, "bin.rdx");
3583 // The result is in the first element of the vector.
3584 return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
3588 /// \brief Recognize construction of vectors like
3589 /// %ra = insertelement <4 x float> undef, float %s0, i32 0
3590 /// %rb = insertelement <4 x float> %ra, float %s1, i32 1
3591 /// %rc = insertelement <4 x float> %rb, float %s2, i32 2
3592 /// %rd = insertelement <4 x float> %rc, float %s3, i32 3
3594 /// Returns true if it matches
3596 static bool findBuildVector(InsertElementInst *FirstInsertElem,
3597 SmallVectorImpl<Value *> &BuildVector,
3598 SmallVectorImpl<Value *> &BuildVectorOpds) {
3599 if (!isa<UndefValue>(FirstInsertElem->getOperand(0)))
3602 InsertElementInst *IE = FirstInsertElem;
3604 BuildVector.push_back(IE);
3605 BuildVectorOpds.push_back(IE->getOperand(1));
3607 if (IE->use_empty())
3610 InsertElementInst *NextUse = dyn_cast<InsertElementInst>(IE->user_back());
3614 // If this isn't the final use, make sure the next insertelement is the only
3615 // use. It's OK if the final constructed vector is used multiple times
3616 if (!IE->hasOneUse())
3625 static bool PhiTypeSorterFunc(Value *V, Value *V2) {
3626 return V->getType() < V2->getType();
3629 bool SLPVectorizer::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
3630 bool Changed = false;
3631 SmallVector<Value *, 4> Incoming;
3632 SmallSet<Value *, 16> VisitedInstrs;
3634 bool HaveVectorizedPhiNodes = true;
3635 while (HaveVectorizedPhiNodes) {
3636 HaveVectorizedPhiNodes = false;
3638 // Collect the incoming values from the PHIs.
3640 for (BasicBlock::iterator instr = BB->begin(), ie = BB->end(); instr != ie;
3642 PHINode *P = dyn_cast<PHINode>(instr);
3646 if (!VisitedInstrs.count(P))
3647 Incoming.push_back(P);
3651 std::stable_sort(Incoming.begin(), Incoming.end(), PhiTypeSorterFunc);
3653 // Try to vectorize elements base on their type.
3654 for (SmallVector<Value *, 4>::iterator IncIt = Incoming.begin(),
3658 // Look for the next elements with the same type.
3659 SmallVector<Value *, 4>::iterator SameTypeIt = IncIt;
3660 while (SameTypeIt != E &&
3661 (*SameTypeIt)->getType() == (*IncIt)->getType()) {
3662 VisitedInstrs.insert(*SameTypeIt);
3666 // Try to vectorize them.
3667 unsigned NumElts = (SameTypeIt - IncIt);
3668 DEBUG(errs() << "SLP: Trying to vectorize starting at PHIs (" << NumElts << ")\n");
3669 if (NumElts > 1 && tryToVectorizeList(makeArrayRef(IncIt, NumElts), R)) {
3670 // Success start over because instructions might have been changed.
3671 HaveVectorizedPhiNodes = true;
3676 // Start over at the next instruction of a different type (or the end).
3681 VisitedInstrs.clear();
3683 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) {
3684 // We may go through BB multiple times so skip the one we have checked.
3685 if (!VisitedInstrs.insert(it).second)
3688 if (isa<DbgInfoIntrinsic>(it))
3691 // Try to vectorize reductions that use PHINodes.
3692 if (PHINode *P = dyn_cast<PHINode>(it)) {
3693 // Check that the PHI is a reduction PHI.
3694 if (P->getNumIncomingValues() != 2)
3697 (P->getIncomingBlock(0) == BB
3698 ? (P->getIncomingValue(0))
3699 : (P->getIncomingBlock(1) == BB ? P->getIncomingValue(1)
3701 // Check if this is a Binary Operator.
3702 BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx);
3706 // Try to match and vectorize a horizontal reduction.
3707 HorizontalReduction HorRdx;
3708 if (ShouldVectorizeHor &&
3709 HorRdx.matchAssociativeReduction(P, BI, DL) &&
3710 HorRdx.tryToReduce(R, TTI)) {
3717 Value *Inst = BI->getOperand(0);
3719 Inst = BI->getOperand(1);
3721 if (tryToVectorize(dyn_cast<BinaryOperator>(Inst), R)) {
3722 // We would like to start over since some instructions are deleted
3723 // and the iterator may become invalid value.
3733 // Try to vectorize horizontal reductions feeding into a store.
3734 if (ShouldStartVectorizeHorAtStore)
3735 if (StoreInst *SI = dyn_cast<StoreInst>(it))
3736 if (BinaryOperator *BinOp =
3737 dyn_cast<BinaryOperator>(SI->getValueOperand())) {
3738 HorizontalReduction HorRdx;
3739 if (((HorRdx.matchAssociativeReduction(nullptr, BinOp, DL) &&
3740 HorRdx.tryToReduce(R, TTI)) ||
3741 tryToVectorize(BinOp, R))) {
3749 // Try to vectorize horizontal reductions feeding into a return.
3750 if (ReturnInst *RI = dyn_cast<ReturnInst>(it))
3751 if (RI->getNumOperands() != 0)
3752 if (BinaryOperator *BinOp =
3753 dyn_cast<BinaryOperator>(RI->getOperand(0))) {
3754 DEBUG(dbgs() << "SLP: Found a return to vectorize.\n");
3755 if (tryToVectorizePair(BinOp->getOperand(0),
3756 BinOp->getOperand(1), R)) {
3764 // Try to vectorize trees that start at compare instructions.
3765 if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
3766 if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) {
3768 // We would like to start over since some instructions are deleted
3769 // and the iterator may become invalid value.
3775 for (int i = 0; i < 2; ++i) {
3776 if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i))) {
3777 if (tryToVectorizePair(BI->getOperand(0), BI->getOperand(1), R)) {
3779 // We would like to start over since some instructions are deleted
3780 // and the iterator may become invalid value.
3789 // Try to vectorize trees that start at insertelement instructions.
3790 if (InsertElementInst *FirstInsertElem = dyn_cast<InsertElementInst>(it)) {
3791 SmallVector<Value *, 16> BuildVector;
3792 SmallVector<Value *, 16> BuildVectorOpds;
3793 if (!findBuildVector(FirstInsertElem, BuildVector, BuildVectorOpds))
3796 // Vectorize starting with the build vector operands ignoring the
3797 // BuildVector instructions for the purpose of scheduling and user
3799 if (tryToVectorizeList(BuildVectorOpds, R, BuildVector)) {
3812 bool SLPVectorizer::vectorizeStoreChains(BoUpSLP &R) {
3813 bool Changed = false;
3814 // Attempt to sort and vectorize each of the store-groups.
3815 for (StoreListMap::iterator it = StoreRefs.begin(), e = StoreRefs.end();
3817 if (it->second.size() < 2)
3820 DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
3821 << it->second.size() << ".\n");
3823 // Process the stores in chunks of 16.
3824 for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI+=16) {
3825 unsigned Len = std::min<unsigned>(CE - CI, 16);
3826 Changed |= vectorizeStores(makeArrayRef(&it->second[CI], Len),
3827 -SLPCostThreshold, R);
3833 } // end anonymous namespace
3835 char SLPVectorizer::ID = 0;
3836 static const char lv_name[] = "SLP Vectorizer";
3837 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
3838 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3839 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
3840 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
3841 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
3842 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
3843 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
3846 Pass *createSLPVectorizerPass() { return new SLPVectorizer(); }