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 DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
597 /// A list of values that need to extracted out of the tree.
598 /// This list holds pairs of (Internal Scalar : External User).
599 UserList ExternalUses;
601 /// Values used only by @llvm.assume calls.
602 SmallPtrSet<const Value *, 32> EphValues;
604 /// Holds all of the instructions that we gathered.
605 SetVector<Instruction *> GatherSeq;
606 /// A list of blocks that we are going to CSE.
607 SetVector<BasicBlock *> CSEBlocks;
609 /// Contains all scheduling relevant data for an instruction.
610 /// A ScheduleData either represents a single instruction or a member of an
611 /// instruction bundle (= a group of instructions which is combined into a
612 /// vector instruction).
613 struct ScheduleData {
615 // The initial value for the dependency counters. It means that the
616 // dependencies are not calculated yet.
617 enum { InvalidDeps = -1 };
620 : Inst(nullptr), FirstInBundle(nullptr), NextInBundle(nullptr),
621 NextLoadStore(nullptr), SchedulingRegionID(0), SchedulingPriority(0),
622 Dependencies(InvalidDeps), UnscheduledDeps(InvalidDeps),
623 UnscheduledDepsInBundle(InvalidDeps), IsScheduled(false) {}
625 void init(int BlockSchedulingRegionID) {
626 FirstInBundle = this;
627 NextInBundle = nullptr;
628 NextLoadStore = nullptr;
630 SchedulingRegionID = BlockSchedulingRegionID;
631 UnscheduledDepsInBundle = UnscheduledDeps;
635 /// Returns true if the dependency information has been calculated.
636 bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
638 /// Returns true for single instructions and for bundle representatives
639 /// (= the head of a bundle).
640 bool isSchedulingEntity() const { return FirstInBundle == this; }
642 /// Returns true if it represents an instruction bundle and not only a
643 /// single instruction.
644 bool isPartOfBundle() const {
645 return NextInBundle != nullptr || FirstInBundle != this;
648 /// Returns true if it is ready for scheduling, i.e. it has no more
649 /// unscheduled depending instructions/bundles.
650 bool isReady() const {
651 assert(isSchedulingEntity() &&
652 "can't consider non-scheduling entity for ready list");
653 return UnscheduledDepsInBundle == 0 && !IsScheduled;
656 /// Modifies the number of unscheduled dependencies, also updating it for
657 /// the whole bundle.
658 int incrementUnscheduledDeps(int Incr) {
659 UnscheduledDeps += Incr;
660 return FirstInBundle->UnscheduledDepsInBundle += Incr;
663 /// Sets the number of unscheduled dependencies to the number of
665 void resetUnscheduledDeps() {
666 incrementUnscheduledDeps(Dependencies - UnscheduledDeps);
669 /// Clears all dependency information.
670 void clearDependencies() {
671 Dependencies = InvalidDeps;
672 resetUnscheduledDeps();
673 MemoryDependencies.clear();
676 void dump(raw_ostream &os) const {
677 if (!isSchedulingEntity()) {
679 } else if (NextInBundle) {
681 ScheduleData *SD = NextInBundle;
683 os << ';' << *SD->Inst;
684 SD = SD->NextInBundle;
694 /// Points to the head in an instruction bundle (and always to this for
695 /// single instructions).
696 ScheduleData *FirstInBundle;
698 /// Single linked list of all instructions in a bundle. Null if it is a
699 /// single instruction.
700 ScheduleData *NextInBundle;
702 /// Single linked list of all memory instructions (e.g. load, store, call)
703 /// in the block - until the end of the scheduling region.
704 ScheduleData *NextLoadStore;
706 /// The dependent memory instructions.
707 /// This list is derived on demand in calculateDependencies().
708 SmallVector<ScheduleData *, 4> MemoryDependencies;
710 /// This ScheduleData is in the current scheduling region if this matches
711 /// the current SchedulingRegionID of BlockScheduling.
712 int SchedulingRegionID;
714 /// Used for getting a "good" final ordering of instructions.
715 int SchedulingPriority;
717 /// The number of dependencies. Constitutes of the number of users of the
718 /// instruction plus the number of dependent memory instructions (if any).
719 /// This value is calculated on demand.
720 /// If InvalidDeps, the number of dependencies is not calculated yet.
724 /// The number of dependencies minus the number of dependencies of scheduled
725 /// instructions. As soon as this is zero, the instruction/bundle gets ready
727 /// Note that this is negative as long as Dependencies is not calculated.
730 /// The sum of UnscheduledDeps in a bundle. Equals to UnscheduledDeps for
731 /// single instructions.
732 int UnscheduledDepsInBundle;
734 /// True if this instruction is scheduled (or considered as scheduled in the
740 friend raw_ostream &operator<<(raw_ostream &os,
741 const BoUpSLP::ScheduleData &SD);
744 /// Contains all scheduling data for a basic block.
746 struct BlockScheduling {
748 BlockScheduling(BasicBlock *BB)
749 : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize),
750 ScheduleStart(nullptr), ScheduleEnd(nullptr),
751 FirstLoadStoreInRegion(nullptr), LastLoadStoreInRegion(nullptr),
752 // Make sure that the initial SchedulingRegionID is greater than the
753 // initial SchedulingRegionID in ScheduleData (which is 0).
754 SchedulingRegionID(1) {}
758 ScheduleStart = nullptr;
759 ScheduleEnd = nullptr;
760 FirstLoadStoreInRegion = nullptr;
761 LastLoadStoreInRegion = nullptr;
763 // Make a new scheduling region, i.e. all existing ScheduleData is not
764 // in the new region yet.
765 ++SchedulingRegionID;
768 ScheduleData *getScheduleData(Value *V) {
769 ScheduleData *SD = ScheduleDataMap[V];
770 if (SD && SD->SchedulingRegionID == SchedulingRegionID)
775 bool isInSchedulingRegion(ScheduleData *SD) {
776 return SD->SchedulingRegionID == SchedulingRegionID;
779 /// Marks an instruction as scheduled and puts all dependent ready
780 /// instructions into the ready-list.
781 template <typename ReadyListType>
782 void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
783 SD->IsScheduled = true;
784 DEBUG(dbgs() << "SLP: schedule " << *SD << "\n");
786 ScheduleData *BundleMember = SD;
787 while (BundleMember) {
788 // Handle the def-use chain dependencies.
789 for (Use &U : BundleMember->Inst->operands()) {
790 ScheduleData *OpDef = getScheduleData(U.get());
791 if (OpDef && OpDef->hasValidDependencies() &&
792 OpDef->incrementUnscheduledDeps(-1) == 0) {
793 // There are no more unscheduled dependencies after decrementing,
794 // so we can put the dependent instruction into the ready list.
795 ScheduleData *DepBundle = OpDef->FirstInBundle;
796 assert(!DepBundle->IsScheduled &&
797 "already scheduled bundle gets ready");
798 ReadyList.insert(DepBundle);
799 DEBUG(dbgs() << "SLP: gets ready (def): " << *DepBundle << "\n");
802 // Handle the memory dependencies.
803 for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
804 if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
805 // There are no more unscheduled dependencies after decrementing,
806 // so we can put the dependent instruction into the ready list.
807 ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
808 assert(!DepBundle->IsScheduled &&
809 "already scheduled bundle gets ready");
810 ReadyList.insert(DepBundle);
811 DEBUG(dbgs() << "SLP: gets ready (mem): " << *DepBundle << "\n");
814 BundleMember = BundleMember->NextInBundle;
818 /// Put all instructions into the ReadyList which are ready for scheduling.
819 template <typename ReadyListType>
820 void initialFillReadyList(ReadyListType &ReadyList) {
821 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
822 ScheduleData *SD = getScheduleData(I);
823 if (SD->isSchedulingEntity() && SD->isReady()) {
824 ReadyList.insert(SD);
825 DEBUG(dbgs() << "SLP: initially in ready list: " << *I << "\n");
830 /// Checks if a bundle of instructions can be scheduled, i.e. has no
831 /// cyclic dependencies. This is only a dry-run, no instructions are
832 /// actually moved at this stage.
833 bool tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP);
835 /// Un-bundles a group of instructions.
836 void cancelScheduling(ArrayRef<Value *> VL);
838 /// Extends the scheduling region so that V is inside the region.
839 void extendSchedulingRegion(Value *V);
841 /// Initialize the ScheduleData structures for new instructions in the
842 /// scheduling region.
843 void initScheduleData(Instruction *FromI, Instruction *ToI,
844 ScheduleData *PrevLoadStore,
845 ScheduleData *NextLoadStore);
847 /// Updates the dependency information of a bundle and of all instructions/
848 /// bundles which depend on the original bundle.
849 void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
852 /// Sets all instruction in the scheduling region to un-scheduled.
853 void resetSchedule();
857 /// Simple memory allocation for ScheduleData.
858 std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
860 /// The size of a ScheduleData array in ScheduleDataChunks.
863 /// The allocator position in the current chunk, which is the last entry
864 /// of ScheduleDataChunks.
867 /// Attaches ScheduleData to Instruction.
868 /// Note that the mapping survives during all vectorization iterations, i.e.
869 /// ScheduleData structures are recycled.
870 DenseMap<Value *, ScheduleData *> ScheduleDataMap;
872 struct ReadyList : SmallVector<ScheduleData *, 8> {
873 void insert(ScheduleData *SD) { push_back(SD); }
876 /// The ready-list for scheduling (only used for the dry-run).
877 ReadyList ReadyInsts;
879 /// The first instruction of the scheduling region.
880 Instruction *ScheduleStart;
882 /// The first instruction _after_ the scheduling region.
883 Instruction *ScheduleEnd;
885 /// The first memory accessing instruction in the scheduling region
887 ScheduleData *FirstLoadStoreInRegion;
889 /// The last memory accessing instruction in the scheduling region
891 ScheduleData *LastLoadStoreInRegion;
893 /// The ID of the scheduling region. For a new vectorization iteration this
894 /// is incremented which "removes" all ScheduleData from the region.
895 int SchedulingRegionID;
898 /// Attaches the BlockScheduling structures to basic blocks.
899 DenseMap<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
901 /// Performs the "real" scheduling. Done before vectorization is actually
902 /// performed in a basic block.
903 void scheduleBlock(BlockScheduling *BS);
905 /// List of users to ignore during scheduling and that don't need extracting.
906 ArrayRef<Value *> UserIgnoreList;
908 // Number of load-bundles, which contain consecutive loads.
909 int NumLoadsWantToKeepOrder;
911 // Number of load-bundles of size 2, which are consecutive loads if reversed.
912 int NumLoadsWantToChangeOrder;
914 // Analysis and block reference.
917 const DataLayout *DL;
918 TargetTransformInfo *TTI;
919 TargetLibraryInfo *TLI;
923 /// Instruction builder to construct the vectorized tree.
928 raw_ostream &operator<<(raw_ostream &os, const BoUpSLP::ScheduleData &SD) {
934 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
935 ArrayRef<Value *> UserIgnoreLst) {
937 UserIgnoreList = UserIgnoreLst;
938 if (!getSameType(Roots))
940 buildTree_rec(Roots, 0);
942 // Collect the values that we need to extract from the tree.
943 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
944 TreeEntry *Entry = &VectorizableTree[EIdx];
947 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
948 Value *Scalar = Entry->Scalars[Lane];
950 // No need to handle users of gathered values.
951 if (Entry->NeedToGather)
954 for (User *U : Scalar->users()) {
955 DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
957 Instruction *UserInst = dyn_cast<Instruction>(U);
961 // Skip in-tree scalars that become vectors
962 if (ScalarToTreeEntry.count(U)) {
963 int Idx = ScalarToTreeEntry[U];
964 TreeEntry *UseEntry = &VectorizableTree[Idx];
965 Value *UseScalar = UseEntry->Scalars[0];
966 // Some in-tree scalars will remain as scalar in vectorized
967 // instructions. If that is the case, the one in Lane 0 will
969 if (UseScalar != U ||
970 !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
971 DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
973 assert(!VectorizableTree[Idx].NeedToGather && "Bad state");
978 // Ignore users in the user ignore list.
979 if (std::find(UserIgnoreList.begin(), UserIgnoreList.end(), UserInst) !=
980 UserIgnoreList.end())
983 DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane " <<
984 Lane << " from " << *Scalar << ".\n");
985 ExternalUses.push_back(ExternalUser(Scalar, U, Lane));
992 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth) {
993 bool SameTy = getSameType(VL); (void)SameTy;
994 bool isAltShuffle = false;
995 assert(SameTy && "Invalid types!");
997 if (Depth == RecursionMaxDepth) {
998 DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
999 newTreeEntry(VL, false);
1003 // Don't handle vectors.
1004 if (VL[0]->getType()->isVectorTy()) {
1005 DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
1006 newTreeEntry(VL, false);
1010 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1011 if (SI->getValueOperand()->getType()->isVectorTy()) {
1012 DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
1013 newTreeEntry(VL, false);
1016 unsigned Opcode = getSameOpcode(VL);
1018 // Check that this shuffle vector refers to the alternate
1019 // sequence of opcodes.
1020 if (Opcode == Instruction::ShuffleVector) {
1021 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
1022 unsigned Op = I0->getOpcode();
1023 if (Op != Instruction::ShuffleVector)
1024 isAltShuffle = true;
1027 // If all of the operands are identical or constant we have a simple solution.
1028 if (allConstant(VL) || isSplat(VL) || !getSameBlock(VL) || !Opcode) {
1029 DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
1030 newTreeEntry(VL, false);
1034 // We now know that this is a vector of instructions of the same type from
1037 // Don't vectorize ephemeral values.
1038 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1039 if (EphValues.count(VL[i])) {
1040 DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
1041 ") is ephemeral.\n");
1042 newTreeEntry(VL, false);
1047 // Check if this is a duplicate of another entry.
1048 if (ScalarToTreeEntry.count(VL[0])) {
1049 int Idx = ScalarToTreeEntry[VL[0]];
1050 TreeEntry *E = &VectorizableTree[Idx];
1051 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1052 DEBUG(dbgs() << "SLP: \tChecking bundle: " << *VL[i] << ".\n");
1053 if (E->Scalars[i] != VL[i]) {
1054 DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
1055 newTreeEntry(VL, false);
1059 DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *VL[0] << ".\n");
1063 // Check that none of the instructions in the bundle are already in the tree.
1064 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1065 if (ScalarToTreeEntry.count(VL[i])) {
1066 DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
1067 ") is already in tree.\n");
1068 newTreeEntry(VL, false);
1073 // If any of the scalars is marked as a value that needs to stay scalar then
1074 // we need to gather the scalars.
1075 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1076 if (MustGather.count(VL[i])) {
1077 DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
1078 newTreeEntry(VL, false);
1083 // Check that all of the users of the scalars that we want to vectorize are
1085 Instruction *VL0 = cast<Instruction>(VL[0]);
1086 BasicBlock *BB = cast<Instruction>(VL0)->getParent();
1088 if (!DT->isReachableFromEntry(BB)) {
1089 // Don't go into unreachable blocks. They may contain instructions with
1090 // dependency cycles which confuse the final scheduling.
1091 DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
1092 newTreeEntry(VL, false);
1096 // Check that every instructions appears once in this bundle.
1097 for (unsigned i = 0, e = VL.size(); i < e; ++i)
1098 for (unsigned j = i+1; j < e; ++j)
1099 if (VL[i] == VL[j]) {
1100 DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
1101 newTreeEntry(VL, false);
1105 auto &BSRef = BlocksSchedules[BB];
1107 BSRef = llvm::make_unique<BlockScheduling>(BB);
1109 BlockScheduling &BS = *BSRef.get();
1111 if (!BS.tryScheduleBundle(VL, this)) {
1112 DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
1113 BS.cancelScheduling(VL);
1114 newTreeEntry(VL, false);
1117 DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
1120 case Instruction::PHI: {
1121 PHINode *PH = dyn_cast<PHINode>(VL0);
1123 // Check for terminator values (e.g. invoke).
1124 for (unsigned j = 0; j < VL.size(); ++j)
1125 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1126 TerminatorInst *Term = dyn_cast<TerminatorInst>(
1127 cast<PHINode>(VL[j])->getIncomingValueForBlock(PH->getIncomingBlock(i)));
1129 DEBUG(dbgs() << "SLP: Need to swizzle PHINodes (TerminatorInst use).\n");
1130 BS.cancelScheduling(VL);
1131 newTreeEntry(VL, false);
1136 newTreeEntry(VL, true);
1137 DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
1139 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1141 // Prepare the operand vector.
1142 for (unsigned j = 0; j < VL.size(); ++j)
1143 Operands.push_back(cast<PHINode>(VL[j])->getIncomingValueForBlock(
1144 PH->getIncomingBlock(i)));
1146 buildTree_rec(Operands, Depth + 1);
1150 case Instruction::ExtractElement: {
1151 bool Reuse = CanReuseExtract(VL);
1153 DEBUG(dbgs() << "SLP: Reusing extract sequence.\n");
1155 BS.cancelScheduling(VL);
1157 newTreeEntry(VL, Reuse);
1160 case Instruction::Load: {
1161 // Check if the loads are consecutive or of we need to swizzle them.
1162 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i) {
1163 LoadInst *L = cast<LoadInst>(VL[i]);
1164 if (!L->isSimple()) {
1165 BS.cancelScheduling(VL);
1166 newTreeEntry(VL, false);
1167 DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
1170 if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
1171 if (VL.size() == 2 && isConsecutiveAccess(VL[1], VL[0])) {
1172 ++NumLoadsWantToChangeOrder;
1174 BS.cancelScheduling(VL);
1175 newTreeEntry(VL, false);
1176 DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
1180 ++NumLoadsWantToKeepOrder;
1181 newTreeEntry(VL, true);
1182 DEBUG(dbgs() << "SLP: added a vector of loads.\n");
1185 case Instruction::ZExt:
1186 case Instruction::SExt:
1187 case Instruction::FPToUI:
1188 case Instruction::FPToSI:
1189 case Instruction::FPExt:
1190 case Instruction::PtrToInt:
1191 case Instruction::IntToPtr:
1192 case Instruction::SIToFP:
1193 case Instruction::UIToFP:
1194 case Instruction::Trunc:
1195 case Instruction::FPTrunc:
1196 case Instruction::BitCast: {
1197 Type *SrcTy = VL0->getOperand(0)->getType();
1198 for (unsigned i = 0; i < VL.size(); ++i) {
1199 Type *Ty = cast<Instruction>(VL[i])->getOperand(0)->getType();
1200 if (Ty != SrcTy || Ty->isAggregateType() || Ty->isVectorTy()) {
1201 BS.cancelScheduling(VL);
1202 newTreeEntry(VL, false);
1203 DEBUG(dbgs() << "SLP: Gathering casts with different src types.\n");
1207 newTreeEntry(VL, true);
1208 DEBUG(dbgs() << "SLP: added a vector of casts.\n");
1210 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1212 // Prepare the operand vector.
1213 for (unsigned j = 0; j < VL.size(); ++j)
1214 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1216 buildTree_rec(Operands, Depth+1);
1220 case Instruction::ICmp:
1221 case Instruction::FCmp: {
1222 // Check that all of the compares have the same predicate.
1223 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
1224 Type *ComparedTy = cast<Instruction>(VL[0])->getOperand(0)->getType();
1225 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
1226 CmpInst *Cmp = cast<CmpInst>(VL[i]);
1227 if (Cmp->getPredicate() != P0 ||
1228 Cmp->getOperand(0)->getType() != ComparedTy) {
1229 BS.cancelScheduling(VL);
1230 newTreeEntry(VL, false);
1231 DEBUG(dbgs() << "SLP: Gathering cmp with different predicate.\n");
1236 newTreeEntry(VL, true);
1237 DEBUG(dbgs() << "SLP: added a vector of compares.\n");
1239 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1241 // Prepare the operand vector.
1242 for (unsigned j = 0; j < VL.size(); ++j)
1243 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1245 buildTree_rec(Operands, Depth+1);
1249 case Instruction::Select:
1250 case Instruction::Add:
1251 case Instruction::FAdd:
1252 case Instruction::Sub:
1253 case Instruction::FSub:
1254 case Instruction::Mul:
1255 case Instruction::FMul:
1256 case Instruction::UDiv:
1257 case Instruction::SDiv:
1258 case Instruction::FDiv:
1259 case Instruction::URem:
1260 case Instruction::SRem:
1261 case Instruction::FRem:
1262 case Instruction::Shl:
1263 case Instruction::LShr:
1264 case Instruction::AShr:
1265 case Instruction::And:
1266 case Instruction::Or:
1267 case Instruction::Xor: {
1268 newTreeEntry(VL, true);
1269 DEBUG(dbgs() << "SLP: added a vector of bin op.\n");
1271 // Sort operands of the instructions so that each side is more likely to
1272 // have the same opcode.
1273 if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
1274 ValueList Left, Right;
1275 reorderInputsAccordingToOpcode(VL, Left, Right);
1276 buildTree_rec(Left, Depth + 1);
1277 buildTree_rec(Right, Depth + 1);
1281 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1283 // Prepare the operand vector.
1284 for (unsigned j = 0; j < VL.size(); ++j)
1285 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1287 buildTree_rec(Operands, Depth+1);
1291 case Instruction::GetElementPtr: {
1292 // We don't combine GEPs with complicated (nested) indexing.
1293 for (unsigned j = 0; j < VL.size(); ++j) {
1294 if (cast<Instruction>(VL[j])->getNumOperands() != 2) {
1295 DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
1296 BS.cancelScheduling(VL);
1297 newTreeEntry(VL, false);
1302 // We can't combine several GEPs into one vector if they operate on
1304 Type *Ty0 = cast<Instruction>(VL0)->getOperand(0)->getType();
1305 for (unsigned j = 0; j < VL.size(); ++j) {
1306 Type *CurTy = cast<Instruction>(VL[j])->getOperand(0)->getType();
1308 DEBUG(dbgs() << "SLP: not-vectorizable GEP (different types).\n");
1309 BS.cancelScheduling(VL);
1310 newTreeEntry(VL, false);
1315 // We don't combine GEPs with non-constant indexes.
1316 for (unsigned j = 0; j < VL.size(); ++j) {
1317 auto Op = cast<Instruction>(VL[j])->getOperand(1);
1318 if (!isa<ConstantInt>(Op)) {
1320 dbgs() << "SLP: not-vectorizable GEP (non-constant indexes).\n");
1321 BS.cancelScheduling(VL);
1322 newTreeEntry(VL, false);
1327 newTreeEntry(VL, true);
1328 DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
1329 for (unsigned i = 0, e = 2; i < e; ++i) {
1331 // Prepare the operand vector.
1332 for (unsigned j = 0; j < VL.size(); ++j)
1333 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1335 buildTree_rec(Operands, Depth + 1);
1339 case Instruction::Store: {
1340 // Check if the stores are consecutive or of we need to swizzle them.
1341 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
1342 if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
1343 BS.cancelScheduling(VL);
1344 newTreeEntry(VL, false);
1345 DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
1349 newTreeEntry(VL, true);
1350 DEBUG(dbgs() << "SLP: added a vector of stores.\n");
1353 for (unsigned j = 0; j < VL.size(); ++j)
1354 Operands.push_back(cast<Instruction>(VL[j])->getOperand(0));
1356 buildTree_rec(Operands, Depth + 1);
1359 case Instruction::Call: {
1360 // Check if the calls are all to the same vectorizable intrinsic.
1361 CallInst *CI = cast<CallInst>(VL[0]);
1362 // Check if this is an Intrinsic call or something that can be
1363 // represented by an intrinsic call
1364 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
1365 if (!isTriviallyVectorizable(ID)) {
1366 BS.cancelScheduling(VL);
1367 newTreeEntry(VL, false);
1368 DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
1371 Function *Int = CI->getCalledFunction();
1372 Value *A1I = nullptr;
1373 if (hasVectorInstrinsicScalarOpd(ID, 1))
1374 A1I = CI->getArgOperand(1);
1375 for (unsigned i = 1, e = VL.size(); i != e; ++i) {
1376 CallInst *CI2 = dyn_cast<CallInst>(VL[i]);
1377 if (!CI2 || CI2->getCalledFunction() != Int ||
1378 getIntrinsicIDForCall(CI2, TLI) != ID) {
1379 BS.cancelScheduling(VL);
1380 newTreeEntry(VL, false);
1381 DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *VL[i]
1385 // ctlz,cttz and powi are special intrinsics whose second argument
1386 // should be same in order for them to be vectorized.
1387 if (hasVectorInstrinsicScalarOpd(ID, 1)) {
1388 Value *A1J = CI2->getArgOperand(1);
1390 BS.cancelScheduling(VL);
1391 newTreeEntry(VL, false);
1392 DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
1393 << " argument "<< A1I<<"!=" << A1J
1400 newTreeEntry(VL, true);
1401 for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i) {
1403 // Prepare the operand vector.
1404 for (unsigned j = 0; j < VL.size(); ++j) {
1405 CallInst *CI2 = dyn_cast<CallInst>(VL[j]);
1406 Operands.push_back(CI2->getArgOperand(i));
1408 buildTree_rec(Operands, Depth + 1);
1412 case Instruction::ShuffleVector: {
1413 // If this is not an alternate sequence of opcode like add-sub
1414 // then do not vectorize this instruction.
1415 if (!isAltShuffle) {
1416 BS.cancelScheduling(VL);
1417 newTreeEntry(VL, false);
1418 DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
1421 newTreeEntry(VL, true);
1422 DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
1423 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1425 // Prepare the operand vector.
1426 for (unsigned j = 0; j < VL.size(); ++j)
1427 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1429 buildTree_rec(Operands, Depth + 1);
1434 BS.cancelScheduling(VL);
1435 newTreeEntry(VL, false);
1436 DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
1441 int BoUpSLP::getEntryCost(TreeEntry *E) {
1442 ArrayRef<Value*> VL = E->Scalars;
1444 Type *ScalarTy = VL[0]->getType();
1445 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1446 ScalarTy = SI->getValueOperand()->getType();
1447 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1449 if (E->NeedToGather) {
1450 if (allConstant(VL))
1453 return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
1455 return getGatherCost(E->Scalars);
1457 unsigned Opcode = getSameOpcode(VL);
1458 assert(Opcode && getSameType(VL) && getSameBlock(VL) && "Invalid VL");
1459 Instruction *VL0 = cast<Instruction>(VL[0]);
1461 case Instruction::PHI: {
1464 case Instruction::ExtractElement: {
1465 if (CanReuseExtract(VL)) {
1467 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
1468 ExtractElementInst *E = cast<ExtractElementInst>(VL[i]);
1470 // Take credit for instruction that will become dead.
1472 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, i);
1476 return getGatherCost(VecTy);
1478 case Instruction::ZExt:
1479 case Instruction::SExt:
1480 case Instruction::FPToUI:
1481 case Instruction::FPToSI:
1482 case Instruction::FPExt:
1483 case Instruction::PtrToInt:
1484 case Instruction::IntToPtr:
1485 case Instruction::SIToFP:
1486 case Instruction::UIToFP:
1487 case Instruction::Trunc:
1488 case Instruction::FPTrunc:
1489 case Instruction::BitCast: {
1490 Type *SrcTy = VL0->getOperand(0)->getType();
1492 // Calculate the cost of this instruction.
1493 int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(),
1494 VL0->getType(), SrcTy);
1496 VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
1497 int VecCost = TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy);
1498 return VecCost - ScalarCost;
1500 case Instruction::FCmp:
1501 case Instruction::ICmp:
1502 case Instruction::Select:
1503 case Instruction::Add:
1504 case Instruction::FAdd:
1505 case Instruction::Sub:
1506 case Instruction::FSub:
1507 case Instruction::Mul:
1508 case Instruction::FMul:
1509 case Instruction::UDiv:
1510 case Instruction::SDiv:
1511 case Instruction::FDiv:
1512 case Instruction::URem:
1513 case Instruction::SRem:
1514 case Instruction::FRem:
1515 case Instruction::Shl:
1516 case Instruction::LShr:
1517 case Instruction::AShr:
1518 case Instruction::And:
1519 case Instruction::Or:
1520 case Instruction::Xor: {
1521 // Calculate the cost of this instruction.
1524 if (Opcode == Instruction::FCmp || Opcode == Instruction::ICmp ||
1525 Opcode == Instruction::Select) {
1526 VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
1527 ScalarCost = VecTy->getNumElements() *
1528 TTI->getCmpSelInstrCost(Opcode, ScalarTy, Builder.getInt1Ty());
1529 VecCost = TTI->getCmpSelInstrCost(Opcode, VecTy, MaskTy);
1531 // Certain instructions can be cheaper to vectorize if they have a
1532 // constant second vector operand.
1533 TargetTransformInfo::OperandValueKind Op1VK =
1534 TargetTransformInfo::OK_AnyValue;
1535 TargetTransformInfo::OperandValueKind Op2VK =
1536 TargetTransformInfo::OK_UniformConstantValue;
1537 TargetTransformInfo::OperandValueProperties Op1VP =
1538 TargetTransformInfo::OP_None;
1539 TargetTransformInfo::OperandValueProperties Op2VP =
1540 TargetTransformInfo::OP_None;
1542 // If all operands are exactly the same ConstantInt then set the
1543 // operand kind to OK_UniformConstantValue.
1544 // If instead not all operands are constants, then set the operand kind
1545 // to OK_AnyValue. If all operands are constants but not the same,
1546 // then set the operand kind to OK_NonUniformConstantValue.
1547 ConstantInt *CInt = nullptr;
1548 for (unsigned i = 0; i < VL.size(); ++i) {
1549 const Instruction *I = cast<Instruction>(VL[i]);
1550 if (!isa<ConstantInt>(I->getOperand(1))) {
1551 Op2VK = TargetTransformInfo::OK_AnyValue;
1555 CInt = cast<ConstantInt>(I->getOperand(1));
1558 if (Op2VK == TargetTransformInfo::OK_UniformConstantValue &&
1559 CInt != cast<ConstantInt>(I->getOperand(1)))
1560 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
1562 // FIXME: Currently cost of model modification for division by
1563 // power of 2 is handled only for X86. Add support for other targets.
1564 if (Op2VK == TargetTransformInfo::OK_UniformConstantValue && CInt &&
1565 CInt->getValue().isPowerOf2())
1566 Op2VP = TargetTransformInfo::OP_PowerOf2;
1568 ScalarCost = VecTy->getNumElements() *
1569 TTI->getArithmeticInstrCost(Opcode, ScalarTy, Op1VK, Op2VK,
1571 VecCost = TTI->getArithmeticInstrCost(Opcode, VecTy, Op1VK, Op2VK,
1574 return VecCost - ScalarCost;
1576 case Instruction::GetElementPtr: {
1577 TargetTransformInfo::OperandValueKind Op1VK =
1578 TargetTransformInfo::OK_AnyValue;
1579 TargetTransformInfo::OperandValueKind Op2VK =
1580 TargetTransformInfo::OK_UniformConstantValue;
1583 VecTy->getNumElements() *
1584 TTI->getArithmeticInstrCost(Instruction::Add, ScalarTy, Op1VK, Op2VK);
1586 TTI->getArithmeticInstrCost(Instruction::Add, VecTy, Op1VK, Op2VK);
1588 return VecCost - ScalarCost;
1590 case Instruction::Load: {
1591 // Cost of wide load - cost of scalar loads.
1592 int ScalarLdCost = VecTy->getNumElements() *
1593 TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
1594 int VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, 1, 0);
1595 return VecLdCost - ScalarLdCost;
1597 case Instruction::Store: {
1598 // We know that we can merge the stores. Calculate the cost.
1599 int ScalarStCost = VecTy->getNumElements() *
1600 TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
1601 int VecStCost = TTI->getMemoryOpCost(Instruction::Store, VecTy, 1, 0);
1602 return VecStCost - ScalarStCost;
1604 case Instruction::Call: {
1605 CallInst *CI = cast<CallInst>(VL0);
1606 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
1608 // Calculate the cost of the scalar and vector calls.
1609 SmallVector<Type*, 4> ScalarTys, VecTys;
1610 for (unsigned op = 0, opc = CI->getNumArgOperands(); op!= opc; ++op) {
1611 ScalarTys.push_back(CI->getArgOperand(op)->getType());
1612 VecTys.push_back(VectorType::get(CI->getArgOperand(op)->getType(),
1613 VecTy->getNumElements()));
1616 int ScalarCallCost = VecTy->getNumElements() *
1617 TTI->getIntrinsicInstrCost(ID, ScalarTy, ScalarTys);
1619 int VecCallCost = TTI->getIntrinsicInstrCost(ID, VecTy, VecTys);
1621 DEBUG(dbgs() << "SLP: Call cost "<< VecCallCost - ScalarCallCost
1622 << " (" << VecCallCost << "-" << ScalarCallCost << ")"
1623 << " for " << *CI << "\n");
1625 return VecCallCost - ScalarCallCost;
1627 case Instruction::ShuffleVector: {
1628 TargetTransformInfo::OperandValueKind Op1VK =
1629 TargetTransformInfo::OK_AnyValue;
1630 TargetTransformInfo::OperandValueKind Op2VK =
1631 TargetTransformInfo::OK_AnyValue;
1634 for (unsigned i = 0; i < VL.size(); ++i) {
1635 Instruction *I = cast<Instruction>(VL[i]);
1639 TTI->getArithmeticInstrCost(I->getOpcode(), ScalarTy, Op1VK, Op2VK);
1641 // VecCost is equal to sum of the cost of creating 2 vectors
1642 // and the cost of creating shuffle.
1643 Instruction *I0 = cast<Instruction>(VL[0]);
1645 TTI->getArithmeticInstrCost(I0->getOpcode(), VecTy, Op1VK, Op2VK);
1646 Instruction *I1 = cast<Instruction>(VL[1]);
1648 TTI->getArithmeticInstrCost(I1->getOpcode(), VecTy, Op1VK, Op2VK);
1650 TTI->getShuffleCost(TargetTransformInfo::SK_Alternate, VecTy, 0);
1651 return VecCost - ScalarCost;
1654 llvm_unreachable("Unknown instruction");
1658 bool BoUpSLP::isFullyVectorizableTinyTree() {
1659 DEBUG(dbgs() << "SLP: Check whether the tree with height " <<
1660 VectorizableTree.size() << " is fully vectorizable .\n");
1662 // We only handle trees of height 2.
1663 if (VectorizableTree.size() != 2)
1666 // Handle splat stores.
1667 if (!VectorizableTree[0].NeedToGather && isSplat(VectorizableTree[1].Scalars))
1670 // Gathering cost would be too much for tiny trees.
1671 if (VectorizableTree[0].NeedToGather || VectorizableTree[1].NeedToGather)
1677 int BoUpSLP::getSpillCost() {
1678 // Walk from the bottom of the tree to the top, tracking which values are
1679 // live. When we see a call instruction that is not part of our tree,
1680 // query TTI to see if there is a cost to keeping values live over it
1681 // (for example, if spills and fills are required).
1682 unsigned BundleWidth = VectorizableTree.front().Scalars.size();
1685 SmallPtrSet<Instruction*, 4> LiveValues;
1686 Instruction *PrevInst = nullptr;
1688 for (unsigned N = 0; N < VectorizableTree.size(); ++N) {
1689 Instruction *Inst = dyn_cast<Instruction>(VectorizableTree[N].Scalars[0]);
1699 dbgs() << "SLP: #LV: " << LiveValues.size();
1700 for (auto *X : LiveValues)
1701 dbgs() << " " << X->getName();
1702 dbgs() << ", Looking at ";
1706 // Update LiveValues.
1707 LiveValues.erase(PrevInst);
1708 for (auto &J : PrevInst->operands()) {
1709 if (isa<Instruction>(&*J) && ScalarToTreeEntry.count(&*J))
1710 LiveValues.insert(cast<Instruction>(&*J));
1713 // Now find the sequence of instructions between PrevInst and Inst.
1714 BasicBlock::reverse_iterator InstIt(Inst), PrevInstIt(PrevInst);
1716 while (InstIt != PrevInstIt) {
1717 if (PrevInstIt == PrevInst->getParent()->rend()) {
1718 PrevInstIt = Inst->getParent()->rbegin();
1722 if (isa<CallInst>(&*PrevInstIt) && &*PrevInstIt != PrevInst) {
1723 SmallVector<Type*, 4> V;
1724 for (auto *II : LiveValues)
1725 V.push_back(VectorType::get(II->getType(), BundleWidth));
1726 Cost += TTI->getCostOfKeepingLiveOverCall(V);
1735 DEBUG(dbgs() << "SLP: SpillCost=" << Cost << "\n");
1739 int BoUpSLP::getTreeCost() {
1741 DEBUG(dbgs() << "SLP: Calculating cost for tree of size " <<
1742 VectorizableTree.size() << ".\n");
1744 // We only vectorize tiny trees if it is fully vectorizable.
1745 if (VectorizableTree.size() < 3 && !isFullyVectorizableTinyTree()) {
1746 if (!VectorizableTree.size()) {
1747 assert(!ExternalUses.size() && "We should not have any external users");
1752 unsigned BundleWidth = VectorizableTree[0].Scalars.size();
1754 for (unsigned i = 0, e = VectorizableTree.size(); i != e; ++i) {
1755 int C = getEntryCost(&VectorizableTree[i]);
1756 DEBUG(dbgs() << "SLP: Adding cost " << C << " for bundle that starts with "
1757 << *VectorizableTree[i].Scalars[0] << " .\n");
1761 SmallSet<Value *, 16> ExtractCostCalculated;
1762 int ExtractCost = 0;
1763 for (UserList::iterator I = ExternalUses.begin(), E = ExternalUses.end();
1765 // We only add extract cost once for the same scalar.
1766 if (!ExtractCostCalculated.insert(I->Scalar).second)
1769 // Uses by ephemeral values are free (because the ephemeral value will be
1770 // removed prior to code generation, and so the extraction will be
1771 // removed as well).
1772 if (EphValues.count(I->User))
1775 VectorType *VecTy = VectorType::get(I->Scalar->getType(), BundleWidth);
1776 ExtractCost += TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy,
1780 Cost += getSpillCost();
1782 DEBUG(dbgs() << "SLP: Total Cost " << Cost + ExtractCost<< ".\n");
1783 return Cost + ExtractCost;
1786 int BoUpSLP::getGatherCost(Type *Ty) {
1788 for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
1789 Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
1793 int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) {
1794 // Find the type of the operands in VL.
1795 Type *ScalarTy = VL[0]->getType();
1796 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1797 ScalarTy = SI->getValueOperand()->getType();
1798 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1799 // Find the cost of inserting/extracting values from the vector.
1800 return getGatherCost(VecTy);
1803 Value *BoUpSLP::getPointerOperand(Value *I) {
1804 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1805 return LI->getPointerOperand();
1806 if (StoreInst *SI = dyn_cast<StoreInst>(I))
1807 return SI->getPointerOperand();
1811 unsigned BoUpSLP::getAddressSpaceOperand(Value *I) {
1812 if (LoadInst *L = dyn_cast<LoadInst>(I))
1813 return L->getPointerAddressSpace();
1814 if (StoreInst *S = dyn_cast<StoreInst>(I))
1815 return S->getPointerAddressSpace();
1819 bool BoUpSLP::isConsecutiveAccess(Value *A, Value *B) {
1820 Value *PtrA = getPointerOperand(A);
1821 Value *PtrB = getPointerOperand(B);
1822 unsigned ASA = getAddressSpaceOperand(A);
1823 unsigned ASB = getAddressSpaceOperand(B);
1825 // Check that the address spaces match and that the pointers are valid.
1826 if (!PtrA || !PtrB || (ASA != ASB))
1829 // Make sure that A and B are different pointers of the same type.
1830 if (PtrA == PtrB || PtrA->getType() != PtrB->getType())
1833 unsigned PtrBitWidth = DL->getPointerSizeInBits(ASA);
1834 Type *Ty = cast<PointerType>(PtrA->getType())->getElementType();
1835 APInt Size(PtrBitWidth, DL->getTypeStoreSize(Ty));
1837 APInt OffsetA(PtrBitWidth, 0), OffsetB(PtrBitWidth, 0);
1838 PtrA = PtrA->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetA);
1839 PtrB = PtrB->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetB);
1841 APInt OffsetDelta = OffsetB - OffsetA;
1843 // Check if they are based on the same pointer. That makes the offsets
1846 return OffsetDelta == Size;
1848 // Compute the necessary base pointer delta to have the necessary final delta
1849 // equal to the size.
1850 APInt BaseDelta = Size - OffsetDelta;
1852 // Otherwise compute the distance with SCEV between the base pointers.
1853 const SCEV *PtrSCEVA = SE->getSCEV(PtrA);
1854 const SCEV *PtrSCEVB = SE->getSCEV(PtrB);
1855 const SCEV *C = SE->getConstant(BaseDelta);
1856 const SCEV *X = SE->getAddExpr(PtrSCEVA, C);
1857 return X == PtrSCEVB;
1860 void BoUpSLP::setInsertPointAfterBundle(ArrayRef<Value *> VL) {
1861 Instruction *VL0 = cast<Instruction>(VL[0]);
1862 BasicBlock::iterator NextInst = VL0;
1864 Builder.SetInsertPoint(VL0->getParent(), NextInst);
1865 Builder.SetCurrentDebugLocation(VL0->getDebugLoc());
1868 Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
1869 Value *Vec = UndefValue::get(Ty);
1870 // Generate the 'InsertElement' instruction.
1871 for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
1872 Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
1873 if (Instruction *Insrt = dyn_cast<Instruction>(Vec)) {
1874 GatherSeq.insert(Insrt);
1875 CSEBlocks.insert(Insrt->getParent());
1877 // Add to our 'need-to-extract' list.
1878 if (ScalarToTreeEntry.count(VL[i])) {
1879 int Idx = ScalarToTreeEntry[VL[i]];
1880 TreeEntry *E = &VectorizableTree[Idx];
1881 // Find which lane we need to extract.
1883 for (unsigned Lane = 0, LE = VL.size(); Lane != LE; ++Lane) {
1884 // Is this the lane of the scalar that we are looking for ?
1885 if (E->Scalars[Lane] == VL[i]) {
1890 assert(FoundLane >= 0 && "Could not find the correct lane");
1891 ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
1899 Value *BoUpSLP::alreadyVectorized(ArrayRef<Value *> VL) const {
1900 SmallDenseMap<Value*, int>::const_iterator Entry
1901 = ScalarToTreeEntry.find(VL[0]);
1902 if (Entry != ScalarToTreeEntry.end()) {
1903 int Idx = Entry->second;
1904 const TreeEntry *En = &VectorizableTree[Idx];
1905 if (En->isSame(VL) && En->VectorizedValue)
1906 return En->VectorizedValue;
1911 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
1912 if (ScalarToTreeEntry.count(VL[0])) {
1913 int Idx = ScalarToTreeEntry[VL[0]];
1914 TreeEntry *E = &VectorizableTree[Idx];
1916 return vectorizeTree(E);
1919 Type *ScalarTy = VL[0]->getType();
1920 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1921 ScalarTy = SI->getValueOperand()->getType();
1922 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1924 return Gather(VL, VecTy);
1927 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
1928 IRBuilder<>::InsertPointGuard Guard(Builder);
1930 if (E->VectorizedValue) {
1931 DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
1932 return E->VectorizedValue;
1935 Instruction *VL0 = cast<Instruction>(E->Scalars[0]);
1936 Type *ScalarTy = VL0->getType();
1937 if (StoreInst *SI = dyn_cast<StoreInst>(VL0))
1938 ScalarTy = SI->getValueOperand()->getType();
1939 VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size());
1941 if (E->NeedToGather) {
1942 setInsertPointAfterBundle(E->Scalars);
1943 return Gather(E->Scalars, VecTy);
1946 unsigned Opcode = getSameOpcode(E->Scalars);
1949 case Instruction::PHI: {
1950 PHINode *PH = dyn_cast<PHINode>(VL0);
1951 Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
1952 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1953 PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
1954 E->VectorizedValue = NewPhi;
1956 // PHINodes may have multiple entries from the same block. We want to
1957 // visit every block once.
1958 SmallSet<BasicBlock*, 4> VisitedBBs;
1960 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1962 BasicBlock *IBB = PH->getIncomingBlock(i);
1964 if (!VisitedBBs.insert(IBB).second) {
1965 NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
1969 // Prepare the operand vector.
1970 for (unsigned j = 0; j < E->Scalars.size(); ++j)
1971 Operands.push_back(cast<PHINode>(E->Scalars[j])->
1972 getIncomingValueForBlock(IBB));
1974 Builder.SetInsertPoint(IBB->getTerminator());
1975 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1976 Value *Vec = vectorizeTree(Operands);
1977 NewPhi->addIncoming(Vec, IBB);
1980 assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
1981 "Invalid number of incoming values");
1985 case Instruction::ExtractElement: {
1986 if (CanReuseExtract(E->Scalars)) {
1987 Value *V = VL0->getOperand(0);
1988 E->VectorizedValue = V;
1991 return Gather(E->Scalars, VecTy);
1993 case Instruction::ZExt:
1994 case Instruction::SExt:
1995 case Instruction::FPToUI:
1996 case Instruction::FPToSI:
1997 case Instruction::FPExt:
1998 case Instruction::PtrToInt:
1999 case Instruction::IntToPtr:
2000 case Instruction::SIToFP:
2001 case Instruction::UIToFP:
2002 case Instruction::Trunc:
2003 case Instruction::FPTrunc:
2004 case Instruction::BitCast: {
2006 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
2007 INVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
2009 setInsertPointAfterBundle(E->Scalars);
2011 Value *InVec = vectorizeTree(INVL);
2013 if (Value *V = alreadyVectorized(E->Scalars))
2016 CastInst *CI = dyn_cast<CastInst>(VL0);
2017 Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
2018 E->VectorizedValue = V;
2019 ++NumVectorInstructions;
2022 case Instruction::FCmp:
2023 case Instruction::ICmp: {
2024 ValueList LHSV, RHSV;
2025 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
2026 LHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
2027 RHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
2030 setInsertPointAfterBundle(E->Scalars);
2032 Value *L = vectorizeTree(LHSV);
2033 Value *R = vectorizeTree(RHSV);
2035 if (Value *V = alreadyVectorized(E->Scalars))
2038 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
2040 if (Opcode == Instruction::FCmp)
2041 V = Builder.CreateFCmp(P0, L, R);
2043 V = Builder.CreateICmp(P0, L, R);
2045 E->VectorizedValue = V;
2046 ++NumVectorInstructions;
2049 case Instruction::Select: {
2050 ValueList TrueVec, FalseVec, CondVec;
2051 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
2052 CondVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
2053 TrueVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
2054 FalseVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(2));
2057 setInsertPointAfterBundle(E->Scalars);
2059 Value *Cond = vectorizeTree(CondVec);
2060 Value *True = vectorizeTree(TrueVec);
2061 Value *False = vectorizeTree(FalseVec);
2063 if (Value *V = alreadyVectorized(E->Scalars))
2066 Value *V = Builder.CreateSelect(Cond, True, False);
2067 E->VectorizedValue = V;
2068 ++NumVectorInstructions;
2071 case Instruction::Add:
2072 case Instruction::FAdd:
2073 case Instruction::Sub:
2074 case Instruction::FSub:
2075 case Instruction::Mul:
2076 case Instruction::FMul:
2077 case Instruction::UDiv:
2078 case Instruction::SDiv:
2079 case Instruction::FDiv:
2080 case Instruction::URem:
2081 case Instruction::SRem:
2082 case Instruction::FRem:
2083 case Instruction::Shl:
2084 case Instruction::LShr:
2085 case Instruction::AShr:
2086 case Instruction::And:
2087 case Instruction::Or:
2088 case Instruction::Xor: {
2089 ValueList LHSVL, RHSVL;
2090 if (isa<BinaryOperator>(VL0) && VL0->isCommutative())
2091 reorderInputsAccordingToOpcode(E->Scalars, LHSVL, RHSVL);
2093 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
2094 LHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
2095 RHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
2098 setInsertPointAfterBundle(E->Scalars);
2100 Value *LHS = vectorizeTree(LHSVL);
2101 Value *RHS = vectorizeTree(RHSVL);
2103 if (LHS == RHS && isa<Instruction>(LHS)) {
2104 assert((VL0->getOperand(0) == VL0->getOperand(1)) && "Invalid order");
2107 if (Value *V = alreadyVectorized(E->Scalars))
2110 BinaryOperator *BinOp = cast<BinaryOperator>(VL0);
2111 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), LHS, RHS);
2112 E->VectorizedValue = V;
2113 propagateIRFlags(E->VectorizedValue, E->Scalars);
2114 ++NumVectorInstructions;
2116 if (Instruction *I = dyn_cast<Instruction>(V))
2117 return propagateMetadata(I, E->Scalars);
2121 case Instruction::Load: {
2122 // Loads are inserted at the head of the tree because we don't want to
2123 // sink them all the way down past store instructions.
2124 setInsertPointAfterBundle(E->Scalars);
2126 LoadInst *LI = cast<LoadInst>(VL0);
2127 Type *ScalarLoadTy = LI->getType();
2128 unsigned AS = LI->getPointerAddressSpace();
2130 Value *VecPtr = Builder.CreateBitCast(LI->getPointerOperand(),
2131 VecTy->getPointerTo(AS));
2133 // The pointer operand uses an in-tree scalar so we add the new BitCast to
2134 // ExternalUses list to make sure that an extract will be generated in the
2136 if (ScalarToTreeEntry.count(LI->getPointerOperand()))
2137 ExternalUses.push_back(
2138 ExternalUser(LI->getPointerOperand(), cast<User>(VecPtr), 0));
2140 unsigned Alignment = LI->getAlignment();
2141 LI = Builder.CreateLoad(VecPtr);
2143 Alignment = DL->getABITypeAlignment(ScalarLoadTy);
2144 LI->setAlignment(Alignment);
2145 E->VectorizedValue = LI;
2146 ++NumVectorInstructions;
2147 return propagateMetadata(LI, E->Scalars);
2149 case Instruction::Store: {
2150 StoreInst *SI = cast<StoreInst>(VL0);
2151 unsigned Alignment = SI->getAlignment();
2152 unsigned AS = SI->getPointerAddressSpace();
2155 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
2156 ValueOp.push_back(cast<StoreInst>(E->Scalars[i])->getValueOperand());
2158 setInsertPointAfterBundle(E->Scalars);
2160 Value *VecValue = vectorizeTree(ValueOp);
2161 Value *VecPtr = Builder.CreateBitCast(SI->getPointerOperand(),
2162 VecTy->getPointerTo(AS));
2163 StoreInst *S = Builder.CreateStore(VecValue, VecPtr);
2165 // The pointer operand uses an in-tree scalar so we add the new BitCast to
2166 // ExternalUses list to make sure that an extract will be generated in the
2168 if (ScalarToTreeEntry.count(SI->getPointerOperand()))
2169 ExternalUses.push_back(
2170 ExternalUser(SI->getPointerOperand(), cast<User>(VecPtr), 0));
2173 Alignment = DL->getABITypeAlignment(SI->getValueOperand()->getType());
2174 S->setAlignment(Alignment);
2175 E->VectorizedValue = S;
2176 ++NumVectorInstructions;
2177 return propagateMetadata(S, E->Scalars);
2179 case Instruction::GetElementPtr: {
2180 setInsertPointAfterBundle(E->Scalars);
2183 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
2184 Op0VL.push_back(cast<GetElementPtrInst>(E->Scalars[i])->getOperand(0));
2186 Value *Op0 = vectorizeTree(Op0VL);
2188 std::vector<Value *> OpVecs;
2189 for (int j = 1, e = cast<GetElementPtrInst>(VL0)->getNumOperands(); j < e;
2192 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
2193 OpVL.push_back(cast<GetElementPtrInst>(E->Scalars[i])->getOperand(j));
2195 Value *OpVec = vectorizeTree(OpVL);
2196 OpVecs.push_back(OpVec);
2199 Value *V = Builder.CreateGEP(Op0, OpVecs);
2200 E->VectorizedValue = V;
2201 ++NumVectorInstructions;
2203 if (Instruction *I = dyn_cast<Instruction>(V))
2204 return propagateMetadata(I, E->Scalars);
2208 case Instruction::Call: {
2209 CallInst *CI = cast<CallInst>(VL0);
2210 setInsertPointAfterBundle(E->Scalars);
2212 Intrinsic::ID IID = Intrinsic::not_intrinsic;
2213 Value *ScalarArg = nullptr;
2214 if (CI && (FI = CI->getCalledFunction())) {
2215 IID = (Intrinsic::ID) FI->getIntrinsicID();
2217 std::vector<Value *> OpVecs;
2218 for (int j = 0, e = CI->getNumArgOperands(); j < e; ++j) {
2220 // ctlz,cttz and powi are special intrinsics whose second argument is
2221 // a scalar. This argument should not be vectorized.
2222 if (hasVectorInstrinsicScalarOpd(IID, 1) && j == 1) {
2223 CallInst *CEI = cast<CallInst>(E->Scalars[0]);
2224 ScalarArg = CEI->getArgOperand(j);
2225 OpVecs.push_back(CEI->getArgOperand(j));
2228 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
2229 CallInst *CEI = cast<CallInst>(E->Scalars[i]);
2230 OpVL.push_back(CEI->getArgOperand(j));
2233 Value *OpVec = vectorizeTree(OpVL);
2234 DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
2235 OpVecs.push_back(OpVec);
2238 Module *M = F->getParent();
2239 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
2240 Type *Tys[] = { VectorType::get(CI->getType(), E->Scalars.size()) };
2241 Function *CF = Intrinsic::getDeclaration(M, ID, Tys);
2242 Value *V = Builder.CreateCall(CF, OpVecs);
2244 // The scalar argument uses an in-tree scalar so we add the new vectorized
2245 // call to ExternalUses list to make sure that an extract will be
2246 // generated in the future.
2247 if (ScalarArg && ScalarToTreeEntry.count(ScalarArg))
2248 ExternalUses.push_back(ExternalUser(ScalarArg, cast<User>(V), 0));
2250 E->VectorizedValue = V;
2251 ++NumVectorInstructions;
2254 case Instruction::ShuffleVector: {
2255 ValueList LHSVL, RHSVL;
2256 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
2257 LHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
2258 RHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
2260 setInsertPointAfterBundle(E->Scalars);
2262 Value *LHS = vectorizeTree(LHSVL);
2263 Value *RHS = vectorizeTree(RHSVL);
2265 if (Value *V = alreadyVectorized(E->Scalars))
2268 // Create a vector of LHS op1 RHS
2269 BinaryOperator *BinOp0 = cast<BinaryOperator>(VL0);
2270 Value *V0 = Builder.CreateBinOp(BinOp0->getOpcode(), LHS, RHS);
2272 // Create a vector of LHS op2 RHS
2273 Instruction *VL1 = cast<Instruction>(E->Scalars[1]);
2274 BinaryOperator *BinOp1 = cast<BinaryOperator>(VL1);
2275 Value *V1 = Builder.CreateBinOp(BinOp1->getOpcode(), LHS, RHS);
2277 // Create shuffle to take alternate operations from the vector.
2278 // Also, gather up odd and even scalar ops to propagate IR flags to
2279 // each vector operation.
2280 ValueList OddScalars, EvenScalars;
2281 unsigned e = E->Scalars.size();
2282 SmallVector<Constant *, 8> Mask(e);
2283 for (unsigned i = 0; i < e; ++i) {
2285 Mask[i] = Builder.getInt32(e + i);
2286 OddScalars.push_back(E->Scalars[i]);
2288 Mask[i] = Builder.getInt32(i);
2289 EvenScalars.push_back(E->Scalars[i]);
2293 Value *ShuffleMask = ConstantVector::get(Mask);
2294 propagateIRFlags(V0, EvenScalars);
2295 propagateIRFlags(V1, OddScalars);
2297 Value *V = Builder.CreateShuffleVector(V0, V1, ShuffleMask);
2298 E->VectorizedValue = V;
2299 ++NumVectorInstructions;
2300 if (Instruction *I = dyn_cast<Instruction>(V))
2301 return propagateMetadata(I, E->Scalars);
2306 llvm_unreachable("unknown inst");
2311 Value *BoUpSLP::vectorizeTree() {
2313 // All blocks must be scheduled before any instructions are inserted.
2314 for (auto &BSIter : BlocksSchedules) {
2315 scheduleBlock(BSIter.second.get());
2318 Builder.SetInsertPoint(F->getEntryBlock().begin());
2319 vectorizeTree(&VectorizableTree[0]);
2321 DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() << " values .\n");
2323 // Extract all of the elements with the external uses.
2324 for (UserList::iterator it = ExternalUses.begin(), e = ExternalUses.end();
2326 Value *Scalar = it->Scalar;
2327 llvm::User *User = it->User;
2329 // Skip users that we already RAUW. This happens when one instruction
2330 // has multiple uses of the same value.
2331 if (std::find(Scalar->user_begin(), Scalar->user_end(), User) ==
2334 assert(ScalarToTreeEntry.count(Scalar) && "Invalid scalar");
2336 int Idx = ScalarToTreeEntry[Scalar];
2337 TreeEntry *E = &VectorizableTree[Idx];
2338 assert(!E->NeedToGather && "Extracting from a gather list");
2340 Value *Vec = E->VectorizedValue;
2341 assert(Vec && "Can't find vectorizable value");
2343 Value *Lane = Builder.getInt32(it->Lane);
2344 // Generate extracts for out-of-tree users.
2345 // Find the insertion point for the extractelement lane.
2346 if (isa<Instruction>(Vec)){
2347 if (PHINode *PH = dyn_cast<PHINode>(User)) {
2348 for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
2349 if (PH->getIncomingValue(i) == Scalar) {
2350 Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
2351 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2352 CSEBlocks.insert(PH->getIncomingBlock(i));
2353 PH->setOperand(i, Ex);
2357 Builder.SetInsertPoint(cast<Instruction>(User));
2358 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2359 CSEBlocks.insert(cast<Instruction>(User)->getParent());
2360 User->replaceUsesOfWith(Scalar, Ex);
2363 Builder.SetInsertPoint(F->getEntryBlock().begin());
2364 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2365 CSEBlocks.insert(&F->getEntryBlock());
2366 User->replaceUsesOfWith(Scalar, Ex);
2369 DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
2372 // For each vectorized value:
2373 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
2374 TreeEntry *Entry = &VectorizableTree[EIdx];
2377 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
2378 Value *Scalar = Entry->Scalars[Lane];
2379 // No need to handle users of gathered values.
2380 if (Entry->NeedToGather)
2383 assert(Entry->VectorizedValue && "Can't find vectorizable value");
2385 Type *Ty = Scalar->getType();
2386 if (!Ty->isVoidTy()) {
2388 for (User *U : Scalar->users()) {
2389 DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
2391 assert((ScalarToTreeEntry.count(U) ||
2392 // It is legal to replace users in the ignorelist by undef.
2393 (std::find(UserIgnoreList.begin(), UserIgnoreList.end(), U) !=
2394 UserIgnoreList.end())) &&
2395 "Replacing out-of-tree value with undef");
2398 Value *Undef = UndefValue::get(Ty);
2399 Scalar->replaceAllUsesWith(Undef);
2401 DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
2402 cast<Instruction>(Scalar)->eraseFromParent();
2406 Builder.ClearInsertionPoint();
2408 return VectorizableTree[0].VectorizedValue;
2411 void BoUpSLP::optimizeGatherSequence() {
2412 DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
2413 << " gather sequences instructions.\n");
2414 // LICM InsertElementInst sequences.
2415 for (SetVector<Instruction *>::iterator it = GatherSeq.begin(),
2416 e = GatherSeq.end(); it != e; ++it) {
2417 InsertElementInst *Insert = dyn_cast<InsertElementInst>(*it);
2422 // Check if this block is inside a loop.
2423 Loop *L = LI->getLoopFor(Insert->getParent());
2427 // Check if it has a preheader.
2428 BasicBlock *PreHeader = L->getLoopPreheader();
2432 // If the vector or the element that we insert into it are
2433 // instructions that are defined in this basic block then we can't
2434 // hoist this instruction.
2435 Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
2436 Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
2437 if (CurrVec && L->contains(CurrVec))
2439 if (NewElem && L->contains(NewElem))
2442 // We can hoist this instruction. Move it to the pre-header.
2443 Insert->moveBefore(PreHeader->getTerminator());
2446 // Make a list of all reachable blocks in our CSE queue.
2447 SmallVector<const DomTreeNode *, 8> CSEWorkList;
2448 CSEWorkList.reserve(CSEBlocks.size());
2449 for (BasicBlock *BB : CSEBlocks)
2450 if (DomTreeNode *N = DT->getNode(BB)) {
2451 assert(DT->isReachableFromEntry(N));
2452 CSEWorkList.push_back(N);
2455 // Sort blocks by domination. This ensures we visit a block after all blocks
2456 // dominating it are visited.
2457 std::stable_sort(CSEWorkList.begin(), CSEWorkList.end(),
2458 [this](const DomTreeNode *A, const DomTreeNode *B) {
2459 return DT->properlyDominates(A, B);
2462 // Perform O(N^2) search over the gather sequences and merge identical
2463 // instructions. TODO: We can further optimize this scan if we split the
2464 // instructions into different buckets based on the insert lane.
2465 SmallVector<Instruction *, 16> Visited;
2466 for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
2467 assert((I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
2468 "Worklist not sorted properly!");
2469 BasicBlock *BB = (*I)->getBlock();
2470 // For all instructions in blocks containing gather sequences:
2471 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) {
2472 Instruction *In = it++;
2473 if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In))
2476 // Check if we can replace this instruction with any of the
2477 // visited instructions.
2478 for (SmallVectorImpl<Instruction *>::iterator v = Visited.begin(),
2481 if (In->isIdenticalTo(*v) &&
2482 DT->dominates((*v)->getParent(), In->getParent())) {
2483 In->replaceAllUsesWith(*v);
2484 In->eraseFromParent();
2490 assert(std::find(Visited.begin(), Visited.end(), In) == Visited.end());
2491 Visited.push_back(In);
2499 // Groups the instructions to a bundle (which is then a single scheduling entity)
2500 // and schedules instructions until the bundle gets ready.
2501 bool BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL,
2503 if (isa<PHINode>(VL[0]))
2506 // Initialize the instruction bundle.
2507 Instruction *OldScheduleEnd = ScheduleEnd;
2508 ScheduleData *PrevInBundle = nullptr;
2509 ScheduleData *Bundle = nullptr;
2510 bool ReSchedule = false;
2511 DEBUG(dbgs() << "SLP: bundle: " << *VL[0] << "\n");
2512 for (Value *V : VL) {
2513 extendSchedulingRegion(V);
2514 ScheduleData *BundleMember = getScheduleData(V);
2515 assert(BundleMember &&
2516 "no ScheduleData for bundle member (maybe not in same basic block)");
2517 if (BundleMember->IsScheduled) {
2518 // A bundle member was scheduled as single instruction before and now
2519 // needs to be scheduled as part of the bundle. We just get rid of the
2520 // existing schedule.
2521 DEBUG(dbgs() << "SLP: reset schedule because " << *BundleMember
2522 << " was already scheduled\n");
2525 assert(BundleMember->isSchedulingEntity() &&
2526 "bundle member already part of other bundle");
2528 PrevInBundle->NextInBundle = BundleMember;
2530 Bundle = BundleMember;
2532 BundleMember->UnscheduledDepsInBundle = 0;
2533 Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps;
2535 // Group the instructions to a bundle.
2536 BundleMember->FirstInBundle = Bundle;
2537 PrevInBundle = BundleMember;
2539 if (ScheduleEnd != OldScheduleEnd) {
2540 // The scheduling region got new instructions at the lower end (or it is a
2541 // new region for the first bundle). This makes it necessary to
2542 // recalculate all dependencies.
2543 // It is seldom that this needs to be done a second time after adding the
2544 // initial bundle to the region.
2545 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2546 ScheduleData *SD = getScheduleData(I);
2547 SD->clearDependencies();
2553 initialFillReadyList(ReadyInsts);
2556 DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle << " in block "
2557 << BB->getName() << "\n");
2559 calculateDependencies(Bundle, true, SLP);
2561 // Now try to schedule the new bundle. As soon as the bundle is "ready" it
2562 // means that there are no cyclic dependencies and we can schedule it.
2563 // Note that's important that we don't "schedule" the bundle yet (see
2564 // cancelScheduling).
2565 while (!Bundle->isReady() && !ReadyInsts.empty()) {
2567 ScheduleData *pickedSD = ReadyInsts.back();
2568 ReadyInsts.pop_back();
2570 if (pickedSD->isSchedulingEntity() && pickedSD->isReady()) {
2571 schedule(pickedSD, ReadyInsts);
2574 return Bundle->isReady();
2577 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL) {
2578 if (isa<PHINode>(VL[0]))
2581 ScheduleData *Bundle = getScheduleData(VL[0]);
2582 DEBUG(dbgs() << "SLP: cancel scheduling of " << *Bundle << "\n");
2583 assert(!Bundle->IsScheduled &&
2584 "Can't cancel bundle which is already scheduled");
2585 assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
2586 "tried to unbundle something which is not a bundle");
2588 // Un-bundle: make single instructions out of the bundle.
2589 ScheduleData *BundleMember = Bundle;
2590 while (BundleMember) {
2591 assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
2592 BundleMember->FirstInBundle = BundleMember;
2593 ScheduleData *Next = BundleMember->NextInBundle;
2594 BundleMember->NextInBundle = nullptr;
2595 BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps;
2596 if (BundleMember->UnscheduledDepsInBundle == 0) {
2597 ReadyInsts.insert(BundleMember);
2599 BundleMember = Next;
2603 void BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V) {
2604 if (getScheduleData(V))
2606 Instruction *I = dyn_cast<Instruction>(V);
2607 assert(I && "bundle member must be an instruction");
2608 assert(!isa<PHINode>(I) && "phi nodes don't need to be scheduled");
2609 if (!ScheduleStart) {
2610 // It's the first instruction in the new region.
2611 initScheduleData(I, I->getNextNode(), nullptr, nullptr);
2613 ScheduleEnd = I->getNextNode();
2614 assert(ScheduleEnd && "tried to vectorize a TerminatorInst?");
2615 DEBUG(dbgs() << "SLP: initialize schedule region to " << *I << "\n");
2618 // Search up and down at the same time, because we don't know if the new
2619 // instruction is above or below the existing scheduling region.
2620 BasicBlock::reverse_iterator UpIter(ScheduleStart);
2621 BasicBlock::reverse_iterator UpperEnd = BB->rend();
2622 BasicBlock::iterator DownIter(ScheduleEnd);
2623 BasicBlock::iterator LowerEnd = BB->end();
2625 if (UpIter != UpperEnd) {
2626 if (&*UpIter == I) {
2627 initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
2629 DEBUG(dbgs() << "SLP: extend schedule region start to " << *I << "\n");
2634 if (DownIter != LowerEnd) {
2635 if (&*DownIter == I) {
2636 initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
2638 ScheduleEnd = I->getNextNode();
2639 assert(ScheduleEnd && "tried to vectorize a TerminatorInst?");
2640 DEBUG(dbgs() << "SLP: extend schedule region end to " << *I << "\n");
2645 assert((UpIter != UpperEnd || DownIter != LowerEnd) &&
2646 "instruction not found in block");
2650 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
2652 ScheduleData *PrevLoadStore,
2653 ScheduleData *NextLoadStore) {
2654 ScheduleData *CurrentLoadStore = PrevLoadStore;
2655 for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
2656 ScheduleData *SD = ScheduleDataMap[I];
2658 // Allocate a new ScheduleData for the instruction.
2659 if (ChunkPos >= ChunkSize) {
2660 ScheduleDataChunks.push_back(
2661 llvm::make_unique<ScheduleData[]>(ChunkSize));
2664 SD = &(ScheduleDataChunks.back()[ChunkPos++]);
2665 ScheduleDataMap[I] = SD;
2668 assert(!isInSchedulingRegion(SD) &&
2669 "new ScheduleData already in scheduling region");
2670 SD->init(SchedulingRegionID);
2672 if (I->mayReadOrWriteMemory()) {
2673 // Update the linked list of memory accessing instructions.
2674 if (CurrentLoadStore) {
2675 CurrentLoadStore->NextLoadStore = SD;
2677 FirstLoadStoreInRegion = SD;
2679 CurrentLoadStore = SD;
2682 if (NextLoadStore) {
2683 if (CurrentLoadStore)
2684 CurrentLoadStore->NextLoadStore = NextLoadStore;
2686 LastLoadStoreInRegion = CurrentLoadStore;
2690 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
2691 bool InsertInReadyList,
2693 assert(SD->isSchedulingEntity());
2695 SmallVector<ScheduleData *, 10> WorkList;
2696 WorkList.push_back(SD);
2698 while (!WorkList.empty()) {
2699 ScheduleData *SD = WorkList.back();
2700 WorkList.pop_back();
2702 ScheduleData *BundleMember = SD;
2703 while (BundleMember) {
2704 assert(isInSchedulingRegion(BundleMember));
2705 if (!BundleMember->hasValidDependencies()) {
2707 DEBUG(dbgs() << "SLP: update deps of " << *BundleMember << "\n");
2708 BundleMember->Dependencies = 0;
2709 BundleMember->resetUnscheduledDeps();
2711 // Handle def-use chain dependencies.
2712 for (User *U : BundleMember->Inst->users()) {
2713 if (isa<Instruction>(U)) {
2714 ScheduleData *UseSD = getScheduleData(U);
2715 if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
2716 BundleMember->Dependencies++;
2717 ScheduleData *DestBundle = UseSD->FirstInBundle;
2718 if (!DestBundle->IsScheduled) {
2719 BundleMember->incrementUnscheduledDeps(1);
2721 if (!DestBundle->hasValidDependencies()) {
2722 WorkList.push_back(DestBundle);
2726 // I'm not sure if this can ever happen. But we need to be safe.
2727 // This lets the instruction/bundle never be scheduled and eventally
2728 // disable vectorization.
2729 BundleMember->Dependencies++;
2730 BundleMember->incrementUnscheduledDeps(1);
2734 // Handle the memory dependencies.
2735 ScheduleData *DepDest = BundleMember->NextLoadStore;
2737 Instruction *SrcInst = BundleMember->Inst;
2738 AliasAnalysis::Location SrcLoc = getLocation(SrcInst, SLP->AA);
2739 bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
2742 assert(isInSchedulingRegion(DepDest));
2743 if (SrcMayWrite || DepDest->Inst->mayWriteToMemory()) {
2744 if (SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)) {
2745 DepDest->MemoryDependencies.push_back(BundleMember);
2746 BundleMember->Dependencies++;
2747 ScheduleData *DestBundle = DepDest->FirstInBundle;
2748 if (!DestBundle->IsScheduled) {
2749 BundleMember->incrementUnscheduledDeps(1);
2751 if (!DestBundle->hasValidDependencies()) {
2752 WorkList.push_back(DestBundle);
2756 DepDest = DepDest->NextLoadStore;
2760 BundleMember = BundleMember->NextInBundle;
2762 if (InsertInReadyList && SD->isReady()) {
2763 ReadyInsts.push_back(SD);
2764 DEBUG(dbgs() << "SLP: gets ready on update: " << *SD->Inst << "\n");
2769 void BoUpSLP::BlockScheduling::resetSchedule() {
2770 assert(ScheduleStart &&
2771 "tried to reset schedule on block which has not been scheduled");
2772 for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2773 ScheduleData *SD = getScheduleData(I);
2774 assert(isInSchedulingRegion(SD));
2775 SD->IsScheduled = false;
2776 SD->resetUnscheduledDeps();
2781 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
2783 if (!BS->ScheduleStart)
2786 DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
2788 BS->resetSchedule();
2790 // For the real scheduling we use a more sophisticated ready-list: it is
2791 // sorted by the original instruction location. This lets the final schedule
2792 // be as close as possible to the original instruction order.
2793 struct ScheduleDataCompare {
2794 bool operator()(ScheduleData *SD1, ScheduleData *SD2) {
2795 return SD2->SchedulingPriority < SD1->SchedulingPriority;
2798 std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
2800 // Ensure that all depencency data is updated and fill the ready-list with
2801 // initial instructions.
2803 int NumToSchedule = 0;
2804 for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
2805 I = I->getNextNode()) {
2806 ScheduleData *SD = BS->getScheduleData(I);
2808 SD->isPartOfBundle() == (ScalarToTreeEntry.count(SD->Inst) != 0) &&
2809 "scheduler and vectorizer have different opinion on what is a bundle");
2810 SD->FirstInBundle->SchedulingPriority = Idx++;
2811 if (SD->isSchedulingEntity()) {
2812 BS->calculateDependencies(SD, false, this);
2816 BS->initialFillReadyList(ReadyInsts);
2818 Instruction *LastScheduledInst = BS->ScheduleEnd;
2820 // Do the "real" scheduling.
2821 while (!ReadyInsts.empty()) {
2822 ScheduleData *picked = *ReadyInsts.begin();
2823 ReadyInsts.erase(ReadyInsts.begin());
2825 // Move the scheduled instruction(s) to their dedicated places, if not
2827 ScheduleData *BundleMember = picked;
2828 while (BundleMember) {
2829 Instruction *pickedInst = BundleMember->Inst;
2830 if (LastScheduledInst->getNextNode() != pickedInst) {
2831 BS->BB->getInstList().remove(pickedInst);
2832 BS->BB->getInstList().insert(LastScheduledInst, pickedInst);
2834 LastScheduledInst = pickedInst;
2835 BundleMember = BundleMember->NextInBundle;
2838 BS->schedule(picked, ReadyInsts);
2841 assert(NumToSchedule == 0 && "could not schedule all instructions");
2843 // Avoid duplicate scheduling of the block.
2844 BS->ScheduleStart = nullptr;
2847 /// The SLPVectorizer Pass.
2848 struct SLPVectorizer : public FunctionPass {
2849 typedef SmallVector<StoreInst *, 8> StoreList;
2850 typedef MapVector<Value *, StoreList> StoreListMap;
2852 /// Pass identification, replacement for typeid
2855 explicit SLPVectorizer() : FunctionPass(ID) {
2856 initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
2859 ScalarEvolution *SE;
2860 const DataLayout *DL;
2861 TargetTransformInfo *TTI;
2862 TargetLibraryInfo *TLI;
2866 AssumptionCache *AC;
2868 bool runOnFunction(Function &F) override {
2869 if (skipOptnoneFunction(F))
2872 SE = &getAnalysis<ScalarEvolution>();
2873 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
2874 DL = DLP ? &DLP->getDataLayout() : nullptr;
2875 TTI = &getAnalysis<TargetTransformInfo>();
2876 TLI = getAnalysisIfAvailable<TargetLibraryInfo>();
2877 AA = &getAnalysis<AliasAnalysis>();
2878 LI = &getAnalysis<LoopInfo>();
2879 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2880 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
2883 bool Changed = false;
2885 // If the target claims to have no vector registers don't attempt
2887 if (!TTI->getNumberOfRegisters(true))
2890 // Must have DataLayout. We can't require it because some tests run w/o
2895 // Don't vectorize when the attribute NoImplicitFloat is used.
2896 if (F.hasFnAttribute(Attribute::NoImplicitFloat))
2899 DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
2901 // Use the bottom up slp vectorizer to construct chains that start with
2902 // store instructions.
2903 BoUpSLP R(&F, SE, DL, TTI, TLI, AA, LI, DT, AC);
2905 // Scan the blocks in the function in post order.
2906 for (po_iterator<BasicBlock*> it = po_begin(&F.getEntryBlock()),
2907 e = po_end(&F.getEntryBlock()); it != e; ++it) {
2908 BasicBlock *BB = *it;
2909 // Vectorize trees that end at stores.
2910 if (unsigned count = collectStores(BB, R)) {
2912 DEBUG(dbgs() << "SLP: Found " << count << " stores to vectorize.\n");
2913 Changed |= vectorizeStoreChains(R);
2916 // Vectorize trees that end at reductions.
2917 Changed |= vectorizeChainsInBlock(BB, R);
2921 R.optimizeGatherSequence();
2922 DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
2923 DEBUG(verifyFunction(F));
2928 void getAnalysisUsage(AnalysisUsage &AU) const override {
2929 FunctionPass::getAnalysisUsage(AU);
2930 AU.addRequired<AssumptionCacheTracker>();
2931 AU.addRequired<ScalarEvolution>();
2932 AU.addRequired<AliasAnalysis>();
2933 AU.addRequired<TargetTransformInfo>();
2934 AU.addRequired<LoopInfo>();
2935 AU.addRequired<DominatorTreeWrapperPass>();
2936 AU.addPreserved<LoopInfo>();
2937 AU.addPreserved<DominatorTreeWrapperPass>();
2938 AU.setPreservesCFG();
2943 /// \brief Collect memory references and sort them according to their base
2944 /// object. We sort the stores to their base objects to reduce the cost of the
2945 /// quadratic search on the stores. TODO: We can further reduce this cost
2946 /// if we flush the chain creation every time we run into a memory barrier.
2947 unsigned collectStores(BasicBlock *BB, BoUpSLP &R);
2949 /// \brief Try to vectorize a chain that starts at two arithmetic instrs.
2950 bool tryToVectorizePair(Value *A, Value *B, BoUpSLP &R);
2952 /// \brief Try to vectorize a list of operands.
2953 /// \@param BuildVector A list of users to ignore for the purpose of
2954 /// scheduling and that don't need extracting.
2955 /// \returns true if a value was vectorized.
2956 bool tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
2957 ArrayRef<Value *> BuildVector = None,
2958 bool allowReorder = false);
2960 /// \brief Try to vectorize a chain that may start at the operands of \V;
2961 bool tryToVectorize(BinaryOperator *V, BoUpSLP &R);
2963 /// \brief Vectorize the stores that were collected in StoreRefs.
2964 bool vectorizeStoreChains(BoUpSLP &R);
2966 /// \brief Scan the basic block and look for patterns that are likely to start
2967 /// a vectorization chain.
2968 bool vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R);
2970 bool vectorizeStoreChain(ArrayRef<Value *> Chain, int CostThreshold,
2973 bool vectorizeStores(ArrayRef<StoreInst *> Stores, int costThreshold,
2976 StoreListMap StoreRefs;
2979 /// \brief Check that the Values in the slice in VL array are still existent in
2980 /// the WeakVH array.
2981 /// Vectorization of part of the VL array may cause later values in the VL array
2982 /// to become invalid. We track when this has happened in the WeakVH array.
2983 static bool hasValueBeenRAUWed(ArrayRef<Value *> &VL,
2984 SmallVectorImpl<WeakVH> &VH,
2985 unsigned SliceBegin,
2986 unsigned SliceSize) {
2987 for (unsigned i = SliceBegin; i < SliceBegin + SliceSize; ++i)
2994 bool SLPVectorizer::vectorizeStoreChain(ArrayRef<Value *> Chain,
2995 int CostThreshold, BoUpSLP &R) {
2996 unsigned ChainLen = Chain.size();
2997 DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
2999 Type *StoreTy = cast<StoreInst>(Chain[0])->getValueOperand()->getType();
3000 unsigned Sz = DL->getTypeSizeInBits(StoreTy);
3001 unsigned VF = MinVecRegSize / Sz;
3003 if (!isPowerOf2_32(Sz) || VF < 2)
3006 // Keep track of values that were deleted by vectorizing in the loop below.
3007 SmallVector<WeakVH, 8> TrackValues(Chain.begin(), Chain.end());
3009 bool Changed = false;
3010 // Look for profitable vectorizable trees at all offsets, starting at zero.
3011 for (unsigned i = 0, e = ChainLen; i < e; ++i) {
3015 // Check that a previous iteration of this loop did not delete the Value.
3016 if (hasValueBeenRAUWed(Chain, TrackValues, i, VF))
3019 DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
3021 ArrayRef<Value *> Operands = Chain.slice(i, VF);
3023 R.buildTree(Operands);
3025 int Cost = R.getTreeCost();
3027 DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
3028 if (Cost < CostThreshold) {
3029 DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
3032 // Move to the next bundle.
3041 bool SLPVectorizer::vectorizeStores(ArrayRef<StoreInst *> Stores,
3042 int costThreshold, BoUpSLP &R) {
3043 SetVector<Value *> Heads, Tails;
3044 SmallDenseMap<Value *, Value *> ConsecutiveChain;
3046 // We may run into multiple chains that merge into a single chain. We mark the
3047 // stores that we vectorized so that we don't visit the same store twice.
3048 BoUpSLP::ValueSet VectorizedStores;
3049 bool Changed = false;
3051 // Do a quadratic search on all of the given stores and find
3052 // all of the pairs of stores that follow each other.
3053 for (unsigned i = 0, e = Stores.size(); i < e; ++i) {
3054 for (unsigned j = 0; j < e; ++j) {
3058 if (R.isConsecutiveAccess(Stores[i], Stores[j])) {
3059 Tails.insert(Stores[j]);
3060 Heads.insert(Stores[i]);
3061 ConsecutiveChain[Stores[i]] = Stores[j];
3066 // For stores that start but don't end a link in the chain:
3067 for (SetVector<Value *>::iterator it = Heads.begin(), e = Heads.end();
3069 if (Tails.count(*it))
3072 // We found a store instr that starts a chain. Now follow the chain and try
3074 BoUpSLP::ValueList Operands;
3076 // Collect the chain into a list.
3077 while (Tails.count(I) || Heads.count(I)) {
3078 if (VectorizedStores.count(I))
3080 Operands.push_back(I);
3081 // Move to the next value in the chain.
3082 I = ConsecutiveChain[I];
3085 bool Vectorized = vectorizeStoreChain(Operands, costThreshold, R);
3087 // Mark the vectorized stores so that we don't vectorize them again.
3089 VectorizedStores.insert(Operands.begin(), Operands.end());
3090 Changed |= Vectorized;
3097 unsigned SLPVectorizer::collectStores(BasicBlock *BB, BoUpSLP &R) {
3100 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
3101 StoreInst *SI = dyn_cast<StoreInst>(it);
3105 // Don't touch volatile stores.
3106 if (!SI->isSimple())
3109 // Check that the pointer points to scalars.
3110 Type *Ty = SI->getValueOperand()->getType();
3111 if (Ty->isAggregateType() || Ty->isVectorTy())
3114 // Find the base pointer.
3115 Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), DL);
3117 // Save the store locations.
3118 StoreRefs[Ptr].push_back(SI);
3124 bool SLPVectorizer::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
3127 Value *VL[] = { A, B };
3128 return tryToVectorizeList(VL, R, None, true);
3131 bool SLPVectorizer::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
3132 ArrayRef<Value *> BuildVector,
3133 bool allowReorder) {
3137 DEBUG(dbgs() << "SLP: Vectorizing a list of length = " << VL.size() << ".\n");
3139 // Check that all of the parts are scalar instructions of the same type.
3140 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
3144 unsigned Opcode0 = I0->getOpcode();
3146 Type *Ty0 = I0->getType();
3147 unsigned Sz = DL->getTypeSizeInBits(Ty0);
3148 unsigned VF = MinVecRegSize / Sz;
3150 for (int i = 0, e = VL.size(); i < e; ++i) {
3151 Type *Ty = VL[i]->getType();
3152 if (Ty->isAggregateType() || Ty->isVectorTy())
3154 Instruction *Inst = dyn_cast<Instruction>(VL[i]);
3155 if (!Inst || Inst->getOpcode() != Opcode0)
3159 bool Changed = false;
3161 // Keep track of values that were deleted by vectorizing in the loop below.
3162 SmallVector<WeakVH, 8> TrackValues(VL.begin(), VL.end());
3164 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
3165 unsigned OpsWidth = 0;
3172 if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
3175 // Check that a previous iteration of this loop did not delete the Value.
3176 if (hasValueBeenRAUWed(VL, TrackValues, i, OpsWidth))
3179 DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
3181 ArrayRef<Value *> Ops = VL.slice(i, OpsWidth);
3183 ArrayRef<Value *> BuildVectorSlice;
3184 if (!BuildVector.empty())
3185 BuildVectorSlice = BuildVector.slice(i, OpsWidth);
3187 R.buildTree(Ops, BuildVectorSlice);
3188 // TODO: check if we can allow reordering also for other cases than
3189 // tryToVectorizePair()
3190 if (allowReorder && R.shouldReorder()) {
3191 assert(Ops.size() == 2);
3192 assert(BuildVectorSlice.empty());
3193 Value *ReorderedOps[] = { Ops[1], Ops[0] };
3194 R.buildTree(ReorderedOps, None);
3196 int Cost = R.getTreeCost();
3198 if (Cost < -SLPCostThreshold) {
3199 DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
3200 Value *VectorizedRoot = R.vectorizeTree();
3202 // Reconstruct the build vector by extracting the vectorized root. This
3203 // way we handle the case where some elements of the vector are undefined.
3204 // (return (inserelt <4 xi32> (insertelt undef (opd0) 0) (opd1) 2))
3205 if (!BuildVectorSlice.empty()) {
3206 // The insert point is the last build vector instruction. The vectorized
3207 // root will precede it. This guarantees that we get an instruction. The
3208 // vectorized tree could have been constant folded.
3209 Instruction *InsertAfter = cast<Instruction>(BuildVectorSlice.back());
3210 unsigned VecIdx = 0;
3211 for (auto &V : BuildVectorSlice) {
3212 IRBuilder<true, NoFolder> Builder(
3213 ++BasicBlock::iterator(InsertAfter));
3214 InsertElementInst *IE = cast<InsertElementInst>(V);
3215 Instruction *Extract = cast<Instruction>(Builder.CreateExtractElement(
3216 VectorizedRoot, Builder.getInt32(VecIdx++)));
3217 IE->setOperand(1, Extract);
3218 IE->removeFromParent();
3219 IE->insertAfter(Extract);
3223 // Move to the next bundle.
3232 bool SLPVectorizer::tryToVectorize(BinaryOperator *V, BoUpSLP &R) {
3236 // Try to vectorize V.
3237 if (tryToVectorizePair(V->getOperand(0), V->getOperand(1), R))
3240 BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0));
3241 BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1));
3243 if (B && B->hasOneUse()) {
3244 BinaryOperator *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
3245 BinaryOperator *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
3246 if (tryToVectorizePair(A, B0, R)) {
3249 if (tryToVectorizePair(A, B1, R)) {
3255 if (A && A->hasOneUse()) {
3256 BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
3257 BinaryOperator *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
3258 if (tryToVectorizePair(A0, B, R)) {
3261 if (tryToVectorizePair(A1, B, R)) {
3268 /// \brief Generate a shuffle mask to be used in a reduction tree.
3270 /// \param VecLen The length of the vector to be reduced.
3271 /// \param NumEltsToRdx The number of elements that should be reduced in the
3273 /// \param IsPairwise Whether the reduction is a pairwise or splitting
3274 /// reduction. A pairwise reduction will generate a mask of
3275 /// <0,2,...> or <1,3,..> while a splitting reduction will generate
3276 /// <2,3, undef,undef> for a vector of 4 and NumElts = 2.
3277 /// \param IsLeft True will generate a mask of even elements, odd otherwise.
3278 static Value *createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx,
3279 bool IsPairwise, bool IsLeft,
3280 IRBuilder<> &Builder) {
3281 assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask");
3283 SmallVector<Constant *, 32> ShuffleMask(
3284 VecLen, UndefValue::get(Builder.getInt32Ty()));
3287 // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
3288 for (unsigned i = 0; i != NumEltsToRdx; ++i)
3289 ShuffleMask[i] = Builder.getInt32(2 * i + !IsLeft);
3291 // Move the upper half of the vector to the lower half.
3292 for (unsigned i = 0; i != NumEltsToRdx; ++i)
3293 ShuffleMask[i] = Builder.getInt32(NumEltsToRdx + i);
3295 return ConstantVector::get(ShuffleMask);
3299 /// Model horizontal reductions.
3301 /// A horizontal reduction is a tree of reduction operations (currently add and
3302 /// fadd) that has operations that can be put into a vector as its leaf.
3303 /// For example, this tree:
3310 /// This tree has "mul" as its reduced values and "+" as its reduction
3311 /// operations. A reduction might be feeding into a store or a binary operation
3326 class HorizontalReduction {
3327 SmallVector<Value *, 16> ReductionOps;
3328 SmallVector<Value *, 32> ReducedVals;
3330 BinaryOperator *ReductionRoot;
3331 PHINode *ReductionPHI;
3333 /// The opcode of the reduction.
3334 unsigned ReductionOpcode;
3335 /// The opcode of the values we perform a reduction on.
3336 unsigned ReducedValueOpcode;
3337 /// The width of one full horizontal reduction operation.
3338 unsigned ReduxWidth;
3339 /// Should we model this reduction as a pairwise reduction tree or a tree that
3340 /// splits the vector in halves and adds those halves.
3341 bool IsPairwiseReduction;
3344 HorizontalReduction()
3345 : ReductionRoot(nullptr), ReductionPHI(nullptr), ReductionOpcode(0),
3346 ReducedValueOpcode(0), ReduxWidth(0), IsPairwiseReduction(false) {}
3348 /// \brief Try to find a reduction tree.
3349 bool matchAssociativeReduction(PHINode *Phi, BinaryOperator *B,
3350 const DataLayout *DL) {
3352 std::find(Phi->op_begin(), Phi->op_end(), B) != Phi->op_end()) &&
3353 "Thi phi needs to use the binary operator");
3355 // We could have a initial reductions that is not an add.
3356 // r *= v1 + v2 + v3 + v4
3357 // In such a case start looking for a tree rooted in the first '+'.
3359 if (B->getOperand(0) == Phi) {
3361 B = dyn_cast<BinaryOperator>(B->getOperand(1));
3362 } else if (B->getOperand(1) == Phi) {
3364 B = dyn_cast<BinaryOperator>(B->getOperand(0));
3371 Type *Ty = B->getType();
3372 if (Ty->isVectorTy())
3375 ReductionOpcode = B->getOpcode();
3376 ReducedValueOpcode = 0;
3377 ReduxWidth = MinVecRegSize / DL->getTypeSizeInBits(Ty);
3384 // We currently only support adds.
3385 if (ReductionOpcode != Instruction::Add &&
3386 ReductionOpcode != Instruction::FAdd)
3389 // Post order traverse the reduction tree starting at B. We only handle true
3390 // trees containing only binary operators.
3391 SmallVector<std::pair<BinaryOperator *, unsigned>, 32> Stack;
3392 Stack.push_back(std::make_pair(B, 0));
3393 while (!Stack.empty()) {
3394 BinaryOperator *TreeN = Stack.back().first;
3395 unsigned EdgeToVist = Stack.back().second++;
3396 bool IsReducedValue = TreeN->getOpcode() != ReductionOpcode;
3398 // Only handle trees in the current basic block.
3399 if (TreeN->getParent() != B->getParent())
3402 // Each tree node needs to have one user except for the ultimate
3404 if (!TreeN->hasOneUse() && TreeN != B)
3408 if (EdgeToVist == 2 || IsReducedValue) {
3409 if (IsReducedValue) {
3410 // Make sure that the opcodes of the operations that we are going to
3412 if (!ReducedValueOpcode)
3413 ReducedValueOpcode = TreeN->getOpcode();
3414 else if (ReducedValueOpcode != TreeN->getOpcode())
3416 ReducedVals.push_back(TreeN);
3418 // We need to be able to reassociate the adds.
3419 if (!TreeN->isAssociative())
3421 ReductionOps.push_back(TreeN);
3428 // Visit left or right.
3429 Value *NextV = TreeN->getOperand(EdgeToVist);
3430 BinaryOperator *Next = dyn_cast<BinaryOperator>(NextV);
3432 Stack.push_back(std::make_pair(Next, 0));
3433 else if (NextV != Phi)
3439 /// \brief Attempt to vectorize the tree found by
3440 /// matchAssociativeReduction.
3441 bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
3442 if (ReducedVals.empty())
3445 unsigned NumReducedVals = ReducedVals.size();
3446 if (NumReducedVals < ReduxWidth)
3449 Value *VectorizedTree = nullptr;
3450 IRBuilder<> Builder(ReductionRoot);
3451 FastMathFlags Unsafe;
3452 Unsafe.setUnsafeAlgebra();
3453 Builder.SetFastMathFlags(Unsafe);
3456 for (; i < NumReducedVals - ReduxWidth + 1; i += ReduxWidth) {
3457 V.buildTree(makeArrayRef(&ReducedVals[i], ReduxWidth), ReductionOps);
3460 int Cost = V.getTreeCost() + getReductionCost(TTI, ReducedVals[i]);
3461 if (Cost >= -SLPCostThreshold)
3464 DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" << Cost
3467 // Vectorize a tree.
3468 DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
3469 Value *VectorizedRoot = V.vectorizeTree();
3471 // Emit a reduction.
3472 Value *ReducedSubTree = emitReduction(VectorizedRoot, Builder);
3473 if (VectorizedTree) {
3474 Builder.SetCurrentDebugLocation(Loc);
3475 VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
3476 ReducedSubTree, "bin.rdx");
3478 VectorizedTree = ReducedSubTree;
3481 if (VectorizedTree) {
3482 // Finish the reduction.
3483 for (; i < NumReducedVals; ++i) {
3484 Builder.SetCurrentDebugLocation(
3485 cast<Instruction>(ReducedVals[i])->getDebugLoc());
3486 VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
3491 assert(ReductionRoot && "Need a reduction operation");
3492 ReductionRoot->setOperand(0, VectorizedTree);
3493 ReductionRoot->setOperand(1, ReductionPHI);
3495 ReductionRoot->replaceAllUsesWith(VectorizedTree);
3497 return VectorizedTree != nullptr;
3502 /// \brief Calcuate the cost of a reduction.
3503 int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal) {
3504 Type *ScalarTy = FirstReducedVal->getType();
3505 Type *VecTy = VectorType::get(ScalarTy, ReduxWidth);
3507 int PairwiseRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, true);
3508 int SplittingRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, false);
3510 IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
3511 int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
3513 int ScalarReduxCost =
3514 ReduxWidth * TTI->getArithmeticInstrCost(ReductionOpcode, VecTy);
3516 DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost
3517 << " for reduction that starts with " << *FirstReducedVal
3519 << (IsPairwiseReduction ? "pairwise" : "splitting")
3520 << " reduction)\n");
3522 return VecReduxCost - ScalarReduxCost;
3525 static Value *createBinOp(IRBuilder<> &Builder, unsigned Opcode, Value *L,
3526 Value *R, const Twine &Name = "") {
3527 if (Opcode == Instruction::FAdd)
3528 return Builder.CreateFAdd(L, R, Name);
3529 return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, L, R, Name);
3532 /// \brief Emit a horizontal reduction of the vectorized value.
3533 Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder) {
3534 assert(VectorizedValue && "Need to have a vectorized tree node");
3535 assert(isPowerOf2_32(ReduxWidth) &&
3536 "We only handle power-of-two reductions for now");
3538 Value *TmpVec = VectorizedValue;
3539 for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
3540 if (IsPairwiseReduction) {
3542 createRdxShuffleMask(ReduxWidth, i, true, true, Builder);
3544 createRdxShuffleMask(ReduxWidth, i, true, false, Builder);
3546 Value *LeftShuf = Builder.CreateShuffleVector(
3547 TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l");
3548 Value *RightShuf = Builder.CreateShuffleVector(
3549 TmpVec, UndefValue::get(TmpVec->getType()), (RightMask),
3551 TmpVec = createBinOp(Builder, ReductionOpcode, LeftShuf, RightShuf,
3555 createRdxShuffleMask(ReduxWidth, i, false, false, Builder);
3556 Value *Shuf = Builder.CreateShuffleVector(
3557 TmpVec, UndefValue::get(TmpVec->getType()), UpperHalf, "rdx.shuf");
3558 TmpVec = createBinOp(Builder, ReductionOpcode, TmpVec, Shuf, "bin.rdx");
3562 // The result is in the first element of the vector.
3563 return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
3567 /// \brief Recognize construction of vectors like
3568 /// %ra = insertelement <4 x float> undef, float %s0, i32 0
3569 /// %rb = insertelement <4 x float> %ra, float %s1, i32 1
3570 /// %rc = insertelement <4 x float> %rb, float %s2, i32 2
3571 /// %rd = insertelement <4 x float> %rc, float %s3, i32 3
3573 /// Returns true if it matches
3575 static bool findBuildVector(InsertElementInst *FirstInsertElem,
3576 SmallVectorImpl<Value *> &BuildVector,
3577 SmallVectorImpl<Value *> &BuildVectorOpds) {
3578 if (!isa<UndefValue>(FirstInsertElem->getOperand(0)))
3581 InsertElementInst *IE = FirstInsertElem;
3583 BuildVector.push_back(IE);
3584 BuildVectorOpds.push_back(IE->getOperand(1));
3586 if (IE->use_empty())
3589 InsertElementInst *NextUse = dyn_cast<InsertElementInst>(IE->user_back());
3593 // If this isn't the final use, make sure the next insertelement is the only
3594 // use. It's OK if the final constructed vector is used multiple times
3595 if (!IE->hasOneUse())
3604 static bool PhiTypeSorterFunc(Value *V, Value *V2) {
3605 return V->getType() < V2->getType();
3608 bool SLPVectorizer::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
3609 bool Changed = false;
3610 SmallVector<Value *, 4> Incoming;
3611 SmallSet<Value *, 16> VisitedInstrs;
3613 bool HaveVectorizedPhiNodes = true;
3614 while (HaveVectorizedPhiNodes) {
3615 HaveVectorizedPhiNodes = false;
3617 // Collect the incoming values from the PHIs.
3619 for (BasicBlock::iterator instr = BB->begin(), ie = BB->end(); instr != ie;
3621 PHINode *P = dyn_cast<PHINode>(instr);
3625 if (!VisitedInstrs.count(P))
3626 Incoming.push_back(P);
3630 std::stable_sort(Incoming.begin(), Incoming.end(), PhiTypeSorterFunc);
3632 // Try to vectorize elements base on their type.
3633 for (SmallVector<Value *, 4>::iterator IncIt = Incoming.begin(),
3637 // Look for the next elements with the same type.
3638 SmallVector<Value *, 4>::iterator SameTypeIt = IncIt;
3639 while (SameTypeIt != E &&
3640 (*SameTypeIt)->getType() == (*IncIt)->getType()) {
3641 VisitedInstrs.insert(*SameTypeIt);
3645 // Try to vectorize them.
3646 unsigned NumElts = (SameTypeIt - IncIt);
3647 DEBUG(errs() << "SLP: Trying to vectorize starting at PHIs (" << NumElts << ")\n");
3648 if (NumElts > 1 && tryToVectorizeList(makeArrayRef(IncIt, NumElts), R)) {
3649 // Success start over because instructions might have been changed.
3650 HaveVectorizedPhiNodes = true;
3655 // Start over at the next instruction of a different type (or the end).
3660 VisitedInstrs.clear();
3662 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) {
3663 // We may go through BB multiple times so skip the one we have checked.
3664 if (!VisitedInstrs.insert(it).second)
3667 if (isa<DbgInfoIntrinsic>(it))
3670 // Try to vectorize reductions that use PHINodes.
3671 if (PHINode *P = dyn_cast<PHINode>(it)) {
3672 // Check that the PHI is a reduction PHI.
3673 if (P->getNumIncomingValues() != 2)
3676 (P->getIncomingBlock(0) == BB
3677 ? (P->getIncomingValue(0))
3678 : (P->getIncomingBlock(1) == BB ? P->getIncomingValue(1)
3680 // Check if this is a Binary Operator.
3681 BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx);
3685 // Try to match and vectorize a horizontal reduction.
3686 HorizontalReduction HorRdx;
3687 if (ShouldVectorizeHor &&
3688 HorRdx.matchAssociativeReduction(P, BI, DL) &&
3689 HorRdx.tryToReduce(R, TTI)) {
3696 Value *Inst = BI->getOperand(0);
3698 Inst = BI->getOperand(1);
3700 if (tryToVectorize(dyn_cast<BinaryOperator>(Inst), R)) {
3701 // We would like to start over since some instructions are deleted
3702 // and the iterator may become invalid value.
3712 // Try to vectorize horizontal reductions feeding into a store.
3713 if (ShouldStartVectorizeHorAtStore)
3714 if (StoreInst *SI = dyn_cast<StoreInst>(it))
3715 if (BinaryOperator *BinOp =
3716 dyn_cast<BinaryOperator>(SI->getValueOperand())) {
3717 HorizontalReduction HorRdx;
3718 if (((HorRdx.matchAssociativeReduction(nullptr, BinOp, DL) &&
3719 HorRdx.tryToReduce(R, TTI)) ||
3720 tryToVectorize(BinOp, R))) {
3728 // Try to vectorize horizontal reductions feeding into a return.
3729 if (ReturnInst *RI = dyn_cast<ReturnInst>(it))
3730 if (RI->getNumOperands() != 0)
3731 if (BinaryOperator *BinOp =
3732 dyn_cast<BinaryOperator>(RI->getOperand(0))) {
3733 DEBUG(dbgs() << "SLP: Found a return to vectorize.\n");
3734 if (tryToVectorizePair(BinOp->getOperand(0),
3735 BinOp->getOperand(1), R)) {
3743 // Try to vectorize trees that start at compare instructions.
3744 if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
3745 if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) {
3747 // We would like to start over since some instructions are deleted
3748 // and the iterator may become invalid value.
3754 for (int i = 0; i < 2; ++i) {
3755 if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i))) {
3756 if (tryToVectorizePair(BI->getOperand(0), BI->getOperand(1), R)) {
3758 // We would like to start over since some instructions are deleted
3759 // and the iterator may become invalid value.
3768 // Try to vectorize trees that start at insertelement instructions.
3769 if (InsertElementInst *FirstInsertElem = dyn_cast<InsertElementInst>(it)) {
3770 SmallVector<Value *, 16> BuildVector;
3771 SmallVector<Value *, 16> BuildVectorOpds;
3772 if (!findBuildVector(FirstInsertElem, BuildVector, BuildVectorOpds))
3775 // Vectorize starting with the build vector operands ignoring the
3776 // BuildVector instructions for the purpose of scheduling and user
3778 if (tryToVectorizeList(BuildVectorOpds, R, BuildVector)) {
3791 bool SLPVectorizer::vectorizeStoreChains(BoUpSLP &R) {
3792 bool Changed = false;
3793 // Attempt to sort and vectorize each of the store-groups.
3794 for (StoreListMap::iterator it = StoreRefs.begin(), e = StoreRefs.end();
3796 if (it->second.size() < 2)
3799 DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
3800 << it->second.size() << ".\n");
3802 // Process the stores in chunks of 16.
3803 for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI+=16) {
3804 unsigned Len = std::min<unsigned>(CE - CI, 16);
3805 Changed |= vectorizeStores(makeArrayRef(&it->second[CI], Len),
3806 -SLPCostThreshold, R);
3812 } // end anonymous namespace
3814 char SLPVectorizer::ID = 0;
3815 static const char lv_name[] = "SLP Vectorizer";
3816 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
3817 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3818 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
3819 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
3820 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
3821 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
3822 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
3825 Pass *createSLPVectorizerPass() { return new SLPVectorizer(); }