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/SLPVectorizer.h"
19 #include "llvm/ADT/Optional.h"
20 #include "llvm/ADT/PostOrderIterator.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/CodeMetrics.h"
24 #include "llvm/Analysis/GlobalsModRef.h"
25 #include "llvm/Analysis/LoopAccessAnalysis.h"
26 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
27 #include "llvm/Analysis/ValueTracking.h"
28 #include "llvm/Analysis/VectorUtils.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/Dominators.h"
31 #include "llvm/IR/IRBuilder.h"
32 #include "llvm/IR/Instructions.h"
33 #include "llvm/IR/IntrinsicInst.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/IR/NoFolder.h"
36 #include "llvm/IR/Type.h"
37 #include "llvm/IR/Value.h"
38 #include "llvm/IR/Verifier.h"
39 #include "llvm/Pass.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include "llvm/Transforms/Vectorize.h"
48 using namespace slpvectorizer;
50 #define SV_NAME "slp-vectorizer"
51 #define DEBUG_TYPE "SLP"
53 STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
56 SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
57 cl::desc("Only vectorize if you gain more than this "
61 ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden,
62 cl::desc("Attempt to vectorize horizontal reductions"));
64 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
65 "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
67 "Attempt to vectorize horizontal reductions feeding into a store"));
70 MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden,
71 cl::desc("Attempt to vectorize for this register size in bits"));
73 /// Limits the size of scheduling regions in a block.
74 /// It avoid long compile times for _very_ large blocks where vector
75 /// instructions are spread over a wide range.
76 /// This limit is way higher than needed by real-world functions.
78 ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden,
79 cl::desc("Limit the size of the SLP scheduling region per block"));
81 static cl::opt<int> MinVectorRegSizeOption(
82 "slp-min-reg-size", cl::init(128), cl::Hidden,
83 cl::desc("Attempt to vectorize for this register size in bits"));
85 static cl::opt<unsigned> RecursionMaxDepth(
86 "slp-recursion-max-depth", cl::init(12), cl::Hidden,
87 cl::desc("Limit the recursion depth when building a vectorizable tree"));
89 static cl::opt<unsigned> MinTreeSize(
90 "slp-min-tree-size", cl::init(3), cl::Hidden,
91 cl::desc("Only vectorize small trees if they are fully vectorizable"));
93 // Limit the number of alias checks. The limit is chosen so that
94 // it has no negative effect on the llvm benchmarks.
95 static const unsigned AliasedCheckLimit = 10;
97 // Another limit for the alias checks: The maximum distance between load/store
98 // instructions where alias checks are done.
99 // This limit is useful for very large basic blocks.
100 static const unsigned MaxMemDepDistance = 160;
102 /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
103 /// regions to be handled.
104 static const int MinScheduleRegionSize = 16;
106 /// \brief Predicate for the element types that the SLP vectorizer supports.
108 /// The most important thing to filter here are types which are invalid in LLVM
109 /// vectors. We also filter target specific types which have absolutely no
110 /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
111 /// avoids spending time checking the cost model and realizing that they will
112 /// be inevitably scalarized.
113 static bool isValidElementType(Type *Ty) {
114 return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() &&
115 !Ty->isPPC_FP128Ty();
118 /// \returns true if all of the instructions in \p VL are in the same block or
120 static bool allSameBlock(ArrayRef<Value *> VL) {
121 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
124 BasicBlock *BB = I0->getParent();
125 for (int i = 1, e = VL.size(); i < e; i++) {
126 Instruction *I = dyn_cast<Instruction>(VL[i]);
130 if (BB != I->getParent())
136 /// \returns True if all of the values in \p VL are constants.
137 static bool allConstant(ArrayRef<Value *> VL) {
139 if (!isa<Constant>(i))
144 /// \returns True if all of the values in \p VL are identical.
145 static bool isSplat(ArrayRef<Value *> VL) {
146 for (unsigned i = 1, e = VL.size(); i < e; ++i)
152 ///\returns Opcode that can be clubbed with \p Op to create an alternate
153 /// sequence which can later be merged as a ShuffleVector instruction.
154 static unsigned getAltOpcode(unsigned Op) {
156 case Instruction::FAdd:
157 return Instruction::FSub;
158 case Instruction::FSub:
159 return Instruction::FAdd;
160 case Instruction::Add:
161 return Instruction::Sub;
162 case Instruction::Sub:
163 return Instruction::Add;
169 ///\returns bool representing if Opcode \p Op can be part
170 /// of an alternate sequence which can later be merged as
171 /// a ShuffleVector instruction.
172 static bool canCombineAsAltInst(unsigned Op) {
173 return Op == Instruction::FAdd || Op == Instruction::FSub ||
174 Op == Instruction::Sub || Op == Instruction::Add;
177 /// \returns ShuffleVector instruction if instructions in \p VL have
178 /// alternate fadd,fsub / fsub,fadd/add,sub/sub,add sequence.
179 /// (i.e. e.g. opcodes of fadd,fsub,fadd,fsub...)
180 static unsigned isAltInst(ArrayRef<Value *> VL) {
181 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
182 unsigned Opcode = I0->getOpcode();
183 unsigned AltOpcode = getAltOpcode(Opcode);
184 for (int i = 1, e = VL.size(); i < e; i++) {
185 Instruction *I = dyn_cast<Instruction>(VL[i]);
186 if (!I || I->getOpcode() != ((i & 1) ? AltOpcode : Opcode))
189 return Instruction::ShuffleVector;
192 /// \returns The opcode if all of the Instructions in \p VL have the same
194 static unsigned getSameOpcode(ArrayRef<Value *> VL) {
195 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
198 unsigned Opcode = I0->getOpcode();
199 for (int i = 1, e = VL.size(); i < e; i++) {
200 Instruction *I = dyn_cast<Instruction>(VL[i]);
201 if (!I || Opcode != I->getOpcode()) {
202 if (canCombineAsAltInst(Opcode) && i == 1)
203 return isAltInst(VL);
210 /// Get the intersection (logical and) of all of the potential IR flags
211 /// of each scalar operation (VL) that will be converted into a vector (I).
212 /// Flag set: NSW, NUW, exact, and all of fast-math.
213 static void propagateIRFlags(Value *I, ArrayRef<Value *> VL) {
214 if (auto *VecOp = dyn_cast<Instruction>(I)) {
215 if (auto *Intersection = dyn_cast<Instruction>(VL[0])) {
216 // Intersection is initialized to the 0th scalar,
217 // so start counting from index '1'.
218 for (int i = 1, e = VL.size(); i < e; ++i) {
219 if (auto *Scalar = dyn_cast<Instruction>(VL[i]))
220 Intersection->andIRFlags(Scalar);
222 VecOp->copyIRFlags(Intersection);
227 /// \returns true if all of the values in \p VL have the same type or false
229 static bool allSameType(ArrayRef<Value *> VL) {
230 Type *Ty = VL[0]->getType();
231 for (int i = 1, e = VL.size(); i < e; i++)
232 if (VL[i]->getType() != Ty)
238 /// \returns True if Extract{Value,Element} instruction extracts element Idx.
239 static bool matchExtractIndex(Instruction *E, unsigned Idx, unsigned Opcode) {
240 assert(Opcode == Instruction::ExtractElement ||
241 Opcode == Instruction::ExtractValue);
242 if (Opcode == Instruction::ExtractElement) {
243 ConstantInt *CI = dyn_cast<ConstantInt>(E->getOperand(1));
244 return CI && CI->getZExtValue() == Idx;
246 ExtractValueInst *EI = cast<ExtractValueInst>(E);
247 return EI->getNumIndices() == 1 && *EI->idx_begin() == Idx;
251 /// \returns True if in-tree use also needs extract. This refers to
252 /// possible scalar operand in vectorized instruction.
253 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
254 TargetLibraryInfo *TLI) {
256 unsigned Opcode = UserInst->getOpcode();
258 case Instruction::Load: {
259 LoadInst *LI = cast<LoadInst>(UserInst);
260 return (LI->getPointerOperand() == Scalar);
262 case Instruction::Store: {
263 StoreInst *SI = cast<StoreInst>(UserInst);
264 return (SI->getPointerOperand() == Scalar);
266 case Instruction::Call: {
267 CallInst *CI = cast<CallInst>(UserInst);
268 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
269 if (hasVectorInstrinsicScalarOpd(ID, 1)) {
270 return (CI->getArgOperand(1) == Scalar);
278 /// \returns the AA location that is being access by the instruction.
279 static MemoryLocation getLocation(Instruction *I, AliasAnalysis *AA) {
280 if (StoreInst *SI = dyn_cast<StoreInst>(I))
281 return MemoryLocation::get(SI);
282 if (LoadInst *LI = dyn_cast<LoadInst>(I))
283 return MemoryLocation::get(LI);
284 return MemoryLocation();
287 /// \returns True if the instruction is not a volatile or atomic load/store.
288 static bool isSimple(Instruction *I) {
289 if (LoadInst *LI = dyn_cast<LoadInst>(I))
290 return LI->isSimple();
291 if (StoreInst *SI = dyn_cast<StoreInst>(I))
292 return SI->isSimple();
293 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
294 return !MI->isVolatile();
299 namespace slpvectorizer {
300 /// Bottom Up SLP Vectorizer.
303 typedef SmallVector<Value *, 8> ValueList;
304 typedef SmallVector<Instruction *, 16> InstrList;
305 typedef SmallPtrSet<Value *, 16> ValueSet;
306 typedef SmallVector<StoreInst *, 8> StoreList;
308 BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
309 TargetLibraryInfo *TLi, AliasAnalysis *Aa, LoopInfo *Li,
310 DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB,
311 const DataLayout *DL)
312 : NumLoadsWantToKeepOrder(0), NumLoadsWantToChangeOrder(0), F(Func),
313 SE(Se), TTI(Tti), TLI(TLi), AA(Aa), LI(Li), DT(Dt), AC(AC), DB(DB),
314 DL(DL), Builder(Se->getContext()) {
315 CodeMetrics::collectEphemeralValues(F, AC, EphValues);
316 // Use the vector register size specified by the target unless overridden
317 // by a command-line option.
318 // TODO: It would be better to limit the vectorization factor based on
319 // data type rather than just register size. For example, x86 AVX has
320 // 256-bit registers, but it does not support integer operations
321 // at that width (that requires AVX2).
322 if (MaxVectorRegSizeOption.getNumOccurrences())
323 MaxVecRegSize = MaxVectorRegSizeOption;
325 MaxVecRegSize = TTI->getRegisterBitWidth(true);
327 MinVecRegSize = MinVectorRegSizeOption;
330 /// \brief Vectorize the tree that starts with the elements in \p VL.
331 /// Returns the vectorized root.
332 Value *vectorizeTree();
334 /// \returns the cost incurred by unwanted spills and fills, caused by
335 /// holding live values over call sites.
338 /// \returns the vectorization cost of the subtree that starts at \p VL.
339 /// A negative number means that this is profitable.
342 /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
343 /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
344 void buildTree(ArrayRef<Value *> Roots,
345 ArrayRef<Value *> UserIgnoreLst = None);
347 /// Clear the internal data structures that are created by 'buildTree'.
349 VectorizableTree.clear();
350 ScalarToTreeEntry.clear();
352 ExternalUses.clear();
353 NumLoadsWantToKeepOrder = 0;
354 NumLoadsWantToChangeOrder = 0;
355 for (auto &Iter : BlocksSchedules) {
356 BlockScheduling *BS = Iter.second.get();
362 /// \brief Perform LICM and CSE on the newly generated gather sequences.
363 void optimizeGatherSequence();
365 /// \returns true if it is beneficial to reverse the vector order.
366 bool shouldReorder() const {
367 return NumLoadsWantToChangeOrder > NumLoadsWantToKeepOrder;
370 /// \return The vector element size in bits to use when vectorizing the
371 /// expression tree ending at \p V. If V is a store, the size is the width of
372 /// the stored value. Otherwise, the size is the width of the largest loaded
373 /// value reaching V. This method is used by the vectorizer to calculate
374 /// vectorization factors.
375 unsigned getVectorElementSize(Value *V);
377 /// Compute the minimum type sizes required to represent the entries in a
378 /// vectorizable tree.
379 void computeMinimumValueSizes();
381 // \returns maximum vector register size as set by TTI or overridden by cl::opt.
382 unsigned getMaxVecRegSize() const {
383 return MaxVecRegSize;
386 // \returns minimum vector register size as set by cl::opt.
387 unsigned getMinVecRegSize() const {
388 return MinVecRegSize;
391 /// \brief Check if ArrayType or StructType is isomorphic to some VectorType.
393 /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
394 unsigned canMapToVector(Type *T, const DataLayout &DL) const;
396 /// \returns True if the VectorizableTree is both tiny and not fully
397 /// vectorizable. We do not vectorize such trees.
398 bool isTreeTinyAndNotFullyVectorizable();
403 /// \returns the cost of the vectorizable entry.
404 int getEntryCost(TreeEntry *E);
406 /// This is the recursive part of buildTree.
407 void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth);
409 /// \returns True if the ExtractElement/ExtractValue instructions in VL can
410 /// be vectorized to use the original vector (or aggregate "bitcast" to a vector).
411 bool canReuseExtract(ArrayRef<Value *> VL, unsigned Opcode) const;
413 /// Vectorize a single entry in the tree.
414 Value *vectorizeTree(TreeEntry *E);
416 /// Vectorize a single entry in the tree, starting in \p VL.
417 Value *vectorizeTree(ArrayRef<Value *> VL);
419 /// \returns the pointer to the vectorized value if \p VL is already
420 /// vectorized, or NULL. They may happen in cycles.
421 Value *alreadyVectorized(ArrayRef<Value *> VL) const;
423 /// \returns the scalarization cost for this type. Scalarization in this
424 /// context means the creation of vectors from a group of scalars.
425 int getGatherCost(Type *Ty);
427 /// \returns the scalarization cost for this list of values. Assuming that
428 /// this subtree gets vectorized, we may need to extract the values from the
429 /// roots. This method calculates the cost of extracting the values.
430 int getGatherCost(ArrayRef<Value *> VL);
432 /// \brief Set the Builder insert point to one after the last instruction in
434 void setInsertPointAfterBundle(ArrayRef<Value *> VL);
436 /// \returns a vector from a collection of scalars in \p VL.
437 Value *Gather(ArrayRef<Value *> VL, VectorType *Ty);
439 /// \returns whether the VectorizableTree is fully vectorizable and will
440 /// be beneficial even the tree height is tiny.
441 bool isFullyVectorizableTinyTree();
443 /// \reorder commutative operands in alt shuffle if they result in
445 void reorderAltShuffleOperands(ArrayRef<Value *> VL,
446 SmallVectorImpl<Value *> &Left,
447 SmallVectorImpl<Value *> &Right);
448 /// \reorder commutative operands to get better probability of
449 /// generating vectorized code.
450 void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
451 SmallVectorImpl<Value *> &Left,
452 SmallVectorImpl<Value *> &Right);
454 TreeEntry() : Scalars(), VectorizedValue(nullptr),
457 /// \returns true if the scalars in VL are equal to this entry.
458 bool isSame(ArrayRef<Value *> VL) const {
459 assert(VL.size() == Scalars.size() && "Invalid size");
460 return std::equal(VL.begin(), VL.end(), Scalars.begin());
463 /// A vector of scalars.
466 /// The Scalars are vectorized into this value. It is initialized to Null.
467 Value *VectorizedValue;
469 /// Do we need to gather this sequence ?
473 /// Create a new VectorizableTree entry.
474 TreeEntry *newTreeEntry(ArrayRef<Value *> VL, bool Vectorized) {
475 VectorizableTree.emplace_back();
476 int idx = VectorizableTree.size() - 1;
477 TreeEntry *Last = &VectorizableTree[idx];
478 Last->Scalars.insert(Last->Scalars.begin(), VL.begin(), VL.end());
479 Last->NeedToGather = !Vectorized;
481 for (int i = 0, e = VL.size(); i != e; ++i) {
482 assert(!ScalarToTreeEntry.count(VL[i]) && "Scalar already in tree!");
483 ScalarToTreeEntry[VL[i]] = idx;
486 MustGather.insert(VL.begin(), VL.end());
491 /// -- Vectorization State --
492 /// Holds all of the tree entries.
493 std::vector<TreeEntry> VectorizableTree;
495 /// Maps a specific scalar to its tree entry.
496 SmallDenseMap<Value*, int> ScalarToTreeEntry;
498 /// A list of scalars that we found that we need to keep as scalars.
501 /// This POD struct describes one external user in the vectorized tree.
502 struct ExternalUser {
503 ExternalUser (Value *S, llvm::User *U, int L) :
504 Scalar(S), User(U), Lane(L){}
505 // Which scalar in our function.
507 // Which user that uses the scalar.
509 // Which lane does the scalar belong to.
512 typedef SmallVector<ExternalUser, 16> UserList;
514 /// Checks if two instructions may access the same memory.
516 /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
517 /// is invariant in the calling loop.
518 bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
519 Instruction *Inst2) {
521 // First check if the result is already in the cache.
522 AliasCacheKey key = std::make_pair(Inst1, Inst2);
523 Optional<bool> &result = AliasCache[key];
524 if (result.hasValue()) {
525 return result.getValue();
527 MemoryLocation Loc2 = getLocation(Inst2, AA);
529 if (Loc1.Ptr && Loc2.Ptr && isSimple(Inst1) && isSimple(Inst2)) {
530 // Do the alias check.
531 aliased = AA->alias(Loc1, Loc2);
533 // Store the result in the cache.
538 typedef std::pair<Instruction *, Instruction *> AliasCacheKey;
540 /// Cache for alias results.
541 /// TODO: consider moving this to the AliasAnalysis itself.
542 DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
544 /// Removes an instruction from its block and eventually deletes it.
545 /// It's like Instruction::eraseFromParent() except that the actual deletion
546 /// is delayed until BoUpSLP is destructed.
547 /// This is required to ensure that there are no incorrect collisions in the
548 /// AliasCache, which can happen if a new instruction is allocated at the
549 /// same address as a previously deleted instruction.
550 void eraseInstruction(Instruction *I) {
551 I->removeFromParent();
552 I->dropAllReferences();
553 DeletedInstructions.push_back(std::unique_ptr<Instruction>(I));
556 /// Temporary store for deleted instructions. Instructions will be deleted
557 /// eventually when the BoUpSLP is destructed.
558 SmallVector<std::unique_ptr<Instruction>, 8> DeletedInstructions;
560 /// A list of values that need to extracted out of the tree.
561 /// This list holds pairs of (Internal Scalar : External User).
562 UserList ExternalUses;
564 /// Values used only by @llvm.assume calls.
565 SmallPtrSet<const Value *, 32> EphValues;
567 /// Holds all of the instructions that we gathered.
568 SetVector<Instruction *> GatherSeq;
569 /// A list of blocks that we are going to CSE.
570 SetVector<BasicBlock *> CSEBlocks;
572 /// Contains all scheduling relevant data for an instruction.
573 /// A ScheduleData either represents a single instruction or a member of an
574 /// instruction bundle (= a group of instructions which is combined into a
575 /// vector instruction).
576 struct ScheduleData {
578 // The initial value for the dependency counters. It means that the
579 // dependencies are not calculated yet.
580 enum { InvalidDeps = -1 };
583 : Inst(nullptr), FirstInBundle(nullptr), NextInBundle(nullptr),
584 NextLoadStore(nullptr), SchedulingRegionID(0), SchedulingPriority(0),
585 Dependencies(InvalidDeps), UnscheduledDeps(InvalidDeps),
586 UnscheduledDepsInBundle(InvalidDeps), IsScheduled(false) {}
588 void init(int BlockSchedulingRegionID) {
589 FirstInBundle = this;
590 NextInBundle = nullptr;
591 NextLoadStore = nullptr;
593 SchedulingRegionID = BlockSchedulingRegionID;
594 UnscheduledDepsInBundle = UnscheduledDeps;
598 /// Returns true if the dependency information has been calculated.
599 bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
601 /// Returns true for single instructions and for bundle representatives
602 /// (= the head of a bundle).
603 bool isSchedulingEntity() const { return FirstInBundle == this; }
605 /// Returns true if it represents an instruction bundle and not only a
606 /// single instruction.
607 bool isPartOfBundle() const {
608 return NextInBundle != nullptr || FirstInBundle != this;
611 /// Returns true if it is ready for scheduling, i.e. it has no more
612 /// unscheduled depending instructions/bundles.
613 bool isReady() const {
614 assert(isSchedulingEntity() &&
615 "can't consider non-scheduling entity for ready list");
616 return UnscheduledDepsInBundle == 0 && !IsScheduled;
619 /// Modifies the number of unscheduled dependencies, also updating it for
620 /// the whole bundle.
621 int incrementUnscheduledDeps(int Incr) {
622 UnscheduledDeps += Incr;
623 return FirstInBundle->UnscheduledDepsInBundle += Incr;
626 /// Sets the number of unscheduled dependencies to the number of
628 void resetUnscheduledDeps() {
629 incrementUnscheduledDeps(Dependencies - UnscheduledDeps);
632 /// Clears all dependency information.
633 void clearDependencies() {
634 Dependencies = InvalidDeps;
635 resetUnscheduledDeps();
636 MemoryDependencies.clear();
639 void dump(raw_ostream &os) const {
640 if (!isSchedulingEntity()) {
642 } else if (NextInBundle) {
644 ScheduleData *SD = NextInBundle;
646 os << ';' << *SD->Inst;
647 SD = SD->NextInBundle;
657 /// Points to the head in an instruction bundle (and always to this for
658 /// single instructions).
659 ScheduleData *FirstInBundle;
661 /// Single linked list of all instructions in a bundle. Null if it is a
662 /// single instruction.
663 ScheduleData *NextInBundle;
665 /// Single linked list of all memory instructions (e.g. load, store, call)
666 /// in the block - until the end of the scheduling region.
667 ScheduleData *NextLoadStore;
669 /// The dependent memory instructions.
670 /// This list is derived on demand in calculateDependencies().
671 SmallVector<ScheduleData *, 4> MemoryDependencies;
673 /// This ScheduleData is in the current scheduling region if this matches
674 /// the current SchedulingRegionID of BlockScheduling.
675 int SchedulingRegionID;
677 /// Used for getting a "good" final ordering of instructions.
678 int SchedulingPriority;
680 /// The number of dependencies. Constitutes of the number of users of the
681 /// instruction plus the number of dependent memory instructions (if any).
682 /// This value is calculated on demand.
683 /// If InvalidDeps, the number of dependencies is not calculated yet.
687 /// The number of dependencies minus the number of dependencies of scheduled
688 /// instructions. As soon as this is zero, the instruction/bundle gets ready
690 /// Note that this is negative as long as Dependencies is not calculated.
693 /// The sum of UnscheduledDeps in a bundle. Equals to UnscheduledDeps for
694 /// single instructions.
695 int UnscheduledDepsInBundle;
697 /// True if this instruction is scheduled (or considered as scheduled in the
703 friend inline raw_ostream &operator<<(raw_ostream &os,
704 const BoUpSLP::ScheduleData &SD) {
710 /// Contains all scheduling data for a basic block.
712 struct BlockScheduling {
714 BlockScheduling(BasicBlock *BB)
715 : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize),
716 ScheduleStart(nullptr), ScheduleEnd(nullptr),
717 FirstLoadStoreInRegion(nullptr), LastLoadStoreInRegion(nullptr),
718 ScheduleRegionSize(0),
719 ScheduleRegionSizeLimit(ScheduleRegionSizeBudget),
720 // Make sure that the initial SchedulingRegionID is greater than the
721 // initial SchedulingRegionID in ScheduleData (which is 0).
722 SchedulingRegionID(1) {}
726 ScheduleStart = nullptr;
727 ScheduleEnd = nullptr;
728 FirstLoadStoreInRegion = nullptr;
729 LastLoadStoreInRegion = nullptr;
731 // Reduce the maximum schedule region size by the size of the
732 // previous scheduling run.
733 ScheduleRegionSizeLimit -= ScheduleRegionSize;
734 if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
735 ScheduleRegionSizeLimit = MinScheduleRegionSize;
736 ScheduleRegionSize = 0;
738 // Make a new scheduling region, i.e. all existing ScheduleData is not
739 // in the new region yet.
740 ++SchedulingRegionID;
743 ScheduleData *getScheduleData(Value *V) {
744 ScheduleData *SD = ScheduleDataMap[V];
745 if (SD && SD->SchedulingRegionID == SchedulingRegionID)
750 bool isInSchedulingRegion(ScheduleData *SD) {
751 return SD->SchedulingRegionID == SchedulingRegionID;
754 /// Marks an instruction as scheduled and puts all dependent ready
755 /// instructions into the ready-list.
756 template <typename ReadyListType>
757 void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
758 SD->IsScheduled = true;
759 DEBUG(dbgs() << "SLP: schedule " << *SD << "\n");
761 ScheduleData *BundleMember = SD;
762 while (BundleMember) {
763 // Handle the def-use chain dependencies.
764 for (Use &U : BundleMember->Inst->operands()) {
765 ScheduleData *OpDef = getScheduleData(U.get());
766 if (OpDef && OpDef->hasValidDependencies() &&
767 OpDef->incrementUnscheduledDeps(-1) == 0) {
768 // There are no more unscheduled dependencies after decrementing,
769 // so we can put the dependent instruction into the ready list.
770 ScheduleData *DepBundle = OpDef->FirstInBundle;
771 assert(!DepBundle->IsScheduled &&
772 "already scheduled bundle gets ready");
773 ReadyList.insert(DepBundle);
774 DEBUG(dbgs() << "SLP: gets ready (def): " << *DepBundle << "\n");
777 // Handle the memory dependencies.
778 for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
779 if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
780 // There are no more unscheduled dependencies after decrementing,
781 // so we can put the dependent instruction into the ready list.
782 ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
783 assert(!DepBundle->IsScheduled &&
784 "already scheduled bundle gets ready");
785 ReadyList.insert(DepBundle);
786 DEBUG(dbgs() << "SLP: gets ready (mem): " << *DepBundle << "\n");
789 BundleMember = BundleMember->NextInBundle;
793 /// Put all instructions into the ReadyList which are ready for scheduling.
794 template <typename ReadyListType>
795 void initialFillReadyList(ReadyListType &ReadyList) {
796 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
797 ScheduleData *SD = getScheduleData(I);
798 if (SD->isSchedulingEntity() && SD->isReady()) {
799 ReadyList.insert(SD);
800 DEBUG(dbgs() << "SLP: initially in ready list: " << *I << "\n");
805 /// Checks if a bundle of instructions can be scheduled, i.e. has no
806 /// cyclic dependencies. This is only a dry-run, no instructions are
807 /// actually moved at this stage.
808 bool tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP);
810 /// Un-bundles a group of instructions.
811 void cancelScheduling(ArrayRef<Value *> VL);
813 /// Extends the scheduling region so that V is inside the region.
814 /// \returns true if the region size is within the limit.
815 bool extendSchedulingRegion(Value *V);
817 /// Initialize the ScheduleData structures for new instructions in the
818 /// scheduling region.
819 void initScheduleData(Instruction *FromI, Instruction *ToI,
820 ScheduleData *PrevLoadStore,
821 ScheduleData *NextLoadStore);
823 /// Updates the dependency information of a bundle and of all instructions/
824 /// bundles which depend on the original bundle.
825 void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
828 /// Sets all instruction in the scheduling region to un-scheduled.
829 void resetSchedule();
833 /// Simple memory allocation for ScheduleData.
834 std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
836 /// The size of a ScheduleData array in ScheduleDataChunks.
839 /// The allocator position in the current chunk, which is the last entry
840 /// of ScheduleDataChunks.
843 /// Attaches ScheduleData to Instruction.
844 /// Note that the mapping survives during all vectorization iterations, i.e.
845 /// ScheduleData structures are recycled.
846 DenseMap<Value *, ScheduleData *> ScheduleDataMap;
848 struct ReadyList : SmallVector<ScheduleData *, 8> {
849 void insert(ScheduleData *SD) { push_back(SD); }
852 /// The ready-list for scheduling (only used for the dry-run).
853 ReadyList ReadyInsts;
855 /// The first instruction of the scheduling region.
856 Instruction *ScheduleStart;
858 /// The first instruction _after_ the scheduling region.
859 Instruction *ScheduleEnd;
861 /// The first memory accessing instruction in the scheduling region
863 ScheduleData *FirstLoadStoreInRegion;
865 /// The last memory accessing instruction in the scheduling region
867 ScheduleData *LastLoadStoreInRegion;
869 /// The current size of the scheduling region.
870 int ScheduleRegionSize;
872 /// The maximum size allowed for the scheduling region.
873 int ScheduleRegionSizeLimit;
875 /// The ID of the scheduling region. For a new vectorization iteration this
876 /// is incremented which "removes" all ScheduleData from the region.
877 int SchedulingRegionID;
880 /// Attaches the BlockScheduling structures to basic blocks.
881 MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
883 /// Performs the "real" scheduling. Done before vectorization is actually
884 /// performed in a basic block.
885 void scheduleBlock(BlockScheduling *BS);
887 /// List of users to ignore during scheduling and that don't need extracting.
888 ArrayRef<Value *> UserIgnoreList;
890 // Number of load bundles that contain consecutive loads.
891 int NumLoadsWantToKeepOrder;
893 // Number of load bundles that contain consecutive loads in reversed order.
894 int NumLoadsWantToChangeOrder;
896 // Analysis and block reference.
899 TargetTransformInfo *TTI;
900 TargetLibraryInfo *TLI;
906 const DataLayout *DL;
907 unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
908 unsigned MinVecRegSize; // Set by cl::opt (default: 128).
909 /// Instruction builder to construct the vectorized tree.
912 /// A map of scalar integer values to the smallest bit width with which they
913 /// can legally be represented. The values map to (width, signed) pairs,
914 /// where "width" indicates the minimum bit width and "signed" is True if the
915 /// value must be signed-extended, rather than zero-extended, back to its
917 MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
920 } // end namespace llvm
921 } // end namespace slpvectorizer
923 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
924 ArrayRef<Value *> UserIgnoreLst) {
926 UserIgnoreList = UserIgnoreLst;
927 if (!allSameType(Roots))
929 buildTree_rec(Roots, 0);
931 // Collect the values that we need to extract from the tree.
932 for (TreeEntry &EIdx : VectorizableTree) {
933 TreeEntry *Entry = &EIdx;
936 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
937 Value *Scalar = Entry->Scalars[Lane];
939 // No need to handle users of gathered values.
940 if (Entry->NeedToGather)
943 for (User *U : Scalar->users()) {
944 DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
946 Instruction *UserInst = dyn_cast<Instruction>(U);
950 // Skip in-tree scalars that become vectors
951 if (ScalarToTreeEntry.count(U)) {
952 int Idx = ScalarToTreeEntry[U];
953 TreeEntry *UseEntry = &VectorizableTree[Idx];
954 Value *UseScalar = UseEntry->Scalars[0];
955 // Some in-tree scalars will remain as scalar in vectorized
956 // instructions. If that is the case, the one in Lane 0 will
958 if (UseScalar != U ||
959 !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
960 DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
962 assert(!VectorizableTree[Idx].NeedToGather && "Bad state");
967 // Ignore users in the user ignore list.
968 if (is_contained(UserIgnoreList, UserInst))
971 DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane " <<
972 Lane << " from " << *Scalar << ".\n");
973 ExternalUses.push_back(ExternalUser(Scalar, U, Lane));
980 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth) {
981 bool isAltShuffle = false;
982 assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
984 if (Depth == RecursionMaxDepth) {
985 DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
986 newTreeEntry(VL, false);
990 // Don't handle vectors.
991 if (VL[0]->getType()->isVectorTy()) {
992 DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
993 newTreeEntry(VL, false);
997 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
998 if (SI->getValueOperand()->getType()->isVectorTy()) {
999 DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
1000 newTreeEntry(VL, false);
1003 unsigned Opcode = getSameOpcode(VL);
1005 // Check that this shuffle vector refers to the alternate
1006 // sequence of opcodes.
1007 if (Opcode == Instruction::ShuffleVector) {
1008 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
1009 unsigned Op = I0->getOpcode();
1010 if (Op != Instruction::ShuffleVector)
1011 isAltShuffle = true;
1014 // If all of the operands are identical or constant we have a simple solution.
1015 if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !Opcode) {
1016 DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
1017 newTreeEntry(VL, false);
1021 // We now know that this is a vector of instructions of the same type from
1024 // Don't vectorize ephemeral values.
1025 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1026 if (EphValues.count(VL[i])) {
1027 DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
1028 ") is ephemeral.\n");
1029 newTreeEntry(VL, false);
1034 // Check if this is a duplicate of another entry.
1035 if (ScalarToTreeEntry.count(VL[0])) {
1036 int Idx = ScalarToTreeEntry[VL[0]];
1037 TreeEntry *E = &VectorizableTree[Idx];
1038 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1039 DEBUG(dbgs() << "SLP: \tChecking bundle: " << *VL[i] << ".\n");
1040 if (E->Scalars[i] != VL[i]) {
1041 DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
1042 newTreeEntry(VL, false);
1046 DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *VL[0] << ".\n");
1050 // Check that none of the instructions in the bundle are already in the tree.
1051 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1052 if (ScalarToTreeEntry.count(VL[i])) {
1053 DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
1054 ") is already in tree.\n");
1055 newTreeEntry(VL, false);
1060 // If any of the scalars is marked as a value that needs to stay scalar then
1061 // we need to gather the scalars.
1062 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1063 if (MustGather.count(VL[i])) {
1064 DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
1065 newTreeEntry(VL, false);
1070 // Check that all of the users of the scalars that we want to vectorize are
1072 Instruction *VL0 = cast<Instruction>(VL[0]);
1073 BasicBlock *BB = cast<Instruction>(VL0)->getParent();
1075 if (!DT->isReachableFromEntry(BB)) {
1076 // Don't go into unreachable blocks. They may contain instructions with
1077 // dependency cycles which confuse the final scheduling.
1078 DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
1079 newTreeEntry(VL, false);
1083 // Check that every instructions appears once in this bundle.
1084 for (unsigned i = 0, e = VL.size(); i < e; ++i)
1085 for (unsigned j = i+1; j < e; ++j)
1086 if (VL[i] == VL[j]) {
1087 DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
1088 newTreeEntry(VL, false);
1092 auto &BSRef = BlocksSchedules[BB];
1094 BSRef = llvm::make_unique<BlockScheduling>(BB);
1096 BlockScheduling &BS = *BSRef.get();
1098 if (!BS.tryScheduleBundle(VL, this)) {
1099 DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
1100 assert((!BS.getScheduleData(VL[0]) ||
1101 !BS.getScheduleData(VL[0])->isPartOfBundle()) &&
1102 "tryScheduleBundle should cancelScheduling on failure");
1103 newTreeEntry(VL, false);
1106 DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
1109 case Instruction::PHI: {
1110 PHINode *PH = dyn_cast<PHINode>(VL0);
1112 // Check for terminator values (e.g. invoke).
1113 for (unsigned j = 0; j < VL.size(); ++j)
1114 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1115 TerminatorInst *Term = dyn_cast<TerminatorInst>(
1116 cast<PHINode>(VL[j])->getIncomingValueForBlock(PH->getIncomingBlock(i)));
1118 DEBUG(dbgs() << "SLP: Need to swizzle PHINodes (TerminatorInst use).\n");
1119 BS.cancelScheduling(VL);
1120 newTreeEntry(VL, false);
1125 newTreeEntry(VL, true);
1126 DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
1128 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1130 // Prepare the operand vector.
1132 Operands.push_back(cast<PHINode>(j)->getIncomingValueForBlock(
1133 PH->getIncomingBlock(i)));
1135 buildTree_rec(Operands, Depth + 1);
1139 case Instruction::ExtractValue:
1140 case Instruction::ExtractElement: {
1141 bool Reuse = canReuseExtract(VL, Opcode);
1143 DEBUG(dbgs() << "SLP: Reusing extract sequence.\n");
1145 BS.cancelScheduling(VL);
1147 newTreeEntry(VL, Reuse);
1150 case Instruction::Load: {
1151 // Check that a vectorized load would load the same memory as a scalar
1153 // For example we don't want vectorize loads that are smaller than 8 bit.
1154 // Even though we have a packed struct {<i2, i2, i2, i2>} LLVM treats
1155 // loading/storing it as an i8 struct. If we vectorize loads/stores from
1156 // such a struct we read/write packed bits disagreeing with the
1157 // unvectorized version.
1158 Type *ScalarTy = VL[0]->getType();
1160 if (DL->getTypeSizeInBits(ScalarTy) !=
1161 DL->getTypeAllocSizeInBits(ScalarTy)) {
1162 BS.cancelScheduling(VL);
1163 newTreeEntry(VL, false);
1164 DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
1168 // Make sure all loads in the bundle are simple - we can't vectorize
1169 // atomic or volatile loads.
1170 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i) {
1171 LoadInst *L = cast<LoadInst>(VL[i]);
1172 if (!L->isSimple()) {
1173 BS.cancelScheduling(VL);
1174 newTreeEntry(VL, false);
1175 DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
1180 // Check if the loads are consecutive, reversed, or neither.
1181 // TODO: What we really want is to sort the loads, but for now, check
1182 // the two likely directions.
1183 bool Consecutive = true;
1184 bool ReverseConsecutive = true;
1185 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i) {
1186 if (!isConsecutiveAccess(VL[i], VL[i + 1], *DL, *SE)) {
1187 Consecutive = false;
1190 ReverseConsecutive = false;
1195 ++NumLoadsWantToKeepOrder;
1196 newTreeEntry(VL, true);
1197 DEBUG(dbgs() << "SLP: added a vector of loads.\n");
1201 // If none of the load pairs were consecutive when checked in order,
1202 // check the reverse order.
1203 if (ReverseConsecutive)
1204 for (unsigned i = VL.size() - 1; i > 0; --i)
1205 if (!isConsecutiveAccess(VL[i], VL[i - 1], *DL, *SE)) {
1206 ReverseConsecutive = false;
1210 BS.cancelScheduling(VL);
1211 newTreeEntry(VL, false);
1213 if (ReverseConsecutive) {
1214 ++NumLoadsWantToChangeOrder;
1215 DEBUG(dbgs() << "SLP: Gathering reversed loads.\n");
1217 DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
1221 case Instruction::ZExt:
1222 case Instruction::SExt:
1223 case Instruction::FPToUI:
1224 case Instruction::FPToSI:
1225 case Instruction::FPExt:
1226 case Instruction::PtrToInt:
1227 case Instruction::IntToPtr:
1228 case Instruction::SIToFP:
1229 case Instruction::UIToFP:
1230 case Instruction::Trunc:
1231 case Instruction::FPTrunc:
1232 case Instruction::BitCast: {
1233 Type *SrcTy = VL0->getOperand(0)->getType();
1234 for (unsigned i = 0; i < VL.size(); ++i) {
1235 Type *Ty = cast<Instruction>(VL[i])->getOperand(0)->getType();
1236 if (Ty != SrcTy || !isValidElementType(Ty)) {
1237 BS.cancelScheduling(VL);
1238 newTreeEntry(VL, false);
1239 DEBUG(dbgs() << "SLP: Gathering casts with different src types.\n");
1243 newTreeEntry(VL, true);
1244 DEBUG(dbgs() << "SLP: added a vector of casts.\n");
1246 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1248 // Prepare the operand vector.
1250 Operands.push_back(cast<Instruction>(j)->getOperand(i));
1252 buildTree_rec(Operands, Depth+1);
1256 case Instruction::ICmp:
1257 case Instruction::FCmp: {
1258 // Check that all of the compares have the same predicate.
1259 CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
1260 Type *ComparedTy = cast<Instruction>(VL[0])->getOperand(0)->getType();
1261 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
1262 CmpInst *Cmp = cast<CmpInst>(VL[i]);
1263 if (Cmp->getPredicate() != P0 ||
1264 Cmp->getOperand(0)->getType() != ComparedTy) {
1265 BS.cancelScheduling(VL);
1266 newTreeEntry(VL, false);
1267 DEBUG(dbgs() << "SLP: Gathering cmp with different predicate.\n");
1272 newTreeEntry(VL, true);
1273 DEBUG(dbgs() << "SLP: added a vector of compares.\n");
1275 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1277 // Prepare the operand vector.
1279 Operands.push_back(cast<Instruction>(j)->getOperand(i));
1281 buildTree_rec(Operands, Depth+1);
1285 case Instruction::Select:
1286 case Instruction::Add:
1287 case Instruction::FAdd:
1288 case Instruction::Sub:
1289 case Instruction::FSub:
1290 case Instruction::Mul:
1291 case Instruction::FMul:
1292 case Instruction::UDiv:
1293 case Instruction::SDiv:
1294 case Instruction::FDiv:
1295 case Instruction::URem:
1296 case Instruction::SRem:
1297 case Instruction::FRem:
1298 case Instruction::Shl:
1299 case Instruction::LShr:
1300 case Instruction::AShr:
1301 case Instruction::And:
1302 case Instruction::Or:
1303 case Instruction::Xor: {
1304 newTreeEntry(VL, true);
1305 DEBUG(dbgs() << "SLP: added a vector of bin op.\n");
1307 // Sort operands of the instructions so that each side is more likely to
1308 // have the same opcode.
1309 if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
1310 ValueList Left, Right;
1311 reorderInputsAccordingToOpcode(VL, Left, Right);
1312 buildTree_rec(Left, Depth + 1);
1313 buildTree_rec(Right, Depth + 1);
1317 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1319 // Prepare the operand vector.
1321 Operands.push_back(cast<Instruction>(j)->getOperand(i));
1323 buildTree_rec(Operands, Depth+1);
1327 case Instruction::GetElementPtr: {
1328 // We don't combine GEPs with complicated (nested) indexing.
1329 for (unsigned j = 0; j < VL.size(); ++j) {
1330 if (cast<Instruction>(VL[j])->getNumOperands() != 2) {
1331 DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
1332 BS.cancelScheduling(VL);
1333 newTreeEntry(VL, false);
1338 // We can't combine several GEPs into one vector if they operate on
1340 Type *Ty0 = cast<Instruction>(VL0)->getOperand(0)->getType();
1341 for (unsigned j = 0; j < VL.size(); ++j) {
1342 Type *CurTy = cast<Instruction>(VL[j])->getOperand(0)->getType();
1344 DEBUG(dbgs() << "SLP: not-vectorizable GEP (different types).\n");
1345 BS.cancelScheduling(VL);
1346 newTreeEntry(VL, false);
1351 // We don't combine GEPs with non-constant indexes.
1352 for (unsigned j = 0; j < VL.size(); ++j) {
1353 auto Op = cast<Instruction>(VL[j])->getOperand(1);
1354 if (!isa<ConstantInt>(Op)) {
1356 dbgs() << "SLP: not-vectorizable GEP (non-constant indexes).\n");
1357 BS.cancelScheduling(VL);
1358 newTreeEntry(VL, false);
1363 newTreeEntry(VL, true);
1364 DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
1365 for (unsigned i = 0, e = 2; i < e; ++i) {
1367 // Prepare the operand vector.
1369 Operands.push_back(cast<Instruction>(j)->getOperand(i));
1371 buildTree_rec(Operands, Depth + 1);
1375 case Instruction::Store: {
1376 // Check if the stores are consecutive or of we need to swizzle them.
1377 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
1378 if (!isConsecutiveAccess(VL[i], VL[i + 1], *DL, *SE)) {
1379 BS.cancelScheduling(VL);
1380 newTreeEntry(VL, false);
1381 DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
1385 newTreeEntry(VL, true);
1386 DEBUG(dbgs() << "SLP: added a vector of stores.\n");
1390 Operands.push_back(cast<Instruction>(j)->getOperand(0));
1392 buildTree_rec(Operands, Depth + 1);
1395 case Instruction::Call: {
1396 // Check if the calls are all to the same vectorizable intrinsic.
1397 CallInst *CI = cast<CallInst>(VL[0]);
1398 // Check if this is an Intrinsic call or something that can be
1399 // represented by an intrinsic call
1400 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
1401 if (!isTriviallyVectorizable(ID)) {
1402 BS.cancelScheduling(VL);
1403 newTreeEntry(VL, false);
1404 DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
1407 Function *Int = CI->getCalledFunction();
1408 Value *A1I = nullptr;
1409 if (hasVectorInstrinsicScalarOpd(ID, 1))
1410 A1I = CI->getArgOperand(1);
1411 for (unsigned i = 1, e = VL.size(); i != e; ++i) {
1412 CallInst *CI2 = dyn_cast<CallInst>(VL[i]);
1413 if (!CI2 || CI2->getCalledFunction() != Int ||
1414 getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
1415 !CI->hasIdenticalOperandBundleSchema(*CI2)) {
1416 BS.cancelScheduling(VL);
1417 newTreeEntry(VL, false);
1418 DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *VL[i]
1422 // ctlz,cttz and powi are special intrinsics whose second argument
1423 // should be same in order for them to be vectorized.
1424 if (hasVectorInstrinsicScalarOpd(ID, 1)) {
1425 Value *A1J = CI2->getArgOperand(1);
1427 BS.cancelScheduling(VL);
1428 newTreeEntry(VL, false);
1429 DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
1430 << " argument "<< A1I<<"!=" << A1J
1435 // Verify that the bundle operands are identical between the two calls.
1436 if (CI->hasOperandBundles() &&
1437 !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
1438 CI->op_begin() + CI->getBundleOperandsEndIndex(),
1439 CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
1440 BS.cancelScheduling(VL);
1441 newTreeEntry(VL, false);
1442 DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:" << *CI << "!="
1448 newTreeEntry(VL, true);
1449 for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i) {
1451 // Prepare the operand vector.
1452 for (Value *j : VL) {
1453 CallInst *CI2 = dyn_cast<CallInst>(j);
1454 Operands.push_back(CI2->getArgOperand(i));
1456 buildTree_rec(Operands, Depth + 1);
1460 case Instruction::ShuffleVector: {
1461 // If this is not an alternate sequence of opcode like add-sub
1462 // then do not vectorize this instruction.
1463 if (!isAltShuffle) {
1464 BS.cancelScheduling(VL);
1465 newTreeEntry(VL, false);
1466 DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
1469 newTreeEntry(VL, true);
1470 DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
1472 // Reorder operands if reordering would enable vectorization.
1473 if (isa<BinaryOperator>(VL0)) {
1474 ValueList Left, Right;
1475 reorderAltShuffleOperands(VL, Left, Right);
1476 buildTree_rec(Left, Depth + 1);
1477 buildTree_rec(Right, Depth + 1);
1481 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1483 // Prepare the operand vector.
1485 Operands.push_back(cast<Instruction>(j)->getOperand(i));
1487 buildTree_rec(Operands, Depth + 1);
1492 BS.cancelScheduling(VL);
1493 newTreeEntry(VL, false);
1494 DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
1499 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
1502 auto *ST = dyn_cast<StructType>(T);
1504 N = ST->getNumElements();
1505 EltTy = *ST->element_begin();
1507 N = cast<ArrayType>(T)->getNumElements();
1508 EltTy = cast<ArrayType>(T)->getElementType();
1510 if (!isValidElementType(EltTy))
1512 uint64_t VTSize = DL.getTypeStoreSizeInBits(VectorType::get(EltTy, N));
1513 if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
1516 // Check that struct is homogeneous.
1517 for (const auto *Ty : ST->elements())
1524 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, unsigned Opcode) const {
1525 assert(Opcode == Instruction::ExtractElement ||
1526 Opcode == Instruction::ExtractValue);
1527 assert(Opcode == getSameOpcode(VL) && "Invalid opcode");
1528 // Check if all of the extracts come from the same vector and from the
1531 Instruction *E0 = cast<Instruction>(VL0);
1532 Value *Vec = E0->getOperand(0);
1534 // We have to extract from a vector/aggregate with the same number of elements.
1536 if (Opcode == Instruction::ExtractValue) {
1537 const DataLayout &DL = E0->getModule()->getDataLayout();
1538 NElts = canMapToVector(Vec->getType(), DL);
1541 // Check if load can be rewritten as load of vector.
1542 LoadInst *LI = dyn_cast<LoadInst>(Vec);
1543 if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
1546 NElts = Vec->getType()->getVectorNumElements();
1549 if (NElts != VL.size())
1552 // Check that all of the indices extract from the correct offset.
1553 if (!matchExtractIndex(E0, 0, Opcode))
1556 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
1557 Instruction *E = cast<Instruction>(VL[i]);
1558 if (!matchExtractIndex(E, i, Opcode))
1560 if (E->getOperand(0) != Vec)
1567 int BoUpSLP::getEntryCost(TreeEntry *E) {
1568 ArrayRef<Value*> VL = E->Scalars;
1570 Type *ScalarTy = VL[0]->getType();
1571 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1572 ScalarTy = SI->getValueOperand()->getType();
1573 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1575 // If we have computed a smaller type for the expression, update VecTy so
1576 // that the costs will be accurate.
1577 if (MinBWs.count(VL[0]))
1578 VecTy = VectorType::get(
1579 IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
1581 if (E->NeedToGather) {
1582 if (allConstant(VL))
1585 return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
1587 return getGatherCost(E->Scalars);
1589 unsigned Opcode = getSameOpcode(VL);
1590 assert(Opcode && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
1591 Instruction *VL0 = cast<Instruction>(VL[0]);
1593 case Instruction::PHI: {
1596 case Instruction::ExtractValue:
1597 case Instruction::ExtractElement: {
1598 if (canReuseExtract(VL, Opcode)) {
1600 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
1601 Instruction *E = cast<Instruction>(VL[i]);
1603 // Take credit for instruction that will become dead.
1605 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, i);
1609 return getGatherCost(VecTy);
1611 case Instruction::ZExt:
1612 case Instruction::SExt:
1613 case Instruction::FPToUI:
1614 case Instruction::FPToSI:
1615 case Instruction::FPExt:
1616 case Instruction::PtrToInt:
1617 case Instruction::IntToPtr:
1618 case Instruction::SIToFP:
1619 case Instruction::UIToFP:
1620 case Instruction::Trunc:
1621 case Instruction::FPTrunc:
1622 case Instruction::BitCast: {
1623 Type *SrcTy = VL0->getOperand(0)->getType();
1625 // Calculate the cost of this instruction.
1626 int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(),
1627 VL0->getType(), SrcTy);
1629 VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
1630 int VecCost = TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy);
1631 return VecCost - ScalarCost;
1633 case Instruction::FCmp:
1634 case Instruction::ICmp:
1635 case Instruction::Select: {
1636 // Calculate the cost of this instruction.
1637 VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
1638 int ScalarCost = VecTy->getNumElements() *
1639 TTI->getCmpSelInstrCost(Opcode, ScalarTy, Builder.getInt1Ty());
1640 int VecCost = TTI->getCmpSelInstrCost(Opcode, VecTy, MaskTy);
1641 return VecCost - ScalarCost;
1643 case Instruction::Add:
1644 case Instruction::FAdd:
1645 case Instruction::Sub:
1646 case Instruction::FSub:
1647 case Instruction::Mul:
1648 case Instruction::FMul:
1649 case Instruction::UDiv:
1650 case Instruction::SDiv:
1651 case Instruction::FDiv:
1652 case Instruction::URem:
1653 case Instruction::SRem:
1654 case Instruction::FRem:
1655 case Instruction::Shl:
1656 case Instruction::LShr:
1657 case Instruction::AShr:
1658 case Instruction::And:
1659 case Instruction::Or:
1660 case Instruction::Xor: {
1661 // Certain instructions can be cheaper to vectorize if they have a
1662 // constant second vector operand.
1663 TargetTransformInfo::OperandValueKind Op1VK =
1664 TargetTransformInfo::OK_AnyValue;
1665 TargetTransformInfo::OperandValueKind Op2VK =
1666 TargetTransformInfo::OK_UniformConstantValue;
1667 TargetTransformInfo::OperandValueProperties Op1VP =
1668 TargetTransformInfo::OP_None;
1669 TargetTransformInfo::OperandValueProperties Op2VP =
1670 TargetTransformInfo::OP_None;
1672 // If all operands are exactly the same ConstantInt then set the
1673 // operand kind to OK_UniformConstantValue.
1674 // If instead not all operands are constants, then set the operand kind
1675 // to OK_AnyValue. If all operands are constants but not the same,
1676 // then set the operand kind to OK_NonUniformConstantValue.
1677 ConstantInt *CInt = nullptr;
1678 for (unsigned i = 0; i < VL.size(); ++i) {
1679 const Instruction *I = cast<Instruction>(VL[i]);
1680 if (!isa<ConstantInt>(I->getOperand(1))) {
1681 Op2VK = TargetTransformInfo::OK_AnyValue;
1685 CInt = cast<ConstantInt>(I->getOperand(1));
1688 if (Op2VK == TargetTransformInfo::OK_UniformConstantValue &&
1689 CInt != cast<ConstantInt>(I->getOperand(1)))
1690 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
1692 // FIXME: Currently cost of model modification for division by power of
1693 // 2 is handled for X86 and AArch64. Add support for other targets.
1694 if (Op2VK == TargetTransformInfo::OK_UniformConstantValue && CInt &&
1695 CInt->getValue().isPowerOf2())
1696 Op2VP = TargetTransformInfo::OP_PowerOf2;
1698 int ScalarCost = VecTy->getNumElements() *
1699 TTI->getArithmeticInstrCost(Opcode, ScalarTy, Op1VK,
1700 Op2VK, Op1VP, Op2VP);
1701 int VecCost = TTI->getArithmeticInstrCost(Opcode, VecTy, Op1VK, Op2VK,
1703 return VecCost - ScalarCost;
1705 case Instruction::GetElementPtr: {
1706 TargetTransformInfo::OperandValueKind Op1VK =
1707 TargetTransformInfo::OK_AnyValue;
1708 TargetTransformInfo::OperandValueKind Op2VK =
1709 TargetTransformInfo::OK_UniformConstantValue;
1712 VecTy->getNumElements() *
1713 TTI->getArithmeticInstrCost(Instruction::Add, ScalarTy, Op1VK, Op2VK);
1715 TTI->getArithmeticInstrCost(Instruction::Add, VecTy, Op1VK, Op2VK);
1717 return VecCost - ScalarCost;
1719 case Instruction::Load: {
1720 // Cost of wide load - cost of scalar loads.
1721 unsigned alignment = dyn_cast<LoadInst>(VL0)->getAlignment();
1722 int ScalarLdCost = VecTy->getNumElements() *
1723 TTI->getMemoryOpCost(Instruction::Load, ScalarTy, alignment, 0);
1724 int VecLdCost = TTI->getMemoryOpCost(Instruction::Load,
1725 VecTy, alignment, 0);
1726 return VecLdCost - ScalarLdCost;
1728 case Instruction::Store: {
1729 // We know that we can merge the stores. Calculate the cost.
1730 unsigned alignment = dyn_cast<StoreInst>(VL0)->getAlignment();
1731 int ScalarStCost = VecTy->getNumElements() *
1732 TTI->getMemoryOpCost(Instruction::Store, ScalarTy, alignment, 0);
1733 int VecStCost = TTI->getMemoryOpCost(Instruction::Store,
1734 VecTy, alignment, 0);
1735 return VecStCost - ScalarStCost;
1737 case Instruction::Call: {
1738 CallInst *CI = cast<CallInst>(VL0);
1739 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
1741 // Calculate the cost of the scalar and vector calls.
1742 SmallVector<Type*, 4> ScalarTys, VecTys;
1743 for (unsigned op = 0, opc = CI->getNumArgOperands(); op!= opc; ++op) {
1744 ScalarTys.push_back(CI->getArgOperand(op)->getType());
1745 VecTys.push_back(VectorType::get(CI->getArgOperand(op)->getType(),
1746 VecTy->getNumElements()));
1750 if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
1751 FMF = FPMO->getFastMathFlags();
1753 int ScalarCallCost = VecTy->getNumElements() *
1754 TTI->getIntrinsicInstrCost(ID, ScalarTy, ScalarTys, FMF);
1756 int VecCallCost = TTI->getIntrinsicInstrCost(ID, VecTy, VecTys, FMF);
1758 DEBUG(dbgs() << "SLP: Call cost "<< VecCallCost - ScalarCallCost
1759 << " (" << VecCallCost << "-" << ScalarCallCost << ")"
1760 << " for " << *CI << "\n");
1762 return VecCallCost - ScalarCallCost;
1764 case Instruction::ShuffleVector: {
1765 TargetTransformInfo::OperandValueKind Op1VK =
1766 TargetTransformInfo::OK_AnyValue;
1767 TargetTransformInfo::OperandValueKind Op2VK =
1768 TargetTransformInfo::OK_AnyValue;
1771 for (Value *i : VL) {
1772 Instruction *I = cast<Instruction>(i);
1776 TTI->getArithmeticInstrCost(I->getOpcode(), ScalarTy, Op1VK, Op2VK);
1778 // VecCost is equal to sum of the cost of creating 2 vectors
1779 // and the cost of creating shuffle.
1780 Instruction *I0 = cast<Instruction>(VL[0]);
1782 TTI->getArithmeticInstrCost(I0->getOpcode(), VecTy, Op1VK, Op2VK);
1783 Instruction *I1 = cast<Instruction>(VL[1]);
1785 TTI->getArithmeticInstrCost(I1->getOpcode(), VecTy, Op1VK, Op2VK);
1787 TTI->getShuffleCost(TargetTransformInfo::SK_Alternate, VecTy, 0);
1788 return VecCost - ScalarCost;
1791 llvm_unreachable("Unknown instruction");
1795 bool BoUpSLP::isFullyVectorizableTinyTree() {
1796 DEBUG(dbgs() << "SLP: Check whether the tree with height " <<
1797 VectorizableTree.size() << " is fully vectorizable .\n");
1799 // We only handle trees of heights 1 and 2.
1800 if (VectorizableTree.size() == 1 && !VectorizableTree[0].NeedToGather)
1803 if (VectorizableTree.size() != 2)
1806 // Handle splat and all-constants stores.
1807 if (!VectorizableTree[0].NeedToGather &&
1808 (allConstant(VectorizableTree[1].Scalars) ||
1809 isSplat(VectorizableTree[1].Scalars)))
1812 // Gathering cost would be too much for tiny trees.
1813 if (VectorizableTree[0].NeedToGather || VectorizableTree[1].NeedToGather)
1819 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable() {
1821 // We can vectorize the tree if its size is greater than or equal to the
1822 // minimum size specified by the MinTreeSize command line option.
1823 if (VectorizableTree.size() >= MinTreeSize)
1826 // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
1827 // can vectorize it if we can prove it fully vectorizable.
1828 if (isFullyVectorizableTinyTree())
1831 assert(VectorizableTree.empty()
1832 ? ExternalUses.empty()
1833 : true && "We shouldn't have any external users");
1835 // Otherwise, we can't vectorize the tree. It is both tiny and not fully
1840 int BoUpSLP::getSpillCost() {
1841 // Walk from the bottom of the tree to the top, tracking which values are
1842 // live. When we see a call instruction that is not part of our tree,
1843 // query TTI to see if there is a cost to keeping values live over it
1844 // (for example, if spills and fills are required).
1845 unsigned BundleWidth = VectorizableTree.front().Scalars.size();
1848 SmallPtrSet<Instruction*, 4> LiveValues;
1849 Instruction *PrevInst = nullptr;
1851 for (const auto &N : VectorizableTree) {
1852 Instruction *Inst = dyn_cast<Instruction>(N.Scalars[0]);
1861 // Update LiveValues.
1862 LiveValues.erase(PrevInst);
1863 for (auto &J : PrevInst->operands()) {
1864 if (isa<Instruction>(&*J) && ScalarToTreeEntry.count(&*J))
1865 LiveValues.insert(cast<Instruction>(&*J));
1869 dbgs() << "SLP: #LV: " << LiveValues.size();
1870 for (auto *X : LiveValues)
1871 dbgs() << " " << X->getName();
1872 dbgs() << ", Looking at ";
1876 // Now find the sequence of instructions between PrevInst and Inst.
1877 BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
1879 PrevInst->getIterator().getReverse();
1880 while (InstIt != PrevInstIt) {
1881 if (PrevInstIt == PrevInst->getParent()->rend()) {
1882 PrevInstIt = Inst->getParent()->rbegin();
1886 if (isa<CallInst>(&*PrevInstIt) && &*PrevInstIt != PrevInst) {
1887 SmallVector<Type*, 4> V;
1888 for (auto *II : LiveValues)
1889 V.push_back(VectorType::get(II->getType(), BundleWidth));
1890 Cost += TTI->getCostOfKeepingLiveOverCall(V);
1902 int BoUpSLP::getTreeCost() {
1904 DEBUG(dbgs() << "SLP: Calculating cost for tree of size " <<
1905 VectorizableTree.size() << ".\n");
1907 unsigned BundleWidth = VectorizableTree[0].Scalars.size();
1909 for (TreeEntry &TE : VectorizableTree) {
1910 int C = getEntryCost(&TE);
1911 DEBUG(dbgs() << "SLP: Adding cost " << C << " for bundle that starts with "
1912 << *TE.Scalars[0] << ".\n");
1916 SmallSet<Value *, 16> ExtractCostCalculated;
1917 int ExtractCost = 0;
1918 for (ExternalUser &EU : ExternalUses) {
1919 // We only add extract cost once for the same scalar.
1920 if (!ExtractCostCalculated.insert(EU.Scalar).second)
1923 // Uses by ephemeral values are free (because the ephemeral value will be
1924 // removed prior to code generation, and so the extraction will be
1925 // removed as well).
1926 if (EphValues.count(EU.User))
1929 // If we plan to rewrite the tree in a smaller type, we will need to sign
1930 // extend the extracted value back to the original type. Here, we account
1931 // for the extract and the added cost of the sign extend if needed.
1932 auto *VecTy = VectorType::get(EU.Scalar->getType(), BundleWidth);
1933 auto *ScalarRoot = VectorizableTree[0].Scalars[0];
1934 if (MinBWs.count(ScalarRoot)) {
1935 auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
1937 MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
1938 VecTy = VectorType::get(MinTy, BundleWidth);
1939 ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
1943 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
1947 int SpillCost = getSpillCost();
1948 Cost += SpillCost + ExtractCost;
1950 DEBUG(dbgs() << "SLP: Spill Cost = " << SpillCost << ".\n"
1951 << "SLP: Extract Cost = " << ExtractCost << ".\n"
1952 << "SLP: Total Cost = " << Cost << ".\n");
1956 int BoUpSLP::getGatherCost(Type *Ty) {
1958 for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
1959 Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
1963 int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) {
1964 // Find the type of the operands in VL.
1965 Type *ScalarTy = VL[0]->getType();
1966 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1967 ScalarTy = SI->getValueOperand()->getType();
1968 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1969 // Find the cost of inserting/extracting values from the vector.
1970 return getGatherCost(VecTy);
1973 // Reorder commutative operations in alternate shuffle if the resulting vectors
1974 // are consecutive loads. This would allow us to vectorize the tree.
1975 // If we have something like-
1976 // load a[0] - load b[0]
1977 // load b[1] + load a[1]
1978 // load a[2] - load b[2]
1979 // load a[3] + load b[3]
1980 // Reordering the second load b[1] load a[1] would allow us to vectorize this
1982 void BoUpSLP::reorderAltShuffleOperands(ArrayRef<Value *> VL,
1983 SmallVectorImpl<Value *> &Left,
1984 SmallVectorImpl<Value *> &Right) {
1985 // Push left and right operands of binary operation into Left and Right
1986 for (Value *i : VL) {
1987 Left.push_back(cast<Instruction>(i)->getOperand(0));
1988 Right.push_back(cast<Instruction>(i)->getOperand(1));
1991 // Reorder if we have a commutative operation and consecutive access
1992 // are on either side of the alternate instructions.
1993 for (unsigned j = 0; j < VL.size() - 1; ++j) {
1994 if (LoadInst *L = dyn_cast<LoadInst>(Left[j])) {
1995 if (LoadInst *L1 = dyn_cast<LoadInst>(Right[j + 1])) {
1996 Instruction *VL1 = cast<Instruction>(VL[j]);
1997 Instruction *VL2 = cast<Instruction>(VL[j + 1]);
1998 if (VL1->isCommutative() && isConsecutiveAccess(L, L1, *DL, *SE)) {
1999 std::swap(Left[j], Right[j]);
2001 } else if (VL2->isCommutative() &&
2002 isConsecutiveAccess(L, L1, *DL, *SE)) {
2003 std::swap(Left[j + 1], Right[j + 1]);
2009 if (LoadInst *L = dyn_cast<LoadInst>(Right[j])) {
2010 if (LoadInst *L1 = dyn_cast<LoadInst>(Left[j + 1])) {
2011 Instruction *VL1 = cast<Instruction>(VL[j]);
2012 Instruction *VL2 = cast<Instruction>(VL[j + 1]);
2013 if (VL1->isCommutative() && isConsecutiveAccess(L, L1, *DL, *SE)) {
2014 std::swap(Left[j], Right[j]);
2016 } else if (VL2->isCommutative() &&
2017 isConsecutiveAccess(L, L1, *DL, *SE)) {
2018 std::swap(Left[j + 1], Right[j + 1]);
2027 // Return true if I should be commuted before adding it's left and right
2028 // operands to the arrays Left and Right.
2030 // The vectorizer is trying to either have all elements one side being
2031 // instruction with the same opcode to enable further vectorization, or having
2032 // a splat to lower the vectorizing cost.
2033 static bool shouldReorderOperands(int i, Instruction &I,
2034 SmallVectorImpl<Value *> &Left,
2035 SmallVectorImpl<Value *> &Right,
2036 bool AllSameOpcodeLeft,
2037 bool AllSameOpcodeRight, bool SplatLeft,
2039 Value *VLeft = I.getOperand(0);
2040 Value *VRight = I.getOperand(1);
2041 // If we have "SplatRight", try to see if commuting is needed to preserve it.
2043 if (VRight == Right[i - 1])
2044 // Preserve SplatRight
2046 if (VLeft == Right[i - 1]) {
2047 // Commuting would preserve SplatRight, but we don't want to break
2048 // SplatLeft either, i.e. preserve the original order if possible.
2049 // (FIXME: why do we care?)
2050 if (SplatLeft && VLeft == Left[i - 1])
2055 // Symmetrically handle Right side.
2057 if (VLeft == Left[i - 1])
2058 // Preserve SplatLeft
2060 if (VRight == Left[i - 1])
2064 Instruction *ILeft = dyn_cast<Instruction>(VLeft);
2065 Instruction *IRight = dyn_cast<Instruction>(VRight);
2067 // If we have "AllSameOpcodeRight", try to see if the left operands preserves
2068 // it and not the right, in this case we want to commute.
2069 if (AllSameOpcodeRight) {
2070 unsigned RightPrevOpcode = cast<Instruction>(Right[i - 1])->getOpcode();
2071 if (IRight && RightPrevOpcode == IRight->getOpcode())
2072 // Do not commute, a match on the right preserves AllSameOpcodeRight
2074 if (ILeft && RightPrevOpcode == ILeft->getOpcode()) {
2075 // We have a match and may want to commute, but first check if there is
2076 // not also a match on the existing operands on the Left to preserve
2077 // AllSameOpcodeLeft, i.e. preserve the original order if possible.
2078 // (FIXME: why do we care?)
2079 if (AllSameOpcodeLeft && ILeft &&
2080 cast<Instruction>(Left[i - 1])->getOpcode() == ILeft->getOpcode())
2085 // Symmetrically handle Left side.
2086 if (AllSameOpcodeLeft) {
2087 unsigned LeftPrevOpcode = cast<Instruction>(Left[i - 1])->getOpcode();
2088 if (ILeft && LeftPrevOpcode == ILeft->getOpcode())
2090 if (IRight && LeftPrevOpcode == IRight->getOpcode())
2096 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
2097 SmallVectorImpl<Value *> &Left,
2098 SmallVectorImpl<Value *> &Right) {
2101 // Peel the first iteration out of the loop since there's nothing
2102 // interesting to do anyway and it simplifies the checks in the loop.
2103 auto VLeft = cast<Instruction>(VL[0])->getOperand(0);
2104 auto VRight = cast<Instruction>(VL[0])->getOperand(1);
2105 if (!isa<Instruction>(VRight) && isa<Instruction>(VLeft))
2106 // Favor having instruction to the right. FIXME: why?
2107 std::swap(VLeft, VRight);
2108 Left.push_back(VLeft);
2109 Right.push_back(VRight);
2112 // Keep track if we have instructions with all the same opcode on one side.
2113 bool AllSameOpcodeLeft = isa<Instruction>(Left[0]);
2114 bool AllSameOpcodeRight = isa<Instruction>(Right[0]);
2115 // Keep track if we have one side with all the same value (broadcast).
2116 bool SplatLeft = true;
2117 bool SplatRight = true;
2119 for (unsigned i = 1, e = VL.size(); i != e; ++i) {
2120 Instruction *I = cast<Instruction>(VL[i]);
2121 assert(I->isCommutative() && "Can only process commutative instruction");
2122 // Commute to favor either a splat or maximizing having the same opcodes on
2124 if (shouldReorderOperands(i, *I, Left, Right, AllSameOpcodeLeft,
2125 AllSameOpcodeRight, SplatLeft, SplatRight)) {
2126 Left.push_back(I->getOperand(1));
2127 Right.push_back(I->getOperand(0));
2129 Left.push_back(I->getOperand(0));
2130 Right.push_back(I->getOperand(1));
2132 // Update Splat* and AllSameOpcode* after the insertion.
2133 SplatRight = SplatRight && (Right[i - 1] == Right[i]);
2134 SplatLeft = SplatLeft && (Left[i - 1] == Left[i]);
2135 AllSameOpcodeLeft = AllSameOpcodeLeft && isa<Instruction>(Left[i]) &&
2136 (cast<Instruction>(Left[i - 1])->getOpcode() ==
2137 cast<Instruction>(Left[i])->getOpcode());
2138 AllSameOpcodeRight = AllSameOpcodeRight && isa<Instruction>(Right[i]) &&
2139 (cast<Instruction>(Right[i - 1])->getOpcode() ==
2140 cast<Instruction>(Right[i])->getOpcode());
2143 // If one operand end up being broadcast, return this operand order.
2144 if (SplatRight || SplatLeft)
2147 // Finally check if we can get longer vectorizable chain by reordering
2148 // without breaking the good operand order detected above.
2149 // E.g. If we have something like-
2150 // load a[0] load b[0]
2151 // load b[1] load a[1]
2152 // load a[2] load b[2]
2153 // load a[3] load b[3]
2154 // Reordering the second load b[1] load a[1] would allow us to vectorize
2155 // this code and we still retain AllSameOpcode property.
2156 // FIXME: This load reordering might break AllSameOpcode in some rare cases
2158 // add a[0],c[0] load b[0]
2159 // add a[1],c[2] load b[1]
2161 // add a[3],c[3] load b[3]
2162 for (unsigned j = 0; j < VL.size() - 1; ++j) {
2163 if (LoadInst *L = dyn_cast<LoadInst>(Left[j])) {
2164 if (LoadInst *L1 = dyn_cast<LoadInst>(Right[j + 1])) {
2165 if (isConsecutiveAccess(L, L1, *DL, *SE)) {
2166 std::swap(Left[j + 1], Right[j + 1]);
2171 if (LoadInst *L = dyn_cast<LoadInst>(Right[j])) {
2172 if (LoadInst *L1 = dyn_cast<LoadInst>(Left[j + 1])) {
2173 if (isConsecutiveAccess(L, L1, *DL, *SE)) {
2174 std::swap(Left[j + 1], Right[j + 1]);
2183 void BoUpSLP::setInsertPointAfterBundle(ArrayRef<Value *> VL) {
2185 // Get the basic block this bundle is in. All instructions in the bundle
2186 // should be in this block.
2187 auto *Front = cast<Instruction>(VL.front());
2188 auto *BB = Front->getParent();
2189 assert(all_of(make_range(VL.begin(), VL.end()), [&](Value *V) -> bool {
2190 return cast<Instruction>(V)->getParent() == BB;
2193 // The last instruction in the bundle in program order.
2194 Instruction *LastInst = nullptr;
2196 // Find the last instruction. The common case should be that BB has been
2197 // scheduled, and the last instruction is VL.back(). So we start with
2198 // VL.back() and iterate over schedule data until we reach the end of the
2199 // bundle. The end of the bundle is marked by null ScheduleData.
2200 if (BlocksSchedules.count(BB)) {
2201 auto *Bundle = BlocksSchedules[BB]->getScheduleData(VL.back());
2202 if (Bundle && Bundle->isPartOfBundle())
2203 for (; Bundle; Bundle = Bundle->NextInBundle)
2204 LastInst = Bundle->Inst;
2207 // LastInst can still be null at this point if there's either not an entry
2208 // for BB in BlocksSchedules or there's no ScheduleData available for
2209 // VL.back(). This can be the case if buildTree_rec aborts for various
2210 // reasons (e.g., the maximum recursion depth is reached, the maximum region
2211 // size is reached, etc.). ScheduleData is initialized in the scheduling
2214 // If this happens, we can still find the last instruction by brute force. We
2215 // iterate forwards from Front (inclusive) until we either see all
2216 // instructions in the bundle or reach the end of the block. If Front is the
2217 // last instruction in program order, LastInst will be set to Front, and we
2218 // will visit all the remaining instructions in the block.
2220 // One of the reasons we exit early from buildTree_rec is to place an upper
2221 // bound on compile-time. Thus, taking an additional compile-time hit here is
2222 // not ideal. However, this should be exceedingly rare since it requires that
2223 // we both exit early from buildTree_rec and that the bundle be out-of-order
2224 // (causing us to iterate all the way to the end of the block).
2226 SmallPtrSet<Value *, 16> Bundle(VL.begin(), VL.end());
2227 for (auto &I : make_range(BasicBlock::iterator(Front), BB->end())) {
2228 if (Bundle.erase(&I))
2235 // Set the insertion point after the last instruction in the bundle. Set the
2236 // debug location to Front.
2237 Builder.SetInsertPoint(BB, ++LastInst->getIterator());
2238 Builder.SetCurrentDebugLocation(Front->getDebugLoc());
2241 Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
2242 Value *Vec = UndefValue::get(Ty);
2243 // Generate the 'InsertElement' instruction.
2244 for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
2245 Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
2246 if (Instruction *Insrt = dyn_cast<Instruction>(Vec)) {
2247 GatherSeq.insert(Insrt);
2248 CSEBlocks.insert(Insrt->getParent());
2250 // Add to our 'need-to-extract' list.
2251 if (ScalarToTreeEntry.count(VL[i])) {
2252 int Idx = ScalarToTreeEntry[VL[i]];
2253 TreeEntry *E = &VectorizableTree[Idx];
2254 // Find which lane we need to extract.
2256 for (unsigned Lane = 0, LE = VL.size(); Lane != LE; ++Lane) {
2257 // Is this the lane of the scalar that we are looking for ?
2258 if (E->Scalars[Lane] == VL[i]) {
2263 assert(FoundLane >= 0 && "Could not find the correct lane");
2264 ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
2272 Value *BoUpSLP::alreadyVectorized(ArrayRef<Value *> VL) const {
2273 SmallDenseMap<Value*, int>::const_iterator Entry
2274 = ScalarToTreeEntry.find(VL[0]);
2275 if (Entry != ScalarToTreeEntry.end()) {
2276 int Idx = Entry->second;
2277 const TreeEntry *En = &VectorizableTree[Idx];
2278 if (En->isSame(VL) && En->VectorizedValue)
2279 return En->VectorizedValue;
2284 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
2285 if (ScalarToTreeEntry.count(VL[0])) {
2286 int Idx = ScalarToTreeEntry[VL[0]];
2287 TreeEntry *E = &VectorizableTree[Idx];
2289 return vectorizeTree(E);
2292 Type *ScalarTy = VL[0]->getType();
2293 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
2294 ScalarTy = SI->getValueOperand()->getType();
2295 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
2297 return Gather(VL, VecTy);
2300 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
2301 IRBuilder<>::InsertPointGuard Guard(Builder);
2303 if (E->VectorizedValue) {
2304 DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
2305 return E->VectorizedValue;
2308 Instruction *VL0 = cast<Instruction>(E->Scalars[0]);
2309 Type *ScalarTy = VL0->getType();
2310 if (StoreInst *SI = dyn_cast<StoreInst>(VL0))
2311 ScalarTy = SI->getValueOperand()->getType();
2312 VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size());
2314 if (E->NeedToGather) {
2315 setInsertPointAfterBundle(E->Scalars);
2316 auto *V = Gather(E->Scalars, VecTy);
2317 E->VectorizedValue = V;
2321 unsigned Opcode = getSameOpcode(E->Scalars);
2324 case Instruction::PHI: {
2325 PHINode *PH = dyn_cast<PHINode>(VL0);
2326 Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
2327 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
2328 PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
2329 E->VectorizedValue = NewPhi;
2331 // PHINodes may have multiple entries from the same block. We want to
2332 // visit every block once.
2333 SmallSet<BasicBlock*, 4> VisitedBBs;
2335 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
2337 BasicBlock *IBB = PH->getIncomingBlock(i);
2339 if (!VisitedBBs.insert(IBB).second) {
2340 NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
2344 // Prepare the operand vector.
2345 for (Value *V : E->Scalars)
2346 Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(IBB));
2348 Builder.SetInsertPoint(IBB->getTerminator());
2349 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
2350 Value *Vec = vectorizeTree(Operands);
2351 NewPhi->addIncoming(Vec, IBB);
2354 assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
2355 "Invalid number of incoming values");
2359 case Instruction::ExtractElement: {
2360 if (canReuseExtract(E->Scalars, Instruction::ExtractElement)) {
2361 Value *V = VL0->getOperand(0);
2362 E->VectorizedValue = V;
2365 setInsertPointAfterBundle(E->Scalars);
2366 auto *V = Gather(E->Scalars, VecTy);
2367 E->VectorizedValue = V;
2370 case Instruction::ExtractValue: {
2371 if (canReuseExtract(E->Scalars, Instruction::ExtractValue)) {
2372 LoadInst *LI = cast<LoadInst>(VL0->getOperand(0));
2373 Builder.SetInsertPoint(LI);
2374 PointerType *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
2375 Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
2376 LoadInst *V = Builder.CreateAlignedLoad(Ptr, LI->getAlignment());
2377 E->VectorizedValue = V;
2378 return propagateMetadata(V, E->Scalars);
2380 setInsertPointAfterBundle(E->Scalars);
2381 auto *V = Gather(E->Scalars, VecTy);
2382 E->VectorizedValue = V;
2385 case Instruction::ZExt:
2386 case Instruction::SExt:
2387 case Instruction::FPToUI:
2388 case Instruction::FPToSI:
2389 case Instruction::FPExt:
2390 case Instruction::PtrToInt:
2391 case Instruction::IntToPtr:
2392 case Instruction::SIToFP:
2393 case Instruction::UIToFP:
2394 case Instruction::Trunc:
2395 case Instruction::FPTrunc:
2396 case Instruction::BitCast: {
2398 for (Value *V : E->Scalars)
2399 INVL.push_back(cast<Instruction>(V)->getOperand(0));
2401 setInsertPointAfterBundle(E->Scalars);
2403 Value *InVec = vectorizeTree(INVL);
2405 if (Value *V = alreadyVectorized(E->Scalars))
2408 CastInst *CI = dyn_cast<CastInst>(VL0);
2409 Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
2410 E->VectorizedValue = V;
2411 ++NumVectorInstructions;
2414 case Instruction::FCmp:
2415 case Instruction::ICmp: {
2416 ValueList LHSV, RHSV;
2417 for (Value *V : E->Scalars) {
2418 LHSV.push_back(cast<Instruction>(V)->getOperand(0));
2419 RHSV.push_back(cast<Instruction>(V)->getOperand(1));
2422 setInsertPointAfterBundle(E->Scalars);
2424 Value *L = vectorizeTree(LHSV);
2425 Value *R = vectorizeTree(RHSV);
2427 if (Value *V = alreadyVectorized(E->Scalars))
2430 CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
2432 if (Opcode == Instruction::FCmp)
2433 V = Builder.CreateFCmp(P0, L, R);
2435 V = Builder.CreateICmp(P0, L, R);
2437 E->VectorizedValue = V;
2438 propagateIRFlags(E->VectorizedValue, E->Scalars);
2439 ++NumVectorInstructions;
2442 case Instruction::Select: {
2443 ValueList TrueVec, FalseVec, CondVec;
2444 for (Value *V : E->Scalars) {
2445 CondVec.push_back(cast<Instruction>(V)->getOperand(0));
2446 TrueVec.push_back(cast<Instruction>(V)->getOperand(1));
2447 FalseVec.push_back(cast<Instruction>(V)->getOperand(2));
2450 setInsertPointAfterBundle(E->Scalars);
2452 Value *Cond = vectorizeTree(CondVec);
2453 Value *True = vectorizeTree(TrueVec);
2454 Value *False = vectorizeTree(FalseVec);
2456 if (Value *V = alreadyVectorized(E->Scalars))
2459 Value *V = Builder.CreateSelect(Cond, True, False);
2460 E->VectorizedValue = V;
2461 ++NumVectorInstructions;
2464 case Instruction::Add:
2465 case Instruction::FAdd:
2466 case Instruction::Sub:
2467 case Instruction::FSub:
2468 case Instruction::Mul:
2469 case Instruction::FMul:
2470 case Instruction::UDiv:
2471 case Instruction::SDiv:
2472 case Instruction::FDiv:
2473 case Instruction::URem:
2474 case Instruction::SRem:
2475 case Instruction::FRem:
2476 case Instruction::Shl:
2477 case Instruction::LShr:
2478 case Instruction::AShr:
2479 case Instruction::And:
2480 case Instruction::Or:
2481 case Instruction::Xor: {
2482 ValueList LHSVL, RHSVL;
2483 if (isa<BinaryOperator>(VL0) && VL0->isCommutative())
2484 reorderInputsAccordingToOpcode(E->Scalars, LHSVL, RHSVL);
2486 for (Value *V : E->Scalars) {
2487 LHSVL.push_back(cast<Instruction>(V)->getOperand(0));
2488 RHSVL.push_back(cast<Instruction>(V)->getOperand(1));
2491 setInsertPointAfterBundle(E->Scalars);
2493 Value *LHS = vectorizeTree(LHSVL);
2494 Value *RHS = vectorizeTree(RHSVL);
2496 if (Value *V = alreadyVectorized(E->Scalars))
2499 BinaryOperator *BinOp = cast<BinaryOperator>(VL0);
2500 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), LHS, RHS);
2501 E->VectorizedValue = V;
2502 propagateIRFlags(E->VectorizedValue, E->Scalars);
2503 ++NumVectorInstructions;
2505 if (Instruction *I = dyn_cast<Instruction>(V))
2506 return propagateMetadata(I, E->Scalars);
2510 case Instruction::Load: {
2511 // Loads are inserted at the head of the tree because we don't want to
2512 // sink them all the way down past store instructions.
2513 setInsertPointAfterBundle(E->Scalars);
2515 LoadInst *LI = cast<LoadInst>(VL0);
2516 Type *ScalarLoadTy = LI->getType();
2517 unsigned AS = LI->getPointerAddressSpace();
2519 Value *VecPtr = Builder.CreateBitCast(LI->getPointerOperand(),
2520 VecTy->getPointerTo(AS));
2522 // The pointer operand uses an in-tree scalar so we add the new BitCast to
2523 // ExternalUses list to make sure that an extract will be generated in the
2525 if (ScalarToTreeEntry.count(LI->getPointerOperand()))
2526 ExternalUses.push_back(
2527 ExternalUser(LI->getPointerOperand(), cast<User>(VecPtr), 0));
2529 unsigned Alignment = LI->getAlignment();
2530 LI = Builder.CreateLoad(VecPtr);
2532 Alignment = DL->getABITypeAlignment(ScalarLoadTy);
2534 LI->setAlignment(Alignment);
2535 E->VectorizedValue = LI;
2536 ++NumVectorInstructions;
2537 return propagateMetadata(LI, E->Scalars);
2539 case Instruction::Store: {
2540 StoreInst *SI = cast<StoreInst>(VL0);
2541 unsigned Alignment = SI->getAlignment();
2542 unsigned AS = SI->getPointerAddressSpace();
2545 for (Value *V : E->Scalars)
2546 ValueOp.push_back(cast<StoreInst>(V)->getValueOperand());
2548 setInsertPointAfterBundle(E->Scalars);
2550 Value *VecValue = vectorizeTree(ValueOp);
2551 Value *VecPtr = Builder.CreateBitCast(SI->getPointerOperand(),
2552 VecTy->getPointerTo(AS));
2553 StoreInst *S = Builder.CreateStore(VecValue, VecPtr);
2555 // The pointer operand uses an in-tree scalar so we add the new BitCast to
2556 // ExternalUses list to make sure that an extract will be generated in the
2558 if (ScalarToTreeEntry.count(SI->getPointerOperand()))
2559 ExternalUses.push_back(
2560 ExternalUser(SI->getPointerOperand(), cast<User>(VecPtr), 0));
2563 Alignment = DL->getABITypeAlignment(SI->getValueOperand()->getType());
2565 S->setAlignment(Alignment);
2566 E->VectorizedValue = S;
2567 ++NumVectorInstructions;
2568 return propagateMetadata(S, E->Scalars);
2570 case Instruction::GetElementPtr: {
2571 setInsertPointAfterBundle(E->Scalars);
2574 for (Value *V : E->Scalars)
2575 Op0VL.push_back(cast<GetElementPtrInst>(V)->getOperand(0));
2577 Value *Op0 = vectorizeTree(Op0VL);
2579 std::vector<Value *> OpVecs;
2580 for (int j = 1, e = cast<GetElementPtrInst>(VL0)->getNumOperands(); j < e;
2583 for (Value *V : E->Scalars)
2584 OpVL.push_back(cast<GetElementPtrInst>(V)->getOperand(j));
2586 Value *OpVec = vectorizeTree(OpVL);
2587 OpVecs.push_back(OpVec);
2590 Value *V = Builder.CreateGEP(
2591 cast<GetElementPtrInst>(VL0)->getSourceElementType(), Op0, OpVecs);
2592 E->VectorizedValue = V;
2593 ++NumVectorInstructions;
2595 if (Instruction *I = dyn_cast<Instruction>(V))
2596 return propagateMetadata(I, E->Scalars);
2600 case Instruction::Call: {
2601 CallInst *CI = cast<CallInst>(VL0);
2602 setInsertPointAfterBundle(E->Scalars);
2604 Intrinsic::ID IID = Intrinsic::not_intrinsic;
2605 Value *ScalarArg = nullptr;
2606 if (CI && (FI = CI->getCalledFunction())) {
2607 IID = FI->getIntrinsicID();
2609 std::vector<Value *> OpVecs;
2610 for (int j = 0, e = CI->getNumArgOperands(); j < e; ++j) {
2612 // ctlz,cttz and powi are special intrinsics whose second argument is
2613 // a scalar. This argument should not be vectorized.
2614 if (hasVectorInstrinsicScalarOpd(IID, 1) && j == 1) {
2615 CallInst *CEI = cast<CallInst>(E->Scalars[0]);
2616 ScalarArg = CEI->getArgOperand(j);
2617 OpVecs.push_back(CEI->getArgOperand(j));
2620 for (Value *V : E->Scalars) {
2621 CallInst *CEI = cast<CallInst>(V);
2622 OpVL.push_back(CEI->getArgOperand(j));
2625 Value *OpVec = vectorizeTree(OpVL);
2626 DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
2627 OpVecs.push_back(OpVec);
2630 Module *M = F->getParent();
2631 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
2632 Type *Tys[] = { VectorType::get(CI->getType(), E->Scalars.size()) };
2633 Function *CF = Intrinsic::getDeclaration(M, ID, Tys);
2634 SmallVector<OperandBundleDef, 1> OpBundles;
2635 CI->getOperandBundlesAsDefs(OpBundles);
2636 Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
2638 // The scalar argument uses an in-tree scalar so we add the new vectorized
2639 // call to ExternalUses list to make sure that an extract will be
2640 // generated in the future.
2641 if (ScalarArg && ScalarToTreeEntry.count(ScalarArg))
2642 ExternalUses.push_back(ExternalUser(ScalarArg, cast<User>(V), 0));
2644 E->VectorizedValue = V;
2645 propagateIRFlags(E->VectorizedValue, E->Scalars);
2646 ++NumVectorInstructions;
2649 case Instruction::ShuffleVector: {
2650 ValueList LHSVL, RHSVL;
2651 assert(isa<BinaryOperator>(VL0) && "Invalid Shuffle Vector Operand");
2652 reorderAltShuffleOperands(E->Scalars, LHSVL, RHSVL);
2653 setInsertPointAfterBundle(E->Scalars);
2655 Value *LHS = vectorizeTree(LHSVL);
2656 Value *RHS = vectorizeTree(RHSVL);
2658 if (Value *V = alreadyVectorized(E->Scalars))
2661 // Create a vector of LHS op1 RHS
2662 BinaryOperator *BinOp0 = cast<BinaryOperator>(VL0);
2663 Value *V0 = Builder.CreateBinOp(BinOp0->getOpcode(), LHS, RHS);
2665 // Create a vector of LHS op2 RHS
2666 Instruction *VL1 = cast<Instruction>(E->Scalars[1]);
2667 BinaryOperator *BinOp1 = cast<BinaryOperator>(VL1);
2668 Value *V1 = Builder.CreateBinOp(BinOp1->getOpcode(), LHS, RHS);
2670 // Create shuffle to take alternate operations from the vector.
2671 // Also, gather up odd and even scalar ops to propagate IR flags to
2672 // each vector operation.
2673 ValueList OddScalars, EvenScalars;
2674 unsigned e = E->Scalars.size();
2675 SmallVector<Constant *, 8> Mask(e);
2676 for (unsigned i = 0; i < e; ++i) {
2678 Mask[i] = Builder.getInt32(e + i);
2679 OddScalars.push_back(E->Scalars[i]);
2681 Mask[i] = Builder.getInt32(i);
2682 EvenScalars.push_back(E->Scalars[i]);
2686 Value *ShuffleMask = ConstantVector::get(Mask);
2687 propagateIRFlags(V0, EvenScalars);
2688 propagateIRFlags(V1, OddScalars);
2690 Value *V = Builder.CreateShuffleVector(V0, V1, ShuffleMask);
2691 E->VectorizedValue = V;
2692 ++NumVectorInstructions;
2693 if (Instruction *I = dyn_cast<Instruction>(V))
2694 return propagateMetadata(I, E->Scalars);
2699 llvm_unreachable("unknown inst");
2704 Value *BoUpSLP::vectorizeTree() {
2706 // All blocks must be scheduled before any instructions are inserted.
2707 for (auto &BSIter : BlocksSchedules) {
2708 scheduleBlock(BSIter.second.get());
2711 Builder.SetInsertPoint(&F->getEntryBlock().front());
2712 auto *VectorRoot = vectorizeTree(&VectorizableTree[0]);
2714 // If the vectorized tree can be rewritten in a smaller type, we truncate the
2715 // vectorized root. InstCombine will then rewrite the entire expression. We
2716 // sign extend the extracted values below.
2717 auto *ScalarRoot = VectorizableTree[0].Scalars[0];
2718 if (MinBWs.count(ScalarRoot)) {
2719 if (auto *I = dyn_cast<Instruction>(VectorRoot))
2720 Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
2721 auto BundleWidth = VectorizableTree[0].Scalars.size();
2722 auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
2723 auto *VecTy = VectorType::get(MinTy, BundleWidth);
2724 auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
2725 VectorizableTree[0].VectorizedValue = Trunc;
2728 DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() << " values .\n");
2730 // If necessary, sign-extend or zero-extend ScalarRoot to the larger type
2731 // specified by ScalarType.
2732 auto extend = [&](Value *ScalarRoot, Value *Ex, Type *ScalarType) {
2733 if (!MinBWs.count(ScalarRoot))
2735 if (MinBWs[ScalarRoot].second)
2736 return Builder.CreateSExt(Ex, ScalarType);
2737 return Builder.CreateZExt(Ex, ScalarType);
2740 // Extract all of the elements with the external uses.
2741 for (const auto &ExternalUse : ExternalUses) {
2742 Value *Scalar = ExternalUse.Scalar;
2743 llvm::User *User = ExternalUse.User;
2745 // Skip users that we already RAUW. This happens when one instruction
2746 // has multiple uses of the same value.
2747 if (!is_contained(Scalar->users(), User))
2749 assert(ScalarToTreeEntry.count(Scalar) && "Invalid scalar");
2751 int Idx = ScalarToTreeEntry[Scalar];
2752 TreeEntry *E = &VectorizableTree[Idx];
2753 assert(!E->NeedToGather && "Extracting from a gather list");
2755 Value *Vec = E->VectorizedValue;
2756 assert(Vec && "Can't find vectorizable value");
2758 Value *Lane = Builder.getInt32(ExternalUse.Lane);
2759 // Generate extracts for out-of-tree users.
2760 // Find the insertion point for the extractelement lane.
2761 if (auto *VecI = dyn_cast<Instruction>(Vec)) {
2762 if (PHINode *PH = dyn_cast<PHINode>(User)) {
2763 for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
2764 if (PH->getIncomingValue(i) == Scalar) {
2765 TerminatorInst *IncomingTerminator =
2766 PH->getIncomingBlock(i)->getTerminator();
2767 if (isa<CatchSwitchInst>(IncomingTerminator)) {
2768 Builder.SetInsertPoint(VecI->getParent(),
2769 std::next(VecI->getIterator()));
2771 Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
2773 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2774 Ex = extend(ScalarRoot, Ex, Scalar->getType());
2775 CSEBlocks.insert(PH->getIncomingBlock(i));
2776 PH->setOperand(i, Ex);
2780 Builder.SetInsertPoint(cast<Instruction>(User));
2781 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2782 Ex = extend(ScalarRoot, Ex, Scalar->getType());
2783 CSEBlocks.insert(cast<Instruction>(User)->getParent());
2784 User->replaceUsesOfWith(Scalar, Ex);
2787 Builder.SetInsertPoint(&F->getEntryBlock().front());
2788 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2789 Ex = extend(ScalarRoot, Ex, Scalar->getType());
2790 CSEBlocks.insert(&F->getEntryBlock());
2791 User->replaceUsesOfWith(Scalar, Ex);
2794 DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
2797 // For each vectorized value:
2798 for (TreeEntry &EIdx : VectorizableTree) {
2799 TreeEntry *Entry = &EIdx;
2802 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
2803 Value *Scalar = Entry->Scalars[Lane];
2804 // No need to handle users of gathered values.
2805 if (Entry->NeedToGather)
2808 assert(Entry->VectorizedValue && "Can't find vectorizable value");
2810 Type *Ty = Scalar->getType();
2811 if (!Ty->isVoidTy()) {
2813 for (User *U : Scalar->users()) {
2814 DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
2816 assert((ScalarToTreeEntry.count(U) ||
2817 // It is legal to replace users in the ignorelist by undef.
2818 is_contained(UserIgnoreList, U)) &&
2819 "Replacing out-of-tree value with undef");
2822 Value *Undef = UndefValue::get(Ty);
2823 Scalar->replaceAllUsesWith(Undef);
2825 DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
2826 eraseInstruction(cast<Instruction>(Scalar));
2830 Builder.ClearInsertionPoint();
2832 return VectorizableTree[0].VectorizedValue;
2835 void BoUpSLP::optimizeGatherSequence() {
2836 DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
2837 << " gather sequences instructions.\n");
2838 // LICM InsertElementInst sequences.
2839 for (Instruction *it : GatherSeq) {
2840 InsertElementInst *Insert = dyn_cast<InsertElementInst>(it);
2845 // Check if this block is inside a loop.
2846 Loop *L = LI->getLoopFor(Insert->getParent());
2850 // Check if it has a preheader.
2851 BasicBlock *PreHeader = L->getLoopPreheader();
2855 // If the vector or the element that we insert into it are
2856 // instructions that are defined in this basic block then we can't
2857 // hoist this instruction.
2858 Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
2859 Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
2860 if (CurrVec && L->contains(CurrVec))
2862 if (NewElem && L->contains(NewElem))
2865 // We can hoist this instruction. Move it to the pre-header.
2866 Insert->moveBefore(PreHeader->getTerminator());
2869 // Make a list of all reachable blocks in our CSE queue.
2870 SmallVector<const DomTreeNode *, 8> CSEWorkList;
2871 CSEWorkList.reserve(CSEBlocks.size());
2872 for (BasicBlock *BB : CSEBlocks)
2873 if (DomTreeNode *N = DT->getNode(BB)) {
2874 assert(DT->isReachableFromEntry(N));
2875 CSEWorkList.push_back(N);
2878 // Sort blocks by domination. This ensures we visit a block after all blocks
2879 // dominating it are visited.
2880 std::stable_sort(CSEWorkList.begin(), CSEWorkList.end(),
2881 [this](const DomTreeNode *A, const DomTreeNode *B) {
2882 return DT->properlyDominates(A, B);
2885 // Perform O(N^2) search over the gather sequences and merge identical
2886 // instructions. TODO: We can further optimize this scan if we split the
2887 // instructions into different buckets based on the insert lane.
2888 SmallVector<Instruction *, 16> Visited;
2889 for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
2890 assert((I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
2891 "Worklist not sorted properly!");
2892 BasicBlock *BB = (*I)->getBlock();
2893 // For all instructions in blocks containing gather sequences:
2894 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) {
2895 Instruction *In = &*it++;
2896 if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In))
2899 // Check if we can replace this instruction with any of the
2900 // visited instructions.
2901 for (Instruction *v : Visited) {
2902 if (In->isIdenticalTo(v) &&
2903 DT->dominates(v->getParent(), In->getParent())) {
2904 In->replaceAllUsesWith(v);
2905 eraseInstruction(In);
2911 assert(!is_contained(Visited, In));
2912 Visited.push_back(In);
2920 // Groups the instructions to a bundle (which is then a single scheduling entity)
2921 // and schedules instructions until the bundle gets ready.
2922 bool BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL,
2924 if (isa<PHINode>(VL[0]))
2927 // Initialize the instruction bundle.
2928 Instruction *OldScheduleEnd = ScheduleEnd;
2929 ScheduleData *PrevInBundle = nullptr;
2930 ScheduleData *Bundle = nullptr;
2931 bool ReSchedule = false;
2932 DEBUG(dbgs() << "SLP: bundle: " << *VL[0] << "\n");
2934 // Make sure that the scheduling region contains all
2935 // instructions of the bundle.
2936 for (Value *V : VL) {
2937 if (!extendSchedulingRegion(V))
2941 for (Value *V : VL) {
2942 ScheduleData *BundleMember = getScheduleData(V);
2943 assert(BundleMember &&
2944 "no ScheduleData for bundle member (maybe not in same basic block)");
2945 if (BundleMember->IsScheduled) {
2946 // A bundle member was scheduled as single instruction before and now
2947 // needs to be scheduled as part of the bundle. We just get rid of the
2948 // existing schedule.
2949 DEBUG(dbgs() << "SLP: reset schedule because " << *BundleMember
2950 << " was already scheduled\n");
2953 assert(BundleMember->isSchedulingEntity() &&
2954 "bundle member already part of other bundle");
2956 PrevInBundle->NextInBundle = BundleMember;
2958 Bundle = BundleMember;
2960 BundleMember->UnscheduledDepsInBundle = 0;
2961 Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps;
2963 // Group the instructions to a bundle.
2964 BundleMember->FirstInBundle = Bundle;
2965 PrevInBundle = BundleMember;
2967 if (ScheduleEnd != OldScheduleEnd) {
2968 // The scheduling region got new instructions at the lower end (or it is a
2969 // new region for the first bundle). This makes it necessary to
2970 // recalculate all dependencies.
2971 // It is seldom that this needs to be done a second time after adding the
2972 // initial bundle to the region.
2973 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2974 ScheduleData *SD = getScheduleData(I);
2975 SD->clearDependencies();
2981 initialFillReadyList(ReadyInsts);
2984 DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle << " in block "
2985 << BB->getName() << "\n");
2987 calculateDependencies(Bundle, true, SLP);
2989 // Now try to schedule the new bundle. As soon as the bundle is "ready" it
2990 // means that there are no cyclic dependencies and we can schedule it.
2991 // Note that's important that we don't "schedule" the bundle yet (see
2992 // cancelScheduling).
2993 while (!Bundle->isReady() && !ReadyInsts.empty()) {
2995 ScheduleData *pickedSD = ReadyInsts.back();
2996 ReadyInsts.pop_back();
2998 if (pickedSD->isSchedulingEntity() && pickedSD->isReady()) {
2999 schedule(pickedSD, ReadyInsts);
3002 if (!Bundle->isReady()) {
3003 cancelScheduling(VL);
3009 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL) {
3010 if (isa<PHINode>(VL[0]))
3013 ScheduleData *Bundle = getScheduleData(VL[0]);
3014 DEBUG(dbgs() << "SLP: cancel scheduling of " << *Bundle << "\n");
3015 assert(!Bundle->IsScheduled &&
3016 "Can't cancel bundle which is already scheduled");
3017 assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
3018 "tried to unbundle something which is not a bundle");
3020 // Un-bundle: make single instructions out of the bundle.
3021 ScheduleData *BundleMember = Bundle;
3022 while (BundleMember) {
3023 assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
3024 BundleMember->FirstInBundle = BundleMember;
3025 ScheduleData *Next = BundleMember->NextInBundle;
3026 BundleMember->NextInBundle = nullptr;
3027 BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps;
3028 if (BundleMember->UnscheduledDepsInBundle == 0) {
3029 ReadyInsts.insert(BundleMember);
3031 BundleMember = Next;
3035 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V) {
3036 if (getScheduleData(V))
3038 Instruction *I = dyn_cast<Instruction>(V);
3039 assert(I && "bundle member must be an instruction");
3040 assert(!isa<PHINode>(I) && "phi nodes don't need to be scheduled");
3041 if (!ScheduleStart) {
3042 // It's the first instruction in the new region.
3043 initScheduleData(I, I->getNextNode(), nullptr, nullptr);
3045 ScheduleEnd = I->getNextNode();
3046 assert(ScheduleEnd && "tried to vectorize a TerminatorInst?");
3047 DEBUG(dbgs() << "SLP: initialize schedule region to " << *I << "\n");
3050 // Search up and down at the same time, because we don't know if the new
3051 // instruction is above or below the existing scheduling region.
3052 BasicBlock::reverse_iterator UpIter =
3053 ++ScheduleStart->getIterator().getReverse();
3054 BasicBlock::reverse_iterator UpperEnd = BB->rend();
3055 BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
3056 BasicBlock::iterator LowerEnd = BB->end();
3058 if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
3059 DEBUG(dbgs() << "SLP: exceeded schedule region size limit\n");
3063 if (UpIter != UpperEnd) {
3064 if (&*UpIter == I) {
3065 initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
3067 DEBUG(dbgs() << "SLP: extend schedule region start to " << *I << "\n");
3072 if (DownIter != LowerEnd) {
3073 if (&*DownIter == I) {
3074 initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
3076 ScheduleEnd = I->getNextNode();
3077 assert(ScheduleEnd && "tried to vectorize a TerminatorInst?");
3078 DEBUG(dbgs() << "SLP: extend schedule region end to " << *I << "\n");
3083 assert((UpIter != UpperEnd || DownIter != LowerEnd) &&
3084 "instruction not found in block");
3089 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
3091 ScheduleData *PrevLoadStore,
3092 ScheduleData *NextLoadStore) {
3093 ScheduleData *CurrentLoadStore = PrevLoadStore;
3094 for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
3095 ScheduleData *SD = ScheduleDataMap[I];
3097 // Allocate a new ScheduleData for the instruction.
3098 if (ChunkPos >= ChunkSize) {
3099 ScheduleDataChunks.push_back(
3100 llvm::make_unique<ScheduleData[]>(ChunkSize));
3103 SD = &(ScheduleDataChunks.back()[ChunkPos++]);
3104 ScheduleDataMap[I] = SD;
3107 assert(!isInSchedulingRegion(SD) &&
3108 "new ScheduleData already in scheduling region");
3109 SD->init(SchedulingRegionID);
3111 if (I->mayReadOrWriteMemory()) {
3112 // Update the linked list of memory accessing instructions.
3113 if (CurrentLoadStore) {
3114 CurrentLoadStore->NextLoadStore = SD;
3116 FirstLoadStoreInRegion = SD;
3118 CurrentLoadStore = SD;
3121 if (NextLoadStore) {
3122 if (CurrentLoadStore)
3123 CurrentLoadStore->NextLoadStore = NextLoadStore;
3125 LastLoadStoreInRegion = CurrentLoadStore;
3129 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
3130 bool InsertInReadyList,
3132 assert(SD->isSchedulingEntity());
3134 SmallVector<ScheduleData *, 10> WorkList;
3135 WorkList.push_back(SD);
3137 while (!WorkList.empty()) {
3138 ScheduleData *SD = WorkList.back();
3139 WorkList.pop_back();
3141 ScheduleData *BundleMember = SD;
3142 while (BundleMember) {
3143 assert(isInSchedulingRegion(BundleMember));
3144 if (!BundleMember->hasValidDependencies()) {
3146 DEBUG(dbgs() << "SLP: update deps of " << *BundleMember << "\n");
3147 BundleMember->Dependencies = 0;
3148 BundleMember->resetUnscheduledDeps();
3150 // Handle def-use chain dependencies.
3151 for (User *U : BundleMember->Inst->users()) {
3152 if (isa<Instruction>(U)) {
3153 ScheduleData *UseSD = getScheduleData(U);
3154 if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
3155 BundleMember->Dependencies++;
3156 ScheduleData *DestBundle = UseSD->FirstInBundle;
3157 if (!DestBundle->IsScheduled) {
3158 BundleMember->incrementUnscheduledDeps(1);
3160 if (!DestBundle->hasValidDependencies()) {
3161 WorkList.push_back(DestBundle);
3165 // I'm not sure if this can ever happen. But we need to be safe.
3166 // This lets the instruction/bundle never be scheduled and
3167 // eventually disable vectorization.
3168 BundleMember->Dependencies++;
3169 BundleMember->incrementUnscheduledDeps(1);
3173 // Handle the memory dependencies.
3174 ScheduleData *DepDest = BundleMember->NextLoadStore;
3176 Instruction *SrcInst = BundleMember->Inst;
3177 MemoryLocation SrcLoc = getLocation(SrcInst, SLP->AA);
3178 bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
3179 unsigned numAliased = 0;
3180 unsigned DistToSrc = 1;
3183 assert(isInSchedulingRegion(DepDest));
3185 // We have two limits to reduce the complexity:
3186 // 1) AliasedCheckLimit: It's a small limit to reduce calls to
3187 // SLP->isAliased (which is the expensive part in this loop).
3188 // 2) MaxMemDepDistance: It's for very large blocks and it aborts
3189 // the whole loop (even if the loop is fast, it's quadratic).
3190 // It's important for the loop break condition (see below) to
3191 // check this limit even between two read-only instructions.
3192 if (DistToSrc >= MaxMemDepDistance ||
3193 ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
3194 (numAliased >= AliasedCheckLimit ||
3195 SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
3197 // We increment the counter only if the locations are aliased
3198 // (instead of counting all alias checks). This gives a better
3199 // balance between reduced runtime and accurate dependencies.
3202 DepDest->MemoryDependencies.push_back(BundleMember);
3203 BundleMember->Dependencies++;
3204 ScheduleData *DestBundle = DepDest->FirstInBundle;
3205 if (!DestBundle->IsScheduled) {
3206 BundleMember->incrementUnscheduledDeps(1);
3208 if (!DestBundle->hasValidDependencies()) {
3209 WorkList.push_back(DestBundle);
3212 DepDest = DepDest->NextLoadStore;
3214 // Example, explaining the loop break condition: Let's assume our
3215 // starting instruction is i0 and MaxMemDepDistance = 3.
3218 // i0,i1,i2,i3,i4,i5,i6,i7,i8
3221 // MaxMemDepDistance let us stop alias-checking at i3 and we add
3222 // dependencies from i0 to i3,i4,.. (even if they are not aliased).
3223 // Previously we already added dependencies from i3 to i6,i7,i8
3224 // (because of MaxMemDepDistance). As we added a dependency from
3225 // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
3226 // and we can abort this loop at i6.
3227 if (DistToSrc >= 2 * MaxMemDepDistance)
3233 BundleMember = BundleMember->NextInBundle;
3235 if (InsertInReadyList && SD->isReady()) {
3236 ReadyInsts.push_back(SD);
3237 DEBUG(dbgs() << "SLP: gets ready on update: " << *SD->Inst << "\n");
3242 void BoUpSLP::BlockScheduling::resetSchedule() {
3243 assert(ScheduleStart &&
3244 "tried to reset schedule on block which has not been scheduled");
3245 for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
3246 ScheduleData *SD = getScheduleData(I);
3247 assert(isInSchedulingRegion(SD));
3248 SD->IsScheduled = false;
3249 SD->resetUnscheduledDeps();
3254 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
3256 if (!BS->ScheduleStart)
3259 DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
3261 BS->resetSchedule();
3263 // For the real scheduling we use a more sophisticated ready-list: it is
3264 // sorted by the original instruction location. This lets the final schedule
3265 // be as close as possible to the original instruction order.
3266 struct ScheduleDataCompare {
3267 bool operator()(ScheduleData *SD1, ScheduleData *SD2) {
3268 return SD2->SchedulingPriority < SD1->SchedulingPriority;
3271 std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
3273 // Ensure that all dependency data is updated and fill the ready-list with
3274 // initial instructions.
3276 int NumToSchedule = 0;
3277 for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
3278 I = I->getNextNode()) {
3279 ScheduleData *SD = BS->getScheduleData(I);
3281 SD->isPartOfBundle() == (ScalarToTreeEntry.count(SD->Inst) != 0) &&
3282 "scheduler and vectorizer have different opinion on what is a bundle");
3283 SD->FirstInBundle->SchedulingPriority = Idx++;
3284 if (SD->isSchedulingEntity()) {
3285 BS->calculateDependencies(SD, false, this);
3289 BS->initialFillReadyList(ReadyInsts);
3291 Instruction *LastScheduledInst = BS->ScheduleEnd;
3293 // Do the "real" scheduling.
3294 while (!ReadyInsts.empty()) {
3295 ScheduleData *picked = *ReadyInsts.begin();
3296 ReadyInsts.erase(ReadyInsts.begin());
3298 // Move the scheduled instruction(s) to their dedicated places, if not
3300 ScheduleData *BundleMember = picked;
3301 while (BundleMember) {
3302 Instruction *pickedInst = BundleMember->Inst;
3303 if (LastScheduledInst->getNextNode() != pickedInst) {
3304 BS->BB->getInstList().remove(pickedInst);
3305 BS->BB->getInstList().insert(LastScheduledInst->getIterator(),
3308 LastScheduledInst = pickedInst;
3309 BundleMember = BundleMember->NextInBundle;
3312 BS->schedule(picked, ReadyInsts);
3315 assert(NumToSchedule == 0 && "could not schedule all instructions");
3317 // Avoid duplicate scheduling of the block.
3318 BS->ScheduleStart = nullptr;
3321 unsigned BoUpSLP::getVectorElementSize(Value *V) {
3322 // If V is a store, just return the width of the stored value without
3323 // traversing the expression tree. This is the common case.
3324 if (auto *Store = dyn_cast<StoreInst>(V))
3325 return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
3327 // If V is not a store, we can traverse the expression tree to find loads
3328 // that feed it. The type of the loaded value may indicate a more suitable
3329 // width than V's type. We want to base the vector element size on the width
3330 // of memory operations where possible.
3331 SmallVector<Instruction *, 16> Worklist;
3332 SmallPtrSet<Instruction *, 16> Visited;
3333 if (auto *I = dyn_cast<Instruction>(V))
3334 Worklist.push_back(I);
3336 // Traverse the expression tree in bottom-up order looking for loads. If we
3337 // encounter an instruciton we don't yet handle, we give up.
3339 auto FoundUnknownInst = false;
3340 while (!Worklist.empty() && !FoundUnknownInst) {
3341 auto *I = Worklist.pop_back_val();
3344 // We should only be looking at scalar instructions here. If the current
3345 // instruction has a vector type, give up.
3346 auto *Ty = I->getType();
3347 if (isa<VectorType>(Ty))
3348 FoundUnknownInst = true;
3350 // If the current instruction is a load, update MaxWidth to reflect the
3351 // width of the loaded value.
3352 else if (isa<LoadInst>(I))
3353 MaxWidth = std::max<unsigned>(MaxWidth, DL->getTypeSizeInBits(Ty));
3355 // Otherwise, we need to visit the operands of the instruction. We only
3356 // handle the interesting cases from buildTree here. If an operand is an
3357 // instruction we haven't yet visited, we add it to the worklist.
3358 else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
3359 isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I)) {
3360 for (Use &U : I->operands())
3361 if (auto *J = dyn_cast<Instruction>(U.get()))
3362 if (!Visited.count(J))
3363 Worklist.push_back(J);
3366 // If we don't yet handle the instruction, give up.
3368 FoundUnknownInst = true;
3371 // If we didn't encounter a memory access in the expression tree, or if we
3372 // gave up for some reason, just return the width of V.
3373 if (!MaxWidth || FoundUnknownInst)
3374 return DL->getTypeSizeInBits(V->getType());
3376 // Otherwise, return the maximum width we found.
3380 // Determine if a value V in a vectorizable expression Expr can be demoted to a
3381 // smaller type with a truncation. We collect the values that will be demoted
3382 // in ToDemote and additional roots that require investigating in Roots.
3383 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
3384 SmallVectorImpl<Value *> &ToDemote,
3385 SmallVectorImpl<Value *> &Roots) {
3387 // We can always demote constants.
3388 if (isa<Constant>(V)) {
3389 ToDemote.push_back(V);
3393 // If the value is not an instruction in the expression with only one use, it
3394 // cannot be demoted.
3395 auto *I = dyn_cast<Instruction>(V);
3396 if (!I || !I->hasOneUse() || !Expr.count(I))
3399 switch (I->getOpcode()) {
3401 // We can always demote truncations and extensions. Since truncations can
3402 // seed additional demotion, we save the truncated value.
3403 case Instruction::Trunc:
3404 Roots.push_back(I->getOperand(0));
3405 case Instruction::ZExt:
3406 case Instruction::SExt:
3409 // We can demote certain binary operations if we can demote both of their
3411 case Instruction::Add:
3412 case Instruction::Sub:
3413 case Instruction::Mul:
3414 case Instruction::And:
3415 case Instruction::Or:
3416 case Instruction::Xor:
3417 if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
3418 !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
3422 // We can demote selects if we can demote their true and false values.
3423 case Instruction::Select: {
3424 SelectInst *SI = cast<SelectInst>(I);
3425 if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
3426 !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
3431 // We can demote phis if we can demote all their incoming operands. Note that
3432 // we don't need to worry about cycles since we ensure single use above.
3433 case Instruction::PHI: {
3434 PHINode *PN = cast<PHINode>(I);
3435 for (Value *IncValue : PN->incoming_values())
3436 if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
3441 // Otherwise, conservatively give up.
3446 // Record the value that we can demote.
3447 ToDemote.push_back(V);
3451 void BoUpSLP::computeMinimumValueSizes() {
3452 // If there are no external uses, the expression tree must be rooted by a
3453 // store. We can't demote in-memory values, so there is nothing to do here.
3454 if (ExternalUses.empty())
3457 // We only attempt to truncate integer expressions.
3458 auto &TreeRoot = VectorizableTree[0].Scalars;
3459 auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
3463 // If the expression is not rooted by a store, these roots should have
3464 // external uses. We will rely on InstCombine to rewrite the expression in
3465 // the narrower type. However, InstCombine only rewrites single-use values.
3466 // This means that if a tree entry other than a root is used externally, it
3467 // must have multiple uses and InstCombine will not rewrite it. The code
3468 // below ensures that only the roots are used externally.
3469 SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
3470 for (auto &EU : ExternalUses)
3471 if (!Expr.erase(EU.Scalar))
3476 // Collect the scalar values of the vectorizable expression. We will use this
3477 // context to determine which values can be demoted. If we see a truncation,
3478 // we mark it as seeding another demotion.
3479 for (auto &Entry : VectorizableTree)
3480 Expr.insert(Entry.Scalars.begin(), Entry.Scalars.end());
3482 // Ensure the roots of the vectorizable tree don't form a cycle. They must
3483 // have a single external user that is not in the vectorizable tree.
3484 for (auto *Root : TreeRoot)
3485 if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
3488 // Conservatively determine if we can actually truncate the roots of the
3489 // expression. Collect the values that can be demoted in ToDemote and
3490 // additional roots that require investigating in Roots.
3491 SmallVector<Value *, 32> ToDemote;
3492 SmallVector<Value *, 4> Roots;
3493 for (auto *Root : TreeRoot)
3494 if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
3497 // The maximum bit width required to represent all the values that can be
3498 // demoted without loss of precision. It would be safe to truncate the roots
3499 // of the expression to this width.
3500 auto MaxBitWidth = 8u;
3502 // We first check if all the bits of the roots are demanded. If they're not,
3503 // we can truncate the roots to this narrower type.
3504 for (auto *Root : TreeRoot) {
3505 auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
3506 MaxBitWidth = std::max<unsigned>(
3507 Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
3510 // True if the roots can be zero-extended back to their original type, rather
3511 // than sign-extended. We know that if the leading bits are not demanded, we
3512 // can safely zero-extend. So we initialize IsKnownPositive to True.
3513 bool IsKnownPositive = true;
3515 // If all the bits of the roots are demanded, we can try a little harder to
3516 // compute a narrower type. This can happen, for example, if the roots are
3517 // getelementptr indices. InstCombine promotes these indices to the pointer
3518 // width. Thus, all their bits are technically demanded even though the
3519 // address computation might be vectorized in a smaller type.
3521 // We start by looking at each entry that can be demoted. We compute the
3522 // maximum bit width required to store the scalar by using ValueTracking to
3523 // compute the number of high-order bits we can truncate.
3524 if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType())) {
3527 // Determine if the sign bit of all the roots is known to be zero. If not,
3528 // IsKnownPositive is set to False.
3529 IsKnownPositive = all_of(TreeRoot, [&](Value *R) {
3530 bool KnownZero = false;
3531 bool KnownOne = false;
3532 ComputeSignBit(R, KnownZero, KnownOne, *DL);
3536 // Determine the maximum number of bits required to store the scalar
3538 for (auto *Scalar : ToDemote) {
3539 auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, 0, DT);
3540 auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
3541 MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
3544 // If we can't prove that the sign bit is zero, we must add one to the
3545 // maximum bit width to account for the unknown sign bit. This preserves
3546 // the existing sign bit so we can safely sign-extend the root back to the
3547 // original type. Otherwise, if we know the sign bit is zero, we will
3548 // zero-extend the root instead.
3550 // FIXME: This is somewhat suboptimal, as there will be cases where adding
3551 // one to the maximum bit width will yield a larger-than-necessary
3552 // type. In general, we need to add an extra bit only if we can't
3553 // prove that the upper bit of the original type is equal to the
3554 // upper bit of the proposed smaller type. If these two bits are the
3555 // same (either zero or one) we know that sign-extending from the
3556 // smaller type will result in the same value. Here, since we can't
3557 // yet prove this, we are just making the proposed smaller type
3558 // larger to ensure correctness.
3559 if (!IsKnownPositive)
3563 // Round MaxBitWidth up to the next power-of-two.
3564 if (!isPowerOf2_64(MaxBitWidth))
3565 MaxBitWidth = NextPowerOf2(MaxBitWidth);
3567 // If the maximum bit width we compute is less than the with of the roots'
3568 // type, we can proceed with the narrowing. Otherwise, do nothing.
3569 if (MaxBitWidth >= TreeRootIT->getBitWidth())
3572 // If we can truncate the root, we must collect additional values that might
3573 // be demoted as a result. That is, those seeded by truncations we will
3575 while (!Roots.empty())
3576 collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
3578 // Finally, map the values we can demote to the maximum bit with we computed.
3579 for (auto *Scalar : ToDemote)
3580 MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
3584 /// The SLPVectorizer Pass.
3585 struct SLPVectorizer : public FunctionPass {
3586 SLPVectorizerPass Impl;
3588 /// Pass identification, replacement for typeid
3591 explicit SLPVectorizer() : FunctionPass(ID) {
3592 initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
3596 bool doInitialization(Module &M) override {
3600 bool runOnFunction(Function &F) override {
3601 if (skipFunction(F))
3604 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
3605 auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
3606 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
3607 auto *TLI = TLIP ? &TLIP->getTLI() : nullptr;
3608 auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3609 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
3610 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3611 auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
3612 auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
3614 return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB);
3617 void getAnalysisUsage(AnalysisUsage &AU) const override {
3618 FunctionPass::getAnalysisUsage(AU);
3619 AU.addRequired<AssumptionCacheTracker>();
3620 AU.addRequired<ScalarEvolutionWrapperPass>();
3621 AU.addRequired<AAResultsWrapperPass>();
3622 AU.addRequired<TargetTransformInfoWrapperPass>();
3623 AU.addRequired<LoopInfoWrapperPass>();
3624 AU.addRequired<DominatorTreeWrapperPass>();
3625 AU.addRequired<DemandedBitsWrapperPass>();
3626 AU.addPreserved<LoopInfoWrapperPass>();
3627 AU.addPreserved<DominatorTreeWrapperPass>();
3628 AU.addPreserved<AAResultsWrapperPass>();
3629 AU.addPreserved<GlobalsAAWrapperPass>();
3630 AU.setPreservesCFG();
3633 } // end anonymous namespace
3635 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
3636 auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
3637 auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
3638 auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
3639 auto *AA = &AM.getResult<AAManager>(F);
3640 auto *LI = &AM.getResult<LoopAnalysis>(F);
3641 auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
3642 auto *AC = &AM.getResult<AssumptionAnalysis>(F);
3643 auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
3645 bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB);
3647 return PreservedAnalyses::all();
3648 PreservedAnalyses PA;
3649 PA.preserve<LoopAnalysis>();
3650 PA.preserve<DominatorTreeAnalysis>();
3651 PA.preserve<AAManager>();
3652 PA.preserve<GlobalsAA>();
3656 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
3657 TargetTransformInfo *TTI_,
3658 TargetLibraryInfo *TLI_, AliasAnalysis *AA_,
3659 LoopInfo *LI_, DominatorTree *DT_,
3660 AssumptionCache *AC_, DemandedBits *DB_) {
3669 DL = &F.getParent()->getDataLayout();
3673 bool Changed = false;
3675 // If the target claims to have no vector registers don't attempt
3677 if (!TTI->getNumberOfRegisters(true))
3680 // Don't vectorize when the attribute NoImplicitFloat is used.
3681 if (F.hasFnAttribute(Attribute::NoImplicitFloat))
3684 DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
3686 // Use the bottom up slp vectorizer to construct chains that start with
3687 // store instructions.
3688 BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL);
3690 // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
3691 // delete instructions.
3693 // Scan the blocks in the function in post order.
3694 for (auto BB : post_order(&F.getEntryBlock())) {
3695 collectSeedInstructions(BB);
3697 // Vectorize trees that end at stores.
3698 if (!Stores.empty()) {
3699 DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
3700 << " underlying objects.\n");
3701 Changed |= vectorizeStoreChains(R);
3704 // Vectorize trees that end at reductions.
3705 Changed |= vectorizeChainsInBlock(BB, R);
3707 // Vectorize the index computations of getelementptr instructions. This
3708 // is primarily intended to catch gather-like idioms ending at
3709 // non-consecutive loads.
3710 if (!GEPs.empty()) {
3711 DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
3712 << " underlying objects.\n");
3713 Changed |= vectorizeGEPIndices(BB, R);
3718 R.optimizeGatherSequence();
3719 DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
3720 DEBUG(verifyFunction(F));
3725 /// \brief Check that the Values in the slice in VL array are still existent in
3726 /// the WeakVH array.
3727 /// Vectorization of part of the VL array may cause later values in the VL array
3728 /// to become invalid. We track when this has happened in the WeakVH array.
3729 static bool hasValueBeenRAUWed(ArrayRef<Value *> VL, ArrayRef<WeakVH> VH,
3730 unsigned SliceBegin, unsigned SliceSize) {
3731 VL = VL.slice(SliceBegin, SliceSize);
3732 VH = VH.slice(SliceBegin, SliceSize);
3733 return !std::equal(VL.begin(), VL.end(), VH.begin());
3736 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
3737 unsigned VecRegSize) {
3738 unsigned ChainLen = Chain.size();
3739 DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
3741 unsigned Sz = R.getVectorElementSize(Chain[0]);
3742 unsigned VF = VecRegSize / Sz;
3744 if (!isPowerOf2_32(Sz) || VF < 2)
3747 // Keep track of values that were deleted by vectorizing in the loop below.
3748 SmallVector<WeakVH, 8> TrackValues(Chain.begin(), Chain.end());
3750 bool Changed = false;
3751 // Look for profitable vectorizable trees at all offsets, starting at zero.
3752 for (unsigned i = 0, e = ChainLen; i < e; ++i) {
3756 // Check that a previous iteration of this loop did not delete the Value.
3757 if (hasValueBeenRAUWed(Chain, TrackValues, i, VF))
3760 DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
3762 ArrayRef<Value *> Operands = Chain.slice(i, VF);
3764 R.buildTree(Operands);
3765 if (R.isTreeTinyAndNotFullyVectorizable())
3768 R.computeMinimumValueSizes();
3770 int Cost = R.getTreeCost();
3772 DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
3773 if (Cost < -SLPCostThreshold) {
3774 DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
3777 // Move to the next bundle.
3786 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
3788 SetVector<StoreInst *> Heads, Tails;
3789 SmallDenseMap<StoreInst *, StoreInst *> ConsecutiveChain;
3791 // We may run into multiple chains that merge into a single chain. We mark the
3792 // stores that we vectorized so that we don't visit the same store twice.
3793 BoUpSLP::ValueSet VectorizedStores;
3794 bool Changed = false;
3796 // Do a quadratic search on all of the given stores and find
3797 // all of the pairs of stores that follow each other.
3798 SmallVector<unsigned, 16> IndexQueue;
3799 for (unsigned i = 0, e = Stores.size(); i < e; ++i) {
3801 // If a store has multiple consecutive store candidates, search Stores
3802 // array according to the sequence: from i+1 to e, then from i-1 to 0.
3803 // This is because usually pairing with immediate succeeding or preceding
3804 // candidate create the best chance to find slp vectorization opportunity.
3806 for (j = i + 1; j < e; ++j)
3807 IndexQueue.push_back(j);
3808 for (j = i; j > 0; --j)
3809 IndexQueue.push_back(j - 1);
3811 for (auto &k : IndexQueue) {
3812 if (isConsecutiveAccess(Stores[i], Stores[k], *DL, *SE)) {
3813 Tails.insert(Stores[k]);
3814 Heads.insert(Stores[i]);
3815 ConsecutiveChain[Stores[i]] = Stores[k];
3821 // For stores that start but don't end a link in the chain:
3822 for (SetVector<StoreInst *>::iterator it = Heads.begin(), e = Heads.end();
3824 if (Tails.count(*it))
3827 // We found a store instr that starts a chain. Now follow the chain and try
3829 BoUpSLP::ValueList Operands;
3831 // Collect the chain into a list.
3832 while (Tails.count(I) || Heads.count(I)) {
3833 if (VectorizedStores.count(I))
3835 Operands.push_back(I);
3836 // Move to the next value in the chain.
3837 I = ConsecutiveChain[I];
3840 // FIXME: Is division-by-2 the correct step? Should we assert that the
3841 // register size is a power-of-2?
3842 for (unsigned Size = R.getMaxVecRegSize(); Size >= R.getMinVecRegSize();
3844 if (vectorizeStoreChain(Operands, R, Size)) {
3845 // Mark the vectorized stores so that we don't vectorize them again.
3846 VectorizedStores.insert(Operands.begin(), Operands.end());
3856 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
3858 // Initialize the collections. We will make a single pass over the block.
3862 // Visit the store and getelementptr instructions in BB and organize them in
3863 // Stores and GEPs according to the underlying objects of their pointer
3865 for (Instruction &I : *BB) {
3867 // Ignore store instructions that are volatile or have a pointer operand
3868 // that doesn't point to a scalar type.
3869 if (auto *SI = dyn_cast<StoreInst>(&I)) {
3870 if (!SI->isSimple())
3872 if (!isValidElementType(SI->getValueOperand()->getType()))
3874 Stores[GetUnderlyingObject(SI->getPointerOperand(), *DL)].push_back(SI);
3877 // Ignore getelementptr instructions that have more than one index, a
3878 // constant index, or a pointer operand that doesn't point to a scalar
3880 else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
3881 auto Idx = GEP->idx_begin()->get();
3882 if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
3884 if (!isValidElementType(Idx->getType()))
3886 if (GEP->getType()->isVectorTy())
3888 GEPs[GetUnderlyingObject(GEP->getPointerOperand(), *DL)].push_back(GEP);
3893 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
3896 Value *VL[] = { A, B };
3897 return tryToVectorizeList(VL, R, None, true);
3900 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
3901 ArrayRef<Value *> BuildVector,
3902 bool AllowReorder) {
3906 DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = " << VL.size()
3909 // Check that all of the parts are scalar instructions of the same type.
3910 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
3914 unsigned Opcode0 = I0->getOpcode();
3916 unsigned Sz = R.getVectorElementSize(I0);
3917 unsigned MinVF = std::max(2U, R.getMinVecRegSize() / Sz);
3918 unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
3922 for (Value *V : VL) {
3923 Type *Ty = V->getType();
3924 if (!isValidElementType(Ty))
3926 Instruction *Inst = dyn_cast<Instruction>(V);
3927 if (!Inst || Inst->getOpcode() != Opcode0)
3931 bool Changed = false;
3933 // Keep track of values that were deleted by vectorizing in the loop below.
3934 SmallVector<WeakVH, 8> TrackValues(VL.begin(), VL.end());
3936 unsigned NextInst = 0, MaxInst = VL.size();
3937 for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF;
3939 // No actual vectorization should happen, if number of parts is the same as
3940 // provided vectorization factor (i.e. the scalar type is used for vector
3941 // code during codegen).
3942 auto *VecTy = VectorType::get(VL[0]->getType(), VF);
3943 if (TTI->getNumberOfParts(VecTy) == VF)
3945 for (unsigned I = NextInst; I < MaxInst; ++I) {
3946 unsigned OpsWidth = 0;
3948 if (I + VF > MaxInst)
3949 OpsWidth = MaxInst - I;
3953 if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
3956 // Check that a previous iteration of this loop did not delete the Value.
3957 if (hasValueBeenRAUWed(VL, TrackValues, I, OpsWidth))
3960 DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
3962 ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
3964 ArrayRef<Value *> BuildVectorSlice;
3965 if (!BuildVector.empty())
3966 BuildVectorSlice = BuildVector.slice(I, OpsWidth);
3968 R.buildTree(Ops, BuildVectorSlice);
3969 // TODO: check if we can allow reordering for more cases.
3970 if (AllowReorder && R.shouldReorder()) {
3971 // Conceptually, there is nothing actually preventing us from trying to
3972 // reorder a larger list. In fact, we do exactly this when vectorizing
3973 // reductions. However, at this point, we only expect to get here from
3974 // tryToVectorizePair().
3975 assert(Ops.size() == 2);
3976 assert(BuildVectorSlice.empty());
3977 Value *ReorderedOps[] = {Ops[1], Ops[0]};
3978 R.buildTree(ReorderedOps, None);
3980 if (R.isTreeTinyAndNotFullyVectorizable())
3983 R.computeMinimumValueSizes();
3984 int Cost = R.getTreeCost();
3986 if (Cost < -SLPCostThreshold) {
3987 DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
3988 Value *VectorizedRoot = R.vectorizeTree();
3990 // Reconstruct the build vector by extracting the vectorized root. This
3991 // way we handle the case where some elements of the vector are
3993 // (return (inserelt <4 xi32> (insertelt undef (opd0) 0) (opd1) 2))
3994 if (!BuildVectorSlice.empty()) {
3995 // The insert point is the last build vector instruction. The
3996 // vectorized root will precede it. This guarantees that we get an
3997 // instruction. The vectorized tree could have been constant folded.
3998 Instruction *InsertAfter = cast<Instruction>(BuildVectorSlice.back());
3999 unsigned VecIdx = 0;
4000 for (auto &V : BuildVectorSlice) {
4001 IRBuilder<NoFolder> Builder(InsertAfter->getParent(),
4002 ++BasicBlock::iterator(InsertAfter));
4003 Instruction *I = cast<Instruction>(V);
4004 assert(isa<InsertElementInst>(I) || isa<InsertValueInst>(I));
4005 Instruction *Extract =
4006 cast<Instruction>(Builder.CreateExtractElement(
4007 VectorizedRoot, Builder.getInt32(VecIdx++)));
4008 I->setOperand(1, Extract);
4009 I->removeFromParent();
4010 I->insertAfter(Extract);
4014 // Move to the next bundle.
4025 bool SLPVectorizerPass::tryToVectorize(BinaryOperator *V, BoUpSLP &R) {
4029 Value *P = V->getParent();
4031 // Vectorize in current basic block only.
4032 auto *Op0 = dyn_cast<Instruction>(V->getOperand(0));
4033 auto *Op1 = dyn_cast<Instruction>(V->getOperand(1));
4034 if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
4037 // Try to vectorize V.
4038 if (tryToVectorizePair(Op0, Op1, R))
4041 auto *A = dyn_cast<BinaryOperator>(Op0);
4042 auto *B = dyn_cast<BinaryOperator>(Op1);
4044 if (B && B->hasOneUse()) {
4045 auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
4046 auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
4047 if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
4049 if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
4054 if (A && A->hasOneUse()) {
4055 auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
4056 auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
4057 if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
4059 if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
4065 /// \brief Generate a shuffle mask to be used in a reduction tree.
4067 /// \param VecLen The length of the vector to be reduced.
4068 /// \param NumEltsToRdx The number of elements that should be reduced in the
4070 /// \param IsPairwise Whether the reduction is a pairwise or splitting
4071 /// reduction. A pairwise reduction will generate a mask of
4072 /// <0,2,...> or <1,3,..> while a splitting reduction will generate
4073 /// <2,3, undef,undef> for a vector of 4 and NumElts = 2.
4074 /// \param IsLeft True will generate a mask of even elements, odd otherwise.
4075 static Value *createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx,
4076 bool IsPairwise, bool IsLeft,
4077 IRBuilder<> &Builder) {
4078 assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask");
4080 SmallVector<Constant *, 32> ShuffleMask(
4081 VecLen, UndefValue::get(Builder.getInt32Ty()));
4084 // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
4085 for (unsigned i = 0; i != NumEltsToRdx; ++i)
4086 ShuffleMask[i] = Builder.getInt32(2 * i + !IsLeft);
4088 // Move the upper half of the vector to the lower half.
4089 for (unsigned i = 0; i != NumEltsToRdx; ++i)
4090 ShuffleMask[i] = Builder.getInt32(NumEltsToRdx + i);
4092 return ConstantVector::get(ShuffleMask);
4096 /// Model horizontal reductions.
4098 /// A horizontal reduction is a tree of reduction operations (currently add and
4099 /// fadd) that has operations that can be put into a vector as its leaf.
4100 /// For example, this tree:
4107 /// This tree has "mul" as its reduced values and "+" as its reduction
4108 /// operations. A reduction might be feeding into a store or a binary operation
4123 class HorizontalReduction {
4124 SmallVector<Value *, 16> ReductionOps;
4125 SmallVector<Value *, 32> ReducedVals;
4127 BinaryOperator *ReductionRoot;
4128 // After successfull horizontal reduction vectorization attempt for PHI node
4129 // vectorizer tries to update root binary op by combining vectorized tree and
4130 // the ReductionPHI node. But during vectorization this ReductionPHI can be
4131 // vectorized itself and replaced by the undef value, while the instruction
4132 // itself is marked for deletion. This 'marked for deletion' PHI node then can
4133 // be used in new binary operation, causing "Use still stuck around after Def
4134 // is destroyed" crash upon PHI node deletion.
4135 WeakVH ReductionPHI;
4137 /// The opcode of the reduction.
4138 unsigned ReductionOpcode;
4139 /// The opcode of the values we perform a reduction on.
4140 unsigned ReducedValueOpcode;
4141 /// Should we model this reduction as a pairwise reduction tree or a tree that
4142 /// splits the vector in halves and adds those halves.
4143 bool IsPairwiseReduction;
4146 /// The width of one full horizontal reduction operation.
4147 unsigned ReduxWidth;
4149 /// Minimal width of available vector registers. It's used to determine
4151 unsigned MinVecRegSize;
4153 HorizontalReduction(unsigned MinVecRegSize)
4154 : ReductionRoot(nullptr), ReductionOpcode(0), ReducedValueOpcode(0),
4155 IsPairwiseReduction(false), ReduxWidth(0),
4156 MinVecRegSize(MinVecRegSize) {}
4158 /// \brief Try to find a reduction tree.
4159 bool matchAssociativeReduction(PHINode *Phi, BinaryOperator *B) {
4160 assert((!Phi || is_contained(Phi->operands(), B)) &&
4161 "Thi phi needs to use the binary operator");
4163 // We could have a initial reductions that is not an add.
4164 // r *= v1 + v2 + v3 + v4
4165 // In such a case start looking for a tree rooted in the first '+'.
4167 if (B->getOperand(0) == Phi) {
4169 B = dyn_cast<BinaryOperator>(B->getOperand(1));
4170 } else if (B->getOperand(1) == Phi) {
4172 B = dyn_cast<BinaryOperator>(B->getOperand(0));
4179 Type *Ty = B->getType();
4180 if (!isValidElementType(Ty))
4183 const DataLayout &DL = B->getModule()->getDataLayout();
4184 ReductionOpcode = B->getOpcode();
4185 ReducedValueOpcode = 0;
4186 // FIXME: Register size should be a parameter to this function, so we can
4187 // try different vectorization factors.
4188 ReduxWidth = MinVecRegSize / DL.getTypeSizeInBits(Ty);
4195 // We currently only support adds.
4196 if (ReductionOpcode != Instruction::Add &&
4197 ReductionOpcode != Instruction::FAdd)
4200 // Post order traverse the reduction tree starting at B. We only handle true
4201 // trees containing only binary operators or selects.
4202 SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
4203 Stack.push_back(std::make_pair(B, 0));
4204 while (!Stack.empty()) {
4205 Instruction *TreeN = Stack.back().first;
4206 unsigned EdgeToVist = Stack.back().second++;
4207 bool IsReducedValue = TreeN->getOpcode() != ReductionOpcode;
4209 // Only handle trees in the current basic block.
4210 if (TreeN->getParent() != B->getParent())
4213 // Each tree node needs to have one user except for the ultimate
4215 if (!TreeN->hasOneUse() && TreeN != B)
4219 if (EdgeToVist == 2 || IsReducedValue) {
4220 if (IsReducedValue) {
4221 // Make sure that the opcodes of the operations that we are going to
4223 if (!ReducedValueOpcode)
4224 ReducedValueOpcode = TreeN->getOpcode();
4225 else if (ReducedValueOpcode != TreeN->getOpcode())
4227 ReducedVals.push_back(TreeN);
4229 // We need to be able to reassociate the adds.
4230 if (!TreeN->isAssociative())
4232 ReductionOps.push_back(TreeN);
4239 // Visit left or right.
4240 Value *NextV = TreeN->getOperand(EdgeToVist);
4242 auto *I = dyn_cast<Instruction>(NextV);
4243 // Continue analysis if the next operand is a reduction operation or
4244 // (possibly) a reduced value. If the reduced value opcode is not set,
4245 // the first met operation != reduction operation is considered as the
4246 // reduced value class.
4247 if (I && (!ReducedValueOpcode || I->getOpcode() == ReducedValueOpcode ||
4248 I->getOpcode() == ReductionOpcode)) {
4249 if (!ReducedValueOpcode && I->getOpcode() != ReductionOpcode)
4250 ReducedValueOpcode = I->getOpcode();
4251 Stack.push_back(std::make_pair(I, 0));
4260 /// \brief Attempt to vectorize the tree found by
4261 /// matchAssociativeReduction.
4262 bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
4263 if (ReducedVals.empty())
4266 unsigned NumReducedVals = ReducedVals.size();
4267 if (NumReducedVals < ReduxWidth)
4270 Value *VectorizedTree = nullptr;
4271 IRBuilder<> Builder(ReductionRoot);
4272 FastMathFlags Unsafe;
4273 Unsafe.setUnsafeAlgebra();
4274 Builder.setFastMathFlags(Unsafe);
4277 for (; i < NumReducedVals - ReduxWidth + 1; i += ReduxWidth) {
4278 auto VL = makeArrayRef(&ReducedVals[i], ReduxWidth);
4279 V.buildTree(VL, ReductionOps);
4280 if (V.shouldReorder()) {
4281 SmallVector<Value *, 8> Reversed(VL.rbegin(), VL.rend());
4282 V.buildTree(Reversed, ReductionOps);
4284 if (V.isTreeTinyAndNotFullyVectorizable())
4287 V.computeMinimumValueSizes();
4290 int Cost = V.getTreeCost() + getReductionCost(TTI, ReducedVals[i]);
4291 if (Cost >= -SLPCostThreshold)
4294 DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" << Cost
4297 // Vectorize a tree.
4298 DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
4299 Value *VectorizedRoot = V.vectorizeTree();
4301 // Emit a reduction.
4302 Value *ReducedSubTree = emitReduction(VectorizedRoot, Builder);
4303 if (VectorizedTree) {
4304 Builder.SetCurrentDebugLocation(Loc);
4305 VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
4306 ReducedSubTree, "bin.rdx");
4308 VectorizedTree = ReducedSubTree;
4311 if (VectorizedTree) {
4312 // Finish the reduction.
4313 for (; i < NumReducedVals; ++i) {
4314 Builder.SetCurrentDebugLocation(
4315 cast<Instruction>(ReducedVals[i])->getDebugLoc());
4316 VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
4320 if (ReductionPHI && !isa<UndefValue>(ReductionPHI)) {
4321 assert(ReductionRoot && "Need a reduction operation");
4322 ReductionRoot->setOperand(0, VectorizedTree);
4323 ReductionRoot->setOperand(1, ReductionPHI);
4325 ReductionRoot->replaceAllUsesWith(VectorizedTree);
4327 return VectorizedTree != nullptr;
4330 unsigned numReductionValues() const {
4331 return ReducedVals.size();
4335 /// \brief Calculate the cost of a reduction.
4336 int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal) {
4337 Type *ScalarTy = FirstReducedVal->getType();
4338 Type *VecTy = VectorType::get(ScalarTy, ReduxWidth);
4340 int PairwiseRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, true);
4341 int SplittingRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, false);
4343 IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
4344 int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
4346 int ScalarReduxCost =
4348 TTI->getArithmeticInstrCost(ReductionOpcode, ScalarTy);
4350 DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost
4351 << " for reduction that starts with " << *FirstReducedVal
4353 << (IsPairwiseReduction ? "pairwise" : "splitting")
4354 << " reduction)\n");
4356 return VecReduxCost - ScalarReduxCost;
4359 static Value *createBinOp(IRBuilder<> &Builder, unsigned Opcode, Value *L,
4360 Value *R, const Twine &Name = "") {
4361 if (Opcode == Instruction::FAdd)
4362 return Builder.CreateFAdd(L, R, Name);
4363 return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, L, R, Name);
4366 /// \brief Emit a horizontal reduction of the vectorized value.
4367 Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder) {
4368 assert(VectorizedValue && "Need to have a vectorized tree node");
4369 assert(isPowerOf2_32(ReduxWidth) &&
4370 "We only handle power-of-two reductions for now");
4372 Value *TmpVec = VectorizedValue;
4373 for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
4374 if (IsPairwiseReduction) {
4376 createRdxShuffleMask(ReduxWidth, i, true, true, Builder);
4378 createRdxShuffleMask(ReduxWidth, i, true, false, Builder);
4380 Value *LeftShuf = Builder.CreateShuffleVector(
4381 TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l");
4382 Value *RightShuf = Builder.CreateShuffleVector(
4383 TmpVec, UndefValue::get(TmpVec->getType()), (RightMask),
4385 TmpVec = createBinOp(Builder, ReductionOpcode, LeftShuf, RightShuf,
4389 createRdxShuffleMask(ReduxWidth, i, false, false, Builder);
4390 Value *Shuf = Builder.CreateShuffleVector(
4391 TmpVec, UndefValue::get(TmpVec->getType()), UpperHalf, "rdx.shuf");
4392 TmpVec = createBinOp(Builder, ReductionOpcode, TmpVec, Shuf, "bin.rdx");
4396 // The result is in the first element of the vector.
4397 return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
4400 } // end anonymous namespace
4402 /// \brief Recognize construction of vectors like
4403 /// %ra = insertelement <4 x float> undef, float %s0, i32 0
4404 /// %rb = insertelement <4 x float> %ra, float %s1, i32 1
4405 /// %rc = insertelement <4 x float> %rb, float %s2, i32 2
4406 /// %rd = insertelement <4 x float> %rc, float %s3, i32 3
4408 /// Returns true if it matches
4410 static bool findBuildVector(InsertElementInst *FirstInsertElem,
4411 SmallVectorImpl<Value *> &BuildVector,
4412 SmallVectorImpl<Value *> &BuildVectorOpds) {
4413 if (!isa<UndefValue>(FirstInsertElem->getOperand(0)))
4416 InsertElementInst *IE = FirstInsertElem;
4418 BuildVector.push_back(IE);
4419 BuildVectorOpds.push_back(IE->getOperand(1));
4421 if (IE->use_empty())
4424 InsertElementInst *NextUse = dyn_cast<InsertElementInst>(IE->user_back());
4428 // If this isn't the final use, make sure the next insertelement is the only
4429 // use. It's OK if the final constructed vector is used multiple times
4430 if (!IE->hasOneUse())
4439 /// \brief Like findBuildVector, but looks backwards for construction of aggregate.
4441 /// \return true if it matches.
4442 static bool findBuildAggregate(InsertValueInst *IV,
4443 SmallVectorImpl<Value *> &BuildVector,
4444 SmallVectorImpl<Value *> &BuildVectorOpds) {
4445 if (!IV->hasOneUse())
4447 Value *V = IV->getAggregateOperand();
4448 if (!isa<UndefValue>(V)) {
4449 InsertValueInst *I = dyn_cast<InsertValueInst>(V);
4450 if (!I || !findBuildAggregate(I, BuildVector, BuildVectorOpds))
4453 BuildVector.push_back(IV);
4454 BuildVectorOpds.push_back(IV->getInsertedValueOperand());
4458 static bool PhiTypeSorterFunc(Value *V, Value *V2) {
4459 return V->getType() < V2->getType();
4462 /// \brief Try and get a reduction value from a phi node.
4464 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
4465 /// if they come from either \p ParentBB or a containing loop latch.
4467 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
4468 /// if not possible.
4469 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
4470 BasicBlock *ParentBB, LoopInfo *LI) {
4471 // There are situations where the reduction value is not dominated by the
4472 // reduction phi. Vectorizing such cases has been reported to cause
4473 // miscompiles. See PR25787.
4474 auto DominatedReduxValue = [&](Value *R) {
4476 dyn_cast<Instruction>(R) &&
4477 DT->dominates(P->getParent(), dyn_cast<Instruction>(R)->getParent()));
4480 Value *Rdx = nullptr;
4482 // Return the incoming value if it comes from the same BB as the phi node.
4483 if (P->getIncomingBlock(0) == ParentBB) {
4484 Rdx = P->getIncomingValue(0);
4485 } else if (P->getIncomingBlock(1) == ParentBB) {
4486 Rdx = P->getIncomingValue(1);
4489 if (Rdx && DominatedReduxValue(Rdx))
4492 // Otherwise, check whether we have a loop latch to look at.
4493 Loop *BBL = LI->getLoopFor(ParentBB);
4496 BasicBlock *BBLatch = BBL->getLoopLatch();
4500 // There is a loop latch, return the incoming value if it comes from
4501 // that. This reduction pattern occasionally turns up.
4502 if (P->getIncomingBlock(0) == BBLatch) {
4503 Rdx = P->getIncomingValue(0);
4504 } else if (P->getIncomingBlock(1) == BBLatch) {
4505 Rdx = P->getIncomingValue(1);
4508 if (Rdx && DominatedReduxValue(Rdx))
4515 /// Tracks instructons and its children.
4516 class WeakVHWithLevel final : public CallbackVH {
4517 /// Operand index of the instruction currently beeing analized.
4519 /// Is this the instruction that should be vectorized, or are we now
4520 /// processing children (i.e. operands of this instruction) for potential
4522 bool IsInitial = true;
4525 explicit WeakVHWithLevel() = default;
4526 WeakVHWithLevel(Value *V) : CallbackVH(V){};
4527 /// Restart children analysis each time it is repaced by the new instruction.
4528 void allUsesReplacedWith(Value *New) override {
4533 /// Check if the instruction was not deleted during vectorization.
4534 bool isValid() const { return !getValPtr(); }
4535 /// Is the istruction itself must be vectorized?
4536 bool isInitial() const { return IsInitial; }
4537 /// Try to vectorize children.
4538 void clearInitial() { IsInitial = false; }
4539 /// Are all children processed already?
4540 bool isFinal() const {
4541 assert(getValPtr() &&
4542 (isa<Instruction>(getValPtr()) &&
4543 cast<Instruction>(getValPtr())->getNumOperands() >= Level));
4544 return getValPtr() &&
4545 cast<Instruction>(getValPtr())->getNumOperands() == Level;
4547 /// Get next child operation.
4548 Value *nextOperand() {
4549 assert(getValPtr() && isa<Instruction>(getValPtr()) &&
4550 cast<Instruction>(getValPtr())->getNumOperands() > Level);
4551 return cast<Instruction>(getValPtr())->getOperand(Level++);
4553 virtual ~WeakVHWithLevel() = default;
4557 /// \brief Attempt to reduce a horizontal reduction.
4558 /// If it is legal to match a horizontal reduction feeding
4559 /// the phi node P with reduction operators Root in a basic block BB, then check
4560 /// if it can be done.
4561 /// \returns true if a horizontal reduction was matched and reduced.
4562 /// \returns false if a horizontal reduction was not matched.
4563 static bool canBeVectorized(
4564 PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
4565 TargetTransformInfo *TTI,
4566 const function_ref<bool(BinaryOperator *, BoUpSLP &)> Vectorize) {
4567 if (!ShouldVectorizeHor)
4573 if (Root->getParent() != BB)
4575 SmallVector<WeakVHWithLevel, 8> Stack(1, Root);
4576 SmallSet<Value *, 8> VisitedInstrs;
4578 while (!Stack.empty()) {
4579 Value *V = Stack.back();
4584 auto *Inst = dyn_cast<Instruction>(V);
4585 if (!Inst || isa<PHINode>(Inst)) {
4589 if (Stack.back().isInitial()) {
4590 Stack.back().clearInitial();
4591 if (auto *BI = dyn_cast<BinaryOperator>(Inst)) {
4592 HorizontalReduction HorRdx(R.getMinVecRegSize());
4593 if (HorRdx.matchAssociativeReduction(P, BI)) {
4594 // If there is a sufficient number of reduction values, reduce
4595 // to a nearby power-of-2. Can safely generate oversized
4596 // vectors and rely on the backend to split them to legal sizes.
4598 std::max((uint64_t)4, PowerOf2Floor(HorRdx.numReductionValues()));
4600 if (HorRdx.tryToReduce(R, TTI)) {
4607 Inst = dyn_cast<Instruction>(BI->getOperand(0));
4609 Inst = dyn_cast<Instruction>(BI->getOperand(1));
4617 if (Vectorize(dyn_cast<BinaryOperator>(Inst), R)) {
4622 if (Stack.back().isFinal()) {
4627 if (auto *NextV = dyn_cast<Instruction>(Stack.back().nextOperand()))
4628 if (NextV->getParent() == BB && VisitedInstrs.insert(NextV).second &&
4629 Stack.size() < RecursionMaxDepth)
4630 Stack.push_back(NextV);
4635 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
4636 BasicBlock *BB, BoUpSLP &R,
4637 TargetTransformInfo *TTI) {
4640 auto *I = dyn_cast<Instruction>(V);
4644 if (!isa<BinaryOperator>(I))
4646 // Try to match and vectorize a horizontal reduction.
4647 return canBeVectorized(P, I, BB, R, TTI,
4648 [this](BinaryOperator *BI, BoUpSLP &R) -> bool {
4649 return tryToVectorize(BI, R);
4653 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
4654 bool Changed = false;
4655 SmallVector<Value *, 4> Incoming;
4656 SmallSet<Value *, 16> VisitedInstrs;
4658 bool HaveVectorizedPhiNodes = true;
4659 while (HaveVectorizedPhiNodes) {
4660 HaveVectorizedPhiNodes = false;
4662 // Collect the incoming values from the PHIs.
4664 for (Instruction &I : *BB) {
4665 PHINode *P = dyn_cast<PHINode>(&I);
4669 if (!VisitedInstrs.count(P))
4670 Incoming.push_back(P);
4674 std::stable_sort(Incoming.begin(), Incoming.end(), PhiTypeSorterFunc);
4676 // Try to vectorize elements base on their type.
4677 for (SmallVector<Value *, 4>::iterator IncIt = Incoming.begin(),
4681 // Look for the next elements with the same type.
4682 SmallVector<Value *, 4>::iterator SameTypeIt = IncIt;
4683 while (SameTypeIt != E &&
4684 (*SameTypeIt)->getType() == (*IncIt)->getType()) {
4685 VisitedInstrs.insert(*SameTypeIt);
4689 // Try to vectorize them.
4690 unsigned NumElts = (SameTypeIt - IncIt);
4691 DEBUG(errs() << "SLP: Trying to vectorize starting at PHIs (" << NumElts << ")\n");
4692 if (NumElts > 1 && tryToVectorizeList(makeArrayRef(IncIt, NumElts), R)) {
4693 // Success start over because instructions might have been changed.
4694 HaveVectorizedPhiNodes = true;
4699 // Start over at the next instruction of a different type (or the end).
4704 VisitedInstrs.clear();
4706 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) {
4707 // We may go through BB multiple times so skip the one we have checked.
4708 if (!VisitedInstrs.insert(&*it).second)
4711 if (isa<DbgInfoIntrinsic>(it))
4714 // Try to vectorize reductions that use PHINodes.
4715 if (PHINode *P = dyn_cast<PHINode>(it)) {
4716 // Check that the PHI is a reduction PHI.
4717 if (P->getNumIncomingValues() != 2)
4720 // Try to match and vectorize a horizontal reduction.
4721 if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
4731 if (ShouldStartVectorizeHorAtStore) {
4732 if (StoreInst *SI = dyn_cast<StoreInst>(it)) {
4733 // Try to match and vectorize a horizontal reduction.
4734 if (vectorizeRootInstruction(nullptr, SI->getValueOperand(), BB, R,
4744 // Try to vectorize horizontal reductions feeding into a return.
4745 if (ReturnInst *RI = dyn_cast<ReturnInst>(it)) {
4746 if (RI->getNumOperands() != 0) {
4747 // Try to match and vectorize a horizontal reduction.
4748 if (vectorizeRootInstruction(nullptr, RI->getOperand(0), BB, R, TTI)) {
4757 // Try to vectorize trees that start at compare instructions.
4758 if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
4759 if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) {
4761 // We would like to start over since some instructions are deleted
4762 // and the iterator may become invalid value.
4768 for (int I = 0; I < 2; ++I) {
4769 if (vectorizeRootInstruction(nullptr, CI->getOperand(I), BB, R, TTI)) {
4771 // We would like to start over since some instructions are deleted
4772 // and the iterator may become invalid value.
4781 // Try to vectorize trees that start at insertelement instructions.
4782 if (InsertElementInst *FirstInsertElem = dyn_cast<InsertElementInst>(it)) {
4783 SmallVector<Value *, 16> BuildVector;
4784 SmallVector<Value *, 16> BuildVectorOpds;
4785 if (!findBuildVector(FirstInsertElem, BuildVector, BuildVectorOpds))
4788 // Vectorize starting with the build vector operands ignoring the
4789 // BuildVector instructions for the purpose of scheduling and user
4791 if (tryToVectorizeList(BuildVectorOpds, R, BuildVector)) {
4800 // Try to vectorize trees that start at insertvalue instructions feeding into
4802 if (StoreInst *SI = dyn_cast<StoreInst>(it)) {
4803 if (InsertValueInst *LastInsertValue = dyn_cast<InsertValueInst>(SI->getValueOperand())) {
4804 const DataLayout &DL = BB->getModule()->getDataLayout();
4805 if (R.canMapToVector(SI->getValueOperand()->getType(), DL)) {
4806 SmallVector<Value *, 16> BuildVector;
4807 SmallVector<Value *, 16> BuildVectorOpds;
4808 if (!findBuildAggregate(LastInsertValue, BuildVector, BuildVectorOpds))
4811 DEBUG(dbgs() << "SLP: store of array mappable to vector: " << *SI << "\n");
4812 if (tryToVectorizeList(BuildVectorOpds, R, BuildVector, false)) {
4826 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
4827 auto Changed = false;
4828 for (auto &Entry : GEPs) {
4830 // If the getelementptr list has fewer than two elements, there's nothing
4832 if (Entry.second.size() < 2)
4835 DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
4836 << Entry.second.size() << ".\n");
4838 // We process the getelementptr list in chunks of 16 (like we do for
4839 // stores) to minimize compile-time.
4840 for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += 16) {
4841 auto Len = std::min<unsigned>(BE - BI, 16);
4842 auto GEPList = makeArrayRef(&Entry.second[BI], Len);
4844 // Initialize a set a candidate getelementptrs. Note that we use a
4845 // SetVector here to preserve program order. If the index computations
4846 // are vectorizable and begin with loads, we want to minimize the chance
4847 // of having to reorder them later.
4848 SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
4850 // Some of the candidates may have already been vectorized after we
4851 // initially collected them. If so, the WeakVHs will have nullified the
4852 // values, so remove them from the set of candidates.
4853 Candidates.remove(nullptr);
4855 // Remove from the set of candidates all pairs of getelementptrs with
4856 // constant differences. Such getelementptrs are likely not good
4857 // candidates for vectorization in a bottom-up phase since one can be
4858 // computed from the other. We also ensure all candidate getelementptr
4859 // indices are unique.
4860 for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
4861 auto *GEPI = cast<GetElementPtrInst>(GEPList[I]);
4862 if (!Candidates.count(GEPI))
4864 auto *SCEVI = SE->getSCEV(GEPList[I]);
4865 for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
4866 auto *GEPJ = cast<GetElementPtrInst>(GEPList[J]);
4867 auto *SCEVJ = SE->getSCEV(GEPList[J]);
4868 if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
4869 Candidates.remove(GEPList[I]);
4870 Candidates.remove(GEPList[J]);
4871 } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
4872 Candidates.remove(GEPList[J]);
4877 // We break out of the above computation as soon as we know there are
4878 // fewer than two candidates remaining.
4879 if (Candidates.size() < 2)
4882 // Add the single, non-constant index of each candidate to the bundle. We
4883 // ensured the indices met these constraints when we originally collected
4884 // the getelementptrs.
4885 SmallVector<Value *, 16> Bundle(Candidates.size());
4886 auto BundleIndex = 0u;
4887 for (auto *V : Candidates) {
4888 auto *GEP = cast<GetElementPtrInst>(V);
4889 auto *GEPIdx = GEP->idx_begin()->get();
4890 assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
4891 Bundle[BundleIndex++] = GEPIdx;
4894 // Try and vectorize the indices. We are currently only interested in
4895 // gather-like cases of the form:
4897 // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
4899 // where the loads of "a", the loads of "b", and the subtractions can be
4900 // performed in parallel. It's likely that detecting this pattern in a
4901 // bottom-up phase will be simpler and less costly than building a
4902 // full-blown top-down phase beginning at the consecutive loads.
4903 Changed |= tryToVectorizeList(Bundle, R);
4909 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
4910 bool Changed = false;
4911 // Attempt to sort and vectorize each of the store-groups.
4912 for (StoreListMap::iterator it = Stores.begin(), e = Stores.end(); it != e;
4914 if (it->second.size() < 2)
4917 DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
4918 << it->second.size() << ".\n");
4920 // Process the stores in chunks of 16.
4921 // TODO: The limit of 16 inhibits greater vectorization factors.
4922 // For example, AVX2 supports v32i8. Increasing this limit, however,
4923 // may cause a significant compile-time increase.
4924 for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI+=16) {
4925 unsigned Len = std::min<unsigned>(CE - CI, 16);
4926 Changed |= vectorizeStores(makeArrayRef(&it->second[CI], Len), R);
4932 char SLPVectorizer::ID = 0;
4933 static const char lv_name[] = "SLP Vectorizer";
4934 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
4935 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
4936 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
4937 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
4938 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
4939 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
4940 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
4941 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
4944 Pass *createSLPVectorizerPass() { return new SLPVectorizer(); }