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/GraphWriter.h"
43 #include "llvm/Support/KnownBits.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include "llvm/Transforms/Utils/LoopUtils.h"
46 #include "llvm/Transforms/Vectorize.h"
51 using namespace slpvectorizer;
53 #define SV_NAME "slp-vectorizer"
54 #define DEBUG_TYPE "SLP"
56 STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
59 SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
60 cl::desc("Only vectorize if you gain more than this "
64 ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden,
65 cl::desc("Attempt to vectorize horizontal reductions"));
67 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
68 "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
70 "Attempt to vectorize horizontal reductions feeding into a store"));
73 MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden,
74 cl::desc("Attempt to vectorize for this register size in bits"));
76 /// Limits the size of scheduling regions in a block.
77 /// It avoid long compile times for _very_ large blocks where vector
78 /// instructions are spread over a wide range.
79 /// This limit is way higher than needed by real-world functions.
81 ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden,
82 cl::desc("Limit the size of the SLP scheduling region per block"));
84 static cl::opt<int> MinVectorRegSizeOption(
85 "slp-min-reg-size", cl::init(128), cl::Hidden,
86 cl::desc("Attempt to vectorize for this register size in bits"));
88 static cl::opt<unsigned> RecursionMaxDepth(
89 "slp-recursion-max-depth", cl::init(12), cl::Hidden,
90 cl::desc("Limit the recursion depth when building a vectorizable tree"));
92 static cl::opt<unsigned> MinTreeSize(
93 "slp-min-tree-size", cl::init(3), cl::Hidden,
94 cl::desc("Only vectorize small trees if they are fully vectorizable"));
97 ViewSLPTree("view-slp-tree", cl::Hidden,
98 cl::desc("Display the SLP trees with Graphviz"));
100 // Limit the number of alias checks. The limit is chosen so that
101 // it has no negative effect on the llvm benchmarks.
102 static const unsigned AliasedCheckLimit = 10;
104 // Another limit for the alias checks: The maximum distance between load/store
105 // instructions where alias checks are done.
106 // This limit is useful for very large basic blocks.
107 static const unsigned MaxMemDepDistance = 160;
109 /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
110 /// regions to be handled.
111 static const int MinScheduleRegionSize = 16;
113 /// \brief Predicate for the element types that the SLP vectorizer supports.
115 /// The most important thing to filter here are types which are invalid in LLVM
116 /// vectors. We also filter target specific types which have absolutely no
117 /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
118 /// avoids spending time checking the cost model and realizing that they will
119 /// be inevitably scalarized.
120 static bool isValidElementType(Type *Ty) {
121 return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() &&
122 !Ty->isPPC_FP128Ty();
125 /// \returns true if all of the instructions in \p VL are in the same block or
127 static bool allSameBlock(ArrayRef<Value *> VL) {
128 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
131 BasicBlock *BB = I0->getParent();
132 for (int i = 1, e = VL.size(); i < e; i++) {
133 Instruction *I = dyn_cast<Instruction>(VL[i]);
137 if (BB != I->getParent())
143 /// \returns True if all of the values in \p VL are constants.
144 static bool allConstant(ArrayRef<Value *> VL) {
146 if (!isa<Constant>(i))
151 /// \returns True if all of the values in \p VL are identical.
152 static bool isSplat(ArrayRef<Value *> VL) {
153 for (unsigned i = 1, e = VL.size(); i < e; ++i)
159 ///\returns Opcode that can be clubbed with \p Op to create an alternate
160 /// sequence which can later be merged as a ShuffleVector instruction.
161 static unsigned getAltOpcode(unsigned Op) {
163 case Instruction::FAdd:
164 return Instruction::FSub;
165 case Instruction::FSub:
166 return Instruction::FAdd;
167 case Instruction::Add:
168 return Instruction::Sub;
169 case Instruction::Sub:
170 return Instruction::Add;
176 ///\returns bool representing if Opcode \p Op can be part
177 /// of an alternate sequence which can later be merged as
178 /// a ShuffleVector instruction.
179 static bool canCombineAsAltInst(unsigned Op) {
180 return Op == Instruction::FAdd || Op == Instruction::FSub ||
181 Op == Instruction::Sub || Op == Instruction::Add;
184 /// \returns ShuffleVector instruction if instructions in \p VL have
185 /// alternate fadd,fsub / fsub,fadd/add,sub/sub,add sequence.
186 /// (i.e. e.g. opcodes of fadd,fsub,fadd,fsub...)
187 static unsigned isAltInst(ArrayRef<Value *> VL) {
188 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
189 unsigned Opcode = I0->getOpcode();
190 unsigned AltOpcode = getAltOpcode(Opcode);
191 for (int i = 1, e = VL.size(); i < e; i++) {
192 Instruction *I = dyn_cast<Instruction>(VL[i]);
193 if (!I || I->getOpcode() != ((i & 1) ? AltOpcode : Opcode))
196 return Instruction::ShuffleVector;
199 /// \returns The opcode if all of the Instructions in \p VL have the same
201 static unsigned getSameOpcode(ArrayRef<Value *> VL) {
202 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
205 unsigned Opcode = I0->getOpcode();
206 for (int i = 1, e = VL.size(); i < e; i++) {
207 Instruction *I = dyn_cast<Instruction>(VL[i]);
208 if (!I || Opcode != I->getOpcode()) {
209 if (canCombineAsAltInst(Opcode) && i == 1)
210 return isAltInst(VL);
217 /// \returns true if all of the values in \p VL have the same type or false
219 static bool allSameType(ArrayRef<Value *> VL) {
220 Type *Ty = VL[0]->getType();
221 for (int i = 1, e = VL.size(); i < e; i++)
222 if (VL[i]->getType() != Ty)
228 /// \returns True if Extract{Value,Element} instruction extracts element Idx.
229 static bool matchExtractIndex(Instruction *E, unsigned Idx, unsigned Opcode) {
230 assert(Opcode == Instruction::ExtractElement ||
231 Opcode == Instruction::ExtractValue);
232 if (Opcode == Instruction::ExtractElement) {
233 ConstantInt *CI = dyn_cast<ConstantInt>(E->getOperand(1));
234 return CI && CI->getZExtValue() == Idx;
236 ExtractValueInst *EI = cast<ExtractValueInst>(E);
237 return EI->getNumIndices() == 1 && *EI->idx_begin() == Idx;
241 /// \returns True if in-tree use also needs extract. This refers to
242 /// possible scalar operand in vectorized instruction.
243 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
244 TargetLibraryInfo *TLI) {
246 unsigned Opcode = UserInst->getOpcode();
248 case Instruction::Load: {
249 LoadInst *LI = cast<LoadInst>(UserInst);
250 return (LI->getPointerOperand() == Scalar);
252 case Instruction::Store: {
253 StoreInst *SI = cast<StoreInst>(UserInst);
254 return (SI->getPointerOperand() == Scalar);
256 case Instruction::Call: {
257 CallInst *CI = cast<CallInst>(UserInst);
258 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
259 if (hasVectorInstrinsicScalarOpd(ID, 1)) {
260 return (CI->getArgOperand(1) == Scalar);
269 /// \returns the AA location that is being access by the instruction.
270 static MemoryLocation getLocation(Instruction *I, AliasAnalysis *AA) {
271 if (StoreInst *SI = dyn_cast<StoreInst>(I))
272 return MemoryLocation::get(SI);
273 if (LoadInst *LI = dyn_cast<LoadInst>(I))
274 return MemoryLocation::get(LI);
275 return MemoryLocation();
278 /// \returns True if the instruction is not a volatile or atomic load/store.
279 static bool isSimple(Instruction *I) {
280 if (LoadInst *LI = dyn_cast<LoadInst>(I))
281 return LI->isSimple();
282 if (StoreInst *SI = dyn_cast<StoreInst>(I))
283 return SI->isSimple();
284 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
285 return !MI->isVolatile();
290 namespace slpvectorizer {
291 /// Bottom Up SLP Vectorizer.
294 typedef SmallVector<Value *, 8> ValueList;
295 typedef SmallVector<Instruction *, 16> InstrList;
296 typedef SmallPtrSet<Value *, 16> ValueSet;
297 typedef SmallVector<StoreInst *, 8> StoreList;
298 typedef MapVector<Value *, SmallVector<Instruction *, 2>>
299 ExtraValueToDebugLocsMap;
301 BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
302 TargetLibraryInfo *TLi, AliasAnalysis *Aa, LoopInfo *Li,
303 DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB,
304 const DataLayout *DL, OptimizationRemarkEmitter *ORE)
305 : NumLoadsWantToKeepOrder(0), NumLoadsWantToChangeOrder(0), F(Func),
306 SE(Se), TTI(Tti), TLI(TLi), AA(Aa), LI(Li), DT(Dt), AC(AC), DB(DB),
307 DL(DL), ORE(ORE), Builder(Se->getContext()) {
308 CodeMetrics::collectEphemeralValues(F, AC, EphValues);
309 // Use the vector register size specified by the target unless overridden
310 // by a command-line option.
311 // TODO: It would be better to limit the vectorization factor based on
312 // data type rather than just register size. For example, x86 AVX has
313 // 256-bit registers, but it does not support integer operations
314 // at that width (that requires AVX2).
315 if (MaxVectorRegSizeOption.getNumOccurrences())
316 MaxVecRegSize = MaxVectorRegSizeOption;
318 MaxVecRegSize = TTI->getRegisterBitWidth(true);
320 if (MinVectorRegSizeOption.getNumOccurrences())
321 MinVecRegSize = MinVectorRegSizeOption;
323 MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
326 /// \brief Vectorize the tree that starts with the elements in \p VL.
327 /// Returns the vectorized root.
328 Value *vectorizeTree();
329 /// Vectorize the tree but with the list of externally used values \p
330 /// ExternallyUsedValues. Values in this MapVector can be replaced but the
331 /// generated extractvalue instructions.
332 Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues);
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);
346 /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
347 /// the purpose of scheduling and extraction in the \p UserIgnoreLst taking
348 /// into account (anf updating it, if required) list of externally used
349 /// values stored in \p ExternallyUsedValues.
350 void buildTree(ArrayRef<Value *> Roots,
351 ExtraValueToDebugLocsMap &ExternallyUsedValues,
352 ArrayRef<Value *> UserIgnoreLst = None);
354 /// Clear the internal data structures that are created by 'buildTree'.
356 VectorizableTree.clear();
357 ScalarToTreeEntry.clear();
359 ExternalUses.clear();
360 NumLoadsWantToKeepOrder = 0;
361 NumLoadsWantToChangeOrder = 0;
362 for (auto &Iter : BlocksSchedules) {
363 BlockScheduling *BS = Iter.second.get();
369 unsigned getTreeSize() const { return VectorizableTree.size(); }
371 /// \brief Perform LICM and CSE on the newly generated gather sequences.
372 void optimizeGatherSequence();
374 /// \returns true if it is beneficial to reverse the vector order.
375 bool shouldReorder() const {
376 return NumLoadsWantToChangeOrder > NumLoadsWantToKeepOrder;
379 /// \return The vector element size in bits to use when vectorizing the
380 /// expression tree ending at \p V. If V is a store, the size is the width of
381 /// the stored value. Otherwise, the size is the width of the largest loaded
382 /// value reaching V. This method is used by the vectorizer to calculate
383 /// vectorization factors.
384 unsigned getVectorElementSize(Value *V);
386 /// Compute the minimum type sizes required to represent the entries in a
387 /// vectorizable tree.
388 void computeMinimumValueSizes();
390 // \returns maximum vector register size as set by TTI or overridden by cl::opt.
391 unsigned getMaxVecRegSize() const {
392 return MaxVecRegSize;
395 // \returns minimum vector register size as set by cl::opt.
396 unsigned getMinVecRegSize() const {
397 return MinVecRegSize;
400 /// \brief Check if ArrayType or StructType is isomorphic to some VectorType.
402 /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
403 unsigned canMapToVector(Type *T, const DataLayout &DL) const;
405 /// \returns True if the VectorizableTree is both tiny and not fully
406 /// vectorizable. We do not vectorize such trees.
407 bool isTreeTinyAndNotFullyVectorizable();
409 OptimizationRemarkEmitter *getORE() { return ORE; }
414 /// \returns the cost of the vectorizable entry.
415 int getEntryCost(TreeEntry *E);
417 /// This is the recursive part of buildTree.
418 void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth, int);
420 /// \returns True if the ExtractElement/ExtractValue instructions in VL can
421 /// be vectorized to use the original vector (or aggregate "bitcast" to a vector).
422 bool canReuseExtract(ArrayRef<Value *> VL, unsigned Opcode) const;
424 /// Vectorize a single entry in the tree.
425 Value *vectorizeTree(TreeEntry *E);
427 /// Vectorize a single entry in the tree, starting in \p VL.
428 Value *vectorizeTree(ArrayRef<Value *> VL);
430 /// \returns the pointer to the vectorized value if \p VL is already
431 /// vectorized, or NULL. They may happen in cycles.
432 Value *alreadyVectorized(ArrayRef<Value *> VL) const;
434 /// \returns the scalarization cost for this type. Scalarization in this
435 /// context means the creation of vectors from a group of scalars.
436 int getGatherCost(Type *Ty);
438 /// \returns the scalarization cost for this list of values. Assuming that
439 /// this subtree gets vectorized, we may need to extract the values from the
440 /// roots. This method calculates the cost of extracting the values.
441 int getGatherCost(ArrayRef<Value *> VL);
443 /// \brief Set the Builder insert point to one after the last instruction in
445 void setInsertPointAfterBundle(ArrayRef<Value *> VL);
447 /// \returns a vector from a collection of scalars in \p VL.
448 Value *Gather(ArrayRef<Value *> VL, VectorType *Ty);
450 /// \returns whether the VectorizableTree is fully vectorizable and will
451 /// be beneficial even the tree height is tiny.
452 bool isFullyVectorizableTinyTree();
454 /// \reorder commutative operands in alt shuffle if they result in
456 void reorderAltShuffleOperands(ArrayRef<Value *> VL,
457 SmallVectorImpl<Value *> &Left,
458 SmallVectorImpl<Value *> &Right);
459 /// \reorder commutative operands to get better probability of
460 /// generating vectorized code.
461 void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
462 SmallVectorImpl<Value *> &Left,
463 SmallVectorImpl<Value *> &Right);
465 TreeEntry(std::vector<TreeEntry> &Container)
466 : Scalars(), VectorizedValue(nullptr), NeedToGather(0),
467 Container(Container) {}
469 /// \returns true if the scalars in VL are equal to this entry.
470 bool isSame(ArrayRef<Value *> VL) const {
471 assert(VL.size() == Scalars.size() && "Invalid size");
472 return std::equal(VL.begin(), VL.end(), Scalars.begin());
475 /// A vector of scalars.
478 /// The Scalars are vectorized into this value. It is initialized to Null.
479 Value *VectorizedValue;
481 /// Do we need to gather this sequence ?
484 /// Points back to the VectorizableTree.
486 /// Only used for Graphviz right now. Unfortunately GraphTrait::NodeRef has
487 /// to be a pointer and needs to be able to initialize the child iterator.
488 /// Thus we need a reference back to the container to translate the indices
490 std::vector<TreeEntry> &Container;
492 /// The TreeEntry index containing the user of this entry. We can actually
493 /// have multiple users so the data structure is not truly a tree.
494 SmallVector<int, 1> UserTreeIndices;
497 /// Create a new VectorizableTree entry.
498 TreeEntry *newTreeEntry(ArrayRef<Value *> VL, bool Vectorized,
500 VectorizableTree.emplace_back(VectorizableTree);
501 int idx = VectorizableTree.size() - 1;
502 TreeEntry *Last = &VectorizableTree[idx];
503 Last->Scalars.insert(Last->Scalars.begin(), VL.begin(), VL.end());
504 Last->NeedToGather = !Vectorized;
506 for (int i = 0, e = VL.size(); i != e; ++i) {
507 assert(!ScalarToTreeEntry.count(VL[i]) && "Scalar already in tree!");
508 ScalarToTreeEntry[VL[i]] = idx;
511 MustGather.insert(VL.begin(), VL.end());
514 if (UserTreeIdx >= 0)
515 Last->UserTreeIndices.push_back(UserTreeIdx);
520 /// -- Vectorization State --
521 /// Holds all of the tree entries.
522 std::vector<TreeEntry> VectorizableTree;
524 /// Maps a specific scalar to its tree entry.
525 SmallDenseMap<Value*, int> ScalarToTreeEntry;
527 /// A list of scalars that we found that we need to keep as scalars.
530 /// This POD struct describes one external user in the vectorized tree.
531 struct ExternalUser {
532 ExternalUser (Value *S, llvm::User *U, int L) :
533 Scalar(S), User(U), Lane(L){}
534 // Which scalar in our function.
536 // Which user that uses the scalar.
538 // Which lane does the scalar belong to.
541 typedef SmallVector<ExternalUser, 16> UserList;
543 /// Checks if two instructions may access the same memory.
545 /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
546 /// is invariant in the calling loop.
547 bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
548 Instruction *Inst2) {
550 // First check if the result is already in the cache.
551 AliasCacheKey key = std::make_pair(Inst1, Inst2);
552 Optional<bool> &result = AliasCache[key];
553 if (result.hasValue()) {
554 return result.getValue();
556 MemoryLocation Loc2 = getLocation(Inst2, AA);
558 if (Loc1.Ptr && Loc2.Ptr && isSimple(Inst1) && isSimple(Inst2)) {
559 // Do the alias check.
560 aliased = AA->alias(Loc1, Loc2);
562 // Store the result in the cache.
567 typedef std::pair<Instruction *, Instruction *> AliasCacheKey;
569 /// Cache for alias results.
570 /// TODO: consider moving this to the AliasAnalysis itself.
571 DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
573 /// Removes an instruction from its block and eventually deletes it.
574 /// It's like Instruction::eraseFromParent() except that the actual deletion
575 /// is delayed until BoUpSLP is destructed.
576 /// This is required to ensure that there are no incorrect collisions in the
577 /// AliasCache, which can happen if a new instruction is allocated at the
578 /// same address as a previously deleted instruction.
579 void eraseInstruction(Instruction *I) {
580 I->removeFromParent();
581 I->dropAllReferences();
582 DeletedInstructions.emplace_back(I);
585 /// Temporary store for deleted instructions. Instructions will be deleted
586 /// eventually when the BoUpSLP is destructed.
587 SmallVector<unique_value, 8> DeletedInstructions;
589 /// A list of values that need to extracted out of the tree.
590 /// This list holds pairs of (Internal Scalar : External User). External User
591 /// can be nullptr, it means that this Internal Scalar will be used later,
592 /// after vectorization.
593 UserList ExternalUses;
595 /// Values used only by @llvm.assume calls.
596 SmallPtrSet<const Value *, 32> EphValues;
598 /// Holds all of the instructions that we gathered.
599 SetVector<Instruction *> GatherSeq;
600 /// A list of blocks that we are going to CSE.
601 SetVector<BasicBlock *> CSEBlocks;
603 /// Contains all scheduling relevant data for an instruction.
604 /// A ScheduleData either represents a single instruction or a member of an
605 /// instruction bundle (= a group of instructions which is combined into a
606 /// vector instruction).
607 struct ScheduleData {
609 // The initial value for the dependency counters. It means that the
610 // dependencies are not calculated yet.
611 enum { InvalidDeps = -1 };
614 : Inst(nullptr), FirstInBundle(nullptr), NextInBundle(nullptr),
615 NextLoadStore(nullptr), SchedulingRegionID(0), SchedulingPriority(0),
616 Dependencies(InvalidDeps), UnscheduledDeps(InvalidDeps),
617 UnscheduledDepsInBundle(InvalidDeps), IsScheduled(false) {}
619 void init(int BlockSchedulingRegionID) {
620 FirstInBundle = this;
621 NextInBundle = nullptr;
622 NextLoadStore = nullptr;
624 SchedulingRegionID = BlockSchedulingRegionID;
625 UnscheduledDepsInBundle = UnscheduledDeps;
629 /// Returns true if the dependency information has been calculated.
630 bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
632 /// Returns true for single instructions and for bundle representatives
633 /// (= the head of a bundle).
634 bool isSchedulingEntity() const { return FirstInBundle == this; }
636 /// Returns true if it represents an instruction bundle and not only a
637 /// single instruction.
638 bool isPartOfBundle() const {
639 return NextInBundle != nullptr || FirstInBundle != this;
642 /// Returns true if it is ready for scheduling, i.e. it has no more
643 /// unscheduled depending instructions/bundles.
644 bool isReady() const {
645 assert(isSchedulingEntity() &&
646 "can't consider non-scheduling entity for ready list");
647 return UnscheduledDepsInBundle == 0 && !IsScheduled;
650 /// Modifies the number of unscheduled dependencies, also updating it for
651 /// the whole bundle.
652 int incrementUnscheduledDeps(int Incr) {
653 UnscheduledDeps += Incr;
654 return FirstInBundle->UnscheduledDepsInBundle += Incr;
657 /// Sets the number of unscheduled dependencies to the number of
659 void resetUnscheduledDeps() {
660 incrementUnscheduledDeps(Dependencies - UnscheduledDeps);
663 /// Clears all dependency information.
664 void clearDependencies() {
665 Dependencies = InvalidDeps;
666 resetUnscheduledDeps();
667 MemoryDependencies.clear();
670 void dump(raw_ostream &os) const {
671 if (!isSchedulingEntity()) {
673 } else if (NextInBundle) {
675 ScheduleData *SD = NextInBundle;
677 os << ';' << *SD->Inst;
678 SD = SD->NextInBundle;
688 /// Points to the head in an instruction bundle (and always to this for
689 /// single instructions).
690 ScheduleData *FirstInBundle;
692 /// Single linked list of all instructions in a bundle. Null if it is a
693 /// single instruction.
694 ScheduleData *NextInBundle;
696 /// Single linked list of all memory instructions (e.g. load, store, call)
697 /// in the block - until the end of the scheduling region.
698 ScheduleData *NextLoadStore;
700 /// The dependent memory instructions.
701 /// This list is derived on demand in calculateDependencies().
702 SmallVector<ScheduleData *, 4> MemoryDependencies;
704 /// This ScheduleData is in the current scheduling region if this matches
705 /// the current SchedulingRegionID of BlockScheduling.
706 int SchedulingRegionID;
708 /// Used for getting a "good" final ordering of instructions.
709 int SchedulingPriority;
711 /// The number of dependencies. Constitutes of the number of users of the
712 /// instruction plus the number of dependent memory instructions (if any).
713 /// This value is calculated on demand.
714 /// If InvalidDeps, the number of dependencies is not calculated yet.
718 /// The number of dependencies minus the number of dependencies of scheduled
719 /// instructions. As soon as this is zero, the instruction/bundle gets ready
721 /// Note that this is negative as long as Dependencies is not calculated.
724 /// The sum of UnscheduledDeps in a bundle. Equals to UnscheduledDeps for
725 /// single instructions.
726 int UnscheduledDepsInBundle;
728 /// True if this instruction is scheduled (or considered as scheduled in the
734 friend inline raw_ostream &operator<<(raw_ostream &os,
735 const BoUpSLP::ScheduleData &SD) {
740 friend struct GraphTraits<BoUpSLP *>;
741 friend struct DOTGraphTraits<BoUpSLP *>;
743 /// Contains all scheduling data for a basic block.
745 struct BlockScheduling {
747 BlockScheduling(BasicBlock *BB)
748 : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize),
749 ScheduleStart(nullptr), ScheduleEnd(nullptr),
750 FirstLoadStoreInRegion(nullptr), LastLoadStoreInRegion(nullptr),
751 ScheduleRegionSize(0),
752 ScheduleRegionSizeLimit(ScheduleRegionSizeBudget),
753 // Make sure that the initial SchedulingRegionID is greater than the
754 // initial SchedulingRegionID in ScheduleData (which is 0).
755 SchedulingRegionID(1) {}
759 ScheduleStart = nullptr;
760 ScheduleEnd = nullptr;
761 FirstLoadStoreInRegion = nullptr;
762 LastLoadStoreInRegion = nullptr;
764 // Reduce the maximum schedule region size by the size of the
765 // previous scheduling run.
766 ScheduleRegionSizeLimit -= ScheduleRegionSize;
767 if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
768 ScheduleRegionSizeLimit = MinScheduleRegionSize;
769 ScheduleRegionSize = 0;
771 // Make a new scheduling region, i.e. all existing ScheduleData is not
772 // in the new region yet.
773 ++SchedulingRegionID;
776 ScheduleData *getScheduleData(Value *V) {
777 ScheduleData *SD = ScheduleDataMap[V];
778 if (SD && SD->SchedulingRegionID == SchedulingRegionID)
783 bool isInSchedulingRegion(ScheduleData *SD) {
784 return SD->SchedulingRegionID == SchedulingRegionID;
787 /// Marks an instruction as scheduled and puts all dependent ready
788 /// instructions into the ready-list.
789 template <typename ReadyListType>
790 void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
791 SD->IsScheduled = true;
792 DEBUG(dbgs() << "SLP: schedule " << *SD << "\n");
794 ScheduleData *BundleMember = SD;
795 while (BundleMember) {
796 // Handle the def-use chain dependencies.
797 for (Use &U : BundleMember->Inst->operands()) {
798 ScheduleData *OpDef = getScheduleData(U.get());
799 if (OpDef && OpDef->hasValidDependencies() &&
800 OpDef->incrementUnscheduledDeps(-1) == 0) {
801 // There are no more unscheduled dependencies after decrementing,
802 // so we can put the dependent instruction into the ready list.
803 ScheduleData *DepBundle = OpDef->FirstInBundle;
804 assert(!DepBundle->IsScheduled &&
805 "already scheduled bundle gets ready");
806 ReadyList.insert(DepBundle);
807 DEBUG(dbgs() << "SLP: gets ready (def): " << *DepBundle << "\n");
810 // Handle the memory dependencies.
811 for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
812 if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
813 // There are no more unscheduled dependencies after decrementing,
814 // so we can put the dependent instruction into the ready list.
815 ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
816 assert(!DepBundle->IsScheduled &&
817 "already scheduled bundle gets ready");
818 ReadyList.insert(DepBundle);
819 DEBUG(dbgs() << "SLP: gets ready (mem): " << *DepBundle << "\n");
822 BundleMember = BundleMember->NextInBundle;
826 /// Put all instructions into the ReadyList which are ready for scheduling.
827 template <typename ReadyListType>
828 void initialFillReadyList(ReadyListType &ReadyList) {
829 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
830 ScheduleData *SD = getScheduleData(I);
831 if (SD->isSchedulingEntity() && SD->isReady()) {
832 ReadyList.insert(SD);
833 DEBUG(dbgs() << "SLP: initially in ready list: " << *I << "\n");
838 /// Checks if a bundle of instructions can be scheduled, i.e. has no
839 /// cyclic dependencies. This is only a dry-run, no instructions are
840 /// actually moved at this stage.
841 bool tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP);
843 /// Un-bundles a group of instructions.
844 void cancelScheduling(ArrayRef<Value *> VL);
846 /// Extends the scheduling region so that V is inside the region.
847 /// \returns true if the region size is within the limit.
848 bool extendSchedulingRegion(Value *V);
850 /// Initialize the ScheduleData structures for new instructions in the
851 /// scheduling region.
852 void initScheduleData(Instruction *FromI, Instruction *ToI,
853 ScheduleData *PrevLoadStore,
854 ScheduleData *NextLoadStore);
856 /// Updates the dependency information of a bundle and of all instructions/
857 /// bundles which depend on the original bundle.
858 void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
861 /// Sets all instruction in the scheduling region to un-scheduled.
862 void resetSchedule();
866 /// Simple memory allocation for ScheduleData.
867 std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
869 /// The size of a ScheduleData array in ScheduleDataChunks.
872 /// The allocator position in the current chunk, which is the last entry
873 /// of ScheduleDataChunks.
876 /// Attaches ScheduleData to Instruction.
877 /// Note that the mapping survives during all vectorization iterations, i.e.
878 /// ScheduleData structures are recycled.
879 DenseMap<Value *, ScheduleData *> ScheduleDataMap;
881 struct ReadyList : SmallVector<ScheduleData *, 8> {
882 void insert(ScheduleData *SD) { push_back(SD); }
885 /// The ready-list for scheduling (only used for the dry-run).
886 ReadyList ReadyInsts;
888 /// The first instruction of the scheduling region.
889 Instruction *ScheduleStart;
891 /// The first instruction _after_ the scheduling region.
892 Instruction *ScheduleEnd;
894 /// The first memory accessing instruction in the scheduling region
896 ScheduleData *FirstLoadStoreInRegion;
898 /// The last memory accessing instruction in the scheduling region
900 ScheduleData *LastLoadStoreInRegion;
902 /// The current size of the scheduling region.
903 int ScheduleRegionSize;
905 /// The maximum size allowed for the scheduling region.
906 int ScheduleRegionSizeLimit;
908 /// The ID of the scheduling region. For a new vectorization iteration this
909 /// is incremented which "removes" all ScheduleData from the region.
910 int SchedulingRegionID;
913 /// Attaches the BlockScheduling structures to basic blocks.
914 MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
916 /// Performs the "real" scheduling. Done before vectorization is actually
917 /// performed in a basic block.
918 void scheduleBlock(BlockScheduling *BS);
920 /// List of users to ignore during scheduling and that don't need extracting.
921 ArrayRef<Value *> UserIgnoreList;
923 // Number of load bundles that contain consecutive loads.
924 int NumLoadsWantToKeepOrder;
926 // Number of load bundles that contain consecutive loads in reversed order.
927 int NumLoadsWantToChangeOrder;
929 // Analysis and block reference.
932 TargetTransformInfo *TTI;
933 TargetLibraryInfo *TLI;
939 const DataLayout *DL;
940 OptimizationRemarkEmitter *ORE;
942 unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
943 unsigned MinVecRegSize; // Set by cl::opt (default: 128).
944 /// Instruction builder to construct the vectorized tree.
947 /// A map of scalar integer values to the smallest bit width with which they
948 /// can legally be represented. The values map to (width, signed) pairs,
949 /// where "width" indicates the minimum bit width and "signed" is True if the
950 /// value must be signed-extended, rather than zero-extended, back to its
952 MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
954 } // end namespace slpvectorizer
956 template <> struct GraphTraits<BoUpSLP *> {
957 typedef BoUpSLP::TreeEntry TreeEntry;
959 /// NodeRef has to be a pointer per the GraphWriter.
960 typedef TreeEntry *NodeRef;
962 /// \brief Add the VectorizableTree to the index iterator to be able to return
963 /// TreeEntry pointers.
964 struct ChildIteratorType
965 : public iterator_adaptor_base<ChildIteratorType,
966 SmallVector<int, 1>::iterator> {
968 std::vector<TreeEntry> &VectorizableTree;
970 ChildIteratorType(SmallVector<int, 1>::iterator W,
971 std::vector<TreeEntry> &VT)
972 : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
974 NodeRef operator*() { return &VectorizableTree[*I]; }
977 static NodeRef getEntryNode(BoUpSLP &R) { return &R.VectorizableTree[0]; }
979 static ChildIteratorType child_begin(NodeRef N) {
980 return {N->UserTreeIndices.begin(), N->Container};
982 static ChildIteratorType child_end(NodeRef N) {
983 return {N->UserTreeIndices.end(), N->Container};
986 /// For the node iterator we just need to turn the TreeEntry iterator into a
987 /// TreeEntry* iterator so that it dereferences to NodeRef.
988 typedef pointer_iterator<std::vector<TreeEntry>::iterator> nodes_iterator;
990 static nodes_iterator nodes_begin(BoUpSLP *R) {
991 return nodes_iterator(R->VectorizableTree.begin());
993 static nodes_iterator nodes_end(BoUpSLP *R) {
994 return nodes_iterator(R->VectorizableTree.end());
997 static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
1000 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
1001 typedef BoUpSLP::TreeEntry TreeEntry;
1003 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
1005 std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
1007 raw_string_ostream OS(Str);
1008 if (isSplat(Entry->Scalars)) {
1009 OS << "<splat> " << *Entry->Scalars[0];
1012 for (auto V : Entry->Scalars) {
1015 R->ExternalUses.begin(), R->ExternalUses.end(),
1016 [&](const BoUpSLP::ExternalUser &EU) { return EU.Scalar == V; }))
1023 static std::string getNodeAttributes(const TreeEntry *Entry,
1025 if (Entry->NeedToGather)
1031 } // end namespace llvm
1033 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
1034 ArrayRef<Value *> UserIgnoreLst) {
1035 ExtraValueToDebugLocsMap ExternallyUsedValues;
1036 buildTree(Roots, ExternallyUsedValues, UserIgnoreLst);
1038 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
1039 ExtraValueToDebugLocsMap &ExternallyUsedValues,
1040 ArrayRef<Value *> UserIgnoreLst) {
1042 UserIgnoreList = UserIgnoreLst;
1043 if (!allSameType(Roots))
1045 buildTree_rec(Roots, 0, -1);
1047 // Collect the values that we need to extract from the tree.
1048 for (TreeEntry &EIdx : VectorizableTree) {
1049 TreeEntry *Entry = &EIdx;
1052 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
1053 Value *Scalar = Entry->Scalars[Lane];
1055 // No need to handle users of gathered values.
1056 if (Entry->NeedToGather)
1059 // Check if the scalar is externally used as an extra arg.
1060 auto ExtI = ExternallyUsedValues.find(Scalar);
1061 if (ExtI != ExternallyUsedValues.end()) {
1062 DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane " <<
1063 Lane << " from " << *Scalar << ".\n");
1064 ExternalUses.emplace_back(Scalar, nullptr, Lane);
1067 for (User *U : Scalar->users()) {
1068 DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
1070 Instruction *UserInst = dyn_cast<Instruction>(U);
1074 // Skip in-tree scalars that become vectors
1075 if (ScalarToTreeEntry.count(U)) {
1076 int Idx = ScalarToTreeEntry[U];
1077 TreeEntry *UseEntry = &VectorizableTree[Idx];
1078 Value *UseScalar = UseEntry->Scalars[0];
1079 // Some in-tree scalars will remain as scalar in vectorized
1080 // instructions. If that is the case, the one in Lane 0 will
1082 if (UseScalar != U ||
1083 !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
1084 DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
1086 assert(!VectorizableTree[Idx].NeedToGather && "Bad state");
1091 // Ignore users in the user ignore list.
1092 if (is_contained(UserIgnoreList, UserInst))
1095 DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane " <<
1096 Lane << " from " << *Scalar << ".\n");
1097 ExternalUses.push_back(ExternalUser(Scalar, U, Lane));
1103 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
1105 bool isAltShuffle = false;
1106 assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
1108 if (Depth == RecursionMaxDepth) {
1109 DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
1110 newTreeEntry(VL, false, UserTreeIdx);
1114 // Don't handle vectors.
1115 if (VL[0]->getType()->isVectorTy()) {
1116 DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
1117 newTreeEntry(VL, false, UserTreeIdx);
1121 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1122 if (SI->getValueOperand()->getType()->isVectorTy()) {
1123 DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
1124 newTreeEntry(VL, false, UserTreeIdx);
1127 unsigned Opcode = getSameOpcode(VL);
1129 // Check that this shuffle vector refers to the alternate
1130 // sequence of opcodes.
1131 if (Opcode == Instruction::ShuffleVector) {
1132 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
1133 unsigned Op = I0->getOpcode();
1134 if (Op != Instruction::ShuffleVector)
1135 isAltShuffle = true;
1138 // If all of the operands are identical or constant we have a simple solution.
1139 if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !Opcode) {
1140 DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
1141 newTreeEntry(VL, false, UserTreeIdx);
1145 // We now know that this is a vector of instructions of the same type from
1148 // Don't vectorize ephemeral values.
1149 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1150 if (EphValues.count(VL[i])) {
1151 DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
1152 ") is ephemeral.\n");
1153 newTreeEntry(VL, false, UserTreeIdx);
1158 // Check if this is a duplicate of another entry.
1159 if (ScalarToTreeEntry.count(VL[0])) {
1160 int Idx = ScalarToTreeEntry[VL[0]];
1161 TreeEntry *E = &VectorizableTree[Idx];
1162 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1163 DEBUG(dbgs() << "SLP: \tChecking bundle: " << *VL[i] << ".\n");
1164 if (E->Scalars[i] != VL[i]) {
1165 DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
1166 newTreeEntry(VL, false, UserTreeIdx);
1170 // Record the reuse of the tree node. FIXME, currently this is only used to
1171 // properly draw the graph rather than for the actual vectorization.
1172 E->UserTreeIndices.push_back(UserTreeIdx);
1173 DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *VL[0] << ".\n");
1177 // Check that none of the instructions in the bundle are already in the tree.
1178 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1179 if (ScalarToTreeEntry.count(VL[i])) {
1180 DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
1181 ") is already in tree.\n");
1182 newTreeEntry(VL, false, UserTreeIdx);
1187 // If any of the scalars is marked as a value that needs to stay scalar then
1188 // we need to gather the scalars.
1189 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1190 if (MustGather.count(VL[i])) {
1191 DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
1192 newTreeEntry(VL, false, UserTreeIdx);
1197 // Check that all of the users of the scalars that we want to vectorize are
1199 Instruction *VL0 = cast<Instruction>(VL[0]);
1200 BasicBlock *BB = cast<Instruction>(VL0)->getParent();
1202 if (!DT->isReachableFromEntry(BB)) {
1203 // Don't go into unreachable blocks. They may contain instructions with
1204 // dependency cycles which confuse the final scheduling.
1205 DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
1206 newTreeEntry(VL, false, UserTreeIdx);
1210 // Check that every instructions appears once in this bundle.
1211 for (unsigned i = 0, e = VL.size(); i < e; ++i)
1212 for (unsigned j = i+1; j < e; ++j)
1213 if (VL[i] == VL[j]) {
1214 DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
1215 newTreeEntry(VL, false, UserTreeIdx);
1219 auto &BSRef = BlocksSchedules[BB];
1221 BSRef = llvm::make_unique<BlockScheduling>(BB);
1223 BlockScheduling &BS = *BSRef.get();
1225 if (!BS.tryScheduleBundle(VL, this)) {
1226 DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
1227 assert((!BS.getScheduleData(VL[0]) ||
1228 !BS.getScheduleData(VL[0])->isPartOfBundle()) &&
1229 "tryScheduleBundle should cancelScheduling on failure");
1230 newTreeEntry(VL, false, UserTreeIdx);
1233 DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
1236 case Instruction::PHI: {
1237 PHINode *PH = dyn_cast<PHINode>(VL0);
1239 // Check for terminator values (e.g. invoke).
1240 for (unsigned j = 0; j < VL.size(); ++j)
1241 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1242 TerminatorInst *Term = dyn_cast<TerminatorInst>(
1243 cast<PHINode>(VL[j])->getIncomingValueForBlock(PH->getIncomingBlock(i)));
1245 DEBUG(dbgs() << "SLP: Need to swizzle PHINodes (TerminatorInst use).\n");
1246 BS.cancelScheduling(VL);
1247 newTreeEntry(VL, false, UserTreeIdx);
1252 newTreeEntry(VL, true, UserTreeIdx);
1253 DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
1255 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1257 // Prepare the operand vector.
1259 Operands.push_back(cast<PHINode>(j)->getIncomingValueForBlock(
1260 PH->getIncomingBlock(i)));
1262 buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1266 case Instruction::ExtractValue:
1267 case Instruction::ExtractElement: {
1268 bool Reuse = canReuseExtract(VL, Opcode);
1270 DEBUG(dbgs() << "SLP: Reusing extract sequence.\n");
1272 BS.cancelScheduling(VL);
1274 newTreeEntry(VL, Reuse, UserTreeIdx);
1277 case Instruction::Load: {
1278 // Check that a vectorized load would load the same memory as a scalar
1280 // For example we don't want vectorize loads that are smaller than 8 bit.
1281 // Even though we have a packed struct {<i2, i2, i2, i2>} LLVM treats
1282 // loading/storing it as an i8 struct. If we vectorize loads/stores from
1283 // such a struct we read/write packed bits disagreeing with the
1284 // unvectorized version.
1285 Type *ScalarTy = VL[0]->getType();
1287 if (DL->getTypeSizeInBits(ScalarTy) !=
1288 DL->getTypeAllocSizeInBits(ScalarTy)) {
1289 BS.cancelScheduling(VL);
1290 newTreeEntry(VL, false, UserTreeIdx);
1291 DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
1295 // Make sure all loads in the bundle are simple - we can't vectorize
1296 // atomic or volatile loads.
1297 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i) {
1298 LoadInst *L = cast<LoadInst>(VL[i]);
1299 if (!L->isSimple()) {
1300 BS.cancelScheduling(VL);
1301 newTreeEntry(VL, false, UserTreeIdx);
1302 DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
1307 // Check if the loads are consecutive, reversed, or neither.
1308 // TODO: What we really want is to sort the loads, but for now, check
1309 // the two likely directions.
1310 bool Consecutive = true;
1311 bool ReverseConsecutive = true;
1312 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i) {
1313 if (!isConsecutiveAccess(VL[i], VL[i + 1], *DL, *SE)) {
1314 Consecutive = false;
1317 ReverseConsecutive = false;
1322 ++NumLoadsWantToKeepOrder;
1323 newTreeEntry(VL, true, UserTreeIdx);
1324 DEBUG(dbgs() << "SLP: added a vector of loads.\n");
1328 // If none of the load pairs were consecutive when checked in order,
1329 // check the reverse order.
1330 if (ReverseConsecutive)
1331 for (unsigned i = VL.size() - 1; i > 0; --i)
1332 if (!isConsecutiveAccess(VL[i], VL[i - 1], *DL, *SE)) {
1333 ReverseConsecutive = false;
1337 BS.cancelScheduling(VL);
1338 newTreeEntry(VL, false, UserTreeIdx);
1340 if (ReverseConsecutive) {
1341 ++NumLoadsWantToChangeOrder;
1342 DEBUG(dbgs() << "SLP: Gathering reversed loads.\n");
1344 DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
1348 case Instruction::ZExt:
1349 case Instruction::SExt:
1350 case Instruction::FPToUI:
1351 case Instruction::FPToSI:
1352 case Instruction::FPExt:
1353 case Instruction::PtrToInt:
1354 case Instruction::IntToPtr:
1355 case Instruction::SIToFP:
1356 case Instruction::UIToFP:
1357 case Instruction::Trunc:
1358 case Instruction::FPTrunc:
1359 case Instruction::BitCast: {
1360 Type *SrcTy = VL0->getOperand(0)->getType();
1361 for (unsigned i = 0; i < VL.size(); ++i) {
1362 Type *Ty = cast<Instruction>(VL[i])->getOperand(0)->getType();
1363 if (Ty != SrcTy || !isValidElementType(Ty)) {
1364 BS.cancelScheduling(VL);
1365 newTreeEntry(VL, false, UserTreeIdx);
1366 DEBUG(dbgs() << "SLP: Gathering casts with different src types.\n");
1370 newTreeEntry(VL, true, UserTreeIdx);
1371 DEBUG(dbgs() << "SLP: added a vector of casts.\n");
1373 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1375 // Prepare the operand vector.
1377 Operands.push_back(cast<Instruction>(j)->getOperand(i));
1379 buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1383 case Instruction::ICmp:
1384 case Instruction::FCmp: {
1385 // Check that all of the compares have the same predicate.
1386 CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
1387 Type *ComparedTy = cast<Instruction>(VL[0])->getOperand(0)->getType();
1388 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
1389 CmpInst *Cmp = cast<CmpInst>(VL[i]);
1390 if (Cmp->getPredicate() != P0 ||
1391 Cmp->getOperand(0)->getType() != ComparedTy) {
1392 BS.cancelScheduling(VL);
1393 newTreeEntry(VL, false, UserTreeIdx);
1394 DEBUG(dbgs() << "SLP: Gathering cmp with different predicate.\n");
1399 newTreeEntry(VL, true, UserTreeIdx);
1400 DEBUG(dbgs() << "SLP: added a vector of compares.\n");
1402 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1404 // Prepare the operand vector.
1406 Operands.push_back(cast<Instruction>(j)->getOperand(i));
1408 buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1412 case Instruction::Select:
1413 case Instruction::Add:
1414 case Instruction::FAdd:
1415 case Instruction::Sub:
1416 case Instruction::FSub:
1417 case Instruction::Mul:
1418 case Instruction::FMul:
1419 case Instruction::UDiv:
1420 case Instruction::SDiv:
1421 case Instruction::FDiv:
1422 case Instruction::URem:
1423 case Instruction::SRem:
1424 case Instruction::FRem:
1425 case Instruction::Shl:
1426 case Instruction::LShr:
1427 case Instruction::AShr:
1428 case Instruction::And:
1429 case Instruction::Or:
1430 case Instruction::Xor: {
1431 newTreeEntry(VL, true, UserTreeIdx);
1432 DEBUG(dbgs() << "SLP: added a vector of bin op.\n");
1434 // Sort operands of the instructions so that each side is more likely to
1435 // have the same opcode.
1436 if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
1437 ValueList Left, Right;
1438 reorderInputsAccordingToOpcode(VL, Left, Right);
1439 buildTree_rec(Left, Depth + 1, UserTreeIdx);
1440 buildTree_rec(Right, Depth + 1, UserTreeIdx);
1444 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1446 // Prepare the operand vector.
1448 Operands.push_back(cast<Instruction>(j)->getOperand(i));
1450 buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1454 case Instruction::GetElementPtr: {
1455 // We don't combine GEPs with complicated (nested) indexing.
1456 for (unsigned j = 0; j < VL.size(); ++j) {
1457 if (cast<Instruction>(VL[j])->getNumOperands() != 2) {
1458 DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
1459 BS.cancelScheduling(VL);
1460 newTreeEntry(VL, false, UserTreeIdx);
1465 // We can't combine several GEPs into one vector if they operate on
1467 Type *Ty0 = cast<Instruction>(VL0)->getOperand(0)->getType();
1468 for (unsigned j = 0; j < VL.size(); ++j) {
1469 Type *CurTy = cast<Instruction>(VL[j])->getOperand(0)->getType();
1471 DEBUG(dbgs() << "SLP: not-vectorizable GEP (different types).\n");
1472 BS.cancelScheduling(VL);
1473 newTreeEntry(VL, false, UserTreeIdx);
1478 // We don't combine GEPs with non-constant indexes.
1479 for (unsigned j = 0; j < VL.size(); ++j) {
1480 auto Op = cast<Instruction>(VL[j])->getOperand(1);
1481 if (!isa<ConstantInt>(Op)) {
1483 dbgs() << "SLP: not-vectorizable GEP (non-constant indexes).\n");
1484 BS.cancelScheduling(VL);
1485 newTreeEntry(VL, false, UserTreeIdx);
1490 newTreeEntry(VL, true, UserTreeIdx);
1491 DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
1492 for (unsigned i = 0, e = 2; i < e; ++i) {
1494 // Prepare the operand vector.
1496 Operands.push_back(cast<Instruction>(j)->getOperand(i));
1498 buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1502 case Instruction::Store: {
1503 // Check if the stores are consecutive or of we need to swizzle them.
1504 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
1505 if (!isConsecutiveAccess(VL[i], VL[i + 1], *DL, *SE)) {
1506 BS.cancelScheduling(VL);
1507 newTreeEntry(VL, false, UserTreeIdx);
1508 DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
1512 newTreeEntry(VL, true, UserTreeIdx);
1513 DEBUG(dbgs() << "SLP: added a vector of stores.\n");
1517 Operands.push_back(cast<Instruction>(j)->getOperand(0));
1519 buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1522 case Instruction::Call: {
1523 // Check if the calls are all to the same vectorizable intrinsic.
1524 CallInst *CI = cast<CallInst>(VL[0]);
1525 // Check if this is an Intrinsic call or something that can be
1526 // represented by an intrinsic call
1527 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
1528 if (!isTriviallyVectorizable(ID)) {
1529 BS.cancelScheduling(VL);
1530 newTreeEntry(VL, false, UserTreeIdx);
1531 DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
1534 Function *Int = CI->getCalledFunction();
1535 Value *A1I = nullptr;
1536 if (hasVectorInstrinsicScalarOpd(ID, 1))
1537 A1I = CI->getArgOperand(1);
1538 for (unsigned i = 1, e = VL.size(); i != e; ++i) {
1539 CallInst *CI2 = dyn_cast<CallInst>(VL[i]);
1540 if (!CI2 || CI2->getCalledFunction() != Int ||
1541 getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
1542 !CI->hasIdenticalOperandBundleSchema(*CI2)) {
1543 BS.cancelScheduling(VL);
1544 newTreeEntry(VL, false, UserTreeIdx);
1545 DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *VL[i]
1549 // ctlz,cttz and powi are special intrinsics whose second argument
1550 // should be same in order for them to be vectorized.
1551 if (hasVectorInstrinsicScalarOpd(ID, 1)) {
1552 Value *A1J = CI2->getArgOperand(1);
1554 BS.cancelScheduling(VL);
1555 newTreeEntry(VL, false, UserTreeIdx);
1556 DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
1557 << " argument "<< A1I<<"!=" << A1J
1562 // Verify that the bundle operands are identical between the two calls.
1563 if (CI->hasOperandBundles() &&
1564 !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
1565 CI->op_begin() + CI->getBundleOperandsEndIndex(),
1566 CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
1567 BS.cancelScheduling(VL);
1568 newTreeEntry(VL, false, UserTreeIdx);
1569 DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:" << *CI << "!="
1575 newTreeEntry(VL, true, UserTreeIdx);
1576 for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i) {
1578 // Prepare the operand vector.
1579 for (Value *j : VL) {
1580 CallInst *CI2 = dyn_cast<CallInst>(j);
1581 Operands.push_back(CI2->getArgOperand(i));
1583 buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1587 case Instruction::ShuffleVector: {
1588 // If this is not an alternate sequence of opcode like add-sub
1589 // then do not vectorize this instruction.
1590 if (!isAltShuffle) {
1591 BS.cancelScheduling(VL);
1592 newTreeEntry(VL, false, UserTreeIdx);
1593 DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
1596 newTreeEntry(VL, true, UserTreeIdx);
1597 DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
1599 // Reorder operands if reordering would enable vectorization.
1600 if (isa<BinaryOperator>(VL0)) {
1601 ValueList Left, Right;
1602 reorderAltShuffleOperands(VL, Left, Right);
1603 buildTree_rec(Left, Depth + 1, UserTreeIdx);
1604 buildTree_rec(Right, Depth + 1, UserTreeIdx);
1608 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1610 // Prepare the operand vector.
1612 Operands.push_back(cast<Instruction>(j)->getOperand(i));
1614 buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1619 BS.cancelScheduling(VL);
1620 newTreeEntry(VL, false, UserTreeIdx);
1621 DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
1626 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
1629 auto *ST = dyn_cast<StructType>(T);
1631 N = ST->getNumElements();
1632 EltTy = *ST->element_begin();
1634 N = cast<ArrayType>(T)->getNumElements();
1635 EltTy = cast<ArrayType>(T)->getElementType();
1637 if (!isValidElementType(EltTy))
1639 uint64_t VTSize = DL.getTypeStoreSizeInBits(VectorType::get(EltTy, N));
1640 if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
1643 // Check that struct is homogeneous.
1644 for (const auto *Ty : ST->elements())
1651 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, unsigned Opcode) const {
1652 assert(Opcode == Instruction::ExtractElement ||
1653 Opcode == Instruction::ExtractValue);
1654 assert(Opcode == getSameOpcode(VL) && "Invalid opcode");
1655 // Check if all of the extracts come from the same vector and from the
1658 Instruction *E0 = cast<Instruction>(VL0);
1659 Value *Vec = E0->getOperand(0);
1661 // We have to extract from a vector/aggregate with the same number of elements.
1663 if (Opcode == Instruction::ExtractValue) {
1664 const DataLayout &DL = E0->getModule()->getDataLayout();
1665 NElts = canMapToVector(Vec->getType(), DL);
1668 // Check if load can be rewritten as load of vector.
1669 LoadInst *LI = dyn_cast<LoadInst>(Vec);
1670 if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
1673 NElts = Vec->getType()->getVectorNumElements();
1676 if (NElts != VL.size())
1679 // Check that all of the indices extract from the correct offset.
1680 if (!matchExtractIndex(E0, 0, Opcode))
1683 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
1684 Instruction *E = cast<Instruction>(VL[i]);
1685 if (!matchExtractIndex(E, i, Opcode))
1687 if (E->getOperand(0) != Vec)
1694 int BoUpSLP::getEntryCost(TreeEntry *E) {
1695 ArrayRef<Value*> VL = E->Scalars;
1697 Type *ScalarTy = VL[0]->getType();
1698 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1699 ScalarTy = SI->getValueOperand()->getType();
1700 else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
1701 ScalarTy = CI->getOperand(0)->getType();
1702 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1704 // If we have computed a smaller type for the expression, update VecTy so
1705 // that the costs will be accurate.
1706 if (MinBWs.count(VL[0]))
1707 VecTy = VectorType::get(
1708 IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
1710 if (E->NeedToGather) {
1711 if (allConstant(VL))
1714 return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
1716 return getGatherCost(E->Scalars);
1718 unsigned Opcode = getSameOpcode(VL);
1719 assert(Opcode && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
1720 Instruction *VL0 = cast<Instruction>(VL[0]);
1722 case Instruction::PHI: {
1725 case Instruction::ExtractValue:
1726 case Instruction::ExtractElement: {
1727 if (canReuseExtract(VL, Opcode)) {
1729 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
1730 Instruction *E = cast<Instruction>(VL[i]);
1731 // If all users are going to be vectorized, instruction can be
1732 // considered as dead.
1733 // The same, if have only one user, it will be vectorized for sure.
1734 if (E->hasOneUse() ||
1735 std::all_of(E->user_begin(), E->user_end(), [this](User *U) {
1736 return ScalarToTreeEntry.count(U) > 0;
1738 // Take credit for instruction that will become dead.
1740 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, i);
1744 return getGatherCost(VecTy);
1746 case Instruction::ZExt:
1747 case Instruction::SExt:
1748 case Instruction::FPToUI:
1749 case Instruction::FPToSI:
1750 case Instruction::FPExt:
1751 case Instruction::PtrToInt:
1752 case Instruction::IntToPtr:
1753 case Instruction::SIToFP:
1754 case Instruction::UIToFP:
1755 case Instruction::Trunc:
1756 case Instruction::FPTrunc:
1757 case Instruction::BitCast: {
1758 Type *SrcTy = VL0->getOperand(0)->getType();
1760 // Calculate the cost of this instruction.
1761 int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(),
1762 VL0->getType(), SrcTy, VL0);
1764 VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
1765 int VecCost = TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy, VL0);
1766 return VecCost - ScalarCost;
1768 case Instruction::FCmp:
1769 case Instruction::ICmp:
1770 case Instruction::Select: {
1771 // Calculate the cost of this instruction.
1772 VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
1773 int ScalarCost = VecTy->getNumElements() *
1774 TTI->getCmpSelInstrCost(Opcode, ScalarTy, Builder.getInt1Ty(), VL0);
1775 int VecCost = TTI->getCmpSelInstrCost(Opcode, VecTy, MaskTy, VL0);
1776 return VecCost - ScalarCost;
1778 case Instruction::Add:
1779 case Instruction::FAdd:
1780 case Instruction::Sub:
1781 case Instruction::FSub:
1782 case Instruction::Mul:
1783 case Instruction::FMul:
1784 case Instruction::UDiv:
1785 case Instruction::SDiv:
1786 case Instruction::FDiv:
1787 case Instruction::URem:
1788 case Instruction::SRem:
1789 case Instruction::FRem:
1790 case Instruction::Shl:
1791 case Instruction::LShr:
1792 case Instruction::AShr:
1793 case Instruction::And:
1794 case Instruction::Or:
1795 case Instruction::Xor: {
1796 // Certain instructions can be cheaper to vectorize if they have a
1797 // constant second vector operand.
1798 TargetTransformInfo::OperandValueKind Op1VK =
1799 TargetTransformInfo::OK_AnyValue;
1800 TargetTransformInfo::OperandValueKind Op2VK =
1801 TargetTransformInfo::OK_UniformConstantValue;
1802 TargetTransformInfo::OperandValueProperties Op1VP =
1803 TargetTransformInfo::OP_None;
1804 TargetTransformInfo::OperandValueProperties Op2VP =
1805 TargetTransformInfo::OP_None;
1807 // If all operands are exactly the same ConstantInt then set the
1808 // operand kind to OK_UniformConstantValue.
1809 // If instead not all operands are constants, then set the operand kind
1810 // to OK_AnyValue. If all operands are constants but not the same,
1811 // then set the operand kind to OK_NonUniformConstantValue.
1812 ConstantInt *CInt = nullptr;
1813 for (unsigned i = 0; i < VL.size(); ++i) {
1814 const Instruction *I = cast<Instruction>(VL[i]);
1815 if (!isa<ConstantInt>(I->getOperand(1))) {
1816 Op2VK = TargetTransformInfo::OK_AnyValue;
1820 CInt = cast<ConstantInt>(I->getOperand(1));
1823 if (Op2VK == TargetTransformInfo::OK_UniformConstantValue &&
1824 CInt != cast<ConstantInt>(I->getOperand(1)))
1825 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
1827 // FIXME: Currently cost of model modification for division by power of
1828 // 2 is handled for X86 and AArch64. Add support for other targets.
1829 if (Op2VK == TargetTransformInfo::OK_UniformConstantValue && CInt &&
1830 CInt->getValue().isPowerOf2())
1831 Op2VP = TargetTransformInfo::OP_PowerOf2;
1833 SmallVector<const Value *, 4> Operands(VL0->operand_values());
1835 VecTy->getNumElements() *
1836 TTI->getArithmeticInstrCost(Opcode, ScalarTy, Op1VK, Op2VK, Op1VP,
1838 int VecCost = TTI->getArithmeticInstrCost(Opcode, VecTy, Op1VK, Op2VK,
1839 Op1VP, Op2VP, Operands);
1840 return VecCost - ScalarCost;
1842 case Instruction::GetElementPtr: {
1843 TargetTransformInfo::OperandValueKind Op1VK =
1844 TargetTransformInfo::OK_AnyValue;
1845 TargetTransformInfo::OperandValueKind Op2VK =
1846 TargetTransformInfo::OK_UniformConstantValue;
1849 VecTy->getNumElements() *
1850 TTI->getArithmeticInstrCost(Instruction::Add, ScalarTy, Op1VK, Op2VK);
1852 TTI->getArithmeticInstrCost(Instruction::Add, VecTy, Op1VK, Op2VK);
1854 return VecCost - ScalarCost;
1856 case Instruction::Load: {
1857 // Cost of wide load - cost of scalar loads.
1858 unsigned alignment = dyn_cast<LoadInst>(VL0)->getAlignment();
1859 int ScalarLdCost = VecTy->getNumElements() *
1860 TTI->getMemoryOpCost(Instruction::Load, ScalarTy, alignment, 0, VL0);
1861 int VecLdCost = TTI->getMemoryOpCost(Instruction::Load,
1862 VecTy, alignment, 0, VL0);
1863 return VecLdCost - ScalarLdCost;
1865 case Instruction::Store: {
1866 // We know that we can merge the stores. Calculate the cost.
1867 unsigned alignment = dyn_cast<StoreInst>(VL0)->getAlignment();
1868 int ScalarStCost = VecTy->getNumElements() *
1869 TTI->getMemoryOpCost(Instruction::Store, ScalarTy, alignment, 0, VL0);
1870 int VecStCost = TTI->getMemoryOpCost(Instruction::Store,
1871 VecTy, alignment, 0, VL0);
1872 return VecStCost - ScalarStCost;
1874 case Instruction::Call: {
1875 CallInst *CI = cast<CallInst>(VL0);
1876 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
1878 // Calculate the cost of the scalar and vector calls.
1879 SmallVector<Type*, 4> ScalarTys;
1880 for (unsigned op = 0, opc = CI->getNumArgOperands(); op!= opc; ++op)
1881 ScalarTys.push_back(CI->getArgOperand(op)->getType());
1884 if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
1885 FMF = FPMO->getFastMathFlags();
1887 int ScalarCallCost = VecTy->getNumElements() *
1888 TTI->getIntrinsicInstrCost(ID, ScalarTy, ScalarTys, FMF);
1890 SmallVector<Value *, 4> Args(CI->arg_operands());
1891 int VecCallCost = TTI->getIntrinsicInstrCost(ID, CI->getType(), Args, FMF,
1892 VecTy->getNumElements());
1894 DEBUG(dbgs() << "SLP: Call cost "<< VecCallCost - ScalarCallCost
1895 << " (" << VecCallCost << "-" << ScalarCallCost << ")"
1896 << " for " << *CI << "\n");
1898 return VecCallCost - ScalarCallCost;
1900 case Instruction::ShuffleVector: {
1901 TargetTransformInfo::OperandValueKind Op1VK =
1902 TargetTransformInfo::OK_AnyValue;
1903 TargetTransformInfo::OperandValueKind Op2VK =
1904 TargetTransformInfo::OK_AnyValue;
1907 for (Value *i : VL) {
1908 Instruction *I = cast<Instruction>(i);
1912 TTI->getArithmeticInstrCost(I->getOpcode(), ScalarTy, Op1VK, Op2VK);
1914 // VecCost is equal to sum of the cost of creating 2 vectors
1915 // and the cost of creating shuffle.
1916 Instruction *I0 = cast<Instruction>(VL[0]);
1918 TTI->getArithmeticInstrCost(I0->getOpcode(), VecTy, Op1VK, Op2VK);
1919 Instruction *I1 = cast<Instruction>(VL[1]);
1921 TTI->getArithmeticInstrCost(I1->getOpcode(), VecTy, Op1VK, Op2VK);
1923 TTI->getShuffleCost(TargetTransformInfo::SK_Alternate, VecTy, 0);
1924 return VecCost - ScalarCost;
1927 llvm_unreachable("Unknown instruction");
1931 bool BoUpSLP::isFullyVectorizableTinyTree() {
1932 DEBUG(dbgs() << "SLP: Check whether the tree with height " <<
1933 VectorizableTree.size() << " is fully vectorizable .\n");
1935 // We only handle trees of heights 1 and 2.
1936 if (VectorizableTree.size() == 1 && !VectorizableTree[0].NeedToGather)
1939 if (VectorizableTree.size() != 2)
1942 // Handle splat and all-constants stores.
1943 if (!VectorizableTree[0].NeedToGather &&
1944 (allConstant(VectorizableTree[1].Scalars) ||
1945 isSplat(VectorizableTree[1].Scalars)))
1948 // Gathering cost would be too much for tiny trees.
1949 if (VectorizableTree[0].NeedToGather || VectorizableTree[1].NeedToGather)
1955 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable() {
1957 // We can vectorize the tree if its size is greater than or equal to the
1958 // minimum size specified by the MinTreeSize command line option.
1959 if (VectorizableTree.size() >= MinTreeSize)
1962 // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
1963 // can vectorize it if we can prove it fully vectorizable.
1964 if (isFullyVectorizableTinyTree())
1967 assert(VectorizableTree.empty()
1968 ? ExternalUses.empty()
1969 : true && "We shouldn't have any external users");
1971 // Otherwise, we can't vectorize the tree. It is both tiny and not fully
1976 int BoUpSLP::getSpillCost() {
1977 // Walk from the bottom of the tree to the top, tracking which values are
1978 // live. When we see a call instruction that is not part of our tree,
1979 // query TTI to see if there is a cost to keeping values live over it
1980 // (for example, if spills and fills are required).
1981 unsigned BundleWidth = VectorizableTree.front().Scalars.size();
1984 SmallPtrSet<Instruction*, 4> LiveValues;
1985 Instruction *PrevInst = nullptr;
1987 for (const auto &N : VectorizableTree) {
1988 Instruction *Inst = dyn_cast<Instruction>(N.Scalars[0]);
1997 // Update LiveValues.
1998 LiveValues.erase(PrevInst);
1999 for (auto &J : PrevInst->operands()) {
2000 if (isa<Instruction>(&*J) && ScalarToTreeEntry.count(&*J))
2001 LiveValues.insert(cast<Instruction>(&*J));
2005 dbgs() << "SLP: #LV: " << LiveValues.size();
2006 for (auto *X : LiveValues)
2007 dbgs() << " " << X->getName();
2008 dbgs() << ", Looking at ";
2012 // Now find the sequence of instructions between PrevInst and Inst.
2013 BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
2015 PrevInst->getIterator().getReverse();
2016 while (InstIt != PrevInstIt) {
2017 if (PrevInstIt == PrevInst->getParent()->rend()) {
2018 PrevInstIt = Inst->getParent()->rbegin();
2022 if (isa<CallInst>(&*PrevInstIt) && &*PrevInstIt != PrevInst) {
2023 SmallVector<Type*, 4> V;
2024 for (auto *II : LiveValues)
2025 V.push_back(VectorType::get(II->getType(), BundleWidth));
2026 Cost += TTI->getCostOfKeepingLiveOverCall(V);
2038 int BoUpSLP::getTreeCost() {
2040 DEBUG(dbgs() << "SLP: Calculating cost for tree of size " <<
2041 VectorizableTree.size() << ".\n");
2043 unsigned BundleWidth = VectorizableTree[0].Scalars.size();
2045 for (TreeEntry &TE : VectorizableTree) {
2046 int C = getEntryCost(&TE);
2047 DEBUG(dbgs() << "SLP: Adding cost " << C << " for bundle that starts with "
2048 << *TE.Scalars[0] << ".\n");
2052 SmallSet<Value *, 16> ExtractCostCalculated;
2053 int ExtractCost = 0;
2054 for (ExternalUser &EU : ExternalUses) {
2055 // We only add extract cost once for the same scalar.
2056 if (!ExtractCostCalculated.insert(EU.Scalar).second)
2059 // Uses by ephemeral values are free (because the ephemeral value will be
2060 // removed prior to code generation, and so the extraction will be
2061 // removed as well).
2062 if (EphValues.count(EU.User))
2065 // If we plan to rewrite the tree in a smaller type, we will need to sign
2066 // extend the extracted value back to the original type. Here, we account
2067 // for the extract and the added cost of the sign extend if needed.
2068 auto *VecTy = VectorType::get(EU.Scalar->getType(), BundleWidth);
2069 auto *ScalarRoot = VectorizableTree[0].Scalars[0];
2070 if (MinBWs.count(ScalarRoot)) {
2071 auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
2073 MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
2074 VecTy = VectorType::get(MinTy, BundleWidth);
2075 ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
2079 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
2083 int SpillCost = getSpillCost();
2084 Cost += SpillCost + ExtractCost;
2088 raw_string_ostream OS(Str);
2089 OS << "SLP: Spill Cost = " << SpillCost << ".\n"
2090 << "SLP: Extract Cost = " << ExtractCost << ".\n"
2091 << "SLP: Total Cost = " << Cost << ".\n";
2093 DEBUG(dbgs() << Str);
2096 ViewGraph(this, "SLP" + F->getName(), false, Str);
2101 int BoUpSLP::getGatherCost(Type *Ty) {
2103 for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
2104 Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
2108 int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) {
2109 // Find the type of the operands in VL.
2110 Type *ScalarTy = VL[0]->getType();
2111 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
2112 ScalarTy = SI->getValueOperand()->getType();
2113 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
2114 // Find the cost of inserting/extracting values from the vector.
2115 return getGatherCost(VecTy);
2118 // Reorder commutative operations in alternate shuffle if the resulting vectors
2119 // are consecutive loads. This would allow us to vectorize the tree.
2120 // If we have something like-
2121 // load a[0] - load b[0]
2122 // load b[1] + load a[1]
2123 // load a[2] - load b[2]
2124 // load a[3] + load b[3]
2125 // Reordering the second load b[1] load a[1] would allow us to vectorize this
2127 void BoUpSLP::reorderAltShuffleOperands(ArrayRef<Value *> VL,
2128 SmallVectorImpl<Value *> &Left,
2129 SmallVectorImpl<Value *> &Right) {
2130 // Push left and right operands of binary operation into Left and Right
2131 for (Value *i : VL) {
2132 Left.push_back(cast<Instruction>(i)->getOperand(0));
2133 Right.push_back(cast<Instruction>(i)->getOperand(1));
2136 // Reorder if we have a commutative operation and consecutive access
2137 // are on either side of the alternate instructions.
2138 for (unsigned j = 0; j < VL.size() - 1; ++j) {
2139 if (LoadInst *L = dyn_cast<LoadInst>(Left[j])) {
2140 if (LoadInst *L1 = dyn_cast<LoadInst>(Right[j + 1])) {
2141 Instruction *VL1 = cast<Instruction>(VL[j]);
2142 Instruction *VL2 = cast<Instruction>(VL[j + 1]);
2143 if (VL1->isCommutative() && isConsecutiveAccess(L, L1, *DL, *SE)) {
2144 std::swap(Left[j], Right[j]);
2146 } else if (VL2->isCommutative() &&
2147 isConsecutiveAccess(L, L1, *DL, *SE)) {
2148 std::swap(Left[j + 1], Right[j + 1]);
2154 if (LoadInst *L = dyn_cast<LoadInst>(Right[j])) {
2155 if (LoadInst *L1 = dyn_cast<LoadInst>(Left[j + 1])) {
2156 Instruction *VL1 = cast<Instruction>(VL[j]);
2157 Instruction *VL2 = cast<Instruction>(VL[j + 1]);
2158 if (VL1->isCommutative() && isConsecutiveAccess(L, L1, *DL, *SE)) {
2159 std::swap(Left[j], Right[j]);
2161 } else if (VL2->isCommutative() &&
2162 isConsecutiveAccess(L, L1, *DL, *SE)) {
2163 std::swap(Left[j + 1], Right[j + 1]);
2172 // Return true if I should be commuted before adding it's left and right
2173 // operands to the arrays Left and Right.
2175 // The vectorizer is trying to either have all elements one side being
2176 // instruction with the same opcode to enable further vectorization, or having
2177 // a splat to lower the vectorizing cost.
2178 static bool shouldReorderOperands(int i, Instruction &I,
2179 SmallVectorImpl<Value *> &Left,
2180 SmallVectorImpl<Value *> &Right,
2181 bool AllSameOpcodeLeft,
2182 bool AllSameOpcodeRight, bool SplatLeft,
2184 Value *VLeft = I.getOperand(0);
2185 Value *VRight = I.getOperand(1);
2186 // If we have "SplatRight", try to see if commuting is needed to preserve it.
2188 if (VRight == Right[i - 1])
2189 // Preserve SplatRight
2191 if (VLeft == Right[i - 1]) {
2192 // Commuting would preserve SplatRight, but we don't want to break
2193 // SplatLeft either, i.e. preserve the original order if possible.
2194 // (FIXME: why do we care?)
2195 if (SplatLeft && VLeft == Left[i - 1])
2200 // Symmetrically handle Right side.
2202 if (VLeft == Left[i - 1])
2203 // Preserve SplatLeft
2205 if (VRight == Left[i - 1])
2209 Instruction *ILeft = dyn_cast<Instruction>(VLeft);
2210 Instruction *IRight = dyn_cast<Instruction>(VRight);
2212 // If we have "AllSameOpcodeRight", try to see if the left operands preserves
2213 // it and not the right, in this case we want to commute.
2214 if (AllSameOpcodeRight) {
2215 unsigned RightPrevOpcode = cast<Instruction>(Right[i - 1])->getOpcode();
2216 if (IRight && RightPrevOpcode == IRight->getOpcode())
2217 // Do not commute, a match on the right preserves AllSameOpcodeRight
2219 if (ILeft && RightPrevOpcode == ILeft->getOpcode()) {
2220 // We have a match and may want to commute, but first check if there is
2221 // not also a match on the existing operands on the Left to preserve
2222 // AllSameOpcodeLeft, i.e. preserve the original order if possible.
2223 // (FIXME: why do we care?)
2224 if (AllSameOpcodeLeft && ILeft &&
2225 cast<Instruction>(Left[i - 1])->getOpcode() == ILeft->getOpcode())
2230 // Symmetrically handle Left side.
2231 if (AllSameOpcodeLeft) {
2232 unsigned LeftPrevOpcode = cast<Instruction>(Left[i - 1])->getOpcode();
2233 if (ILeft && LeftPrevOpcode == ILeft->getOpcode())
2235 if (IRight && LeftPrevOpcode == IRight->getOpcode())
2241 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
2242 SmallVectorImpl<Value *> &Left,
2243 SmallVectorImpl<Value *> &Right) {
2246 // Peel the first iteration out of the loop since there's nothing
2247 // interesting to do anyway and it simplifies the checks in the loop.
2248 auto VLeft = cast<Instruction>(VL[0])->getOperand(0);
2249 auto VRight = cast<Instruction>(VL[0])->getOperand(1);
2250 if (!isa<Instruction>(VRight) && isa<Instruction>(VLeft))
2251 // Favor having instruction to the right. FIXME: why?
2252 std::swap(VLeft, VRight);
2253 Left.push_back(VLeft);
2254 Right.push_back(VRight);
2257 // Keep track if we have instructions with all the same opcode on one side.
2258 bool AllSameOpcodeLeft = isa<Instruction>(Left[0]);
2259 bool AllSameOpcodeRight = isa<Instruction>(Right[0]);
2260 // Keep track if we have one side with all the same value (broadcast).
2261 bool SplatLeft = true;
2262 bool SplatRight = true;
2264 for (unsigned i = 1, e = VL.size(); i != e; ++i) {
2265 Instruction *I = cast<Instruction>(VL[i]);
2266 assert(I->isCommutative() && "Can only process commutative instruction");
2267 // Commute to favor either a splat or maximizing having the same opcodes on
2269 if (shouldReorderOperands(i, *I, Left, Right, AllSameOpcodeLeft,
2270 AllSameOpcodeRight, SplatLeft, SplatRight)) {
2271 Left.push_back(I->getOperand(1));
2272 Right.push_back(I->getOperand(0));
2274 Left.push_back(I->getOperand(0));
2275 Right.push_back(I->getOperand(1));
2277 // Update Splat* and AllSameOpcode* after the insertion.
2278 SplatRight = SplatRight && (Right[i - 1] == Right[i]);
2279 SplatLeft = SplatLeft && (Left[i - 1] == Left[i]);
2280 AllSameOpcodeLeft = AllSameOpcodeLeft && isa<Instruction>(Left[i]) &&
2281 (cast<Instruction>(Left[i - 1])->getOpcode() ==
2282 cast<Instruction>(Left[i])->getOpcode());
2283 AllSameOpcodeRight = AllSameOpcodeRight && isa<Instruction>(Right[i]) &&
2284 (cast<Instruction>(Right[i - 1])->getOpcode() ==
2285 cast<Instruction>(Right[i])->getOpcode());
2288 // If one operand end up being broadcast, return this operand order.
2289 if (SplatRight || SplatLeft)
2292 // Finally check if we can get longer vectorizable chain by reordering
2293 // without breaking the good operand order detected above.
2294 // E.g. If we have something like-
2295 // load a[0] load b[0]
2296 // load b[1] load a[1]
2297 // load a[2] load b[2]
2298 // load a[3] load b[3]
2299 // Reordering the second load b[1] load a[1] would allow us to vectorize
2300 // this code and we still retain AllSameOpcode property.
2301 // FIXME: This load reordering might break AllSameOpcode in some rare cases
2303 // add a[0],c[0] load b[0]
2304 // add a[1],c[2] load b[1]
2306 // add a[3],c[3] load b[3]
2307 for (unsigned j = 0; j < VL.size() - 1; ++j) {
2308 if (LoadInst *L = dyn_cast<LoadInst>(Left[j])) {
2309 if (LoadInst *L1 = dyn_cast<LoadInst>(Right[j + 1])) {
2310 if (isConsecutiveAccess(L, L1, *DL, *SE)) {
2311 std::swap(Left[j + 1], Right[j + 1]);
2316 if (LoadInst *L = dyn_cast<LoadInst>(Right[j])) {
2317 if (LoadInst *L1 = dyn_cast<LoadInst>(Left[j + 1])) {
2318 if (isConsecutiveAccess(L, L1, *DL, *SE)) {
2319 std::swap(Left[j + 1], Right[j + 1]);
2328 void BoUpSLP::setInsertPointAfterBundle(ArrayRef<Value *> VL) {
2330 // Get the basic block this bundle is in. All instructions in the bundle
2331 // should be in this block.
2332 auto *Front = cast<Instruction>(VL.front());
2333 auto *BB = Front->getParent();
2334 assert(all_of(make_range(VL.begin(), VL.end()), [&](Value *V) -> bool {
2335 return cast<Instruction>(V)->getParent() == BB;
2338 // The last instruction in the bundle in program order.
2339 Instruction *LastInst = nullptr;
2341 // Find the last instruction. The common case should be that BB has been
2342 // scheduled, and the last instruction is VL.back(). So we start with
2343 // VL.back() and iterate over schedule data until we reach the end of the
2344 // bundle. The end of the bundle is marked by null ScheduleData.
2345 if (BlocksSchedules.count(BB)) {
2346 auto *Bundle = BlocksSchedules[BB]->getScheduleData(VL.back());
2347 if (Bundle && Bundle->isPartOfBundle())
2348 for (; Bundle; Bundle = Bundle->NextInBundle)
2349 LastInst = Bundle->Inst;
2352 // LastInst can still be null at this point if there's either not an entry
2353 // for BB in BlocksSchedules or there's no ScheduleData available for
2354 // VL.back(). This can be the case if buildTree_rec aborts for various
2355 // reasons (e.g., the maximum recursion depth is reached, the maximum region
2356 // size is reached, etc.). ScheduleData is initialized in the scheduling
2359 // If this happens, we can still find the last instruction by brute force. We
2360 // iterate forwards from Front (inclusive) until we either see all
2361 // instructions in the bundle or reach the end of the block. If Front is the
2362 // last instruction in program order, LastInst will be set to Front, and we
2363 // will visit all the remaining instructions in the block.
2365 // One of the reasons we exit early from buildTree_rec is to place an upper
2366 // bound on compile-time. Thus, taking an additional compile-time hit here is
2367 // not ideal. However, this should be exceedingly rare since it requires that
2368 // we both exit early from buildTree_rec and that the bundle be out-of-order
2369 // (causing us to iterate all the way to the end of the block).
2371 SmallPtrSet<Value *, 16> Bundle(VL.begin(), VL.end());
2372 for (auto &I : make_range(BasicBlock::iterator(Front), BB->end())) {
2373 if (Bundle.erase(&I))
2380 // Set the insertion point after the last instruction in the bundle. Set the
2381 // debug location to Front.
2382 Builder.SetInsertPoint(BB, ++LastInst->getIterator());
2383 Builder.SetCurrentDebugLocation(Front->getDebugLoc());
2386 Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
2387 Value *Vec = UndefValue::get(Ty);
2388 // Generate the 'InsertElement' instruction.
2389 for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
2390 Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
2391 if (Instruction *Insrt = dyn_cast<Instruction>(Vec)) {
2392 GatherSeq.insert(Insrt);
2393 CSEBlocks.insert(Insrt->getParent());
2395 // Add to our 'need-to-extract' list.
2396 if (ScalarToTreeEntry.count(VL[i])) {
2397 int Idx = ScalarToTreeEntry[VL[i]];
2398 TreeEntry *E = &VectorizableTree[Idx];
2399 // Find which lane we need to extract.
2401 for (unsigned Lane = 0, LE = VL.size(); Lane != LE; ++Lane) {
2402 // Is this the lane of the scalar that we are looking for ?
2403 if (E->Scalars[Lane] == VL[i]) {
2408 assert(FoundLane >= 0 && "Could not find the correct lane");
2409 ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
2417 Value *BoUpSLP::alreadyVectorized(ArrayRef<Value *> VL) const {
2418 SmallDenseMap<Value*, int>::const_iterator Entry
2419 = ScalarToTreeEntry.find(VL[0]);
2420 if (Entry != ScalarToTreeEntry.end()) {
2421 int Idx = Entry->second;
2422 const TreeEntry *En = &VectorizableTree[Idx];
2423 if (En->isSame(VL) && En->VectorizedValue)
2424 return En->VectorizedValue;
2429 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
2430 if (ScalarToTreeEntry.count(VL[0])) {
2431 int Idx = ScalarToTreeEntry[VL[0]];
2432 TreeEntry *E = &VectorizableTree[Idx];
2434 return vectorizeTree(E);
2437 Type *ScalarTy = VL[0]->getType();
2438 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
2439 ScalarTy = SI->getValueOperand()->getType();
2440 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
2442 return Gather(VL, VecTy);
2445 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
2446 IRBuilder<>::InsertPointGuard Guard(Builder);
2448 if (E->VectorizedValue) {
2449 DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
2450 return E->VectorizedValue;
2453 Instruction *VL0 = cast<Instruction>(E->Scalars[0]);
2454 Type *ScalarTy = VL0->getType();
2455 if (StoreInst *SI = dyn_cast<StoreInst>(VL0))
2456 ScalarTy = SI->getValueOperand()->getType();
2457 VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size());
2459 if (E->NeedToGather) {
2460 setInsertPointAfterBundle(E->Scalars);
2461 auto *V = Gather(E->Scalars, VecTy);
2462 E->VectorizedValue = V;
2466 unsigned Opcode = getSameOpcode(E->Scalars);
2469 case Instruction::PHI: {
2470 PHINode *PH = dyn_cast<PHINode>(VL0);
2471 Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
2472 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
2473 PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
2474 E->VectorizedValue = NewPhi;
2476 // PHINodes may have multiple entries from the same block. We want to
2477 // visit every block once.
2478 SmallSet<BasicBlock*, 4> VisitedBBs;
2480 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
2482 BasicBlock *IBB = PH->getIncomingBlock(i);
2484 if (!VisitedBBs.insert(IBB).second) {
2485 NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
2489 // Prepare the operand vector.
2490 for (Value *V : E->Scalars)
2491 Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(IBB));
2493 Builder.SetInsertPoint(IBB->getTerminator());
2494 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
2495 Value *Vec = vectorizeTree(Operands);
2496 NewPhi->addIncoming(Vec, IBB);
2499 assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
2500 "Invalid number of incoming values");
2504 case Instruction::ExtractElement: {
2505 if (canReuseExtract(E->Scalars, Instruction::ExtractElement)) {
2506 Value *V = VL0->getOperand(0);
2507 E->VectorizedValue = V;
2510 setInsertPointAfterBundle(E->Scalars);
2511 auto *V = Gather(E->Scalars, VecTy);
2512 E->VectorizedValue = V;
2515 case Instruction::ExtractValue: {
2516 if (canReuseExtract(E->Scalars, Instruction::ExtractValue)) {
2517 LoadInst *LI = cast<LoadInst>(VL0->getOperand(0));
2518 Builder.SetInsertPoint(LI);
2519 PointerType *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
2520 Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
2521 LoadInst *V = Builder.CreateAlignedLoad(Ptr, LI->getAlignment());
2522 E->VectorizedValue = V;
2523 return propagateMetadata(V, E->Scalars);
2525 setInsertPointAfterBundle(E->Scalars);
2526 auto *V = Gather(E->Scalars, VecTy);
2527 E->VectorizedValue = V;
2530 case Instruction::ZExt:
2531 case Instruction::SExt:
2532 case Instruction::FPToUI:
2533 case Instruction::FPToSI:
2534 case Instruction::FPExt:
2535 case Instruction::PtrToInt:
2536 case Instruction::IntToPtr:
2537 case Instruction::SIToFP:
2538 case Instruction::UIToFP:
2539 case Instruction::Trunc:
2540 case Instruction::FPTrunc:
2541 case Instruction::BitCast: {
2543 for (Value *V : E->Scalars)
2544 INVL.push_back(cast<Instruction>(V)->getOperand(0));
2546 setInsertPointAfterBundle(E->Scalars);
2548 Value *InVec = vectorizeTree(INVL);
2550 if (Value *V = alreadyVectorized(E->Scalars))
2553 CastInst *CI = dyn_cast<CastInst>(VL0);
2554 Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
2555 E->VectorizedValue = V;
2556 ++NumVectorInstructions;
2559 case Instruction::FCmp:
2560 case Instruction::ICmp: {
2561 ValueList LHSV, RHSV;
2562 for (Value *V : E->Scalars) {
2563 LHSV.push_back(cast<Instruction>(V)->getOperand(0));
2564 RHSV.push_back(cast<Instruction>(V)->getOperand(1));
2567 setInsertPointAfterBundle(E->Scalars);
2569 Value *L = vectorizeTree(LHSV);
2570 Value *R = vectorizeTree(RHSV);
2572 if (Value *V = alreadyVectorized(E->Scalars))
2575 CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
2577 if (Opcode == Instruction::FCmp)
2578 V = Builder.CreateFCmp(P0, L, R);
2580 V = Builder.CreateICmp(P0, L, R);
2582 E->VectorizedValue = V;
2583 propagateIRFlags(E->VectorizedValue, E->Scalars);
2584 ++NumVectorInstructions;
2587 case Instruction::Select: {
2588 ValueList TrueVec, FalseVec, CondVec;
2589 for (Value *V : E->Scalars) {
2590 CondVec.push_back(cast<Instruction>(V)->getOperand(0));
2591 TrueVec.push_back(cast<Instruction>(V)->getOperand(1));
2592 FalseVec.push_back(cast<Instruction>(V)->getOperand(2));
2595 setInsertPointAfterBundle(E->Scalars);
2597 Value *Cond = vectorizeTree(CondVec);
2598 Value *True = vectorizeTree(TrueVec);
2599 Value *False = vectorizeTree(FalseVec);
2601 if (Value *V = alreadyVectorized(E->Scalars))
2604 Value *V = Builder.CreateSelect(Cond, True, False);
2605 E->VectorizedValue = V;
2606 ++NumVectorInstructions;
2609 case Instruction::Add:
2610 case Instruction::FAdd:
2611 case Instruction::Sub:
2612 case Instruction::FSub:
2613 case Instruction::Mul:
2614 case Instruction::FMul:
2615 case Instruction::UDiv:
2616 case Instruction::SDiv:
2617 case Instruction::FDiv:
2618 case Instruction::URem:
2619 case Instruction::SRem:
2620 case Instruction::FRem:
2621 case Instruction::Shl:
2622 case Instruction::LShr:
2623 case Instruction::AShr:
2624 case Instruction::And:
2625 case Instruction::Or:
2626 case Instruction::Xor: {
2627 ValueList LHSVL, RHSVL;
2628 if (isa<BinaryOperator>(VL0) && VL0->isCommutative())
2629 reorderInputsAccordingToOpcode(E->Scalars, LHSVL, RHSVL);
2631 for (Value *V : E->Scalars) {
2632 LHSVL.push_back(cast<Instruction>(V)->getOperand(0));
2633 RHSVL.push_back(cast<Instruction>(V)->getOperand(1));
2636 setInsertPointAfterBundle(E->Scalars);
2638 Value *LHS = vectorizeTree(LHSVL);
2639 Value *RHS = vectorizeTree(RHSVL);
2641 if (Value *V = alreadyVectorized(E->Scalars))
2644 BinaryOperator *BinOp = cast<BinaryOperator>(VL0);
2645 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), LHS, RHS);
2646 E->VectorizedValue = V;
2647 propagateIRFlags(E->VectorizedValue, E->Scalars);
2648 ++NumVectorInstructions;
2650 if (Instruction *I = dyn_cast<Instruction>(V))
2651 return propagateMetadata(I, E->Scalars);
2655 case Instruction::Load: {
2656 // Loads are inserted at the head of the tree because we don't want to
2657 // sink them all the way down past store instructions.
2658 setInsertPointAfterBundle(E->Scalars);
2660 LoadInst *LI = cast<LoadInst>(VL0);
2661 Type *ScalarLoadTy = LI->getType();
2662 unsigned AS = LI->getPointerAddressSpace();
2664 Value *VecPtr = Builder.CreateBitCast(LI->getPointerOperand(),
2665 VecTy->getPointerTo(AS));
2667 // The pointer operand uses an in-tree scalar so we add the new BitCast to
2668 // ExternalUses list to make sure that an extract will be generated in the
2670 if (ScalarToTreeEntry.count(LI->getPointerOperand()))
2671 ExternalUses.push_back(
2672 ExternalUser(LI->getPointerOperand(), cast<User>(VecPtr), 0));
2674 unsigned Alignment = LI->getAlignment();
2675 LI = Builder.CreateLoad(VecPtr);
2677 Alignment = DL->getABITypeAlignment(ScalarLoadTy);
2679 LI->setAlignment(Alignment);
2680 E->VectorizedValue = LI;
2681 ++NumVectorInstructions;
2682 return propagateMetadata(LI, E->Scalars);
2684 case Instruction::Store: {
2685 StoreInst *SI = cast<StoreInst>(VL0);
2686 unsigned Alignment = SI->getAlignment();
2687 unsigned AS = SI->getPointerAddressSpace();
2690 for (Value *V : E->Scalars)
2691 ValueOp.push_back(cast<StoreInst>(V)->getValueOperand());
2693 setInsertPointAfterBundle(E->Scalars);
2695 Value *VecValue = vectorizeTree(ValueOp);
2696 Value *VecPtr = Builder.CreateBitCast(SI->getPointerOperand(),
2697 VecTy->getPointerTo(AS));
2698 StoreInst *S = Builder.CreateStore(VecValue, VecPtr);
2700 // The pointer operand uses an in-tree scalar so we add the new BitCast to
2701 // ExternalUses list to make sure that an extract will be generated in the
2703 if (ScalarToTreeEntry.count(SI->getPointerOperand()))
2704 ExternalUses.push_back(
2705 ExternalUser(SI->getPointerOperand(), cast<User>(VecPtr), 0));
2708 Alignment = DL->getABITypeAlignment(SI->getValueOperand()->getType());
2710 S->setAlignment(Alignment);
2711 E->VectorizedValue = S;
2712 ++NumVectorInstructions;
2713 return propagateMetadata(S, E->Scalars);
2715 case Instruction::GetElementPtr: {
2716 setInsertPointAfterBundle(E->Scalars);
2719 for (Value *V : E->Scalars)
2720 Op0VL.push_back(cast<GetElementPtrInst>(V)->getOperand(0));
2722 Value *Op0 = vectorizeTree(Op0VL);
2724 std::vector<Value *> OpVecs;
2725 for (int j = 1, e = cast<GetElementPtrInst>(VL0)->getNumOperands(); j < e;
2728 for (Value *V : E->Scalars)
2729 OpVL.push_back(cast<GetElementPtrInst>(V)->getOperand(j));
2731 Value *OpVec = vectorizeTree(OpVL);
2732 OpVecs.push_back(OpVec);
2735 Value *V = Builder.CreateGEP(
2736 cast<GetElementPtrInst>(VL0)->getSourceElementType(), Op0, OpVecs);
2737 E->VectorizedValue = V;
2738 ++NumVectorInstructions;
2740 if (Instruction *I = dyn_cast<Instruction>(V))
2741 return propagateMetadata(I, E->Scalars);
2745 case Instruction::Call: {
2746 CallInst *CI = cast<CallInst>(VL0);
2747 setInsertPointAfterBundle(E->Scalars);
2749 Intrinsic::ID IID = Intrinsic::not_intrinsic;
2750 Value *ScalarArg = nullptr;
2751 if (CI && (FI = CI->getCalledFunction())) {
2752 IID = FI->getIntrinsicID();
2754 std::vector<Value *> OpVecs;
2755 for (int j = 0, e = CI->getNumArgOperands(); j < e; ++j) {
2757 // ctlz,cttz and powi are special intrinsics whose second argument is
2758 // a scalar. This argument should not be vectorized.
2759 if (hasVectorInstrinsicScalarOpd(IID, 1) && j == 1) {
2760 CallInst *CEI = cast<CallInst>(E->Scalars[0]);
2761 ScalarArg = CEI->getArgOperand(j);
2762 OpVecs.push_back(CEI->getArgOperand(j));
2765 for (Value *V : E->Scalars) {
2766 CallInst *CEI = cast<CallInst>(V);
2767 OpVL.push_back(CEI->getArgOperand(j));
2770 Value *OpVec = vectorizeTree(OpVL);
2771 DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
2772 OpVecs.push_back(OpVec);
2775 Module *M = F->getParent();
2776 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
2777 Type *Tys[] = { VectorType::get(CI->getType(), E->Scalars.size()) };
2778 Function *CF = Intrinsic::getDeclaration(M, ID, Tys);
2779 SmallVector<OperandBundleDef, 1> OpBundles;
2780 CI->getOperandBundlesAsDefs(OpBundles);
2781 Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
2783 // The scalar argument uses an in-tree scalar so we add the new vectorized
2784 // call to ExternalUses list to make sure that an extract will be
2785 // generated in the future.
2786 if (ScalarArg && ScalarToTreeEntry.count(ScalarArg))
2787 ExternalUses.push_back(ExternalUser(ScalarArg, cast<User>(V), 0));
2789 E->VectorizedValue = V;
2790 propagateIRFlags(E->VectorizedValue, E->Scalars);
2791 ++NumVectorInstructions;
2794 case Instruction::ShuffleVector: {
2795 ValueList LHSVL, RHSVL;
2796 assert(isa<BinaryOperator>(VL0) && "Invalid Shuffle Vector Operand");
2797 reorderAltShuffleOperands(E->Scalars, LHSVL, RHSVL);
2798 setInsertPointAfterBundle(E->Scalars);
2800 Value *LHS = vectorizeTree(LHSVL);
2801 Value *RHS = vectorizeTree(RHSVL);
2803 if (Value *V = alreadyVectorized(E->Scalars))
2806 // Create a vector of LHS op1 RHS
2807 BinaryOperator *BinOp0 = cast<BinaryOperator>(VL0);
2808 Value *V0 = Builder.CreateBinOp(BinOp0->getOpcode(), LHS, RHS);
2810 // Create a vector of LHS op2 RHS
2811 Instruction *VL1 = cast<Instruction>(E->Scalars[1]);
2812 BinaryOperator *BinOp1 = cast<BinaryOperator>(VL1);
2813 Value *V1 = Builder.CreateBinOp(BinOp1->getOpcode(), LHS, RHS);
2815 // Create shuffle to take alternate operations from the vector.
2816 // Also, gather up odd and even scalar ops to propagate IR flags to
2817 // each vector operation.
2818 ValueList OddScalars, EvenScalars;
2819 unsigned e = E->Scalars.size();
2820 SmallVector<Constant *, 8> Mask(e);
2821 for (unsigned i = 0; i < e; ++i) {
2823 Mask[i] = Builder.getInt32(e + i);
2824 OddScalars.push_back(E->Scalars[i]);
2826 Mask[i] = Builder.getInt32(i);
2827 EvenScalars.push_back(E->Scalars[i]);
2831 Value *ShuffleMask = ConstantVector::get(Mask);
2832 propagateIRFlags(V0, EvenScalars);
2833 propagateIRFlags(V1, OddScalars);
2835 Value *V = Builder.CreateShuffleVector(V0, V1, ShuffleMask);
2836 E->VectorizedValue = V;
2837 ++NumVectorInstructions;
2838 if (Instruction *I = dyn_cast<Instruction>(V))
2839 return propagateMetadata(I, E->Scalars);
2844 llvm_unreachable("unknown inst");
2849 Value *BoUpSLP::vectorizeTree() {
2850 ExtraValueToDebugLocsMap ExternallyUsedValues;
2851 return vectorizeTree(ExternallyUsedValues);
2855 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
2857 // All blocks must be scheduled before any instructions are inserted.
2858 for (auto &BSIter : BlocksSchedules) {
2859 scheduleBlock(BSIter.second.get());
2862 Builder.SetInsertPoint(&F->getEntryBlock().front());
2863 auto *VectorRoot = vectorizeTree(&VectorizableTree[0]);
2865 // If the vectorized tree can be rewritten in a smaller type, we truncate the
2866 // vectorized root. InstCombine will then rewrite the entire expression. We
2867 // sign extend the extracted values below.
2868 auto *ScalarRoot = VectorizableTree[0].Scalars[0];
2869 if (MinBWs.count(ScalarRoot)) {
2870 if (auto *I = dyn_cast<Instruction>(VectorRoot))
2871 Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
2872 auto BundleWidth = VectorizableTree[0].Scalars.size();
2873 auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
2874 auto *VecTy = VectorType::get(MinTy, BundleWidth);
2875 auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
2876 VectorizableTree[0].VectorizedValue = Trunc;
2879 DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() << " values .\n");
2881 // If necessary, sign-extend or zero-extend ScalarRoot to the larger type
2882 // specified by ScalarType.
2883 auto extend = [&](Value *ScalarRoot, Value *Ex, Type *ScalarType) {
2884 if (!MinBWs.count(ScalarRoot))
2886 if (MinBWs[ScalarRoot].second)
2887 return Builder.CreateSExt(Ex, ScalarType);
2888 return Builder.CreateZExt(Ex, ScalarType);
2891 // Extract all of the elements with the external uses.
2892 for (const auto &ExternalUse : ExternalUses) {
2893 Value *Scalar = ExternalUse.Scalar;
2894 llvm::User *User = ExternalUse.User;
2896 // Skip users that we already RAUW. This happens when one instruction
2897 // has multiple uses of the same value.
2898 if (User && !is_contained(Scalar->users(), User))
2900 assert(ScalarToTreeEntry.count(Scalar) && "Invalid scalar");
2902 int Idx = ScalarToTreeEntry[Scalar];
2903 TreeEntry *E = &VectorizableTree[Idx];
2904 assert(!E->NeedToGather && "Extracting from a gather list");
2906 Value *Vec = E->VectorizedValue;
2907 assert(Vec && "Can't find vectorizable value");
2909 Value *Lane = Builder.getInt32(ExternalUse.Lane);
2910 // If User == nullptr, the Scalar is used as extra arg. Generate
2911 // ExtractElement instruction and update the record for this scalar in
2912 // ExternallyUsedValues.
2914 assert(ExternallyUsedValues.count(Scalar) &&
2915 "Scalar with nullptr as an external user must be registered in "
2916 "ExternallyUsedValues map");
2917 if (auto *VecI = dyn_cast<Instruction>(Vec)) {
2918 Builder.SetInsertPoint(VecI->getParent(),
2919 std::next(VecI->getIterator()));
2921 Builder.SetInsertPoint(&F->getEntryBlock().front());
2923 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2924 Ex = extend(ScalarRoot, Ex, Scalar->getType());
2925 CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
2926 auto &Locs = ExternallyUsedValues[Scalar];
2927 ExternallyUsedValues.insert({Ex, Locs});
2928 ExternallyUsedValues.erase(Scalar);
2932 // Generate extracts for out-of-tree users.
2933 // Find the insertion point for the extractelement lane.
2934 if (auto *VecI = dyn_cast<Instruction>(Vec)) {
2935 if (PHINode *PH = dyn_cast<PHINode>(User)) {
2936 for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
2937 if (PH->getIncomingValue(i) == Scalar) {
2938 TerminatorInst *IncomingTerminator =
2939 PH->getIncomingBlock(i)->getTerminator();
2940 if (isa<CatchSwitchInst>(IncomingTerminator)) {
2941 Builder.SetInsertPoint(VecI->getParent(),
2942 std::next(VecI->getIterator()));
2944 Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
2946 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2947 Ex = extend(ScalarRoot, Ex, Scalar->getType());
2948 CSEBlocks.insert(PH->getIncomingBlock(i));
2949 PH->setOperand(i, Ex);
2953 Builder.SetInsertPoint(cast<Instruction>(User));
2954 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2955 Ex = extend(ScalarRoot, Ex, Scalar->getType());
2956 CSEBlocks.insert(cast<Instruction>(User)->getParent());
2957 User->replaceUsesOfWith(Scalar, Ex);
2960 Builder.SetInsertPoint(&F->getEntryBlock().front());
2961 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2962 Ex = extend(ScalarRoot, Ex, Scalar->getType());
2963 CSEBlocks.insert(&F->getEntryBlock());
2964 User->replaceUsesOfWith(Scalar, Ex);
2967 DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
2970 // For each vectorized value:
2971 for (TreeEntry &EIdx : VectorizableTree) {
2972 TreeEntry *Entry = &EIdx;
2975 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
2976 Value *Scalar = Entry->Scalars[Lane];
2977 // No need to handle users of gathered values.
2978 if (Entry->NeedToGather)
2981 assert(Entry->VectorizedValue && "Can't find vectorizable value");
2983 Type *Ty = Scalar->getType();
2984 if (!Ty->isVoidTy()) {
2986 for (User *U : Scalar->users()) {
2987 DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
2989 assert((ScalarToTreeEntry.count(U) ||
2990 // It is legal to replace users in the ignorelist by undef.
2991 is_contained(UserIgnoreList, U)) &&
2992 "Replacing out-of-tree value with undef");
2995 Value *Undef = UndefValue::get(Ty);
2996 Scalar->replaceAllUsesWith(Undef);
2998 DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
2999 eraseInstruction(cast<Instruction>(Scalar));
3003 Builder.ClearInsertionPoint();
3005 return VectorizableTree[0].VectorizedValue;
3008 void BoUpSLP::optimizeGatherSequence() {
3009 DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
3010 << " gather sequences instructions.\n");
3011 // LICM InsertElementInst sequences.
3012 for (Instruction *it : GatherSeq) {
3013 InsertElementInst *Insert = dyn_cast<InsertElementInst>(it);
3018 // Check if this block is inside a loop.
3019 Loop *L = LI->getLoopFor(Insert->getParent());
3023 // Check if it has a preheader.
3024 BasicBlock *PreHeader = L->getLoopPreheader();
3028 // If the vector or the element that we insert into it are
3029 // instructions that are defined in this basic block then we can't
3030 // hoist this instruction.
3031 Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
3032 Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
3033 if (CurrVec && L->contains(CurrVec))
3035 if (NewElem && L->contains(NewElem))
3038 // We can hoist this instruction. Move it to the pre-header.
3039 Insert->moveBefore(PreHeader->getTerminator());
3042 // Make a list of all reachable blocks in our CSE queue.
3043 SmallVector<const DomTreeNode *, 8> CSEWorkList;
3044 CSEWorkList.reserve(CSEBlocks.size());
3045 for (BasicBlock *BB : CSEBlocks)
3046 if (DomTreeNode *N = DT->getNode(BB)) {
3047 assert(DT->isReachableFromEntry(N));
3048 CSEWorkList.push_back(N);
3051 // Sort blocks by domination. This ensures we visit a block after all blocks
3052 // dominating it are visited.
3053 std::stable_sort(CSEWorkList.begin(), CSEWorkList.end(),
3054 [this](const DomTreeNode *A, const DomTreeNode *B) {
3055 return DT->properlyDominates(A, B);
3058 // Perform O(N^2) search over the gather sequences and merge identical
3059 // instructions. TODO: We can further optimize this scan if we split the
3060 // instructions into different buckets based on the insert lane.
3061 SmallVector<Instruction *, 16> Visited;
3062 for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
3063 assert((I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
3064 "Worklist not sorted properly!");
3065 BasicBlock *BB = (*I)->getBlock();
3066 // For all instructions in blocks containing gather sequences:
3067 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) {
3068 Instruction *In = &*it++;
3069 if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In))
3072 // Check if we can replace this instruction with any of the
3073 // visited instructions.
3074 for (Instruction *v : Visited) {
3075 if (In->isIdenticalTo(v) &&
3076 DT->dominates(v->getParent(), In->getParent())) {
3077 In->replaceAllUsesWith(v);
3078 eraseInstruction(In);
3084 assert(!is_contained(Visited, In));
3085 Visited.push_back(In);
3093 // Groups the instructions to a bundle (which is then a single scheduling entity)
3094 // and schedules instructions until the bundle gets ready.
3095 bool BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL,
3097 if (isa<PHINode>(VL[0]))
3100 // Initialize the instruction bundle.
3101 Instruction *OldScheduleEnd = ScheduleEnd;
3102 ScheduleData *PrevInBundle = nullptr;
3103 ScheduleData *Bundle = nullptr;
3104 bool ReSchedule = false;
3105 DEBUG(dbgs() << "SLP: bundle: " << *VL[0] << "\n");
3107 // Make sure that the scheduling region contains all
3108 // instructions of the bundle.
3109 for (Value *V : VL) {
3110 if (!extendSchedulingRegion(V))
3114 for (Value *V : VL) {
3115 ScheduleData *BundleMember = getScheduleData(V);
3116 assert(BundleMember &&
3117 "no ScheduleData for bundle member (maybe not in same basic block)");
3118 if (BundleMember->IsScheduled) {
3119 // A bundle member was scheduled as single instruction before and now
3120 // needs to be scheduled as part of the bundle. We just get rid of the
3121 // existing schedule.
3122 DEBUG(dbgs() << "SLP: reset schedule because " << *BundleMember
3123 << " was already scheduled\n");
3126 assert(BundleMember->isSchedulingEntity() &&
3127 "bundle member already part of other bundle");
3129 PrevInBundle->NextInBundle = BundleMember;
3131 Bundle = BundleMember;
3133 BundleMember->UnscheduledDepsInBundle = 0;
3134 Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps;
3136 // Group the instructions to a bundle.
3137 BundleMember->FirstInBundle = Bundle;
3138 PrevInBundle = BundleMember;
3140 if (ScheduleEnd != OldScheduleEnd) {
3141 // The scheduling region got new instructions at the lower end (or it is a
3142 // new region for the first bundle). This makes it necessary to
3143 // recalculate all dependencies.
3144 // It is seldom that this needs to be done a second time after adding the
3145 // initial bundle to the region.
3146 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
3147 ScheduleData *SD = getScheduleData(I);
3148 SD->clearDependencies();
3154 initialFillReadyList(ReadyInsts);
3157 DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle << " in block "
3158 << BB->getName() << "\n");
3160 calculateDependencies(Bundle, true, SLP);
3162 // Now try to schedule the new bundle. As soon as the bundle is "ready" it
3163 // means that there are no cyclic dependencies and we can schedule it.
3164 // Note that's important that we don't "schedule" the bundle yet (see
3165 // cancelScheduling).
3166 while (!Bundle->isReady() && !ReadyInsts.empty()) {
3168 ScheduleData *pickedSD = ReadyInsts.back();
3169 ReadyInsts.pop_back();
3171 if (pickedSD->isSchedulingEntity() && pickedSD->isReady()) {
3172 schedule(pickedSD, ReadyInsts);
3175 if (!Bundle->isReady()) {
3176 cancelScheduling(VL);
3182 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL) {
3183 if (isa<PHINode>(VL[0]))
3186 ScheduleData *Bundle = getScheduleData(VL[0]);
3187 DEBUG(dbgs() << "SLP: cancel scheduling of " << *Bundle << "\n");
3188 assert(!Bundle->IsScheduled &&
3189 "Can't cancel bundle which is already scheduled");
3190 assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
3191 "tried to unbundle something which is not a bundle");
3193 // Un-bundle: make single instructions out of the bundle.
3194 ScheduleData *BundleMember = Bundle;
3195 while (BundleMember) {
3196 assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
3197 BundleMember->FirstInBundle = BundleMember;
3198 ScheduleData *Next = BundleMember->NextInBundle;
3199 BundleMember->NextInBundle = nullptr;
3200 BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps;
3201 if (BundleMember->UnscheduledDepsInBundle == 0) {
3202 ReadyInsts.insert(BundleMember);
3204 BundleMember = Next;
3208 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V) {
3209 if (getScheduleData(V))
3211 Instruction *I = dyn_cast<Instruction>(V);
3212 assert(I && "bundle member must be an instruction");
3213 assert(!isa<PHINode>(I) && "phi nodes don't need to be scheduled");
3214 if (!ScheduleStart) {
3215 // It's the first instruction in the new region.
3216 initScheduleData(I, I->getNextNode(), nullptr, nullptr);
3218 ScheduleEnd = I->getNextNode();
3219 assert(ScheduleEnd && "tried to vectorize a TerminatorInst?");
3220 DEBUG(dbgs() << "SLP: initialize schedule region to " << *I << "\n");
3223 // Search up and down at the same time, because we don't know if the new
3224 // instruction is above or below the existing scheduling region.
3225 BasicBlock::reverse_iterator UpIter =
3226 ++ScheduleStart->getIterator().getReverse();
3227 BasicBlock::reverse_iterator UpperEnd = BB->rend();
3228 BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
3229 BasicBlock::iterator LowerEnd = BB->end();
3231 if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
3232 DEBUG(dbgs() << "SLP: exceeded schedule region size limit\n");
3236 if (UpIter != UpperEnd) {
3237 if (&*UpIter == I) {
3238 initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
3240 DEBUG(dbgs() << "SLP: extend schedule region start to " << *I << "\n");
3245 if (DownIter != LowerEnd) {
3246 if (&*DownIter == I) {
3247 initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
3249 ScheduleEnd = I->getNextNode();
3250 assert(ScheduleEnd && "tried to vectorize a TerminatorInst?");
3251 DEBUG(dbgs() << "SLP: extend schedule region end to " << *I << "\n");
3256 assert((UpIter != UpperEnd || DownIter != LowerEnd) &&
3257 "instruction not found in block");
3262 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
3264 ScheduleData *PrevLoadStore,
3265 ScheduleData *NextLoadStore) {
3266 ScheduleData *CurrentLoadStore = PrevLoadStore;
3267 for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
3268 ScheduleData *SD = ScheduleDataMap[I];
3270 // Allocate a new ScheduleData for the instruction.
3271 if (ChunkPos >= ChunkSize) {
3272 ScheduleDataChunks.push_back(
3273 llvm::make_unique<ScheduleData[]>(ChunkSize));
3276 SD = &(ScheduleDataChunks.back()[ChunkPos++]);
3277 ScheduleDataMap[I] = SD;
3280 assert(!isInSchedulingRegion(SD) &&
3281 "new ScheduleData already in scheduling region");
3282 SD->init(SchedulingRegionID);
3284 if (I->mayReadOrWriteMemory()) {
3285 // Update the linked list of memory accessing instructions.
3286 if (CurrentLoadStore) {
3287 CurrentLoadStore->NextLoadStore = SD;
3289 FirstLoadStoreInRegion = SD;
3291 CurrentLoadStore = SD;
3294 if (NextLoadStore) {
3295 if (CurrentLoadStore)
3296 CurrentLoadStore->NextLoadStore = NextLoadStore;
3298 LastLoadStoreInRegion = CurrentLoadStore;
3302 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
3303 bool InsertInReadyList,
3305 assert(SD->isSchedulingEntity());
3307 SmallVector<ScheduleData *, 10> WorkList;
3308 WorkList.push_back(SD);
3310 while (!WorkList.empty()) {
3311 ScheduleData *SD = WorkList.back();
3312 WorkList.pop_back();
3314 ScheduleData *BundleMember = SD;
3315 while (BundleMember) {
3316 assert(isInSchedulingRegion(BundleMember));
3317 if (!BundleMember->hasValidDependencies()) {
3319 DEBUG(dbgs() << "SLP: update deps of " << *BundleMember << "\n");
3320 BundleMember->Dependencies = 0;
3321 BundleMember->resetUnscheduledDeps();
3323 // Handle def-use chain dependencies.
3324 for (User *U : BundleMember->Inst->users()) {
3325 if (isa<Instruction>(U)) {
3326 ScheduleData *UseSD = getScheduleData(U);
3327 if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
3328 BundleMember->Dependencies++;
3329 ScheduleData *DestBundle = UseSD->FirstInBundle;
3330 if (!DestBundle->IsScheduled) {
3331 BundleMember->incrementUnscheduledDeps(1);
3333 if (!DestBundle->hasValidDependencies()) {
3334 WorkList.push_back(DestBundle);
3338 // I'm not sure if this can ever happen. But we need to be safe.
3339 // This lets the instruction/bundle never be scheduled and
3340 // eventually disable vectorization.
3341 BundleMember->Dependencies++;
3342 BundleMember->incrementUnscheduledDeps(1);
3346 // Handle the memory dependencies.
3347 ScheduleData *DepDest = BundleMember->NextLoadStore;
3349 Instruction *SrcInst = BundleMember->Inst;
3350 MemoryLocation SrcLoc = getLocation(SrcInst, SLP->AA);
3351 bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
3352 unsigned numAliased = 0;
3353 unsigned DistToSrc = 1;
3356 assert(isInSchedulingRegion(DepDest));
3358 // We have two limits to reduce the complexity:
3359 // 1) AliasedCheckLimit: It's a small limit to reduce calls to
3360 // SLP->isAliased (which is the expensive part in this loop).
3361 // 2) MaxMemDepDistance: It's for very large blocks and it aborts
3362 // the whole loop (even if the loop is fast, it's quadratic).
3363 // It's important for the loop break condition (see below) to
3364 // check this limit even between two read-only instructions.
3365 if (DistToSrc >= MaxMemDepDistance ||
3366 ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
3367 (numAliased >= AliasedCheckLimit ||
3368 SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
3370 // We increment the counter only if the locations are aliased
3371 // (instead of counting all alias checks). This gives a better
3372 // balance between reduced runtime and accurate dependencies.
3375 DepDest->MemoryDependencies.push_back(BundleMember);
3376 BundleMember->Dependencies++;
3377 ScheduleData *DestBundle = DepDest->FirstInBundle;
3378 if (!DestBundle->IsScheduled) {
3379 BundleMember->incrementUnscheduledDeps(1);
3381 if (!DestBundle->hasValidDependencies()) {
3382 WorkList.push_back(DestBundle);
3385 DepDest = DepDest->NextLoadStore;
3387 // Example, explaining the loop break condition: Let's assume our
3388 // starting instruction is i0 and MaxMemDepDistance = 3.
3391 // i0,i1,i2,i3,i4,i5,i6,i7,i8
3394 // MaxMemDepDistance let us stop alias-checking at i3 and we add
3395 // dependencies from i0 to i3,i4,.. (even if they are not aliased).
3396 // Previously we already added dependencies from i3 to i6,i7,i8
3397 // (because of MaxMemDepDistance). As we added a dependency from
3398 // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
3399 // and we can abort this loop at i6.
3400 if (DistToSrc >= 2 * MaxMemDepDistance)
3406 BundleMember = BundleMember->NextInBundle;
3408 if (InsertInReadyList && SD->isReady()) {
3409 ReadyInsts.push_back(SD);
3410 DEBUG(dbgs() << "SLP: gets ready on update: " << *SD->Inst << "\n");
3415 void BoUpSLP::BlockScheduling::resetSchedule() {
3416 assert(ScheduleStart &&
3417 "tried to reset schedule on block which has not been scheduled");
3418 for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
3419 ScheduleData *SD = getScheduleData(I);
3420 assert(isInSchedulingRegion(SD));
3421 SD->IsScheduled = false;
3422 SD->resetUnscheduledDeps();
3427 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
3429 if (!BS->ScheduleStart)
3432 DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
3434 BS->resetSchedule();
3436 // For the real scheduling we use a more sophisticated ready-list: it is
3437 // sorted by the original instruction location. This lets the final schedule
3438 // be as close as possible to the original instruction order.
3439 struct ScheduleDataCompare {
3440 bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
3441 return SD2->SchedulingPriority < SD1->SchedulingPriority;
3444 std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
3446 // Ensure that all dependency data is updated and fill the ready-list with
3447 // initial instructions.
3449 int NumToSchedule = 0;
3450 for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
3451 I = I->getNextNode()) {
3452 ScheduleData *SD = BS->getScheduleData(I);
3454 SD->isPartOfBundle() == (ScalarToTreeEntry.count(SD->Inst) != 0) &&
3455 "scheduler and vectorizer have different opinion on what is a bundle");
3456 SD->FirstInBundle->SchedulingPriority = Idx++;
3457 if (SD->isSchedulingEntity()) {
3458 BS->calculateDependencies(SD, false, this);
3462 BS->initialFillReadyList(ReadyInsts);
3464 Instruction *LastScheduledInst = BS->ScheduleEnd;
3466 // Do the "real" scheduling.
3467 while (!ReadyInsts.empty()) {
3468 ScheduleData *picked = *ReadyInsts.begin();
3469 ReadyInsts.erase(ReadyInsts.begin());
3471 // Move the scheduled instruction(s) to their dedicated places, if not
3473 ScheduleData *BundleMember = picked;
3474 while (BundleMember) {
3475 Instruction *pickedInst = BundleMember->Inst;
3476 if (LastScheduledInst->getNextNode() != pickedInst) {
3477 BS->BB->getInstList().remove(pickedInst);
3478 BS->BB->getInstList().insert(LastScheduledInst->getIterator(),
3481 LastScheduledInst = pickedInst;
3482 BundleMember = BundleMember->NextInBundle;
3485 BS->schedule(picked, ReadyInsts);
3488 assert(NumToSchedule == 0 && "could not schedule all instructions");
3490 // Avoid duplicate scheduling of the block.
3491 BS->ScheduleStart = nullptr;
3494 unsigned BoUpSLP::getVectorElementSize(Value *V) {
3495 // If V is a store, just return the width of the stored value without
3496 // traversing the expression tree. This is the common case.
3497 if (auto *Store = dyn_cast<StoreInst>(V))
3498 return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
3500 // If V is not a store, we can traverse the expression tree to find loads
3501 // that feed it. The type of the loaded value may indicate a more suitable
3502 // width than V's type. We want to base the vector element size on the width
3503 // of memory operations where possible.
3504 SmallVector<Instruction *, 16> Worklist;
3505 SmallPtrSet<Instruction *, 16> Visited;
3506 if (auto *I = dyn_cast<Instruction>(V))
3507 Worklist.push_back(I);
3509 // Traverse the expression tree in bottom-up order looking for loads. If we
3510 // encounter an instruciton we don't yet handle, we give up.
3512 auto FoundUnknownInst = false;
3513 while (!Worklist.empty() && !FoundUnknownInst) {
3514 auto *I = Worklist.pop_back_val();
3517 // We should only be looking at scalar instructions here. If the current
3518 // instruction has a vector type, give up.
3519 auto *Ty = I->getType();
3520 if (isa<VectorType>(Ty))
3521 FoundUnknownInst = true;
3523 // If the current instruction is a load, update MaxWidth to reflect the
3524 // width of the loaded value.
3525 else if (isa<LoadInst>(I))
3526 MaxWidth = std::max<unsigned>(MaxWidth, DL->getTypeSizeInBits(Ty));
3528 // Otherwise, we need to visit the operands of the instruction. We only
3529 // handle the interesting cases from buildTree here. If an operand is an
3530 // instruction we haven't yet visited, we add it to the worklist.
3531 else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
3532 isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I)) {
3533 for (Use &U : I->operands())
3534 if (auto *J = dyn_cast<Instruction>(U.get()))
3535 if (!Visited.count(J))
3536 Worklist.push_back(J);
3539 // If we don't yet handle the instruction, give up.
3541 FoundUnknownInst = true;
3544 // If we didn't encounter a memory access in the expression tree, or if we
3545 // gave up for some reason, just return the width of V.
3546 if (!MaxWidth || FoundUnknownInst)
3547 return DL->getTypeSizeInBits(V->getType());
3549 // Otherwise, return the maximum width we found.
3553 // Determine if a value V in a vectorizable expression Expr can be demoted to a
3554 // smaller type with a truncation. We collect the values that will be demoted
3555 // in ToDemote and additional roots that require investigating in Roots.
3556 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
3557 SmallVectorImpl<Value *> &ToDemote,
3558 SmallVectorImpl<Value *> &Roots) {
3560 // We can always demote constants.
3561 if (isa<Constant>(V)) {
3562 ToDemote.push_back(V);
3566 // If the value is not an instruction in the expression with only one use, it
3567 // cannot be demoted.
3568 auto *I = dyn_cast<Instruction>(V);
3569 if (!I || !I->hasOneUse() || !Expr.count(I))
3572 switch (I->getOpcode()) {
3574 // We can always demote truncations and extensions. Since truncations can
3575 // seed additional demotion, we save the truncated value.
3576 case Instruction::Trunc:
3577 Roots.push_back(I->getOperand(0));
3578 case Instruction::ZExt:
3579 case Instruction::SExt:
3582 // We can demote certain binary operations if we can demote both of their
3584 case Instruction::Add:
3585 case Instruction::Sub:
3586 case Instruction::Mul:
3587 case Instruction::And:
3588 case Instruction::Or:
3589 case Instruction::Xor:
3590 if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
3591 !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
3595 // We can demote selects if we can demote their true and false values.
3596 case Instruction::Select: {
3597 SelectInst *SI = cast<SelectInst>(I);
3598 if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
3599 !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
3604 // We can demote phis if we can demote all their incoming operands. Note that
3605 // we don't need to worry about cycles since we ensure single use above.
3606 case Instruction::PHI: {
3607 PHINode *PN = cast<PHINode>(I);
3608 for (Value *IncValue : PN->incoming_values())
3609 if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
3614 // Otherwise, conservatively give up.
3619 // Record the value that we can demote.
3620 ToDemote.push_back(V);
3624 void BoUpSLP::computeMinimumValueSizes() {
3625 // If there are no external uses, the expression tree must be rooted by a
3626 // store. We can't demote in-memory values, so there is nothing to do here.
3627 if (ExternalUses.empty())
3630 // We only attempt to truncate integer expressions.
3631 auto &TreeRoot = VectorizableTree[0].Scalars;
3632 auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
3636 // If the expression is not rooted by a store, these roots should have
3637 // external uses. We will rely on InstCombine to rewrite the expression in
3638 // the narrower type. However, InstCombine only rewrites single-use values.
3639 // This means that if a tree entry other than a root is used externally, it
3640 // must have multiple uses and InstCombine will not rewrite it. The code
3641 // below ensures that only the roots are used externally.
3642 SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
3643 for (auto &EU : ExternalUses)
3644 if (!Expr.erase(EU.Scalar))
3649 // Collect the scalar values of the vectorizable expression. We will use this
3650 // context to determine which values can be demoted. If we see a truncation,
3651 // we mark it as seeding another demotion.
3652 for (auto &Entry : VectorizableTree)
3653 Expr.insert(Entry.Scalars.begin(), Entry.Scalars.end());
3655 // Ensure the roots of the vectorizable tree don't form a cycle. They must
3656 // have a single external user that is not in the vectorizable tree.
3657 for (auto *Root : TreeRoot)
3658 if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
3661 // Conservatively determine if we can actually truncate the roots of the
3662 // expression. Collect the values that can be demoted in ToDemote and
3663 // additional roots that require investigating in Roots.
3664 SmallVector<Value *, 32> ToDemote;
3665 SmallVector<Value *, 4> Roots;
3666 for (auto *Root : TreeRoot)
3667 if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
3670 // The maximum bit width required to represent all the values that can be
3671 // demoted without loss of precision. It would be safe to truncate the roots
3672 // of the expression to this width.
3673 auto MaxBitWidth = 8u;
3675 // We first check if all the bits of the roots are demanded. If they're not,
3676 // we can truncate the roots to this narrower type.
3677 for (auto *Root : TreeRoot) {
3678 auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
3679 MaxBitWidth = std::max<unsigned>(
3680 Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
3683 // True if the roots can be zero-extended back to their original type, rather
3684 // than sign-extended. We know that if the leading bits are not demanded, we
3685 // can safely zero-extend. So we initialize IsKnownPositive to True.
3686 bool IsKnownPositive = true;
3688 // If all the bits of the roots are demanded, we can try a little harder to
3689 // compute a narrower type. This can happen, for example, if the roots are
3690 // getelementptr indices. InstCombine promotes these indices to the pointer
3691 // width. Thus, all their bits are technically demanded even though the
3692 // address computation might be vectorized in a smaller type.
3694 // We start by looking at each entry that can be demoted. We compute the
3695 // maximum bit width required to store the scalar by using ValueTracking to
3696 // compute the number of high-order bits we can truncate.
3697 if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType())) {
3700 // Determine if the sign bit of all the roots is known to be zero. If not,
3701 // IsKnownPositive is set to False.
3702 IsKnownPositive = all_of(TreeRoot, [&](Value *R) {
3703 KnownBits Known = computeKnownBits(R, *DL);
3704 return Known.isNonNegative();
3707 // Determine the maximum number of bits required to store the scalar
3709 for (auto *Scalar : ToDemote) {
3710 auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, 0, DT);
3711 auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
3712 MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
3715 // If we can't prove that the sign bit is zero, we must add one to the
3716 // maximum bit width to account for the unknown sign bit. This preserves
3717 // the existing sign bit so we can safely sign-extend the root back to the
3718 // original type. Otherwise, if we know the sign bit is zero, we will
3719 // zero-extend the root instead.
3721 // FIXME: This is somewhat suboptimal, as there will be cases where adding
3722 // one to the maximum bit width will yield a larger-than-necessary
3723 // type. In general, we need to add an extra bit only if we can't
3724 // prove that the upper bit of the original type is equal to the
3725 // upper bit of the proposed smaller type. If these two bits are the
3726 // same (either zero or one) we know that sign-extending from the
3727 // smaller type will result in the same value. Here, since we can't
3728 // yet prove this, we are just making the proposed smaller type
3729 // larger to ensure correctness.
3730 if (!IsKnownPositive)
3734 // Round MaxBitWidth up to the next power-of-two.
3735 if (!isPowerOf2_64(MaxBitWidth))
3736 MaxBitWidth = NextPowerOf2(MaxBitWidth);
3738 // If the maximum bit width we compute is less than the with of the roots'
3739 // type, we can proceed with the narrowing. Otherwise, do nothing.
3740 if (MaxBitWidth >= TreeRootIT->getBitWidth())
3743 // If we can truncate the root, we must collect additional values that might
3744 // be demoted as a result. That is, those seeded by truncations we will
3746 while (!Roots.empty())
3747 collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
3749 // Finally, map the values we can demote to the maximum bit with we computed.
3750 for (auto *Scalar : ToDemote)
3751 MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
3755 /// The SLPVectorizer Pass.
3756 struct SLPVectorizer : public FunctionPass {
3757 SLPVectorizerPass Impl;
3759 /// Pass identification, replacement for typeid
3762 explicit SLPVectorizer() : FunctionPass(ID) {
3763 initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
3767 bool doInitialization(Module &M) override {
3771 bool runOnFunction(Function &F) override {
3772 if (skipFunction(F))
3775 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
3776 auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
3777 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
3778 auto *TLI = TLIP ? &TLIP->getTLI() : nullptr;
3779 auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3780 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
3781 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3782 auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
3783 auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
3784 auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
3786 return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
3789 void getAnalysisUsage(AnalysisUsage &AU) const override {
3790 FunctionPass::getAnalysisUsage(AU);
3791 AU.addRequired<AssumptionCacheTracker>();
3792 AU.addRequired<ScalarEvolutionWrapperPass>();
3793 AU.addRequired<AAResultsWrapperPass>();
3794 AU.addRequired<TargetTransformInfoWrapperPass>();
3795 AU.addRequired<LoopInfoWrapperPass>();
3796 AU.addRequired<DominatorTreeWrapperPass>();
3797 AU.addRequired<DemandedBitsWrapperPass>();
3798 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
3799 AU.addPreserved<LoopInfoWrapperPass>();
3800 AU.addPreserved<DominatorTreeWrapperPass>();
3801 AU.addPreserved<AAResultsWrapperPass>();
3802 AU.addPreserved<GlobalsAAWrapperPass>();
3803 AU.setPreservesCFG();
3806 } // end anonymous namespace
3808 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
3809 auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
3810 auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
3811 auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
3812 auto *AA = &AM.getResult<AAManager>(F);
3813 auto *LI = &AM.getResult<LoopAnalysis>(F);
3814 auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
3815 auto *AC = &AM.getResult<AssumptionAnalysis>(F);
3816 auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
3817 auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
3819 bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
3821 return PreservedAnalyses::all();
3823 PreservedAnalyses PA;
3824 PA.preserveSet<CFGAnalyses>();
3825 PA.preserve<AAManager>();
3826 PA.preserve<GlobalsAA>();
3830 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
3831 TargetTransformInfo *TTI_,
3832 TargetLibraryInfo *TLI_, AliasAnalysis *AA_,
3833 LoopInfo *LI_, DominatorTree *DT_,
3834 AssumptionCache *AC_, DemandedBits *DB_,
3835 OptimizationRemarkEmitter *ORE_) {
3844 DL = &F.getParent()->getDataLayout();
3848 bool Changed = false;
3850 // If the target claims to have no vector registers don't attempt
3852 if (!TTI->getNumberOfRegisters(true))
3855 // Don't vectorize when the attribute NoImplicitFloat is used.
3856 if (F.hasFnAttribute(Attribute::NoImplicitFloat))
3859 DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
3861 // Use the bottom up slp vectorizer to construct chains that start with
3862 // store instructions.
3863 BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
3865 // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
3866 // delete instructions.
3868 // Scan the blocks in the function in post order.
3869 for (auto BB : post_order(&F.getEntryBlock())) {
3870 collectSeedInstructions(BB);
3872 // Vectorize trees that end at stores.
3873 if (!Stores.empty()) {
3874 DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
3875 << " underlying objects.\n");
3876 Changed |= vectorizeStoreChains(R);
3879 // Vectorize trees that end at reductions.
3880 Changed |= vectorizeChainsInBlock(BB, R);
3882 // Vectorize the index computations of getelementptr instructions. This
3883 // is primarily intended to catch gather-like idioms ending at
3884 // non-consecutive loads.
3885 if (!GEPs.empty()) {
3886 DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
3887 << " underlying objects.\n");
3888 Changed |= vectorizeGEPIndices(BB, R);
3893 R.optimizeGatherSequence();
3894 DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
3895 DEBUG(verifyFunction(F));
3900 /// \brief Check that the Values in the slice in VL array are still existent in
3901 /// the WeakTrackingVH array.
3902 /// Vectorization of part of the VL array may cause later values in the VL array
3903 /// to become invalid. We track when this has happened in the WeakTrackingVH
3905 static bool hasValueBeenRAUWed(ArrayRef<Value *> VL,
3906 ArrayRef<WeakTrackingVH> VH, unsigned SliceBegin,
3907 unsigned SliceSize) {
3908 VL = VL.slice(SliceBegin, SliceSize);
3909 VH = VH.slice(SliceBegin, SliceSize);
3910 return !std::equal(VL.begin(), VL.end(), VH.begin());
3913 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
3914 unsigned VecRegSize) {
3915 unsigned ChainLen = Chain.size();
3916 DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
3918 unsigned Sz = R.getVectorElementSize(Chain[0]);
3919 unsigned VF = VecRegSize / Sz;
3921 if (!isPowerOf2_32(Sz) || VF < 2)
3924 // Keep track of values that were deleted by vectorizing in the loop below.
3925 SmallVector<WeakTrackingVH, 8> TrackValues(Chain.begin(), Chain.end());
3927 bool Changed = false;
3928 // Look for profitable vectorizable trees at all offsets, starting at zero.
3929 for (unsigned i = 0, e = ChainLen; i < e; ++i) {
3933 // Check that a previous iteration of this loop did not delete the Value.
3934 if (hasValueBeenRAUWed(Chain, TrackValues, i, VF))
3937 DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
3939 ArrayRef<Value *> Operands = Chain.slice(i, VF);
3941 R.buildTree(Operands);
3942 if (R.isTreeTinyAndNotFullyVectorizable())
3945 R.computeMinimumValueSizes();
3947 int Cost = R.getTreeCost();
3949 DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
3950 if (Cost < -SLPCostThreshold) {
3951 DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
3952 using namespace ore;
3953 R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
3954 cast<StoreInst>(Chain[i]))
3955 << "Stores SLP vectorized with cost " << NV("Cost", Cost)
3956 << " and with tree size "
3957 << NV("TreeSize", R.getTreeSize()));
3961 // Move to the next bundle.
3970 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
3972 SetVector<StoreInst *> Heads, Tails;
3973 SmallDenseMap<StoreInst *, StoreInst *> ConsecutiveChain;
3975 // We may run into multiple chains that merge into a single chain. We mark the
3976 // stores that we vectorized so that we don't visit the same store twice.
3977 BoUpSLP::ValueSet VectorizedStores;
3978 bool Changed = false;
3980 // Do a quadratic search on all of the given stores and find
3981 // all of the pairs of stores that follow each other.
3982 SmallVector<unsigned, 16> IndexQueue;
3983 for (unsigned i = 0, e = Stores.size(); i < e; ++i) {
3985 // If a store has multiple consecutive store candidates, search Stores
3986 // array according to the sequence: from i+1 to e, then from i-1 to 0.
3987 // This is because usually pairing with immediate succeeding or preceding
3988 // candidate create the best chance to find slp vectorization opportunity.
3990 for (j = i + 1; j < e; ++j)
3991 IndexQueue.push_back(j);
3992 for (j = i; j > 0; --j)
3993 IndexQueue.push_back(j - 1);
3995 for (auto &k : IndexQueue) {
3996 if (isConsecutiveAccess(Stores[i], Stores[k], *DL, *SE)) {
3997 Tails.insert(Stores[k]);
3998 Heads.insert(Stores[i]);
3999 ConsecutiveChain[Stores[i]] = Stores[k];
4005 // For stores that start but don't end a link in the chain:
4006 for (SetVector<StoreInst *>::iterator it = Heads.begin(), e = Heads.end();
4008 if (Tails.count(*it))
4011 // We found a store instr that starts a chain. Now follow the chain and try
4013 BoUpSLP::ValueList Operands;
4015 // Collect the chain into a list.
4016 while (Tails.count(I) || Heads.count(I)) {
4017 if (VectorizedStores.count(I))
4019 Operands.push_back(I);
4020 // Move to the next value in the chain.
4021 I = ConsecutiveChain[I];
4024 // FIXME: Is division-by-2 the correct step? Should we assert that the
4025 // register size is a power-of-2?
4026 for (unsigned Size = R.getMaxVecRegSize(); Size >= R.getMinVecRegSize();
4028 if (vectorizeStoreChain(Operands, R, Size)) {
4029 // Mark the vectorized stores so that we don't vectorize them again.
4030 VectorizedStores.insert(Operands.begin(), Operands.end());
4040 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
4042 // Initialize the collections. We will make a single pass over the block.
4046 // Visit the store and getelementptr instructions in BB and organize them in
4047 // Stores and GEPs according to the underlying objects of their pointer
4049 for (Instruction &I : *BB) {
4051 // Ignore store instructions that are volatile or have a pointer operand
4052 // that doesn't point to a scalar type.
4053 if (auto *SI = dyn_cast<StoreInst>(&I)) {
4054 if (!SI->isSimple())
4056 if (!isValidElementType(SI->getValueOperand()->getType()))
4058 Stores[GetUnderlyingObject(SI->getPointerOperand(), *DL)].push_back(SI);
4061 // Ignore getelementptr instructions that have more than one index, a
4062 // constant index, or a pointer operand that doesn't point to a scalar
4064 else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
4065 auto Idx = GEP->idx_begin()->get();
4066 if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
4068 if (!isValidElementType(Idx->getType()))
4070 if (GEP->getType()->isVectorTy())
4072 GEPs[GetUnderlyingObject(GEP->getPointerOperand(), *DL)].push_back(GEP);
4077 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
4080 Value *VL[] = { A, B };
4081 return tryToVectorizeList(VL, R, None, true);
4084 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
4085 ArrayRef<Value *> BuildVector,
4086 bool AllowReorder) {
4090 DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = " << VL.size()
4093 // Check that all of the parts are scalar instructions of the same type.
4094 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
4098 unsigned Opcode0 = I0->getOpcode();
4100 unsigned Sz = R.getVectorElementSize(I0);
4101 unsigned MinVF = std::max(2U, R.getMinVecRegSize() / Sz);
4102 unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
4106 for (Value *V : VL) {
4107 Type *Ty = V->getType();
4108 if (!isValidElementType(Ty))
4110 Instruction *Inst = dyn_cast<Instruction>(V);
4111 if (!Inst || Inst->getOpcode() != Opcode0)
4115 bool Changed = false;
4117 // Keep track of values that were deleted by vectorizing in the loop below.
4118 SmallVector<WeakTrackingVH, 8> TrackValues(VL.begin(), VL.end());
4120 unsigned NextInst = 0, MaxInst = VL.size();
4121 for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF;
4123 // No actual vectorization should happen, if number of parts is the same as
4124 // provided vectorization factor (i.e. the scalar type is used for vector
4125 // code during codegen).
4126 auto *VecTy = VectorType::get(VL[0]->getType(), VF);
4127 if (TTI->getNumberOfParts(VecTy) == VF)
4129 for (unsigned I = NextInst; I < MaxInst; ++I) {
4130 unsigned OpsWidth = 0;
4132 if (I + VF > MaxInst)
4133 OpsWidth = MaxInst - I;
4137 if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
4140 // Check that a previous iteration of this loop did not delete the Value.
4141 if (hasValueBeenRAUWed(VL, TrackValues, I, OpsWidth))
4144 DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
4146 ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
4148 ArrayRef<Value *> BuildVectorSlice;
4149 if (!BuildVector.empty())
4150 BuildVectorSlice = BuildVector.slice(I, OpsWidth);
4152 R.buildTree(Ops, BuildVectorSlice);
4153 // TODO: check if we can allow reordering for more cases.
4154 if (AllowReorder && R.shouldReorder()) {
4155 // Conceptually, there is nothing actually preventing us from trying to
4156 // reorder a larger list. In fact, we do exactly this when vectorizing
4157 // reductions. However, at this point, we only expect to get here when
4158 // there are exactly two operations.
4159 assert(Ops.size() == 2);
4160 assert(BuildVectorSlice.empty());
4161 Value *ReorderedOps[] = {Ops[1], Ops[0]};
4162 R.buildTree(ReorderedOps, None);
4164 if (R.isTreeTinyAndNotFullyVectorizable())
4167 R.computeMinimumValueSizes();
4168 int Cost = R.getTreeCost();
4170 if (Cost < -SLPCostThreshold) {
4171 DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
4172 R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
4173 cast<Instruction>(Ops[0]))
4174 << "SLP vectorized with cost " << ore::NV("Cost", Cost)
4175 << " and with tree size "
4176 << ore::NV("TreeSize", R.getTreeSize()));
4178 Value *VectorizedRoot = R.vectorizeTree();
4180 // Reconstruct the build vector by extracting the vectorized root. This
4181 // way we handle the case where some elements of the vector are
4183 // (return (inserelt <4 xi32> (insertelt undef (opd0) 0) (opd1) 2))
4184 if (!BuildVectorSlice.empty()) {
4185 // The insert point is the last build vector instruction. The
4186 // vectorized root will precede it. This guarantees that we get an
4187 // instruction. The vectorized tree could have been constant folded.
4188 Instruction *InsertAfter = cast<Instruction>(BuildVectorSlice.back());
4189 unsigned VecIdx = 0;
4190 for (auto &V : BuildVectorSlice) {
4191 IRBuilder<NoFolder> Builder(InsertAfter->getParent(),
4192 ++BasicBlock::iterator(InsertAfter));
4193 Instruction *I = cast<Instruction>(V);
4194 assert(isa<InsertElementInst>(I) || isa<InsertValueInst>(I));
4195 Instruction *Extract =
4196 cast<Instruction>(Builder.CreateExtractElement(
4197 VectorizedRoot, Builder.getInt32(VecIdx++)));
4198 I->setOperand(1, Extract);
4199 I->removeFromParent();
4200 I->insertAfter(Extract);
4204 // Move to the next bundle.
4215 bool SLPVectorizerPass::tryToVectorize(BinaryOperator *V, BoUpSLP &R) {
4219 Value *P = V->getParent();
4221 // Vectorize in current basic block only.
4222 auto *Op0 = dyn_cast<Instruction>(V->getOperand(0));
4223 auto *Op1 = dyn_cast<Instruction>(V->getOperand(1));
4224 if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
4227 // Try to vectorize V.
4228 if (tryToVectorizePair(Op0, Op1, R))
4231 auto *A = dyn_cast<BinaryOperator>(Op0);
4232 auto *B = dyn_cast<BinaryOperator>(Op1);
4234 if (B && B->hasOneUse()) {
4235 auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
4236 auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
4237 if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
4239 if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
4244 if (A && A->hasOneUse()) {
4245 auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
4246 auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
4247 if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
4249 if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
4255 /// \brief Generate a shuffle mask to be used in a reduction tree.
4257 /// \param VecLen The length of the vector to be reduced.
4258 /// \param NumEltsToRdx The number of elements that should be reduced in the
4260 /// \param IsPairwise Whether the reduction is a pairwise or splitting
4261 /// reduction. A pairwise reduction will generate a mask of
4262 /// <0,2,...> or <1,3,..> while a splitting reduction will generate
4263 /// <2,3, undef,undef> for a vector of 4 and NumElts = 2.
4264 /// \param IsLeft True will generate a mask of even elements, odd otherwise.
4265 static Value *createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx,
4266 bool IsPairwise, bool IsLeft,
4267 IRBuilder<> &Builder) {
4268 assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask");
4270 SmallVector<Constant *, 32> ShuffleMask(
4271 VecLen, UndefValue::get(Builder.getInt32Ty()));
4274 // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
4275 for (unsigned i = 0; i != NumEltsToRdx; ++i)
4276 ShuffleMask[i] = Builder.getInt32(2 * i + !IsLeft);
4278 // Move the upper half of the vector to the lower half.
4279 for (unsigned i = 0; i != NumEltsToRdx; ++i)
4280 ShuffleMask[i] = Builder.getInt32(NumEltsToRdx + i);
4282 return ConstantVector::get(ShuffleMask);
4286 /// Model horizontal reductions.
4288 /// A horizontal reduction is a tree of reduction operations (currently add and
4289 /// fadd) that has operations that can be put into a vector as its leaf.
4290 /// For example, this tree:
4297 /// This tree has "mul" as its reduced values and "+" as its reduction
4298 /// operations. A reduction might be feeding into a store or a binary operation
4313 class HorizontalReduction {
4314 SmallVector<Value *, 16> ReductionOps;
4315 SmallVector<Value *, 32> ReducedVals;
4316 // Use map vector to make stable output.
4317 MapVector<Instruction *, Value *> ExtraArgs;
4319 BinaryOperator *ReductionRoot = nullptr;
4321 /// The opcode of the reduction.
4322 Instruction::BinaryOps ReductionOpcode = Instruction::BinaryOpsEnd;
4323 /// The opcode of the values we perform a reduction on.
4324 unsigned ReducedValueOpcode = 0;
4325 /// Should we model this reduction as a pairwise reduction tree or a tree that
4326 /// splits the vector in halves and adds those halves.
4327 bool IsPairwiseReduction = false;
4329 /// Checks if the ParentStackElem.first should be marked as a reduction
4330 /// operation with an extra argument or as extra argument itself.
4331 void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem,
4333 if (ExtraArgs.count(ParentStackElem.first)) {
4334 ExtraArgs[ParentStackElem.first] = nullptr;
4335 // We ran into something like:
4336 // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg.
4337 // The whole ParentStackElem.first should be considered as an extra value
4339 // Do not perform analysis of remaining operands of ParentStackElem.first
4340 // instruction, this whole instruction is an extra argument.
4341 ParentStackElem.second = ParentStackElem.first->getNumOperands();
4343 // We ran into something like:
4344 // ParentStackElem.first += ... + ExtraArg + ...
4345 ExtraArgs[ParentStackElem.first] = ExtraArg;
4350 HorizontalReduction() = default;
4352 /// \brief Try to find a reduction tree.
4353 bool matchAssociativeReduction(PHINode *Phi, BinaryOperator *B) {
4354 assert((!Phi || is_contained(Phi->operands(), B)) &&
4355 "Thi phi needs to use the binary operator");
4357 // We could have a initial reductions that is not an add.
4358 // r *= v1 + v2 + v3 + v4
4359 // In such a case start looking for a tree rooted in the first '+'.
4361 if (B->getOperand(0) == Phi) {
4363 B = dyn_cast<BinaryOperator>(B->getOperand(1));
4364 } else if (B->getOperand(1) == Phi) {
4366 B = dyn_cast<BinaryOperator>(B->getOperand(0));
4373 Type *Ty = B->getType();
4374 if (!isValidElementType(Ty))
4377 ReductionOpcode = B->getOpcode();
4378 ReducedValueOpcode = 0;
4381 // We currently only support adds.
4382 if ((ReductionOpcode != Instruction::Add &&
4383 ReductionOpcode != Instruction::FAdd) ||
4384 !B->isAssociative())
4387 // Post order traverse the reduction tree starting at B. We only handle true
4388 // trees containing only binary operators or selects.
4389 SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
4390 Stack.push_back(std::make_pair(B, 0));
4391 while (!Stack.empty()) {
4392 Instruction *TreeN = Stack.back().first;
4393 unsigned EdgeToVist = Stack.back().second++;
4394 bool IsReducedValue = TreeN->getOpcode() != ReductionOpcode;
4397 if (EdgeToVist == 2 || IsReducedValue) {
4399 ReducedVals.push_back(TreeN);
4401 auto I = ExtraArgs.find(TreeN);
4402 if (I != ExtraArgs.end() && !I->second) {
4403 // Check if TreeN is an extra argument of its parent operation.
4404 if (Stack.size() <= 1) {
4405 // TreeN can't be an extra argument as it is a root reduction
4409 // Yes, TreeN is an extra argument, do not add it to a list of
4410 // reduction operations.
4411 // Stack[Stack.size() - 2] always points to the parent operation.
4412 markExtraArg(Stack[Stack.size() - 2], TreeN);
4413 ExtraArgs.erase(TreeN);
4415 ReductionOps.push_back(TreeN);
4422 // Visit left or right.
4423 Value *NextV = TreeN->getOperand(EdgeToVist);
4425 auto *I = dyn_cast<Instruction>(NextV);
4426 // Continue analysis if the next operand is a reduction operation or
4427 // (possibly) a reduced value. If the reduced value opcode is not set,
4428 // the first met operation != reduction operation is considered as the
4429 // reduced value class.
4430 if (I && (!ReducedValueOpcode || I->getOpcode() == ReducedValueOpcode ||
4431 I->getOpcode() == ReductionOpcode)) {
4432 // Only handle trees in the current basic block.
4433 if (I->getParent() != B->getParent()) {
4434 // I is an extra argument for TreeN (its parent operation).
4435 markExtraArg(Stack.back(), I);
4439 // Each tree node needs to have one user except for the ultimate
4441 if (!I->hasOneUse() && I != B) {
4442 // I is an extra argument for TreeN (its parent operation).
4443 markExtraArg(Stack.back(), I);
4447 if (I->getOpcode() == ReductionOpcode) {
4448 // We need to be able to reassociate the reduction operations.
4449 if (!I->isAssociative()) {
4450 // I is an extra argument for TreeN (its parent operation).
4451 markExtraArg(Stack.back(), I);
4454 } else if (ReducedValueOpcode &&
4455 ReducedValueOpcode != I->getOpcode()) {
4456 // Make sure that the opcodes of the operations that we are going to
4458 // I is an extra argument for TreeN (its parent operation).
4459 markExtraArg(Stack.back(), I);
4461 } else if (!ReducedValueOpcode)
4462 ReducedValueOpcode = I->getOpcode();
4464 Stack.push_back(std::make_pair(I, 0));
4468 // NextV is an extra argument for TreeN (its parent operation).
4469 markExtraArg(Stack.back(), NextV);
4474 /// \brief Attempt to vectorize the tree found by
4475 /// matchAssociativeReduction.
4476 bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
4477 if (ReducedVals.empty())
4480 // If there is a sufficient number of reduction values, reduce
4481 // to a nearby power-of-2. Can safely generate oversized
4482 // vectors and rely on the backend to split them to legal sizes.
4483 unsigned NumReducedVals = ReducedVals.size();
4484 if (NumReducedVals < 4)
4487 unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
4489 Value *VectorizedTree = nullptr;
4490 IRBuilder<> Builder(ReductionRoot);
4491 FastMathFlags Unsafe;
4492 Unsafe.setUnsafeAlgebra();
4493 Builder.setFastMathFlags(Unsafe);
4496 BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
4497 // The same extra argument may be used several time, so log each attempt
4499 for (auto &Pair : ExtraArgs)
4500 ExternallyUsedValues[Pair.second].push_back(Pair.first);
4501 while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) {
4502 auto VL = makeArrayRef(&ReducedVals[i], ReduxWidth);
4503 V.buildTree(VL, ExternallyUsedValues, ReductionOps);
4504 if (V.shouldReorder()) {
4505 SmallVector<Value *, 8> Reversed(VL.rbegin(), VL.rend());
4506 V.buildTree(Reversed, ExternallyUsedValues, ReductionOps);
4508 if (V.isTreeTinyAndNotFullyVectorizable())
4511 V.computeMinimumValueSizes();
4515 V.getTreeCost() + getReductionCost(TTI, ReducedVals[i], ReduxWidth);
4516 if (Cost >= -SLPCostThreshold)
4519 DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" << Cost
4521 auto *I0 = cast<Instruction>(VL[0]);
4523 OptimizationRemark(SV_NAME, "VectorizedHorizontalReduction", I0)
4524 << "Vectorized horizontal reduction with cost "
4525 << ore::NV("Cost", Cost) << " and with tree size "
4526 << ore::NV("TreeSize", V.getTreeSize()));
4528 // Vectorize a tree.
4529 DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
4530 Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues);
4532 // Emit a reduction.
4533 Value *ReducedSubTree =
4534 emitReduction(VectorizedRoot, Builder, ReduxWidth, ReductionOps, TTI);
4535 if (VectorizedTree) {
4536 Builder.SetCurrentDebugLocation(Loc);
4537 VectorizedTree = Builder.CreateBinOp(ReductionOpcode, VectorizedTree,
4538 ReducedSubTree, "bin.rdx");
4539 propagateIRFlags(VectorizedTree, ReductionOps);
4541 VectorizedTree = ReducedSubTree;
4543 ReduxWidth = PowerOf2Floor(NumReducedVals - i);
4546 if (VectorizedTree) {
4547 // Finish the reduction.
4548 for (; i < NumReducedVals; ++i) {
4549 auto *I = cast<Instruction>(ReducedVals[i]);
4550 Builder.SetCurrentDebugLocation(I->getDebugLoc());
4552 Builder.CreateBinOp(ReductionOpcode, VectorizedTree, I);
4553 propagateIRFlags(VectorizedTree, ReductionOps);
4555 for (auto &Pair : ExternallyUsedValues) {
4556 assert(!Pair.second.empty() &&
4557 "At least one DebugLoc must be inserted");
4558 // Add each externally used value to the final reduction.
4559 for (auto *I : Pair.second) {
4560 Builder.SetCurrentDebugLocation(I->getDebugLoc());
4561 VectorizedTree = Builder.CreateBinOp(ReductionOpcode, VectorizedTree,
4562 Pair.first, "bin.extra");
4563 propagateIRFlags(VectorizedTree, I);
4567 ReductionRoot->replaceAllUsesWith(VectorizedTree);
4569 return VectorizedTree != nullptr;
4572 unsigned numReductionValues() const {
4573 return ReducedVals.size();
4577 /// \brief Calculate the cost of a reduction.
4578 int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal,
4579 unsigned ReduxWidth) {
4580 Type *ScalarTy = FirstReducedVal->getType();
4581 Type *VecTy = VectorType::get(ScalarTy, ReduxWidth);
4583 int PairwiseRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, true);
4584 int SplittingRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, false);
4586 IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
4587 int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
4589 int ScalarReduxCost =
4591 TTI->getArithmeticInstrCost(ReductionOpcode, ScalarTy);
4593 DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost
4594 << " for reduction that starts with " << *FirstReducedVal
4596 << (IsPairwiseReduction ? "pairwise" : "splitting")
4597 << " reduction)\n");
4599 return VecReduxCost - ScalarReduxCost;
4602 /// \brief Emit a horizontal reduction of the vectorized value.
4603 Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
4604 unsigned ReduxWidth, ArrayRef<Value *> RedOps,
4605 const TargetTransformInfo *TTI) {
4606 assert(VectorizedValue && "Need to have a vectorized tree node");
4607 assert(isPowerOf2_32(ReduxWidth) &&
4608 "We only handle power-of-two reductions for now");
4610 if (!IsPairwiseReduction)
4611 return createSimpleTargetReduction(
4612 Builder, TTI, ReductionOpcode, VectorizedValue,
4613 TargetTransformInfo::ReductionFlags(), RedOps);
4615 Value *TmpVec = VectorizedValue;
4616 for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
4618 createRdxShuffleMask(ReduxWidth, i, true, true, Builder);
4620 createRdxShuffleMask(ReduxWidth, i, true, false, Builder);
4622 Value *LeftShuf = Builder.CreateShuffleVector(
4623 TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l");
4624 Value *RightShuf = Builder.CreateShuffleVector(
4625 TmpVec, UndefValue::get(TmpVec->getType()), (RightMask),
4628 Builder.CreateBinOp(ReductionOpcode, LeftShuf, RightShuf, "bin.rdx");
4629 propagateIRFlags(TmpVec, RedOps);
4632 // The result is in the first element of the vector.
4633 return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
4636 } // end anonymous namespace
4638 /// \brief Recognize construction of vectors like
4639 /// %ra = insertelement <4 x float> undef, float %s0, i32 0
4640 /// %rb = insertelement <4 x float> %ra, float %s1, i32 1
4641 /// %rc = insertelement <4 x float> %rb, float %s2, i32 2
4642 /// %rd = insertelement <4 x float> %rc, float %s3, i32 3
4644 /// Returns true if it matches
4646 static bool findBuildVector(InsertElementInst *FirstInsertElem,
4647 SmallVectorImpl<Value *> &BuildVector,
4648 SmallVectorImpl<Value *> &BuildVectorOpds) {
4649 if (!isa<UndefValue>(FirstInsertElem->getOperand(0)))
4652 InsertElementInst *IE = FirstInsertElem;
4654 BuildVector.push_back(IE);
4655 BuildVectorOpds.push_back(IE->getOperand(1));
4657 if (IE->use_empty())
4660 InsertElementInst *NextUse = dyn_cast<InsertElementInst>(IE->user_back());
4664 // If this isn't the final use, make sure the next insertelement is the only
4665 // use. It's OK if the final constructed vector is used multiple times
4666 if (!IE->hasOneUse())
4675 /// \brief Like findBuildVector, but looks backwards for construction of aggregate.
4677 /// \return true if it matches.
4678 static bool findBuildAggregate(InsertValueInst *IV,
4679 SmallVectorImpl<Value *> &BuildVector,
4680 SmallVectorImpl<Value *> &BuildVectorOpds) {
4683 BuildVector.push_back(IV);
4684 BuildVectorOpds.push_back(IV->getInsertedValueOperand());
4685 V = IV->getAggregateOperand();
4686 if (isa<UndefValue>(V))
4688 IV = dyn_cast<InsertValueInst>(V);
4689 if (!IV || !IV->hasOneUse())
4692 std::reverse(BuildVector.begin(), BuildVector.end());
4693 std::reverse(BuildVectorOpds.begin(), BuildVectorOpds.end());
4697 static bool PhiTypeSorterFunc(Value *V, Value *V2) {
4698 return V->getType() < V2->getType();
4701 /// \brief Try and get a reduction value from a phi node.
4703 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
4704 /// if they come from either \p ParentBB or a containing loop latch.
4706 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
4707 /// if not possible.
4708 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
4709 BasicBlock *ParentBB, LoopInfo *LI) {
4710 // There are situations where the reduction value is not dominated by the
4711 // reduction phi. Vectorizing such cases has been reported to cause
4712 // miscompiles. See PR25787.
4713 auto DominatedReduxValue = [&](Value *R) {
4715 dyn_cast<Instruction>(R) &&
4716 DT->dominates(P->getParent(), dyn_cast<Instruction>(R)->getParent()));
4719 Value *Rdx = nullptr;
4721 // Return the incoming value if it comes from the same BB as the phi node.
4722 if (P->getIncomingBlock(0) == ParentBB) {
4723 Rdx = P->getIncomingValue(0);
4724 } else if (P->getIncomingBlock(1) == ParentBB) {
4725 Rdx = P->getIncomingValue(1);
4728 if (Rdx && DominatedReduxValue(Rdx))
4731 // Otherwise, check whether we have a loop latch to look at.
4732 Loop *BBL = LI->getLoopFor(ParentBB);
4735 BasicBlock *BBLatch = BBL->getLoopLatch();
4739 // There is a loop latch, return the incoming value if it comes from
4740 // that. This reduction pattern occasionally turns up.
4741 if (P->getIncomingBlock(0) == BBLatch) {
4742 Rdx = P->getIncomingValue(0);
4743 } else if (P->getIncomingBlock(1) == BBLatch) {
4744 Rdx = P->getIncomingValue(1);
4747 if (Rdx && DominatedReduxValue(Rdx))
4753 /// Attempt to reduce a horizontal reduction.
4754 /// If it is legal to match a horizontal reduction feeding the phi node \a P
4755 /// with reduction operators \a Root (or one of its operands) in a basic block
4756 /// \a BB, then check if it can be done. If horizontal reduction is not found
4757 /// and root instruction is a binary operation, vectorization of the operands is
4759 /// \returns true if a horizontal reduction was matched and reduced or operands
4760 /// of one of the binary instruction were vectorized.
4761 /// \returns false if a horizontal reduction was not matched (or not possible)
4762 /// or no vectorization of any binary operation feeding \a Root instruction was
4764 static bool tryToVectorizeHorReductionOrInstOperands(
4765 PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
4766 TargetTransformInfo *TTI,
4767 const function_ref<bool(BinaryOperator *, BoUpSLP &)> Vectorize) {
4768 if (!ShouldVectorizeHor)
4774 if (Root->getParent() != BB)
4776 // Start analysis starting from Root instruction. If horizontal reduction is
4777 // found, try to vectorize it. If it is not a horizontal reduction or
4778 // vectorization is not possible or not effective, and currently analyzed
4779 // instruction is a binary operation, try to vectorize the operands, using
4780 // pre-order DFS traversal order. If the operands were not vectorized, repeat
4781 // the same procedure considering each operand as a possible root of the
4782 // horizontal reduction.
4783 // Interrupt the process if the Root instruction itself was vectorized or all
4784 // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
4785 SmallVector<std::pair<WeakTrackingVH, unsigned>, 8> Stack(1, {Root, 0});
4786 SmallSet<Value *, 8> VisitedInstrs;
4788 while (!Stack.empty()) {
4791 std::tie(V, Level) = Stack.pop_back_val();
4794 auto *Inst = dyn_cast<Instruction>(V);
4795 if (!Inst || isa<PHINode>(Inst))
4797 if (auto *BI = dyn_cast<BinaryOperator>(Inst)) {
4798 HorizontalReduction HorRdx;
4799 if (HorRdx.matchAssociativeReduction(P, BI)) {
4800 if (HorRdx.tryToReduce(R, TTI)) {
4802 // Set P to nullptr to avoid re-analysis of phi node in
4803 // matchAssociativeReduction function unless this is the root node.
4809 Inst = dyn_cast<Instruction>(BI->getOperand(0));
4811 Inst = dyn_cast<Instruction>(BI->getOperand(1));
4813 // Set P to nullptr to avoid re-analysis of phi node in
4814 // matchAssociativeReduction function unless this is the root node.
4820 // Set P to nullptr to avoid re-analysis of phi node in
4821 // matchAssociativeReduction function unless this is the root node.
4823 if (Vectorize(dyn_cast<BinaryOperator>(Inst), R)) {
4828 // Try to vectorize operands.
4829 if (++Level < RecursionMaxDepth)
4830 for (auto *Op : Inst->operand_values())
4831 Stack.emplace_back(Op, Level);
4836 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
4837 BasicBlock *BB, BoUpSLP &R,
4838 TargetTransformInfo *TTI) {
4841 auto *I = dyn_cast<Instruction>(V);
4845 if (!isa<BinaryOperator>(I))
4847 // Try to match and vectorize a horizontal reduction.
4848 return tryToVectorizeHorReductionOrInstOperands(
4849 P, I, BB, R, TTI, [this](BinaryOperator *BI, BoUpSLP &R) -> bool {
4850 return tryToVectorize(BI, R);
4854 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
4855 bool Changed = false;
4856 SmallVector<Value *, 4> Incoming;
4857 SmallSet<Value *, 16> VisitedInstrs;
4859 bool HaveVectorizedPhiNodes = true;
4860 while (HaveVectorizedPhiNodes) {
4861 HaveVectorizedPhiNodes = false;
4863 // Collect the incoming values from the PHIs.
4865 for (Instruction &I : *BB) {
4866 PHINode *P = dyn_cast<PHINode>(&I);
4870 if (!VisitedInstrs.count(P))
4871 Incoming.push_back(P);
4875 std::stable_sort(Incoming.begin(), Incoming.end(), PhiTypeSorterFunc);
4877 // Try to vectorize elements base on their type.
4878 for (SmallVector<Value *, 4>::iterator IncIt = Incoming.begin(),
4882 // Look for the next elements with the same type.
4883 SmallVector<Value *, 4>::iterator SameTypeIt = IncIt;
4884 while (SameTypeIt != E &&
4885 (*SameTypeIt)->getType() == (*IncIt)->getType()) {
4886 VisitedInstrs.insert(*SameTypeIt);
4890 // Try to vectorize them.
4891 unsigned NumElts = (SameTypeIt - IncIt);
4892 DEBUG(errs() << "SLP: Trying to vectorize starting at PHIs (" << NumElts << ")\n");
4893 // The order in which the phi nodes appear in the program does not matter.
4894 // So allow tryToVectorizeList to reorder them if it is beneficial. This
4895 // is done when there are exactly two elements since tryToVectorizeList
4896 // asserts that there are only two values when AllowReorder is true.
4897 bool AllowReorder = NumElts == 2;
4898 if (NumElts > 1 && tryToVectorizeList(makeArrayRef(IncIt, NumElts), R,
4899 None, AllowReorder)) {
4900 // Success start over because instructions might have been changed.
4901 HaveVectorizedPhiNodes = true;
4906 // Start over at the next instruction of a different type (or the end).
4911 VisitedInstrs.clear();
4913 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) {
4914 // We may go through BB multiple times so skip the one we have checked.
4915 if (!VisitedInstrs.insert(&*it).second)
4918 if (isa<DbgInfoIntrinsic>(it))
4921 // Try to vectorize reductions that use PHINodes.
4922 if (PHINode *P = dyn_cast<PHINode>(it)) {
4923 // Check that the PHI is a reduction PHI.
4924 if (P->getNumIncomingValues() != 2)
4927 // Try to match and vectorize a horizontal reduction.
4928 if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
4938 if (ShouldStartVectorizeHorAtStore) {
4939 if (StoreInst *SI = dyn_cast<StoreInst>(it)) {
4940 // Try to match and vectorize a horizontal reduction.
4941 if (vectorizeRootInstruction(nullptr, SI->getValueOperand(), BB, R,
4951 // Try to vectorize horizontal reductions feeding into a return.
4952 if (ReturnInst *RI = dyn_cast<ReturnInst>(it)) {
4953 if (RI->getNumOperands() != 0) {
4954 // Try to match and vectorize a horizontal reduction.
4955 if (vectorizeRootInstruction(nullptr, RI->getOperand(0), BB, R, TTI)) {
4964 // Try to vectorize trees that start at compare instructions.
4965 if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
4966 if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) {
4968 // We would like to start over since some instructions are deleted
4969 // and the iterator may become invalid value.
4975 for (int I = 0; I < 2; ++I) {
4976 if (vectorizeRootInstruction(nullptr, CI->getOperand(I), BB, R, TTI)) {
4978 // We would like to start over since some instructions are deleted
4979 // and the iterator may become invalid value.
4988 // Try to vectorize trees that start at insertelement instructions.
4989 if (InsertElementInst *FirstInsertElem = dyn_cast<InsertElementInst>(it)) {
4990 SmallVector<Value *, 16> BuildVector;
4991 SmallVector<Value *, 16> BuildVectorOpds;
4992 if (!findBuildVector(FirstInsertElem, BuildVector, BuildVectorOpds))
4995 // Vectorize starting with the build vector operands ignoring the
4996 // BuildVector instructions for the purpose of scheduling and user
4998 if (tryToVectorizeList(BuildVectorOpds, R, BuildVector)) {
5007 // Try to vectorize trees that start at insertvalue instructions feeding into
5009 if (StoreInst *SI = dyn_cast<StoreInst>(it)) {
5010 if (InsertValueInst *LastInsertValue = dyn_cast<InsertValueInst>(SI->getValueOperand())) {
5011 const DataLayout &DL = BB->getModule()->getDataLayout();
5012 if (R.canMapToVector(SI->getValueOperand()->getType(), DL)) {
5013 SmallVector<Value *, 16> BuildVector;
5014 SmallVector<Value *, 16> BuildVectorOpds;
5015 if (!findBuildAggregate(LastInsertValue, BuildVector, BuildVectorOpds))
5018 DEBUG(dbgs() << "SLP: store of array mappable to vector: " << *SI << "\n");
5019 if (tryToVectorizeList(BuildVectorOpds, R, BuildVector, false)) {
5033 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
5034 auto Changed = false;
5035 for (auto &Entry : GEPs) {
5037 // If the getelementptr list has fewer than two elements, there's nothing
5039 if (Entry.second.size() < 2)
5042 DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
5043 << Entry.second.size() << ".\n");
5045 // We process the getelementptr list in chunks of 16 (like we do for
5046 // stores) to minimize compile-time.
5047 for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += 16) {
5048 auto Len = std::min<unsigned>(BE - BI, 16);
5049 auto GEPList = makeArrayRef(&Entry.second[BI], Len);
5051 // Initialize a set a candidate getelementptrs. Note that we use a
5052 // SetVector here to preserve program order. If the index computations
5053 // are vectorizable and begin with loads, we want to minimize the chance
5054 // of having to reorder them later.
5055 SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
5057 // Some of the candidates may have already been vectorized after we
5058 // initially collected them. If so, the WeakTrackingVHs will have
5060 // values, so remove them from the set of candidates.
5061 Candidates.remove(nullptr);
5063 // Remove from the set of candidates all pairs of getelementptrs with
5064 // constant differences. Such getelementptrs are likely not good
5065 // candidates for vectorization in a bottom-up phase since one can be
5066 // computed from the other. We also ensure all candidate getelementptr
5067 // indices are unique.
5068 for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
5069 auto *GEPI = cast<GetElementPtrInst>(GEPList[I]);
5070 if (!Candidates.count(GEPI))
5072 auto *SCEVI = SE->getSCEV(GEPList[I]);
5073 for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
5074 auto *GEPJ = cast<GetElementPtrInst>(GEPList[J]);
5075 auto *SCEVJ = SE->getSCEV(GEPList[J]);
5076 if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
5077 Candidates.remove(GEPList[I]);
5078 Candidates.remove(GEPList[J]);
5079 } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
5080 Candidates.remove(GEPList[J]);
5085 // We break out of the above computation as soon as we know there are
5086 // fewer than two candidates remaining.
5087 if (Candidates.size() < 2)
5090 // Add the single, non-constant index of each candidate to the bundle. We
5091 // ensured the indices met these constraints when we originally collected
5092 // the getelementptrs.
5093 SmallVector<Value *, 16> Bundle(Candidates.size());
5094 auto BundleIndex = 0u;
5095 for (auto *V : Candidates) {
5096 auto *GEP = cast<GetElementPtrInst>(V);
5097 auto *GEPIdx = GEP->idx_begin()->get();
5098 assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
5099 Bundle[BundleIndex++] = GEPIdx;
5102 // Try and vectorize the indices. We are currently only interested in
5103 // gather-like cases of the form:
5105 // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
5107 // where the loads of "a", the loads of "b", and the subtractions can be
5108 // performed in parallel. It's likely that detecting this pattern in a
5109 // bottom-up phase will be simpler and less costly than building a
5110 // full-blown top-down phase beginning at the consecutive loads.
5111 Changed |= tryToVectorizeList(Bundle, R);
5117 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
5118 bool Changed = false;
5119 // Attempt to sort and vectorize each of the store-groups.
5120 for (StoreListMap::iterator it = Stores.begin(), e = Stores.end(); it != e;
5122 if (it->second.size() < 2)
5125 DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
5126 << it->second.size() << ".\n");
5128 // Process the stores in chunks of 16.
5129 // TODO: The limit of 16 inhibits greater vectorization factors.
5130 // For example, AVX2 supports v32i8. Increasing this limit, however,
5131 // may cause a significant compile-time increase.
5132 for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI+=16) {
5133 unsigned Len = std::min<unsigned>(CE - CI, 16);
5134 Changed |= vectorizeStores(makeArrayRef(&it->second[CI], Len), R);
5140 char SLPVectorizer::ID = 0;
5141 static const char lv_name[] = "SLP Vectorizer";
5142 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
5143 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
5144 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
5145 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
5146 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
5147 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
5148 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
5149 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
5150 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
5153 Pass *createSLPVectorizerPass() { return new SLPVectorizer(); }