1 //===- SLPVectorizer.cpp - A bottom up SLP Vectorizer ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
9 // This pass implements the Bottom Up SLP vectorizer. It detects consecutive
10 // stores that can be put together into vector-stores. Next, it attempts to
11 // construct vectorizable tree using the use-def chains. If a profitable tree
12 // was found, the SLP vectorizer performs vectorization on the tree.
14 // The pass is inspired by the work described in the paper:
15 // "Loop-Aware SLP in GCC" by Ira Rosen, Dorit Nuzman, Ayal Zaks.
17 //===----------------------------------------------------------------------===//
18 #include "llvm/Transforms/Vectorize.h"
19 #include "llvm/ADT/MapVector.h"
20 #include "llvm/ADT/PostOrderIterator.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/Analysis/AssumptionCache.h"
26 #include "llvm/Analysis/CodeMetrics.h"
27 #include "llvm/Analysis/LoopInfo.h"
28 #include "llvm/Analysis/ScalarEvolution.h"
29 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
30 #include "llvm/Analysis/TargetTransformInfo.h"
31 #include "llvm/Analysis/ValueTracking.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/Dominators.h"
34 #include "llvm/IR/IRBuilder.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/IR/IntrinsicInst.h"
37 #include "llvm/IR/Module.h"
38 #include "llvm/IR/NoFolder.h"
39 #include "llvm/IR/Type.h"
40 #include "llvm/IR/Value.h"
41 #include "llvm/IR/Verifier.h"
42 #include "llvm/Pass.h"
43 #include "llvm/Support/CommandLine.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/Support/raw_ostream.h"
46 #include "llvm/Transforms/Utils/VectorUtils.h"
53 #define SV_NAME "slp-vectorizer"
54 #define DEBUG_TYPE "SLP"
56 STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
59 SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
60 cl::desc("Only vectorize if you gain more than this "
64 ShouldVectorizeHor("slp-vectorize-hor", cl::init(false), cl::Hidden,
65 cl::desc("Attempt to vectorize horizontal reductions"));
67 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
68 "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
70 "Attempt to vectorize horizontal reductions feeding into a store"));
74 static const unsigned MinVecRegSize = 128;
76 static const unsigned RecursionMaxDepth = 12;
78 // Limit the number of alias checks. The limit is chosen so that
79 // it has no negative effect on the llvm benchmarks.
80 static const unsigned AliasedCheckLimit = 10;
82 // Another limit for the alias checks: The maximum distance between load/store
83 // instructions where alias checks are done.
84 // This limit is useful for very large basic blocks.
85 static const int MaxMemDepDistance = 160;
87 /// \returns the parent basic block if all of the instructions in \p VL
88 /// are in the same block or null otherwise.
89 static BasicBlock *getSameBlock(ArrayRef<Value *> VL) {
90 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
93 BasicBlock *BB = I0->getParent();
94 for (int i = 1, e = VL.size(); i < e; i++) {
95 Instruction *I = dyn_cast<Instruction>(VL[i]);
99 if (BB != I->getParent())
105 /// \returns True if all of the values in \p VL are constants.
106 static bool allConstant(ArrayRef<Value *> VL) {
107 for (unsigned i = 0, e = VL.size(); i < e; ++i)
108 if (!isa<Constant>(VL[i]))
113 /// \returns True if all of the values in \p VL are identical.
114 static bool isSplat(ArrayRef<Value *> VL) {
115 for (unsigned i = 1, e = VL.size(); i < e; ++i)
121 ///\returns Opcode that can be clubbed with \p Op to create an alternate
122 /// sequence which can later be merged as a ShuffleVector instruction.
123 static unsigned getAltOpcode(unsigned Op) {
125 case Instruction::FAdd:
126 return Instruction::FSub;
127 case Instruction::FSub:
128 return Instruction::FAdd;
129 case Instruction::Add:
130 return Instruction::Sub;
131 case Instruction::Sub:
132 return Instruction::Add;
138 ///\returns bool representing if Opcode \p Op can be part
139 /// of an alternate sequence which can later be merged as
140 /// a ShuffleVector instruction.
141 static bool canCombineAsAltInst(unsigned Op) {
142 if (Op == Instruction::FAdd || Op == Instruction::FSub ||
143 Op == Instruction::Sub || Op == Instruction::Add)
148 /// \returns ShuffleVector instruction if intructions in \p VL have
149 /// alternate fadd,fsub / fsub,fadd/add,sub/sub,add sequence.
150 /// (i.e. e.g. opcodes of fadd,fsub,fadd,fsub...)
151 static unsigned isAltInst(ArrayRef<Value *> VL) {
152 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
153 unsigned Opcode = I0->getOpcode();
154 unsigned AltOpcode = getAltOpcode(Opcode);
155 for (int i = 1, e = VL.size(); i < e; i++) {
156 Instruction *I = dyn_cast<Instruction>(VL[i]);
157 if (!I || I->getOpcode() != ((i & 1) ? AltOpcode : Opcode))
160 return Instruction::ShuffleVector;
163 /// \returns The opcode if all of the Instructions in \p VL have the same
165 static unsigned getSameOpcode(ArrayRef<Value *> VL) {
166 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
169 unsigned Opcode = I0->getOpcode();
170 for (int i = 1, e = VL.size(); i < e; i++) {
171 Instruction *I = dyn_cast<Instruction>(VL[i]);
172 if (!I || Opcode != I->getOpcode()) {
173 if (canCombineAsAltInst(Opcode) && i == 1)
174 return isAltInst(VL);
181 /// Get the intersection (logical and) of all of the potential IR flags
182 /// of each scalar operation (VL) that will be converted into a vector (I).
183 /// Flag set: NSW, NUW, exact, and all of fast-math.
184 static void propagateIRFlags(Value *I, ArrayRef<Value *> VL) {
185 if (auto *VecOp = dyn_cast<BinaryOperator>(I)) {
186 if (auto *Intersection = dyn_cast<BinaryOperator>(VL[0])) {
187 // Intersection is initialized to the 0th scalar,
188 // so start counting from index '1'.
189 for (int i = 1, e = VL.size(); i < e; ++i) {
190 if (auto *Scalar = dyn_cast<BinaryOperator>(VL[i]))
191 Intersection->andIRFlags(Scalar);
193 VecOp->copyIRFlags(Intersection);
198 /// \returns \p I after propagating metadata from \p VL.
199 static Instruction *propagateMetadata(Instruction *I, ArrayRef<Value *> VL) {
200 Instruction *I0 = cast<Instruction>(VL[0]);
201 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
202 I0->getAllMetadataOtherThanDebugLoc(Metadata);
204 for (unsigned i = 0, n = Metadata.size(); i != n; ++i) {
205 unsigned Kind = Metadata[i].first;
206 MDNode *MD = Metadata[i].second;
208 for (int i = 1, e = VL.size(); MD && i != e; i++) {
209 Instruction *I = cast<Instruction>(VL[i]);
210 MDNode *IMD = I->getMetadata(Kind);
214 MD = nullptr; // Remove unknown metadata
216 case LLVMContext::MD_tbaa:
217 MD = MDNode::getMostGenericTBAA(MD, IMD);
219 case LLVMContext::MD_alias_scope:
220 case LLVMContext::MD_noalias:
221 MD = MDNode::intersect(MD, IMD);
223 case LLVMContext::MD_fpmath:
224 MD = MDNode::getMostGenericFPMath(MD, IMD);
228 I->setMetadata(Kind, MD);
233 /// \returns The type that all of the values in \p VL have or null if there
234 /// are different types.
235 static Type* getSameType(ArrayRef<Value *> VL) {
236 Type *Ty = VL[0]->getType();
237 for (int i = 1, e = VL.size(); i < e; i++)
238 if (VL[i]->getType() != Ty)
244 /// \returns True if the ExtractElement instructions in VL can be vectorized
245 /// to use the original vector.
246 static bool CanReuseExtract(ArrayRef<Value *> VL) {
247 assert(Instruction::ExtractElement == getSameOpcode(VL) && "Invalid opcode");
248 // Check if all of the extracts come from the same vector and from the
251 ExtractElementInst *E0 = cast<ExtractElementInst>(VL0);
252 Value *Vec = E0->getOperand(0);
254 // We have to extract from the same vector type.
255 unsigned NElts = Vec->getType()->getVectorNumElements();
257 if (NElts != VL.size())
260 // Check that all of the indices extract from the correct offset.
261 ConstantInt *CI = dyn_cast<ConstantInt>(E0->getOperand(1));
262 if (!CI || CI->getZExtValue())
265 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
266 ExtractElementInst *E = cast<ExtractElementInst>(VL[i]);
267 ConstantInt *CI = dyn_cast<ConstantInt>(E->getOperand(1));
269 if (!CI || CI->getZExtValue() != i || E->getOperand(0) != Vec)
276 /// \returns True if in-tree use also needs extract. This refers to
277 /// possible scalar operand in vectorized instruction.
278 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
279 TargetLibraryInfo *TLI) {
281 unsigned Opcode = UserInst->getOpcode();
283 case Instruction::Load: {
284 LoadInst *LI = cast<LoadInst>(UserInst);
285 return (LI->getPointerOperand() == Scalar);
287 case Instruction::Store: {
288 StoreInst *SI = cast<StoreInst>(UserInst);
289 return (SI->getPointerOperand() == Scalar);
291 case Instruction::Call: {
292 CallInst *CI = cast<CallInst>(UserInst);
293 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
294 if (hasVectorInstrinsicScalarOpd(ID, 1)) {
295 return (CI->getArgOperand(1) == Scalar);
303 /// \returns the AA location that is being access by the instruction.
304 static AliasAnalysis::Location getLocation(Instruction *I, AliasAnalysis *AA) {
305 if (StoreInst *SI = dyn_cast<StoreInst>(I))
306 return AA->getLocation(SI);
307 if (LoadInst *LI = dyn_cast<LoadInst>(I))
308 return AA->getLocation(LI);
309 return AliasAnalysis::Location();
312 /// Bottom Up SLP Vectorizer.
315 typedef SmallVector<Value *, 8> ValueList;
316 typedef SmallVector<Instruction *, 16> InstrList;
317 typedef SmallPtrSet<Value *, 16> ValueSet;
318 typedef SmallVector<StoreInst *, 8> StoreList;
320 BoUpSLP(Function *Func, ScalarEvolution *Se, const DataLayout *Dl,
321 TargetTransformInfo *Tti, TargetLibraryInfo *TLi, AliasAnalysis *Aa,
322 LoopInfo *Li, DominatorTree *Dt, AssumptionCache *AC)
323 : NumLoadsWantToKeepOrder(0), NumLoadsWantToChangeOrder(0), F(Func),
324 SE(Se), DL(Dl), TTI(Tti), TLI(TLi), AA(Aa), LI(Li), DT(Dt),
325 Builder(Se->getContext()) {
326 CodeMetrics::collectEphemeralValues(F, AC, EphValues);
329 /// \brief Vectorize the tree that starts with the elements in \p VL.
330 /// Returns the vectorized root.
331 Value *vectorizeTree();
333 /// \returns the cost incurred by unwanted spills and fills, caused by
334 /// holding live values over call sites.
337 /// \returns the vectorization cost of the subtree that starts at \p VL.
338 /// A negative number means that this is profitable.
341 /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
342 /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
343 void buildTree(ArrayRef<Value *> Roots,
344 ArrayRef<Value *> UserIgnoreLst = None);
346 /// Clear the internal data structures that are created by 'buildTree'.
348 VectorizableTree.clear();
349 ScalarToTreeEntry.clear();
351 ExternalUses.clear();
352 NumLoadsWantToKeepOrder = 0;
353 NumLoadsWantToChangeOrder = 0;
354 for (auto &Iter : BlocksSchedules) {
355 BlockScheduling *BS = Iter.second.get();
360 /// \returns true if the memory operations A and B are consecutive.
361 bool isConsecutiveAccess(Value *A, Value *B);
363 /// \brief Perform LICM and CSE on the newly generated gather sequences.
364 void optimizeGatherSequence();
366 /// \returns true if it is benefitial to reverse the vector order.
367 bool shouldReorder() const {
368 return NumLoadsWantToChangeOrder > NumLoadsWantToKeepOrder;
374 /// \returns the cost of the vectorizable entry.
375 int getEntryCost(TreeEntry *E);
377 /// This is the recursive part of buildTree.
378 void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth);
380 /// Vectorize a single entry in the tree.
381 Value *vectorizeTree(TreeEntry *E);
383 /// Vectorize a single entry in the tree, starting in \p VL.
384 Value *vectorizeTree(ArrayRef<Value *> VL);
386 /// \returns the pointer to the vectorized value if \p VL is already
387 /// vectorized, or NULL. They may happen in cycles.
388 Value *alreadyVectorized(ArrayRef<Value *> VL) const;
390 /// \brief Take the pointer operand from the Load/Store instruction.
391 /// \returns NULL if this is not a valid Load/Store instruction.
392 static Value *getPointerOperand(Value *I);
394 /// \brief Take the address space operand from the Load/Store instruction.
395 /// \returns -1 if this is not a valid Load/Store instruction.
396 static unsigned getAddressSpaceOperand(Value *I);
398 /// \returns the scalarization cost for this type. Scalarization in this
399 /// context means the creation of vectors from a group of scalars.
400 int getGatherCost(Type *Ty);
402 /// \returns the scalarization cost for this list of values. Assuming that
403 /// this subtree gets vectorized, we may need to extract the values from the
404 /// roots. This method calculates the cost of extracting the values.
405 int getGatherCost(ArrayRef<Value *> VL);
407 /// \brief Set the Builder insert point to one after the last instruction in
409 void setInsertPointAfterBundle(ArrayRef<Value *> VL);
411 /// \returns a vector from a collection of scalars in \p VL.
412 Value *Gather(ArrayRef<Value *> VL, VectorType *Ty);
414 /// \returns whether the VectorizableTree is fully vectoriable and will
415 /// be beneficial even the tree height is tiny.
416 bool isFullyVectorizableTinyTree();
418 /// \reorder commutative operands in alt shuffle if they result in
420 void reorderAltShuffleOperands(ArrayRef<Value *> VL,
421 SmallVectorImpl<Value *> &Left,
422 SmallVectorImpl<Value *> &Right);
423 /// \reorder commutative operands to get better probability of
424 /// generating vectorized code.
425 void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
426 SmallVectorImpl<Value *> &Left,
427 SmallVectorImpl<Value *> &Right);
429 TreeEntry() : Scalars(), VectorizedValue(nullptr),
432 /// \returns true if the scalars in VL are equal to this entry.
433 bool isSame(ArrayRef<Value *> VL) const {
434 assert(VL.size() == Scalars.size() && "Invalid size");
435 return std::equal(VL.begin(), VL.end(), Scalars.begin());
438 /// A vector of scalars.
441 /// The Scalars are vectorized into this value. It is initialized to Null.
442 Value *VectorizedValue;
444 /// Do we need to gather this sequence ?
448 /// Create a new VectorizableTree entry.
449 TreeEntry *newTreeEntry(ArrayRef<Value *> VL, bool Vectorized) {
450 VectorizableTree.push_back(TreeEntry());
451 int idx = VectorizableTree.size() - 1;
452 TreeEntry *Last = &VectorizableTree[idx];
453 Last->Scalars.insert(Last->Scalars.begin(), VL.begin(), VL.end());
454 Last->NeedToGather = !Vectorized;
456 for (int i = 0, e = VL.size(); i != e; ++i) {
457 assert(!ScalarToTreeEntry.count(VL[i]) && "Scalar already in tree!");
458 ScalarToTreeEntry[VL[i]] = idx;
461 MustGather.insert(VL.begin(), VL.end());
466 /// -- Vectorization State --
467 /// Holds all of the tree entries.
468 std::vector<TreeEntry> VectorizableTree;
470 /// Maps a specific scalar to its tree entry.
471 SmallDenseMap<Value*, int> ScalarToTreeEntry;
473 /// A list of scalars that we found that we need to keep as scalars.
476 /// This POD struct describes one external user in the vectorized tree.
477 struct ExternalUser {
478 ExternalUser (Value *S, llvm::User *U, int L) :
479 Scalar(S), User(U), Lane(L){};
480 // Which scalar in our function.
482 // Which user that uses the scalar.
484 // Which lane does the scalar belong to.
487 typedef SmallVector<ExternalUser, 16> UserList;
489 /// Checks if two instructions may access the same memory.
491 /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
492 /// is invariant in the calling loop.
493 bool isAliased(const AliasAnalysis::Location &Loc1, Instruction *Inst1,
494 Instruction *Inst2) {
496 // First check if the result is already in the cache.
497 AliasCacheKey key = std::make_pair(Inst1, Inst2);
498 Optional<bool> &result = AliasCache[key];
499 if (result.hasValue()) {
500 return result.getValue();
502 AliasAnalysis::Location Loc2 = getLocation(Inst2, AA);
504 if (Loc1.Ptr && Loc2.Ptr) {
505 // Do the alias check.
506 aliased = AA->alias(Loc1, Loc2);
508 // Store the result in the cache.
513 typedef std::pair<Instruction *, Instruction *> AliasCacheKey;
515 /// Cache for alias results.
516 /// TODO: consider moving this to the AliasAnalysis itself.
517 DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
519 /// Removes an instruction from its block and eventually deletes it.
520 /// It's like Instruction::eraseFromParent() except that the actual deletion
521 /// is delayed until BoUpSLP is destructed.
522 /// This is required to ensure that there are no incorrect collisions in the
523 /// AliasCache, which can happen if a new instruction is allocated at the
524 /// same address as a previously deleted instruction.
525 void eraseInstruction(Instruction *I) {
526 I->removeFromParent();
527 I->dropAllReferences();
528 DeletedInstructions.push_back(std::unique_ptr<Instruction>(I));
531 /// Temporary store for deleted instructions. Instructions will be deleted
532 /// eventually when the BoUpSLP is destructed.
533 SmallVector<std::unique_ptr<Instruction>, 8> DeletedInstructions;
535 /// A list of values that need to extracted out of the tree.
536 /// This list holds pairs of (Internal Scalar : External User).
537 UserList ExternalUses;
539 /// Values used only by @llvm.assume calls.
540 SmallPtrSet<const Value *, 32> EphValues;
542 /// Holds all of the instructions that we gathered.
543 SetVector<Instruction *> GatherSeq;
544 /// A list of blocks that we are going to CSE.
545 SetVector<BasicBlock *> CSEBlocks;
547 /// Contains all scheduling relevant data for an instruction.
548 /// A ScheduleData either represents a single instruction or a member of an
549 /// instruction bundle (= a group of instructions which is combined into a
550 /// vector instruction).
551 struct ScheduleData {
553 // The initial value for the dependency counters. It means that the
554 // dependencies are not calculated yet.
555 enum { InvalidDeps = -1 };
558 : Inst(nullptr), FirstInBundle(nullptr), NextInBundle(nullptr),
559 NextLoadStore(nullptr), SchedulingRegionID(0), SchedulingPriority(0),
560 Dependencies(InvalidDeps), UnscheduledDeps(InvalidDeps),
561 UnscheduledDepsInBundle(InvalidDeps), IsScheduled(false) {}
563 void init(int BlockSchedulingRegionID) {
564 FirstInBundle = this;
565 NextInBundle = nullptr;
566 NextLoadStore = nullptr;
568 SchedulingRegionID = BlockSchedulingRegionID;
569 UnscheduledDepsInBundle = UnscheduledDeps;
573 /// Returns true if the dependency information has been calculated.
574 bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
576 /// Returns true for single instructions and for bundle representatives
577 /// (= the head of a bundle).
578 bool isSchedulingEntity() const { return FirstInBundle == this; }
580 /// Returns true if it represents an instruction bundle and not only a
581 /// single instruction.
582 bool isPartOfBundle() const {
583 return NextInBundle != nullptr || FirstInBundle != this;
586 /// Returns true if it is ready for scheduling, i.e. it has no more
587 /// unscheduled depending instructions/bundles.
588 bool isReady() const {
589 assert(isSchedulingEntity() &&
590 "can't consider non-scheduling entity for ready list");
591 return UnscheduledDepsInBundle == 0 && !IsScheduled;
594 /// Modifies the number of unscheduled dependencies, also updating it for
595 /// the whole bundle.
596 int incrementUnscheduledDeps(int Incr) {
597 UnscheduledDeps += Incr;
598 return FirstInBundle->UnscheduledDepsInBundle += Incr;
601 /// Sets the number of unscheduled dependencies to the number of
603 void resetUnscheduledDeps() {
604 incrementUnscheduledDeps(Dependencies - UnscheduledDeps);
607 /// Clears all dependency information.
608 void clearDependencies() {
609 Dependencies = InvalidDeps;
610 resetUnscheduledDeps();
611 MemoryDependencies.clear();
614 void dump(raw_ostream &os) const {
615 if (!isSchedulingEntity()) {
617 } else if (NextInBundle) {
619 ScheduleData *SD = NextInBundle;
621 os << ';' << *SD->Inst;
622 SD = SD->NextInBundle;
632 /// Points to the head in an instruction bundle (and always to this for
633 /// single instructions).
634 ScheduleData *FirstInBundle;
636 /// Single linked list of all instructions in a bundle. Null if it is a
637 /// single instruction.
638 ScheduleData *NextInBundle;
640 /// Single linked list of all memory instructions (e.g. load, store, call)
641 /// in the block - until the end of the scheduling region.
642 ScheduleData *NextLoadStore;
644 /// The dependent memory instructions.
645 /// This list is derived on demand in calculateDependencies().
646 SmallVector<ScheduleData *, 4> MemoryDependencies;
648 /// This ScheduleData is in the current scheduling region if this matches
649 /// the current SchedulingRegionID of BlockScheduling.
650 int SchedulingRegionID;
652 /// Used for getting a "good" final ordering of instructions.
653 int SchedulingPriority;
655 /// The number of dependencies. Constitutes of the number of users of the
656 /// instruction plus the number of dependent memory instructions (if any).
657 /// This value is calculated on demand.
658 /// If InvalidDeps, the number of dependencies is not calculated yet.
662 /// The number of dependencies minus the number of dependencies of scheduled
663 /// instructions. As soon as this is zero, the instruction/bundle gets ready
665 /// Note that this is negative as long as Dependencies is not calculated.
668 /// The sum of UnscheduledDeps in a bundle. Equals to UnscheduledDeps for
669 /// single instructions.
670 int UnscheduledDepsInBundle;
672 /// True if this instruction is scheduled (or considered as scheduled in the
678 friend raw_ostream &operator<<(raw_ostream &os,
679 const BoUpSLP::ScheduleData &SD);
682 /// Contains all scheduling data for a basic block.
684 struct BlockScheduling {
686 BlockScheduling(BasicBlock *BB)
687 : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize),
688 ScheduleStart(nullptr), ScheduleEnd(nullptr),
689 FirstLoadStoreInRegion(nullptr), LastLoadStoreInRegion(nullptr),
690 // Make sure that the initial SchedulingRegionID is greater than the
691 // initial SchedulingRegionID in ScheduleData (which is 0).
692 SchedulingRegionID(1) {}
696 ScheduleStart = nullptr;
697 ScheduleEnd = nullptr;
698 FirstLoadStoreInRegion = nullptr;
699 LastLoadStoreInRegion = nullptr;
701 // Make a new scheduling region, i.e. all existing ScheduleData is not
702 // in the new region yet.
703 ++SchedulingRegionID;
706 ScheduleData *getScheduleData(Value *V) {
707 ScheduleData *SD = ScheduleDataMap[V];
708 if (SD && SD->SchedulingRegionID == SchedulingRegionID)
713 bool isInSchedulingRegion(ScheduleData *SD) {
714 return SD->SchedulingRegionID == SchedulingRegionID;
717 /// Marks an instruction as scheduled and puts all dependent ready
718 /// instructions into the ready-list.
719 template <typename ReadyListType>
720 void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
721 SD->IsScheduled = true;
722 DEBUG(dbgs() << "SLP: schedule " << *SD << "\n");
724 ScheduleData *BundleMember = SD;
725 while (BundleMember) {
726 // Handle the def-use chain dependencies.
727 for (Use &U : BundleMember->Inst->operands()) {
728 ScheduleData *OpDef = getScheduleData(U.get());
729 if (OpDef && OpDef->hasValidDependencies() &&
730 OpDef->incrementUnscheduledDeps(-1) == 0) {
731 // There are no more unscheduled dependencies after decrementing,
732 // so we can put the dependent instruction into the ready list.
733 ScheduleData *DepBundle = OpDef->FirstInBundle;
734 assert(!DepBundle->IsScheduled &&
735 "already scheduled bundle gets ready");
736 ReadyList.insert(DepBundle);
737 DEBUG(dbgs() << "SLP: gets ready (def): " << *DepBundle << "\n");
740 // Handle the memory dependencies.
741 for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
742 if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
743 // There are no more unscheduled dependencies after decrementing,
744 // so we can put the dependent instruction into the ready list.
745 ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
746 assert(!DepBundle->IsScheduled &&
747 "already scheduled bundle gets ready");
748 ReadyList.insert(DepBundle);
749 DEBUG(dbgs() << "SLP: gets ready (mem): " << *DepBundle << "\n");
752 BundleMember = BundleMember->NextInBundle;
756 /// Put all instructions into the ReadyList which are ready for scheduling.
757 template <typename ReadyListType>
758 void initialFillReadyList(ReadyListType &ReadyList) {
759 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
760 ScheduleData *SD = getScheduleData(I);
761 if (SD->isSchedulingEntity() && SD->isReady()) {
762 ReadyList.insert(SD);
763 DEBUG(dbgs() << "SLP: initially in ready list: " << *I << "\n");
768 /// Checks if a bundle of instructions can be scheduled, i.e. has no
769 /// cyclic dependencies. This is only a dry-run, no instructions are
770 /// actually moved at this stage.
771 bool tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP);
773 /// Un-bundles a group of instructions.
774 void cancelScheduling(ArrayRef<Value *> VL);
776 /// Extends the scheduling region so that V is inside the region.
777 void extendSchedulingRegion(Value *V);
779 /// Initialize the ScheduleData structures for new instructions in the
780 /// scheduling region.
781 void initScheduleData(Instruction *FromI, Instruction *ToI,
782 ScheduleData *PrevLoadStore,
783 ScheduleData *NextLoadStore);
785 /// Updates the dependency information of a bundle and of all instructions/
786 /// bundles which depend on the original bundle.
787 void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
790 /// Sets all instruction in the scheduling region to un-scheduled.
791 void resetSchedule();
795 /// Simple memory allocation for ScheduleData.
796 std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
798 /// The size of a ScheduleData array in ScheduleDataChunks.
801 /// The allocator position in the current chunk, which is the last entry
802 /// of ScheduleDataChunks.
805 /// Attaches ScheduleData to Instruction.
806 /// Note that the mapping survives during all vectorization iterations, i.e.
807 /// ScheduleData structures are recycled.
808 DenseMap<Value *, ScheduleData *> ScheduleDataMap;
810 struct ReadyList : SmallVector<ScheduleData *, 8> {
811 void insert(ScheduleData *SD) { push_back(SD); }
814 /// The ready-list for scheduling (only used for the dry-run).
815 ReadyList ReadyInsts;
817 /// The first instruction of the scheduling region.
818 Instruction *ScheduleStart;
820 /// The first instruction _after_ the scheduling region.
821 Instruction *ScheduleEnd;
823 /// The first memory accessing instruction in the scheduling region
825 ScheduleData *FirstLoadStoreInRegion;
827 /// The last memory accessing instruction in the scheduling region
829 ScheduleData *LastLoadStoreInRegion;
831 /// The ID of the scheduling region. For a new vectorization iteration this
832 /// is incremented which "removes" all ScheduleData from the region.
833 int SchedulingRegionID;
836 /// Attaches the BlockScheduling structures to basic blocks.
837 MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
839 /// Performs the "real" scheduling. Done before vectorization is actually
840 /// performed in a basic block.
841 void scheduleBlock(BlockScheduling *BS);
843 /// List of users to ignore during scheduling and that don't need extracting.
844 ArrayRef<Value *> UserIgnoreList;
846 // Number of load-bundles, which contain consecutive loads.
847 int NumLoadsWantToKeepOrder;
849 // Number of load-bundles of size 2, which are consecutive loads if reversed.
850 int NumLoadsWantToChangeOrder;
852 // Analysis and block reference.
855 const DataLayout *DL;
856 TargetTransformInfo *TTI;
857 TargetLibraryInfo *TLI;
861 /// Instruction builder to construct the vectorized tree.
866 raw_ostream &operator<<(raw_ostream &os, const BoUpSLP::ScheduleData &SD) {
872 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
873 ArrayRef<Value *> UserIgnoreLst) {
875 UserIgnoreList = UserIgnoreLst;
876 if (!getSameType(Roots))
878 buildTree_rec(Roots, 0);
880 // Collect the values that we need to extract from the tree.
881 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
882 TreeEntry *Entry = &VectorizableTree[EIdx];
885 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
886 Value *Scalar = Entry->Scalars[Lane];
888 // No need to handle users of gathered values.
889 if (Entry->NeedToGather)
892 for (User *U : Scalar->users()) {
893 DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
895 Instruction *UserInst = dyn_cast<Instruction>(U);
899 // Skip in-tree scalars that become vectors
900 if (ScalarToTreeEntry.count(U)) {
901 int Idx = ScalarToTreeEntry[U];
902 TreeEntry *UseEntry = &VectorizableTree[Idx];
903 Value *UseScalar = UseEntry->Scalars[0];
904 // Some in-tree scalars will remain as scalar in vectorized
905 // instructions. If that is the case, the one in Lane 0 will
907 if (UseScalar != U ||
908 !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
909 DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
911 assert(!VectorizableTree[Idx].NeedToGather && "Bad state");
916 // Ignore users in the user ignore list.
917 if (std::find(UserIgnoreList.begin(), UserIgnoreList.end(), UserInst) !=
918 UserIgnoreList.end())
921 DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane " <<
922 Lane << " from " << *Scalar << ".\n");
923 ExternalUses.push_back(ExternalUser(Scalar, U, Lane));
930 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth) {
931 bool SameTy = getSameType(VL); (void)SameTy;
932 bool isAltShuffle = false;
933 assert(SameTy && "Invalid types!");
935 if (Depth == RecursionMaxDepth) {
936 DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
937 newTreeEntry(VL, false);
941 // Don't handle vectors.
942 if (VL[0]->getType()->isVectorTy()) {
943 DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
944 newTreeEntry(VL, false);
948 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
949 if (SI->getValueOperand()->getType()->isVectorTy()) {
950 DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
951 newTreeEntry(VL, false);
954 unsigned Opcode = getSameOpcode(VL);
956 // Check that this shuffle vector refers to the alternate
957 // sequence of opcodes.
958 if (Opcode == Instruction::ShuffleVector) {
959 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
960 unsigned Op = I0->getOpcode();
961 if (Op != Instruction::ShuffleVector)
965 // If all of the operands are identical or constant we have a simple solution.
966 if (allConstant(VL) || isSplat(VL) || !getSameBlock(VL) || !Opcode) {
967 DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
968 newTreeEntry(VL, false);
972 // We now know that this is a vector of instructions of the same type from
975 // Don't vectorize ephemeral values.
976 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
977 if (EphValues.count(VL[i])) {
978 DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
979 ") is ephemeral.\n");
980 newTreeEntry(VL, false);
985 // Check if this is a duplicate of another entry.
986 if (ScalarToTreeEntry.count(VL[0])) {
987 int Idx = ScalarToTreeEntry[VL[0]];
988 TreeEntry *E = &VectorizableTree[Idx];
989 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
990 DEBUG(dbgs() << "SLP: \tChecking bundle: " << *VL[i] << ".\n");
991 if (E->Scalars[i] != VL[i]) {
992 DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
993 newTreeEntry(VL, false);
997 DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *VL[0] << ".\n");
1001 // Check that none of the instructions in the bundle are already in the tree.
1002 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1003 if (ScalarToTreeEntry.count(VL[i])) {
1004 DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
1005 ") is already in tree.\n");
1006 newTreeEntry(VL, false);
1011 // If any of the scalars is marked as a value that needs to stay scalar then
1012 // we need to gather the scalars.
1013 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1014 if (MustGather.count(VL[i])) {
1015 DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
1016 newTreeEntry(VL, false);
1021 // Check that all of the users of the scalars that we want to vectorize are
1023 Instruction *VL0 = cast<Instruction>(VL[0]);
1024 BasicBlock *BB = cast<Instruction>(VL0)->getParent();
1026 if (!DT->isReachableFromEntry(BB)) {
1027 // Don't go into unreachable blocks. They may contain instructions with
1028 // dependency cycles which confuse the final scheduling.
1029 DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
1030 newTreeEntry(VL, false);
1034 // Check that every instructions appears once in this bundle.
1035 for (unsigned i = 0, e = VL.size(); i < e; ++i)
1036 for (unsigned j = i+1; j < e; ++j)
1037 if (VL[i] == VL[j]) {
1038 DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
1039 newTreeEntry(VL, false);
1043 auto &BSRef = BlocksSchedules[BB];
1045 BSRef = llvm::make_unique<BlockScheduling>(BB);
1047 BlockScheduling &BS = *BSRef.get();
1049 if (!BS.tryScheduleBundle(VL, this)) {
1050 DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
1051 BS.cancelScheduling(VL);
1052 newTreeEntry(VL, false);
1055 DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
1058 case Instruction::PHI: {
1059 PHINode *PH = dyn_cast<PHINode>(VL0);
1061 // Check for terminator values (e.g. invoke).
1062 for (unsigned j = 0; j < VL.size(); ++j)
1063 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1064 TerminatorInst *Term = dyn_cast<TerminatorInst>(
1065 cast<PHINode>(VL[j])->getIncomingValueForBlock(PH->getIncomingBlock(i)));
1067 DEBUG(dbgs() << "SLP: Need to swizzle PHINodes (TerminatorInst use).\n");
1068 BS.cancelScheduling(VL);
1069 newTreeEntry(VL, false);
1074 newTreeEntry(VL, true);
1075 DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
1077 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1079 // Prepare the operand vector.
1080 for (unsigned j = 0; j < VL.size(); ++j)
1081 Operands.push_back(cast<PHINode>(VL[j])->getIncomingValueForBlock(
1082 PH->getIncomingBlock(i)));
1084 buildTree_rec(Operands, Depth + 1);
1088 case Instruction::ExtractElement: {
1089 bool Reuse = CanReuseExtract(VL);
1091 DEBUG(dbgs() << "SLP: Reusing extract sequence.\n");
1093 BS.cancelScheduling(VL);
1095 newTreeEntry(VL, Reuse);
1098 case Instruction::Load: {
1099 // Check if the loads are consecutive or of we need to swizzle them.
1100 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i) {
1101 LoadInst *L = cast<LoadInst>(VL[i]);
1102 if (!L->isSimple()) {
1103 BS.cancelScheduling(VL);
1104 newTreeEntry(VL, false);
1105 DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
1108 if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
1109 if (VL.size() == 2 && isConsecutiveAccess(VL[1], VL[0])) {
1110 ++NumLoadsWantToChangeOrder;
1112 BS.cancelScheduling(VL);
1113 newTreeEntry(VL, false);
1114 DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
1118 ++NumLoadsWantToKeepOrder;
1119 newTreeEntry(VL, true);
1120 DEBUG(dbgs() << "SLP: added a vector of loads.\n");
1123 case Instruction::ZExt:
1124 case Instruction::SExt:
1125 case Instruction::FPToUI:
1126 case Instruction::FPToSI:
1127 case Instruction::FPExt:
1128 case Instruction::PtrToInt:
1129 case Instruction::IntToPtr:
1130 case Instruction::SIToFP:
1131 case Instruction::UIToFP:
1132 case Instruction::Trunc:
1133 case Instruction::FPTrunc:
1134 case Instruction::BitCast: {
1135 Type *SrcTy = VL0->getOperand(0)->getType();
1136 for (unsigned i = 0; i < VL.size(); ++i) {
1137 Type *Ty = cast<Instruction>(VL[i])->getOperand(0)->getType();
1138 if (Ty != SrcTy || Ty->isAggregateType() || Ty->isVectorTy()) {
1139 BS.cancelScheduling(VL);
1140 newTreeEntry(VL, false);
1141 DEBUG(dbgs() << "SLP: Gathering casts with different src types.\n");
1145 newTreeEntry(VL, true);
1146 DEBUG(dbgs() << "SLP: added a vector of casts.\n");
1148 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1150 // Prepare the operand vector.
1151 for (unsigned j = 0; j < VL.size(); ++j)
1152 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1154 buildTree_rec(Operands, Depth+1);
1158 case Instruction::ICmp:
1159 case Instruction::FCmp: {
1160 // Check that all of the compares have the same predicate.
1161 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
1162 Type *ComparedTy = cast<Instruction>(VL[0])->getOperand(0)->getType();
1163 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
1164 CmpInst *Cmp = cast<CmpInst>(VL[i]);
1165 if (Cmp->getPredicate() != P0 ||
1166 Cmp->getOperand(0)->getType() != ComparedTy) {
1167 BS.cancelScheduling(VL);
1168 newTreeEntry(VL, false);
1169 DEBUG(dbgs() << "SLP: Gathering cmp with different predicate.\n");
1174 newTreeEntry(VL, true);
1175 DEBUG(dbgs() << "SLP: added a vector of compares.\n");
1177 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1179 // Prepare the operand vector.
1180 for (unsigned j = 0; j < VL.size(); ++j)
1181 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1183 buildTree_rec(Operands, Depth+1);
1187 case Instruction::Select:
1188 case Instruction::Add:
1189 case Instruction::FAdd:
1190 case Instruction::Sub:
1191 case Instruction::FSub:
1192 case Instruction::Mul:
1193 case Instruction::FMul:
1194 case Instruction::UDiv:
1195 case Instruction::SDiv:
1196 case Instruction::FDiv:
1197 case Instruction::URem:
1198 case Instruction::SRem:
1199 case Instruction::FRem:
1200 case Instruction::Shl:
1201 case Instruction::LShr:
1202 case Instruction::AShr:
1203 case Instruction::And:
1204 case Instruction::Or:
1205 case Instruction::Xor: {
1206 newTreeEntry(VL, true);
1207 DEBUG(dbgs() << "SLP: added a vector of bin op.\n");
1209 // Sort operands of the instructions so that each side is more likely to
1210 // have the same opcode.
1211 if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
1212 ValueList Left, Right;
1213 reorderInputsAccordingToOpcode(VL, Left, Right);
1214 buildTree_rec(Left, Depth + 1);
1215 buildTree_rec(Right, Depth + 1);
1219 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1221 // Prepare the operand vector.
1222 for (unsigned j = 0; j < VL.size(); ++j)
1223 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1225 buildTree_rec(Operands, Depth+1);
1229 case Instruction::GetElementPtr: {
1230 // We don't combine GEPs with complicated (nested) indexing.
1231 for (unsigned j = 0; j < VL.size(); ++j) {
1232 if (cast<Instruction>(VL[j])->getNumOperands() != 2) {
1233 DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
1234 BS.cancelScheduling(VL);
1235 newTreeEntry(VL, false);
1240 // We can't combine several GEPs into one vector if they operate on
1242 Type *Ty0 = cast<Instruction>(VL0)->getOperand(0)->getType();
1243 for (unsigned j = 0; j < VL.size(); ++j) {
1244 Type *CurTy = cast<Instruction>(VL[j])->getOperand(0)->getType();
1246 DEBUG(dbgs() << "SLP: not-vectorizable GEP (different types).\n");
1247 BS.cancelScheduling(VL);
1248 newTreeEntry(VL, false);
1253 // We don't combine GEPs with non-constant indexes.
1254 for (unsigned j = 0; j < VL.size(); ++j) {
1255 auto Op = cast<Instruction>(VL[j])->getOperand(1);
1256 if (!isa<ConstantInt>(Op)) {
1258 dbgs() << "SLP: not-vectorizable GEP (non-constant indexes).\n");
1259 BS.cancelScheduling(VL);
1260 newTreeEntry(VL, false);
1265 newTreeEntry(VL, true);
1266 DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
1267 for (unsigned i = 0, e = 2; i < e; ++i) {
1269 // Prepare the operand vector.
1270 for (unsigned j = 0; j < VL.size(); ++j)
1271 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1273 buildTree_rec(Operands, Depth + 1);
1277 case Instruction::Store: {
1278 // Check if the stores are consecutive or of we need to swizzle them.
1279 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
1280 if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
1281 BS.cancelScheduling(VL);
1282 newTreeEntry(VL, false);
1283 DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
1287 newTreeEntry(VL, true);
1288 DEBUG(dbgs() << "SLP: added a vector of stores.\n");
1291 for (unsigned j = 0; j < VL.size(); ++j)
1292 Operands.push_back(cast<Instruction>(VL[j])->getOperand(0));
1294 buildTree_rec(Operands, Depth + 1);
1297 case Instruction::Call: {
1298 // Check if the calls are all to the same vectorizable intrinsic.
1299 CallInst *CI = cast<CallInst>(VL[0]);
1300 // Check if this is an Intrinsic call or something that can be
1301 // represented by an intrinsic call
1302 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
1303 if (!isTriviallyVectorizable(ID)) {
1304 BS.cancelScheduling(VL);
1305 newTreeEntry(VL, false);
1306 DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
1309 Function *Int = CI->getCalledFunction();
1310 Value *A1I = nullptr;
1311 if (hasVectorInstrinsicScalarOpd(ID, 1))
1312 A1I = CI->getArgOperand(1);
1313 for (unsigned i = 1, e = VL.size(); i != e; ++i) {
1314 CallInst *CI2 = dyn_cast<CallInst>(VL[i]);
1315 if (!CI2 || CI2->getCalledFunction() != Int ||
1316 getIntrinsicIDForCall(CI2, TLI) != ID) {
1317 BS.cancelScheduling(VL);
1318 newTreeEntry(VL, false);
1319 DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *VL[i]
1323 // ctlz,cttz and powi are special intrinsics whose second argument
1324 // should be same in order for them to be vectorized.
1325 if (hasVectorInstrinsicScalarOpd(ID, 1)) {
1326 Value *A1J = CI2->getArgOperand(1);
1328 BS.cancelScheduling(VL);
1329 newTreeEntry(VL, false);
1330 DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
1331 << " argument "<< A1I<<"!=" << A1J
1338 newTreeEntry(VL, true);
1339 for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i) {
1341 // Prepare the operand vector.
1342 for (unsigned j = 0; j < VL.size(); ++j) {
1343 CallInst *CI2 = dyn_cast<CallInst>(VL[j]);
1344 Operands.push_back(CI2->getArgOperand(i));
1346 buildTree_rec(Operands, Depth + 1);
1350 case Instruction::ShuffleVector: {
1351 // If this is not an alternate sequence of opcode like add-sub
1352 // then do not vectorize this instruction.
1353 if (!isAltShuffle) {
1354 BS.cancelScheduling(VL);
1355 newTreeEntry(VL, false);
1356 DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
1359 newTreeEntry(VL, true);
1360 DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
1362 // Reorder operands if reordering would enable vectorization.
1363 if (isa<BinaryOperator>(VL0)) {
1364 ValueList Left, Right;
1365 reorderAltShuffleOperands(VL, Left, Right);
1366 buildTree_rec(Left, Depth + 1);
1367 buildTree_rec(Right, Depth + 1);
1371 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1373 // Prepare the operand vector.
1374 for (unsigned j = 0; j < VL.size(); ++j)
1375 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1377 buildTree_rec(Operands, Depth + 1);
1382 BS.cancelScheduling(VL);
1383 newTreeEntry(VL, false);
1384 DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
1389 int BoUpSLP::getEntryCost(TreeEntry *E) {
1390 ArrayRef<Value*> VL = E->Scalars;
1392 Type *ScalarTy = VL[0]->getType();
1393 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1394 ScalarTy = SI->getValueOperand()->getType();
1395 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1397 if (E->NeedToGather) {
1398 if (allConstant(VL))
1401 return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
1403 return getGatherCost(E->Scalars);
1405 unsigned Opcode = getSameOpcode(VL);
1406 assert(Opcode && getSameType(VL) && getSameBlock(VL) && "Invalid VL");
1407 Instruction *VL0 = cast<Instruction>(VL[0]);
1409 case Instruction::PHI: {
1412 case Instruction::ExtractElement: {
1413 if (CanReuseExtract(VL)) {
1415 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
1416 ExtractElementInst *E = cast<ExtractElementInst>(VL[i]);
1418 // Take credit for instruction that will become dead.
1420 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, i);
1424 return getGatherCost(VecTy);
1426 case Instruction::ZExt:
1427 case Instruction::SExt:
1428 case Instruction::FPToUI:
1429 case Instruction::FPToSI:
1430 case Instruction::FPExt:
1431 case Instruction::PtrToInt:
1432 case Instruction::IntToPtr:
1433 case Instruction::SIToFP:
1434 case Instruction::UIToFP:
1435 case Instruction::Trunc:
1436 case Instruction::FPTrunc:
1437 case Instruction::BitCast: {
1438 Type *SrcTy = VL0->getOperand(0)->getType();
1440 // Calculate the cost of this instruction.
1441 int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(),
1442 VL0->getType(), SrcTy);
1444 VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
1445 int VecCost = TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy);
1446 return VecCost - ScalarCost;
1448 case Instruction::FCmp:
1449 case Instruction::ICmp:
1450 case Instruction::Select:
1451 case Instruction::Add:
1452 case Instruction::FAdd:
1453 case Instruction::Sub:
1454 case Instruction::FSub:
1455 case Instruction::Mul:
1456 case Instruction::FMul:
1457 case Instruction::UDiv:
1458 case Instruction::SDiv:
1459 case Instruction::FDiv:
1460 case Instruction::URem:
1461 case Instruction::SRem:
1462 case Instruction::FRem:
1463 case Instruction::Shl:
1464 case Instruction::LShr:
1465 case Instruction::AShr:
1466 case Instruction::And:
1467 case Instruction::Or:
1468 case Instruction::Xor: {
1469 // Calculate the cost of this instruction.
1472 if (Opcode == Instruction::FCmp || Opcode == Instruction::ICmp ||
1473 Opcode == Instruction::Select) {
1474 VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
1475 ScalarCost = VecTy->getNumElements() *
1476 TTI->getCmpSelInstrCost(Opcode, ScalarTy, Builder.getInt1Ty());
1477 VecCost = TTI->getCmpSelInstrCost(Opcode, VecTy, MaskTy);
1479 // Certain instructions can be cheaper to vectorize if they have a
1480 // constant second vector operand.
1481 TargetTransformInfo::OperandValueKind Op1VK =
1482 TargetTransformInfo::OK_AnyValue;
1483 TargetTransformInfo::OperandValueKind Op2VK =
1484 TargetTransformInfo::OK_UniformConstantValue;
1485 TargetTransformInfo::OperandValueProperties Op1VP =
1486 TargetTransformInfo::OP_None;
1487 TargetTransformInfo::OperandValueProperties Op2VP =
1488 TargetTransformInfo::OP_None;
1490 // If all operands are exactly the same ConstantInt then set the
1491 // operand kind to OK_UniformConstantValue.
1492 // If instead not all operands are constants, then set the operand kind
1493 // to OK_AnyValue. If all operands are constants but not the same,
1494 // then set the operand kind to OK_NonUniformConstantValue.
1495 ConstantInt *CInt = nullptr;
1496 for (unsigned i = 0; i < VL.size(); ++i) {
1497 const Instruction *I = cast<Instruction>(VL[i]);
1498 if (!isa<ConstantInt>(I->getOperand(1))) {
1499 Op2VK = TargetTransformInfo::OK_AnyValue;
1503 CInt = cast<ConstantInt>(I->getOperand(1));
1506 if (Op2VK == TargetTransformInfo::OK_UniformConstantValue &&
1507 CInt != cast<ConstantInt>(I->getOperand(1)))
1508 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
1510 // FIXME: Currently cost of model modification for division by
1511 // power of 2 is handled only for X86. Add support for other targets.
1512 if (Op2VK == TargetTransformInfo::OK_UniformConstantValue && CInt &&
1513 CInt->getValue().isPowerOf2())
1514 Op2VP = TargetTransformInfo::OP_PowerOf2;
1516 ScalarCost = VecTy->getNumElements() *
1517 TTI->getArithmeticInstrCost(Opcode, ScalarTy, Op1VK, Op2VK,
1519 VecCost = TTI->getArithmeticInstrCost(Opcode, VecTy, Op1VK, Op2VK,
1522 return VecCost - ScalarCost;
1524 case Instruction::GetElementPtr: {
1525 TargetTransformInfo::OperandValueKind Op1VK =
1526 TargetTransformInfo::OK_AnyValue;
1527 TargetTransformInfo::OperandValueKind Op2VK =
1528 TargetTransformInfo::OK_UniformConstantValue;
1531 VecTy->getNumElements() *
1532 TTI->getArithmeticInstrCost(Instruction::Add, ScalarTy, Op1VK, Op2VK);
1534 TTI->getArithmeticInstrCost(Instruction::Add, VecTy, Op1VK, Op2VK);
1536 return VecCost - ScalarCost;
1538 case Instruction::Load: {
1539 // Cost of wide load - cost of scalar loads.
1540 int ScalarLdCost = VecTy->getNumElements() *
1541 TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
1542 int VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, 1, 0);
1543 return VecLdCost - ScalarLdCost;
1545 case Instruction::Store: {
1546 // We know that we can merge the stores. Calculate the cost.
1547 int ScalarStCost = VecTy->getNumElements() *
1548 TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
1549 int VecStCost = TTI->getMemoryOpCost(Instruction::Store, VecTy, 1, 0);
1550 return VecStCost - ScalarStCost;
1552 case Instruction::Call: {
1553 CallInst *CI = cast<CallInst>(VL0);
1554 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
1556 // Calculate the cost of the scalar and vector calls.
1557 SmallVector<Type*, 4> ScalarTys, VecTys;
1558 for (unsigned op = 0, opc = CI->getNumArgOperands(); op!= opc; ++op) {
1559 ScalarTys.push_back(CI->getArgOperand(op)->getType());
1560 VecTys.push_back(VectorType::get(CI->getArgOperand(op)->getType(),
1561 VecTy->getNumElements()));
1564 int ScalarCallCost = VecTy->getNumElements() *
1565 TTI->getIntrinsicInstrCost(ID, ScalarTy, ScalarTys);
1567 int VecCallCost = TTI->getIntrinsicInstrCost(ID, VecTy, VecTys);
1569 DEBUG(dbgs() << "SLP: Call cost "<< VecCallCost - ScalarCallCost
1570 << " (" << VecCallCost << "-" << ScalarCallCost << ")"
1571 << " for " << *CI << "\n");
1573 return VecCallCost - ScalarCallCost;
1575 case Instruction::ShuffleVector: {
1576 TargetTransformInfo::OperandValueKind Op1VK =
1577 TargetTransformInfo::OK_AnyValue;
1578 TargetTransformInfo::OperandValueKind Op2VK =
1579 TargetTransformInfo::OK_AnyValue;
1582 for (unsigned i = 0; i < VL.size(); ++i) {
1583 Instruction *I = cast<Instruction>(VL[i]);
1587 TTI->getArithmeticInstrCost(I->getOpcode(), ScalarTy, Op1VK, Op2VK);
1589 // VecCost is equal to sum of the cost of creating 2 vectors
1590 // and the cost of creating shuffle.
1591 Instruction *I0 = cast<Instruction>(VL[0]);
1593 TTI->getArithmeticInstrCost(I0->getOpcode(), VecTy, Op1VK, Op2VK);
1594 Instruction *I1 = cast<Instruction>(VL[1]);
1596 TTI->getArithmeticInstrCost(I1->getOpcode(), VecTy, Op1VK, Op2VK);
1598 TTI->getShuffleCost(TargetTransformInfo::SK_Alternate, VecTy, 0);
1599 return VecCost - ScalarCost;
1602 llvm_unreachable("Unknown instruction");
1606 bool BoUpSLP::isFullyVectorizableTinyTree() {
1607 DEBUG(dbgs() << "SLP: Check whether the tree with height " <<
1608 VectorizableTree.size() << " is fully vectorizable .\n");
1610 // We only handle trees of height 2.
1611 if (VectorizableTree.size() != 2)
1614 // Handle splat stores.
1615 if (!VectorizableTree[0].NeedToGather && isSplat(VectorizableTree[1].Scalars))
1618 // Gathering cost would be too much for tiny trees.
1619 if (VectorizableTree[0].NeedToGather || VectorizableTree[1].NeedToGather)
1625 int BoUpSLP::getSpillCost() {
1626 // Walk from the bottom of the tree to the top, tracking which values are
1627 // live. When we see a call instruction that is not part of our tree,
1628 // query TTI to see if there is a cost to keeping values live over it
1629 // (for example, if spills and fills are required).
1630 unsigned BundleWidth = VectorizableTree.front().Scalars.size();
1633 SmallPtrSet<Instruction*, 4> LiveValues;
1634 Instruction *PrevInst = nullptr;
1636 for (unsigned N = 0; N < VectorizableTree.size(); ++N) {
1637 Instruction *Inst = dyn_cast<Instruction>(VectorizableTree[N].Scalars[0]);
1647 dbgs() << "SLP: #LV: " << LiveValues.size();
1648 for (auto *X : LiveValues)
1649 dbgs() << " " << X->getName();
1650 dbgs() << ", Looking at ";
1654 // Update LiveValues.
1655 LiveValues.erase(PrevInst);
1656 for (auto &J : PrevInst->operands()) {
1657 if (isa<Instruction>(&*J) && ScalarToTreeEntry.count(&*J))
1658 LiveValues.insert(cast<Instruction>(&*J));
1661 // Now find the sequence of instructions between PrevInst and Inst.
1662 BasicBlock::reverse_iterator InstIt(Inst), PrevInstIt(PrevInst);
1664 while (InstIt != PrevInstIt) {
1665 if (PrevInstIt == PrevInst->getParent()->rend()) {
1666 PrevInstIt = Inst->getParent()->rbegin();
1670 if (isa<CallInst>(&*PrevInstIt) && &*PrevInstIt != PrevInst) {
1671 SmallVector<Type*, 4> V;
1672 for (auto *II : LiveValues)
1673 V.push_back(VectorType::get(II->getType(), BundleWidth));
1674 Cost += TTI->getCostOfKeepingLiveOverCall(V);
1683 DEBUG(dbgs() << "SLP: SpillCost=" << Cost << "\n");
1687 int BoUpSLP::getTreeCost() {
1689 DEBUG(dbgs() << "SLP: Calculating cost for tree of size " <<
1690 VectorizableTree.size() << ".\n");
1692 // We only vectorize tiny trees if it is fully vectorizable.
1693 if (VectorizableTree.size() < 3 && !isFullyVectorizableTinyTree()) {
1694 if (VectorizableTree.empty()) {
1695 assert(!ExternalUses.size() && "We should not have any external users");
1700 unsigned BundleWidth = VectorizableTree[0].Scalars.size();
1702 for (unsigned i = 0, e = VectorizableTree.size(); i != e; ++i) {
1703 int C = getEntryCost(&VectorizableTree[i]);
1704 DEBUG(dbgs() << "SLP: Adding cost " << C << " for bundle that starts with "
1705 << *VectorizableTree[i].Scalars[0] << " .\n");
1709 SmallSet<Value *, 16> ExtractCostCalculated;
1710 int ExtractCost = 0;
1711 for (UserList::iterator I = ExternalUses.begin(), E = ExternalUses.end();
1713 // We only add extract cost once for the same scalar.
1714 if (!ExtractCostCalculated.insert(I->Scalar).second)
1717 // Uses by ephemeral values are free (because the ephemeral value will be
1718 // removed prior to code generation, and so the extraction will be
1719 // removed as well).
1720 if (EphValues.count(I->User))
1723 VectorType *VecTy = VectorType::get(I->Scalar->getType(), BundleWidth);
1724 ExtractCost += TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy,
1728 Cost += getSpillCost();
1730 DEBUG(dbgs() << "SLP: Total Cost " << Cost + ExtractCost<< ".\n");
1731 return Cost + ExtractCost;
1734 int BoUpSLP::getGatherCost(Type *Ty) {
1736 for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
1737 Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
1741 int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) {
1742 // Find the type of the operands in VL.
1743 Type *ScalarTy = VL[0]->getType();
1744 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1745 ScalarTy = SI->getValueOperand()->getType();
1746 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1747 // Find the cost of inserting/extracting values from the vector.
1748 return getGatherCost(VecTy);
1751 Value *BoUpSLP::getPointerOperand(Value *I) {
1752 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1753 return LI->getPointerOperand();
1754 if (StoreInst *SI = dyn_cast<StoreInst>(I))
1755 return SI->getPointerOperand();
1759 unsigned BoUpSLP::getAddressSpaceOperand(Value *I) {
1760 if (LoadInst *L = dyn_cast<LoadInst>(I))
1761 return L->getPointerAddressSpace();
1762 if (StoreInst *S = dyn_cast<StoreInst>(I))
1763 return S->getPointerAddressSpace();
1767 bool BoUpSLP::isConsecutiveAccess(Value *A, Value *B) {
1768 Value *PtrA = getPointerOperand(A);
1769 Value *PtrB = getPointerOperand(B);
1770 unsigned ASA = getAddressSpaceOperand(A);
1771 unsigned ASB = getAddressSpaceOperand(B);
1773 // Check that the address spaces match and that the pointers are valid.
1774 if (!PtrA || !PtrB || (ASA != ASB))
1777 // Make sure that A and B are different pointers of the same type.
1778 if (PtrA == PtrB || PtrA->getType() != PtrB->getType())
1781 unsigned PtrBitWidth = DL->getPointerSizeInBits(ASA);
1782 Type *Ty = cast<PointerType>(PtrA->getType())->getElementType();
1783 APInt Size(PtrBitWidth, DL->getTypeStoreSize(Ty));
1785 APInt OffsetA(PtrBitWidth, 0), OffsetB(PtrBitWidth, 0);
1786 PtrA = PtrA->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetA);
1787 PtrB = PtrB->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetB);
1789 APInt OffsetDelta = OffsetB - OffsetA;
1791 // Check if they are based on the same pointer. That makes the offsets
1794 return OffsetDelta == Size;
1796 // Compute the necessary base pointer delta to have the necessary final delta
1797 // equal to the size.
1798 APInt BaseDelta = Size - OffsetDelta;
1800 // Otherwise compute the distance with SCEV between the base pointers.
1801 const SCEV *PtrSCEVA = SE->getSCEV(PtrA);
1802 const SCEV *PtrSCEVB = SE->getSCEV(PtrB);
1803 const SCEV *C = SE->getConstant(BaseDelta);
1804 const SCEV *X = SE->getAddExpr(PtrSCEVA, C);
1805 return X == PtrSCEVB;
1808 // Reorder commutative operations in alternate shuffle if the resulting vectors
1809 // are consecutive loads. This would allow us to vectorize the tree.
1810 // If we have something like-
1811 // load a[0] - load b[0]
1812 // load b[1] + load a[1]
1813 // load a[2] - load b[2]
1814 // load a[3] + load b[3]
1815 // Reordering the second load b[1] load a[1] would allow us to vectorize this
1817 void BoUpSLP::reorderAltShuffleOperands(ArrayRef<Value *> VL,
1818 SmallVectorImpl<Value *> &Left,
1819 SmallVectorImpl<Value *> &Right) {
1821 // Push left and right operands of binary operation into Left and Right
1822 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
1823 Left.push_back(cast<Instruction>(VL[i])->getOperand(0));
1824 Right.push_back(cast<Instruction>(VL[i])->getOperand(1));
1827 // Reorder if we have a commutative operation and consecutive access
1828 // are on either side of the alternate instructions.
1829 for (unsigned j = 0; j < VL.size() - 1; ++j) {
1830 if (LoadInst *L = dyn_cast<LoadInst>(Left[j])) {
1831 if (LoadInst *L1 = dyn_cast<LoadInst>(Right[j + 1])) {
1832 Instruction *VL1 = cast<Instruction>(VL[j]);
1833 Instruction *VL2 = cast<Instruction>(VL[j + 1]);
1834 if (isConsecutiveAccess(L, L1) && VL1->isCommutative()) {
1835 std::swap(Left[j], Right[j]);
1837 } else if (isConsecutiveAccess(L, L1) && VL2->isCommutative()) {
1838 std::swap(Left[j + 1], Right[j + 1]);
1844 if (LoadInst *L = dyn_cast<LoadInst>(Right[j])) {
1845 if (LoadInst *L1 = dyn_cast<LoadInst>(Left[j + 1])) {
1846 Instruction *VL1 = cast<Instruction>(VL[j]);
1847 Instruction *VL2 = cast<Instruction>(VL[j + 1]);
1848 if (isConsecutiveAccess(L, L1) && VL1->isCommutative()) {
1849 std::swap(Left[j], Right[j]);
1851 } else if (isConsecutiveAccess(L, L1) && VL2->isCommutative()) {
1852 std::swap(Left[j + 1], Right[j + 1]);
1861 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
1862 SmallVectorImpl<Value *> &Left,
1863 SmallVectorImpl<Value *> &Right) {
1865 SmallVector<Value *, 16> OrigLeft, OrigRight;
1867 bool AllSameOpcodeLeft = true;
1868 bool AllSameOpcodeRight = true;
1869 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1870 Instruction *I = cast<Instruction>(VL[i]);
1871 Value *VLeft = I->getOperand(0);
1872 Value *VRight = I->getOperand(1);
1874 OrigLeft.push_back(VLeft);
1875 OrigRight.push_back(VRight);
1877 Instruction *ILeft = dyn_cast<Instruction>(VLeft);
1878 Instruction *IRight = dyn_cast<Instruction>(VRight);
1880 // Check whether all operands on one side have the same opcode. In this case
1881 // we want to preserve the original order and not make things worse by
1883 if (i && AllSameOpcodeLeft && ILeft) {
1884 if (Instruction *PLeft = dyn_cast<Instruction>(OrigLeft[i - 1])) {
1885 if (PLeft->getOpcode() != ILeft->getOpcode())
1886 AllSameOpcodeLeft = false;
1888 AllSameOpcodeLeft = false;
1890 if (i && AllSameOpcodeRight && IRight) {
1891 if (Instruction *PRight = dyn_cast<Instruction>(OrigRight[i - 1])) {
1892 if (PRight->getOpcode() != IRight->getOpcode())
1893 AllSameOpcodeRight = false;
1895 AllSameOpcodeRight = false;
1898 // Sort two opcodes. In the code below we try to preserve the ability to use
1899 // broadcast of values instead of individual inserts.
1906 // If we just sorted according to opcode we would leave the first line in
1907 // tact but we would swap vl2 with vr2 because opcode(phi) > opcode(load).
1910 // Because vr2 and vr1 are from the same load we loose the opportunity of a
1911 // broadcast for the packed right side in the backend: we have [vr1, vl2]
1912 // instead of [vr1, vr2=vr1].
1913 if (ILeft && IRight) {
1914 if (!i && ILeft->getOpcode() > IRight->getOpcode()) {
1915 Left.push_back(IRight);
1916 Right.push_back(ILeft);
1917 } else if (i && ILeft->getOpcode() > IRight->getOpcode() &&
1918 Right[i - 1] != IRight) {
1919 // Try not to destroy a broad cast for no apparent benefit.
1920 Left.push_back(IRight);
1921 Right.push_back(ILeft);
1922 } else if (i && ILeft->getOpcode() == IRight->getOpcode() &&
1923 Right[i - 1] == ILeft) {
1924 // Try preserve broadcasts.
1925 Left.push_back(IRight);
1926 Right.push_back(ILeft);
1927 } else if (i && ILeft->getOpcode() == IRight->getOpcode() &&
1928 Left[i - 1] == IRight) {
1929 // Try preserve broadcasts.
1930 Left.push_back(IRight);
1931 Right.push_back(ILeft);
1933 Left.push_back(ILeft);
1934 Right.push_back(IRight);
1938 // One opcode, put the instruction on the right.
1940 Left.push_back(VRight);
1941 Right.push_back(ILeft);
1944 Left.push_back(VLeft);
1945 Right.push_back(VRight);
1948 bool LeftBroadcast = isSplat(Left);
1949 bool RightBroadcast = isSplat(Right);
1951 // If operands end up being broadcast return this operand order.
1952 if (LeftBroadcast || RightBroadcast)
1955 // Don't reorder if the operands where good to begin.
1956 if (AllSameOpcodeRight || AllSameOpcodeLeft) {
1961 // Finally check if we can get longer vectorizable chain by reordering
1962 // without breaking the good operand order detected above.
1963 // E.g. If we have something like-
1964 // load a[0] load b[0]
1965 // load b[1] load a[1]
1966 // load a[2] load b[2]
1967 // load a[3] load b[3]
1968 // Reordering the second load b[1] load a[1] would allow us to vectorize
1969 // this code and we still retain AllSameOpcode property.
1970 // FIXME: This load reordering might break AllSameOpcode in some rare cases
1972 // add a[0],c[0] load b[0]
1973 // add a[1],c[2] load b[1]
1975 // add a[3],c[3] load b[3]
1976 for (unsigned j = 0; j < VL.size() - 1; ++j) {
1977 if (LoadInst *L = dyn_cast<LoadInst>(Left[j])) {
1978 if (LoadInst *L1 = dyn_cast<LoadInst>(Right[j + 1])) {
1979 if (isConsecutiveAccess(L, L1)) {
1980 std::swap(Left[j + 1], Right[j + 1]);
1985 if (LoadInst *L = dyn_cast<LoadInst>(Right[j])) {
1986 if (LoadInst *L1 = dyn_cast<LoadInst>(Left[j + 1])) {
1987 if (isConsecutiveAccess(L, L1)) {
1988 std::swap(Left[j + 1], Right[j + 1]);
1997 void BoUpSLP::setInsertPointAfterBundle(ArrayRef<Value *> VL) {
1998 Instruction *VL0 = cast<Instruction>(VL[0]);
1999 BasicBlock::iterator NextInst = VL0;
2001 Builder.SetInsertPoint(VL0->getParent(), NextInst);
2002 Builder.SetCurrentDebugLocation(VL0->getDebugLoc());
2005 Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
2006 Value *Vec = UndefValue::get(Ty);
2007 // Generate the 'InsertElement' instruction.
2008 for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
2009 Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
2010 if (Instruction *Insrt = dyn_cast<Instruction>(Vec)) {
2011 GatherSeq.insert(Insrt);
2012 CSEBlocks.insert(Insrt->getParent());
2014 // Add to our 'need-to-extract' list.
2015 if (ScalarToTreeEntry.count(VL[i])) {
2016 int Idx = ScalarToTreeEntry[VL[i]];
2017 TreeEntry *E = &VectorizableTree[Idx];
2018 // Find which lane we need to extract.
2020 for (unsigned Lane = 0, LE = VL.size(); Lane != LE; ++Lane) {
2021 // Is this the lane of the scalar that we are looking for ?
2022 if (E->Scalars[Lane] == VL[i]) {
2027 assert(FoundLane >= 0 && "Could not find the correct lane");
2028 ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
2036 Value *BoUpSLP::alreadyVectorized(ArrayRef<Value *> VL) const {
2037 SmallDenseMap<Value*, int>::const_iterator Entry
2038 = ScalarToTreeEntry.find(VL[0]);
2039 if (Entry != ScalarToTreeEntry.end()) {
2040 int Idx = Entry->second;
2041 const TreeEntry *En = &VectorizableTree[Idx];
2042 if (En->isSame(VL) && En->VectorizedValue)
2043 return En->VectorizedValue;
2048 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
2049 if (ScalarToTreeEntry.count(VL[0])) {
2050 int Idx = ScalarToTreeEntry[VL[0]];
2051 TreeEntry *E = &VectorizableTree[Idx];
2053 return vectorizeTree(E);
2056 Type *ScalarTy = VL[0]->getType();
2057 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
2058 ScalarTy = SI->getValueOperand()->getType();
2059 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
2061 return Gather(VL, VecTy);
2064 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
2065 IRBuilder<>::InsertPointGuard Guard(Builder);
2067 if (E->VectorizedValue) {
2068 DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
2069 return E->VectorizedValue;
2072 Instruction *VL0 = cast<Instruction>(E->Scalars[0]);
2073 Type *ScalarTy = VL0->getType();
2074 if (StoreInst *SI = dyn_cast<StoreInst>(VL0))
2075 ScalarTy = SI->getValueOperand()->getType();
2076 VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size());
2078 if (E->NeedToGather) {
2079 setInsertPointAfterBundle(E->Scalars);
2080 return Gather(E->Scalars, VecTy);
2083 unsigned Opcode = getSameOpcode(E->Scalars);
2086 case Instruction::PHI: {
2087 PHINode *PH = dyn_cast<PHINode>(VL0);
2088 Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
2089 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
2090 PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
2091 E->VectorizedValue = NewPhi;
2093 // PHINodes may have multiple entries from the same block. We want to
2094 // visit every block once.
2095 SmallSet<BasicBlock*, 4> VisitedBBs;
2097 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
2099 BasicBlock *IBB = PH->getIncomingBlock(i);
2101 if (!VisitedBBs.insert(IBB).second) {
2102 NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
2106 // Prepare the operand vector.
2107 for (unsigned j = 0; j < E->Scalars.size(); ++j)
2108 Operands.push_back(cast<PHINode>(E->Scalars[j])->
2109 getIncomingValueForBlock(IBB));
2111 Builder.SetInsertPoint(IBB->getTerminator());
2112 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
2113 Value *Vec = vectorizeTree(Operands);
2114 NewPhi->addIncoming(Vec, IBB);
2117 assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
2118 "Invalid number of incoming values");
2122 case Instruction::ExtractElement: {
2123 if (CanReuseExtract(E->Scalars)) {
2124 Value *V = VL0->getOperand(0);
2125 E->VectorizedValue = V;
2128 return Gather(E->Scalars, VecTy);
2130 case Instruction::ZExt:
2131 case Instruction::SExt:
2132 case Instruction::FPToUI:
2133 case Instruction::FPToSI:
2134 case Instruction::FPExt:
2135 case Instruction::PtrToInt:
2136 case Instruction::IntToPtr:
2137 case Instruction::SIToFP:
2138 case Instruction::UIToFP:
2139 case Instruction::Trunc:
2140 case Instruction::FPTrunc:
2141 case Instruction::BitCast: {
2143 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
2144 INVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
2146 setInsertPointAfterBundle(E->Scalars);
2148 Value *InVec = vectorizeTree(INVL);
2150 if (Value *V = alreadyVectorized(E->Scalars))
2153 CastInst *CI = dyn_cast<CastInst>(VL0);
2154 Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
2155 E->VectorizedValue = V;
2156 ++NumVectorInstructions;
2159 case Instruction::FCmp:
2160 case Instruction::ICmp: {
2161 ValueList LHSV, RHSV;
2162 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
2163 LHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
2164 RHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
2167 setInsertPointAfterBundle(E->Scalars);
2169 Value *L = vectorizeTree(LHSV);
2170 Value *R = vectorizeTree(RHSV);
2172 if (Value *V = alreadyVectorized(E->Scalars))
2175 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
2177 if (Opcode == Instruction::FCmp)
2178 V = Builder.CreateFCmp(P0, L, R);
2180 V = Builder.CreateICmp(P0, L, R);
2182 E->VectorizedValue = V;
2183 ++NumVectorInstructions;
2186 case Instruction::Select: {
2187 ValueList TrueVec, FalseVec, CondVec;
2188 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
2189 CondVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
2190 TrueVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
2191 FalseVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(2));
2194 setInsertPointAfterBundle(E->Scalars);
2196 Value *Cond = vectorizeTree(CondVec);
2197 Value *True = vectorizeTree(TrueVec);
2198 Value *False = vectorizeTree(FalseVec);
2200 if (Value *V = alreadyVectorized(E->Scalars))
2203 Value *V = Builder.CreateSelect(Cond, True, False);
2204 E->VectorizedValue = V;
2205 ++NumVectorInstructions;
2208 case Instruction::Add:
2209 case Instruction::FAdd:
2210 case Instruction::Sub:
2211 case Instruction::FSub:
2212 case Instruction::Mul:
2213 case Instruction::FMul:
2214 case Instruction::UDiv:
2215 case Instruction::SDiv:
2216 case Instruction::FDiv:
2217 case Instruction::URem:
2218 case Instruction::SRem:
2219 case Instruction::FRem:
2220 case Instruction::Shl:
2221 case Instruction::LShr:
2222 case Instruction::AShr:
2223 case Instruction::And:
2224 case Instruction::Or:
2225 case Instruction::Xor: {
2226 ValueList LHSVL, RHSVL;
2227 if (isa<BinaryOperator>(VL0) && VL0->isCommutative())
2228 reorderInputsAccordingToOpcode(E->Scalars, LHSVL, RHSVL);
2230 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
2231 LHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
2232 RHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
2235 setInsertPointAfterBundle(E->Scalars);
2237 Value *LHS = vectorizeTree(LHSVL);
2238 Value *RHS = vectorizeTree(RHSVL);
2240 if (LHS == RHS && isa<Instruction>(LHS)) {
2241 assert((VL0->getOperand(0) == VL0->getOperand(1)) && "Invalid order");
2244 if (Value *V = alreadyVectorized(E->Scalars))
2247 BinaryOperator *BinOp = cast<BinaryOperator>(VL0);
2248 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), LHS, RHS);
2249 E->VectorizedValue = V;
2250 propagateIRFlags(E->VectorizedValue, E->Scalars);
2251 ++NumVectorInstructions;
2253 if (Instruction *I = dyn_cast<Instruction>(V))
2254 return propagateMetadata(I, E->Scalars);
2258 case Instruction::Load: {
2259 // Loads are inserted at the head of the tree because we don't want to
2260 // sink them all the way down past store instructions.
2261 setInsertPointAfterBundle(E->Scalars);
2263 LoadInst *LI = cast<LoadInst>(VL0);
2264 Type *ScalarLoadTy = LI->getType();
2265 unsigned AS = LI->getPointerAddressSpace();
2267 Value *VecPtr = Builder.CreateBitCast(LI->getPointerOperand(),
2268 VecTy->getPointerTo(AS));
2270 // The pointer operand uses an in-tree scalar so we add the new BitCast to
2271 // ExternalUses list to make sure that an extract will be generated in the
2273 if (ScalarToTreeEntry.count(LI->getPointerOperand()))
2274 ExternalUses.push_back(
2275 ExternalUser(LI->getPointerOperand(), cast<User>(VecPtr), 0));
2277 unsigned Alignment = LI->getAlignment();
2278 LI = Builder.CreateLoad(VecPtr);
2280 Alignment = DL->getABITypeAlignment(ScalarLoadTy);
2281 LI->setAlignment(Alignment);
2282 E->VectorizedValue = LI;
2283 ++NumVectorInstructions;
2284 return propagateMetadata(LI, E->Scalars);
2286 case Instruction::Store: {
2287 StoreInst *SI = cast<StoreInst>(VL0);
2288 unsigned Alignment = SI->getAlignment();
2289 unsigned AS = SI->getPointerAddressSpace();
2292 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
2293 ValueOp.push_back(cast<StoreInst>(E->Scalars[i])->getValueOperand());
2295 setInsertPointAfterBundle(E->Scalars);
2297 Value *VecValue = vectorizeTree(ValueOp);
2298 Value *VecPtr = Builder.CreateBitCast(SI->getPointerOperand(),
2299 VecTy->getPointerTo(AS));
2300 StoreInst *S = Builder.CreateStore(VecValue, VecPtr);
2302 // The pointer operand uses an in-tree scalar so we add the new BitCast to
2303 // ExternalUses list to make sure that an extract will be generated in the
2305 if (ScalarToTreeEntry.count(SI->getPointerOperand()))
2306 ExternalUses.push_back(
2307 ExternalUser(SI->getPointerOperand(), cast<User>(VecPtr), 0));
2310 Alignment = DL->getABITypeAlignment(SI->getValueOperand()->getType());
2311 S->setAlignment(Alignment);
2312 E->VectorizedValue = S;
2313 ++NumVectorInstructions;
2314 return propagateMetadata(S, E->Scalars);
2316 case Instruction::GetElementPtr: {
2317 setInsertPointAfterBundle(E->Scalars);
2320 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
2321 Op0VL.push_back(cast<GetElementPtrInst>(E->Scalars[i])->getOperand(0));
2323 Value *Op0 = vectorizeTree(Op0VL);
2325 std::vector<Value *> OpVecs;
2326 for (int j = 1, e = cast<GetElementPtrInst>(VL0)->getNumOperands(); j < e;
2329 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
2330 OpVL.push_back(cast<GetElementPtrInst>(E->Scalars[i])->getOperand(j));
2332 Value *OpVec = vectorizeTree(OpVL);
2333 OpVecs.push_back(OpVec);
2336 Value *V = Builder.CreateGEP(Op0, OpVecs);
2337 E->VectorizedValue = V;
2338 ++NumVectorInstructions;
2340 if (Instruction *I = dyn_cast<Instruction>(V))
2341 return propagateMetadata(I, E->Scalars);
2345 case Instruction::Call: {
2346 CallInst *CI = cast<CallInst>(VL0);
2347 setInsertPointAfterBundle(E->Scalars);
2349 Intrinsic::ID IID = Intrinsic::not_intrinsic;
2350 Value *ScalarArg = nullptr;
2351 if (CI && (FI = CI->getCalledFunction())) {
2352 IID = (Intrinsic::ID) FI->getIntrinsicID();
2354 std::vector<Value *> OpVecs;
2355 for (int j = 0, e = CI->getNumArgOperands(); j < e; ++j) {
2357 // ctlz,cttz and powi are special intrinsics whose second argument is
2358 // a scalar. This argument should not be vectorized.
2359 if (hasVectorInstrinsicScalarOpd(IID, 1) && j == 1) {
2360 CallInst *CEI = cast<CallInst>(E->Scalars[0]);
2361 ScalarArg = CEI->getArgOperand(j);
2362 OpVecs.push_back(CEI->getArgOperand(j));
2365 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
2366 CallInst *CEI = cast<CallInst>(E->Scalars[i]);
2367 OpVL.push_back(CEI->getArgOperand(j));
2370 Value *OpVec = vectorizeTree(OpVL);
2371 DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
2372 OpVecs.push_back(OpVec);
2375 Module *M = F->getParent();
2376 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
2377 Type *Tys[] = { VectorType::get(CI->getType(), E->Scalars.size()) };
2378 Function *CF = Intrinsic::getDeclaration(M, ID, Tys);
2379 Value *V = Builder.CreateCall(CF, OpVecs);
2381 // The scalar argument uses an in-tree scalar so we add the new vectorized
2382 // call to ExternalUses list to make sure that an extract will be
2383 // generated in the future.
2384 if (ScalarArg && ScalarToTreeEntry.count(ScalarArg))
2385 ExternalUses.push_back(ExternalUser(ScalarArg, cast<User>(V), 0));
2387 E->VectorizedValue = V;
2388 ++NumVectorInstructions;
2391 case Instruction::ShuffleVector: {
2392 ValueList LHSVL, RHSVL;
2393 assert(isa<BinaryOperator>(VL0) && "Invalid Shuffle Vector Operand");
2394 reorderAltShuffleOperands(E->Scalars, LHSVL, RHSVL);
2395 setInsertPointAfterBundle(E->Scalars);
2397 Value *LHS = vectorizeTree(LHSVL);
2398 Value *RHS = vectorizeTree(RHSVL);
2400 if (Value *V = alreadyVectorized(E->Scalars))
2403 // Create a vector of LHS op1 RHS
2404 BinaryOperator *BinOp0 = cast<BinaryOperator>(VL0);
2405 Value *V0 = Builder.CreateBinOp(BinOp0->getOpcode(), LHS, RHS);
2407 // Create a vector of LHS op2 RHS
2408 Instruction *VL1 = cast<Instruction>(E->Scalars[1]);
2409 BinaryOperator *BinOp1 = cast<BinaryOperator>(VL1);
2410 Value *V1 = Builder.CreateBinOp(BinOp1->getOpcode(), LHS, RHS);
2412 // Create shuffle to take alternate operations from the vector.
2413 // Also, gather up odd and even scalar ops to propagate IR flags to
2414 // each vector operation.
2415 ValueList OddScalars, EvenScalars;
2416 unsigned e = E->Scalars.size();
2417 SmallVector<Constant *, 8> Mask(e);
2418 for (unsigned i = 0; i < e; ++i) {
2420 Mask[i] = Builder.getInt32(e + i);
2421 OddScalars.push_back(E->Scalars[i]);
2423 Mask[i] = Builder.getInt32(i);
2424 EvenScalars.push_back(E->Scalars[i]);
2428 Value *ShuffleMask = ConstantVector::get(Mask);
2429 propagateIRFlags(V0, EvenScalars);
2430 propagateIRFlags(V1, OddScalars);
2432 Value *V = Builder.CreateShuffleVector(V0, V1, ShuffleMask);
2433 E->VectorizedValue = V;
2434 ++NumVectorInstructions;
2435 if (Instruction *I = dyn_cast<Instruction>(V))
2436 return propagateMetadata(I, E->Scalars);
2441 llvm_unreachable("unknown inst");
2446 Value *BoUpSLP::vectorizeTree() {
2448 // All blocks must be scheduled before any instructions are inserted.
2449 for (auto &BSIter : BlocksSchedules) {
2450 scheduleBlock(BSIter.second.get());
2453 Builder.SetInsertPoint(F->getEntryBlock().begin());
2454 vectorizeTree(&VectorizableTree[0]);
2456 DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() << " values .\n");
2458 // Extract all of the elements with the external uses.
2459 for (UserList::iterator it = ExternalUses.begin(), e = ExternalUses.end();
2461 Value *Scalar = it->Scalar;
2462 llvm::User *User = it->User;
2464 // Skip users that we already RAUW. This happens when one instruction
2465 // has multiple uses of the same value.
2466 if (std::find(Scalar->user_begin(), Scalar->user_end(), User) ==
2469 assert(ScalarToTreeEntry.count(Scalar) && "Invalid scalar");
2471 int Idx = ScalarToTreeEntry[Scalar];
2472 TreeEntry *E = &VectorizableTree[Idx];
2473 assert(!E->NeedToGather && "Extracting from a gather list");
2475 Value *Vec = E->VectorizedValue;
2476 assert(Vec && "Can't find vectorizable value");
2478 Value *Lane = Builder.getInt32(it->Lane);
2479 // Generate extracts for out-of-tree users.
2480 // Find the insertion point for the extractelement lane.
2481 if (isa<Instruction>(Vec)){
2482 if (PHINode *PH = dyn_cast<PHINode>(User)) {
2483 for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
2484 if (PH->getIncomingValue(i) == Scalar) {
2485 Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
2486 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2487 CSEBlocks.insert(PH->getIncomingBlock(i));
2488 PH->setOperand(i, Ex);
2492 Builder.SetInsertPoint(cast<Instruction>(User));
2493 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2494 CSEBlocks.insert(cast<Instruction>(User)->getParent());
2495 User->replaceUsesOfWith(Scalar, Ex);
2498 Builder.SetInsertPoint(F->getEntryBlock().begin());
2499 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2500 CSEBlocks.insert(&F->getEntryBlock());
2501 User->replaceUsesOfWith(Scalar, Ex);
2504 DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
2507 // For each vectorized value:
2508 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
2509 TreeEntry *Entry = &VectorizableTree[EIdx];
2512 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
2513 Value *Scalar = Entry->Scalars[Lane];
2514 // No need to handle users of gathered values.
2515 if (Entry->NeedToGather)
2518 assert(Entry->VectorizedValue && "Can't find vectorizable value");
2520 Type *Ty = Scalar->getType();
2521 if (!Ty->isVoidTy()) {
2523 for (User *U : Scalar->users()) {
2524 DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
2526 assert((ScalarToTreeEntry.count(U) ||
2527 // It is legal to replace users in the ignorelist by undef.
2528 (std::find(UserIgnoreList.begin(), UserIgnoreList.end(), U) !=
2529 UserIgnoreList.end())) &&
2530 "Replacing out-of-tree value with undef");
2533 Value *Undef = UndefValue::get(Ty);
2534 Scalar->replaceAllUsesWith(Undef);
2536 DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
2537 eraseInstruction(cast<Instruction>(Scalar));
2541 Builder.ClearInsertionPoint();
2543 return VectorizableTree[0].VectorizedValue;
2546 void BoUpSLP::optimizeGatherSequence() {
2547 DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
2548 << " gather sequences instructions.\n");
2549 // LICM InsertElementInst sequences.
2550 for (SetVector<Instruction *>::iterator it = GatherSeq.begin(),
2551 e = GatherSeq.end(); it != e; ++it) {
2552 InsertElementInst *Insert = dyn_cast<InsertElementInst>(*it);
2557 // Check if this block is inside a loop.
2558 Loop *L = LI->getLoopFor(Insert->getParent());
2562 // Check if it has a preheader.
2563 BasicBlock *PreHeader = L->getLoopPreheader();
2567 // If the vector or the element that we insert into it are
2568 // instructions that are defined in this basic block then we can't
2569 // hoist this instruction.
2570 Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
2571 Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
2572 if (CurrVec && L->contains(CurrVec))
2574 if (NewElem && L->contains(NewElem))
2577 // We can hoist this instruction. Move it to the pre-header.
2578 Insert->moveBefore(PreHeader->getTerminator());
2581 // Make a list of all reachable blocks in our CSE queue.
2582 SmallVector<const DomTreeNode *, 8> CSEWorkList;
2583 CSEWorkList.reserve(CSEBlocks.size());
2584 for (BasicBlock *BB : CSEBlocks)
2585 if (DomTreeNode *N = DT->getNode(BB)) {
2586 assert(DT->isReachableFromEntry(N));
2587 CSEWorkList.push_back(N);
2590 // Sort blocks by domination. This ensures we visit a block after all blocks
2591 // dominating it are visited.
2592 std::stable_sort(CSEWorkList.begin(), CSEWorkList.end(),
2593 [this](const DomTreeNode *A, const DomTreeNode *B) {
2594 return DT->properlyDominates(A, B);
2597 // Perform O(N^2) search over the gather sequences and merge identical
2598 // instructions. TODO: We can further optimize this scan if we split the
2599 // instructions into different buckets based on the insert lane.
2600 SmallVector<Instruction *, 16> Visited;
2601 for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
2602 assert((I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
2603 "Worklist not sorted properly!");
2604 BasicBlock *BB = (*I)->getBlock();
2605 // For all instructions in blocks containing gather sequences:
2606 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) {
2607 Instruction *In = it++;
2608 if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In))
2611 // Check if we can replace this instruction with any of the
2612 // visited instructions.
2613 for (SmallVectorImpl<Instruction *>::iterator v = Visited.begin(),
2616 if (In->isIdenticalTo(*v) &&
2617 DT->dominates((*v)->getParent(), In->getParent())) {
2618 In->replaceAllUsesWith(*v);
2619 eraseInstruction(In);
2625 assert(std::find(Visited.begin(), Visited.end(), In) == Visited.end());
2626 Visited.push_back(In);
2634 // Groups the instructions to a bundle (which is then a single scheduling entity)
2635 // and schedules instructions until the bundle gets ready.
2636 bool BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL,
2638 if (isa<PHINode>(VL[0]))
2641 // Initialize the instruction bundle.
2642 Instruction *OldScheduleEnd = ScheduleEnd;
2643 ScheduleData *PrevInBundle = nullptr;
2644 ScheduleData *Bundle = nullptr;
2645 bool ReSchedule = false;
2646 DEBUG(dbgs() << "SLP: bundle: " << *VL[0] << "\n");
2647 for (Value *V : VL) {
2648 extendSchedulingRegion(V);
2649 ScheduleData *BundleMember = getScheduleData(V);
2650 assert(BundleMember &&
2651 "no ScheduleData for bundle member (maybe not in same basic block)");
2652 if (BundleMember->IsScheduled) {
2653 // A bundle member was scheduled as single instruction before and now
2654 // needs to be scheduled as part of the bundle. We just get rid of the
2655 // existing schedule.
2656 DEBUG(dbgs() << "SLP: reset schedule because " << *BundleMember
2657 << " was already scheduled\n");
2660 assert(BundleMember->isSchedulingEntity() &&
2661 "bundle member already part of other bundle");
2663 PrevInBundle->NextInBundle = BundleMember;
2665 Bundle = BundleMember;
2667 BundleMember->UnscheduledDepsInBundle = 0;
2668 Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps;
2670 // Group the instructions to a bundle.
2671 BundleMember->FirstInBundle = Bundle;
2672 PrevInBundle = BundleMember;
2674 if (ScheduleEnd != OldScheduleEnd) {
2675 // The scheduling region got new instructions at the lower end (or it is a
2676 // new region for the first bundle). This makes it necessary to
2677 // recalculate all dependencies.
2678 // It is seldom that this needs to be done a second time after adding the
2679 // initial bundle to the region.
2680 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2681 ScheduleData *SD = getScheduleData(I);
2682 SD->clearDependencies();
2688 initialFillReadyList(ReadyInsts);
2691 DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle << " in block "
2692 << BB->getName() << "\n");
2694 calculateDependencies(Bundle, true, SLP);
2696 // Now try to schedule the new bundle. As soon as the bundle is "ready" it
2697 // means that there are no cyclic dependencies and we can schedule it.
2698 // Note that's important that we don't "schedule" the bundle yet (see
2699 // cancelScheduling).
2700 while (!Bundle->isReady() && !ReadyInsts.empty()) {
2702 ScheduleData *pickedSD = ReadyInsts.back();
2703 ReadyInsts.pop_back();
2705 if (pickedSD->isSchedulingEntity() && pickedSD->isReady()) {
2706 schedule(pickedSD, ReadyInsts);
2709 return Bundle->isReady();
2712 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL) {
2713 if (isa<PHINode>(VL[0]))
2716 ScheduleData *Bundle = getScheduleData(VL[0]);
2717 DEBUG(dbgs() << "SLP: cancel scheduling of " << *Bundle << "\n");
2718 assert(!Bundle->IsScheduled &&
2719 "Can't cancel bundle which is already scheduled");
2720 assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
2721 "tried to unbundle something which is not a bundle");
2723 // Un-bundle: make single instructions out of the bundle.
2724 ScheduleData *BundleMember = Bundle;
2725 while (BundleMember) {
2726 assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
2727 BundleMember->FirstInBundle = BundleMember;
2728 ScheduleData *Next = BundleMember->NextInBundle;
2729 BundleMember->NextInBundle = nullptr;
2730 BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps;
2731 if (BundleMember->UnscheduledDepsInBundle == 0) {
2732 ReadyInsts.insert(BundleMember);
2734 BundleMember = Next;
2738 void BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V) {
2739 if (getScheduleData(V))
2741 Instruction *I = dyn_cast<Instruction>(V);
2742 assert(I && "bundle member must be an instruction");
2743 assert(!isa<PHINode>(I) && "phi nodes don't need to be scheduled");
2744 if (!ScheduleStart) {
2745 // It's the first instruction in the new region.
2746 initScheduleData(I, I->getNextNode(), nullptr, nullptr);
2748 ScheduleEnd = I->getNextNode();
2749 assert(ScheduleEnd && "tried to vectorize a TerminatorInst?");
2750 DEBUG(dbgs() << "SLP: initialize schedule region to " << *I << "\n");
2753 // Search up and down at the same time, because we don't know if the new
2754 // instruction is above or below the existing scheduling region.
2755 BasicBlock::reverse_iterator UpIter(ScheduleStart);
2756 BasicBlock::reverse_iterator UpperEnd = BB->rend();
2757 BasicBlock::iterator DownIter(ScheduleEnd);
2758 BasicBlock::iterator LowerEnd = BB->end();
2760 if (UpIter != UpperEnd) {
2761 if (&*UpIter == I) {
2762 initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
2764 DEBUG(dbgs() << "SLP: extend schedule region start to " << *I << "\n");
2769 if (DownIter != LowerEnd) {
2770 if (&*DownIter == I) {
2771 initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
2773 ScheduleEnd = I->getNextNode();
2774 assert(ScheduleEnd && "tried to vectorize a TerminatorInst?");
2775 DEBUG(dbgs() << "SLP: extend schedule region end to " << *I << "\n");
2780 assert((UpIter != UpperEnd || DownIter != LowerEnd) &&
2781 "instruction not found in block");
2785 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
2787 ScheduleData *PrevLoadStore,
2788 ScheduleData *NextLoadStore) {
2789 ScheduleData *CurrentLoadStore = PrevLoadStore;
2790 for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
2791 ScheduleData *SD = ScheduleDataMap[I];
2793 // Allocate a new ScheduleData for the instruction.
2794 if (ChunkPos >= ChunkSize) {
2795 ScheduleDataChunks.push_back(
2796 llvm::make_unique<ScheduleData[]>(ChunkSize));
2799 SD = &(ScheduleDataChunks.back()[ChunkPos++]);
2800 ScheduleDataMap[I] = SD;
2803 assert(!isInSchedulingRegion(SD) &&
2804 "new ScheduleData already in scheduling region");
2805 SD->init(SchedulingRegionID);
2807 if (I->mayReadOrWriteMemory()) {
2808 // Update the linked list of memory accessing instructions.
2809 if (CurrentLoadStore) {
2810 CurrentLoadStore->NextLoadStore = SD;
2812 FirstLoadStoreInRegion = SD;
2814 CurrentLoadStore = SD;
2817 if (NextLoadStore) {
2818 if (CurrentLoadStore)
2819 CurrentLoadStore->NextLoadStore = NextLoadStore;
2821 LastLoadStoreInRegion = CurrentLoadStore;
2825 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
2826 bool InsertInReadyList,
2828 assert(SD->isSchedulingEntity());
2830 SmallVector<ScheduleData *, 10> WorkList;
2831 WorkList.push_back(SD);
2833 while (!WorkList.empty()) {
2834 ScheduleData *SD = WorkList.back();
2835 WorkList.pop_back();
2837 ScheduleData *BundleMember = SD;
2838 while (BundleMember) {
2839 assert(isInSchedulingRegion(BundleMember));
2840 if (!BundleMember->hasValidDependencies()) {
2842 DEBUG(dbgs() << "SLP: update deps of " << *BundleMember << "\n");
2843 BundleMember->Dependencies = 0;
2844 BundleMember->resetUnscheduledDeps();
2846 // Handle def-use chain dependencies.
2847 for (User *U : BundleMember->Inst->users()) {
2848 if (isa<Instruction>(U)) {
2849 ScheduleData *UseSD = getScheduleData(U);
2850 if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
2851 BundleMember->Dependencies++;
2852 ScheduleData *DestBundle = UseSD->FirstInBundle;
2853 if (!DestBundle->IsScheduled) {
2854 BundleMember->incrementUnscheduledDeps(1);
2856 if (!DestBundle->hasValidDependencies()) {
2857 WorkList.push_back(DestBundle);
2861 // I'm not sure if this can ever happen. But we need to be safe.
2862 // This lets the instruction/bundle never be scheduled and eventally
2863 // disable vectorization.
2864 BundleMember->Dependencies++;
2865 BundleMember->incrementUnscheduledDeps(1);
2869 // Handle the memory dependencies.
2870 ScheduleData *DepDest = BundleMember->NextLoadStore;
2872 Instruction *SrcInst = BundleMember->Inst;
2873 AliasAnalysis::Location SrcLoc = getLocation(SrcInst, SLP->AA);
2874 bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
2875 unsigned numAliased = 0;
2876 unsigned DistToSrc = 1;
2879 assert(isInSchedulingRegion(DepDest));
2881 // We have two limits to reduce the complexity:
2882 // 1) AliasedCheckLimit: It's a small limit to reduce calls to
2883 // SLP->isAliased (which is the expensive part in this loop).
2884 // 2) MaxMemDepDistance: It's for very large blocks and it aborts
2885 // the whole loop (even if the loop is fast, it's quadratic).
2886 // It's important for the loop break condition (see below) to
2887 // check this limit even between two read-only instructions.
2888 if (DistToSrc >= MaxMemDepDistance ||
2889 ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
2890 (numAliased >= AliasedCheckLimit ||
2891 SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
2893 // We increment the counter only if the locations are aliased
2894 // (instead of counting all alias checks). This gives a better
2895 // balance between reduced runtime and accurate dependencies.
2898 DepDest->MemoryDependencies.push_back(BundleMember);
2899 BundleMember->Dependencies++;
2900 ScheduleData *DestBundle = DepDest->FirstInBundle;
2901 if (!DestBundle->IsScheduled) {
2902 BundleMember->incrementUnscheduledDeps(1);
2904 if (!DestBundle->hasValidDependencies()) {
2905 WorkList.push_back(DestBundle);
2908 DepDest = DepDest->NextLoadStore;
2910 // Example, explaining the loop break condition: Let's assume our
2911 // starting instruction is i0 and MaxMemDepDistance = 3.
2914 // i0,i1,i2,i3,i4,i5,i6,i7,i8
2917 // MaxMemDepDistance let us stop alias-checking at i3 and we add
2918 // dependencies from i0 to i3,i4,.. (even if they are not aliased).
2919 // Previously we already added dependencies from i3 to i6,i7,i8
2920 // (because of MaxMemDepDistance). As we added a dependency from
2921 // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
2922 // and we can abort this loop at i6.
2923 if (DistToSrc >= 2 * MaxMemDepDistance)
2929 BundleMember = BundleMember->NextInBundle;
2931 if (InsertInReadyList && SD->isReady()) {
2932 ReadyInsts.push_back(SD);
2933 DEBUG(dbgs() << "SLP: gets ready on update: " << *SD->Inst << "\n");
2938 void BoUpSLP::BlockScheduling::resetSchedule() {
2939 assert(ScheduleStart &&
2940 "tried to reset schedule on block which has not been scheduled");
2941 for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2942 ScheduleData *SD = getScheduleData(I);
2943 assert(isInSchedulingRegion(SD));
2944 SD->IsScheduled = false;
2945 SD->resetUnscheduledDeps();
2950 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
2952 if (!BS->ScheduleStart)
2955 DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
2957 BS->resetSchedule();
2959 // For the real scheduling we use a more sophisticated ready-list: it is
2960 // sorted by the original instruction location. This lets the final schedule
2961 // be as close as possible to the original instruction order.
2962 struct ScheduleDataCompare {
2963 bool operator()(ScheduleData *SD1, ScheduleData *SD2) {
2964 return SD2->SchedulingPriority < SD1->SchedulingPriority;
2967 std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
2969 // Ensure that all depencency data is updated and fill the ready-list with
2970 // initial instructions.
2972 int NumToSchedule = 0;
2973 for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
2974 I = I->getNextNode()) {
2975 ScheduleData *SD = BS->getScheduleData(I);
2977 SD->isPartOfBundle() == (ScalarToTreeEntry.count(SD->Inst) != 0) &&
2978 "scheduler and vectorizer have different opinion on what is a bundle");
2979 SD->FirstInBundle->SchedulingPriority = Idx++;
2980 if (SD->isSchedulingEntity()) {
2981 BS->calculateDependencies(SD, false, this);
2985 BS->initialFillReadyList(ReadyInsts);
2987 Instruction *LastScheduledInst = BS->ScheduleEnd;
2989 // Do the "real" scheduling.
2990 while (!ReadyInsts.empty()) {
2991 ScheduleData *picked = *ReadyInsts.begin();
2992 ReadyInsts.erase(ReadyInsts.begin());
2994 // Move the scheduled instruction(s) to their dedicated places, if not
2996 ScheduleData *BundleMember = picked;
2997 while (BundleMember) {
2998 Instruction *pickedInst = BundleMember->Inst;
2999 if (LastScheduledInst->getNextNode() != pickedInst) {
3000 BS->BB->getInstList().remove(pickedInst);
3001 BS->BB->getInstList().insert(LastScheduledInst, pickedInst);
3003 LastScheduledInst = pickedInst;
3004 BundleMember = BundleMember->NextInBundle;
3007 BS->schedule(picked, ReadyInsts);
3010 assert(NumToSchedule == 0 && "could not schedule all instructions");
3012 // Avoid duplicate scheduling of the block.
3013 BS->ScheduleStart = nullptr;
3016 /// The SLPVectorizer Pass.
3017 struct SLPVectorizer : public FunctionPass {
3018 typedef SmallVector<StoreInst *, 8> StoreList;
3019 typedef MapVector<Value *, StoreList> StoreListMap;
3021 /// Pass identification, replacement for typeid
3024 explicit SLPVectorizer() : FunctionPass(ID) {
3025 initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
3028 ScalarEvolution *SE;
3029 const DataLayout *DL;
3030 TargetTransformInfo *TTI;
3031 TargetLibraryInfo *TLI;
3035 AssumptionCache *AC;
3037 bool runOnFunction(Function &F) override {
3038 if (skipOptnoneFunction(F))
3041 SE = &getAnalysis<ScalarEvolution>();
3042 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
3043 DL = DLP ? &DLP->getDataLayout() : nullptr;
3044 TTI = &getAnalysis<TargetTransformInfo>();
3045 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
3046 TLI = TLIP ? &TLIP->getTLI() : nullptr;
3047 AA = &getAnalysis<AliasAnalysis>();
3048 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
3049 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3050 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
3053 bool Changed = false;
3055 // If the target claims to have no vector registers don't attempt
3057 if (!TTI->getNumberOfRegisters(true))
3060 // Must have DataLayout. We can't require it because some tests run w/o
3065 // Don't vectorize when the attribute NoImplicitFloat is used.
3066 if (F.hasFnAttribute(Attribute::NoImplicitFloat))
3069 DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
3071 // Use the bottom up slp vectorizer to construct chains that start with
3072 // store instructions.
3073 BoUpSLP R(&F, SE, DL, TTI, TLI, AA, LI, DT, AC);
3075 // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
3076 // delete instructions.
3078 // Scan the blocks in the function in post order.
3079 for (po_iterator<BasicBlock*> it = po_begin(&F.getEntryBlock()),
3080 e = po_end(&F.getEntryBlock()); it != e; ++it) {
3081 BasicBlock *BB = *it;
3082 // Vectorize trees that end at stores.
3083 if (unsigned count = collectStores(BB, R)) {
3085 DEBUG(dbgs() << "SLP: Found " << count << " stores to vectorize.\n");
3086 Changed |= vectorizeStoreChains(R);
3089 // Vectorize trees that end at reductions.
3090 Changed |= vectorizeChainsInBlock(BB, R);
3094 R.optimizeGatherSequence();
3095 DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
3096 DEBUG(verifyFunction(F));
3101 void getAnalysisUsage(AnalysisUsage &AU) const override {
3102 FunctionPass::getAnalysisUsage(AU);
3103 AU.addRequired<AssumptionCacheTracker>();
3104 AU.addRequired<ScalarEvolution>();
3105 AU.addRequired<AliasAnalysis>();
3106 AU.addRequired<TargetTransformInfo>();
3107 AU.addRequired<LoopInfoWrapperPass>();
3108 AU.addRequired<DominatorTreeWrapperPass>();
3109 AU.addPreserved<LoopInfoWrapperPass>();
3110 AU.addPreserved<DominatorTreeWrapperPass>();
3111 AU.setPreservesCFG();
3116 /// \brief Collect memory references and sort them according to their base
3117 /// object. We sort the stores to their base objects to reduce the cost of the
3118 /// quadratic search on the stores. TODO: We can further reduce this cost
3119 /// if we flush the chain creation every time we run into a memory barrier.
3120 unsigned collectStores(BasicBlock *BB, BoUpSLP &R);
3122 /// \brief Try to vectorize a chain that starts at two arithmetic instrs.
3123 bool tryToVectorizePair(Value *A, Value *B, BoUpSLP &R);
3125 /// \brief Try to vectorize a list of operands.
3126 /// \@param BuildVector A list of users to ignore for the purpose of
3127 /// scheduling and that don't need extracting.
3128 /// \returns true if a value was vectorized.
3129 bool tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
3130 ArrayRef<Value *> BuildVector = None,
3131 bool allowReorder = false);
3133 /// \brief Try to vectorize a chain that may start at the operands of \V;
3134 bool tryToVectorize(BinaryOperator *V, BoUpSLP &R);
3136 /// \brief Vectorize the stores that were collected in StoreRefs.
3137 bool vectorizeStoreChains(BoUpSLP &R);
3139 /// \brief Scan the basic block and look for patterns that are likely to start
3140 /// a vectorization chain.
3141 bool vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R);
3143 bool vectorizeStoreChain(ArrayRef<Value *> Chain, int CostThreshold,
3146 bool vectorizeStores(ArrayRef<StoreInst *> Stores, int costThreshold,
3149 StoreListMap StoreRefs;
3152 /// \brief Check that the Values in the slice in VL array are still existent in
3153 /// the WeakVH array.
3154 /// Vectorization of part of the VL array may cause later values in the VL array
3155 /// to become invalid. We track when this has happened in the WeakVH array.
3156 static bool hasValueBeenRAUWed(ArrayRef<Value *> &VL,
3157 SmallVectorImpl<WeakVH> &VH,
3158 unsigned SliceBegin,
3159 unsigned SliceSize) {
3160 for (unsigned i = SliceBegin; i < SliceBegin + SliceSize; ++i)
3167 bool SLPVectorizer::vectorizeStoreChain(ArrayRef<Value *> Chain,
3168 int CostThreshold, BoUpSLP &R) {
3169 unsigned ChainLen = Chain.size();
3170 DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
3172 Type *StoreTy = cast<StoreInst>(Chain[0])->getValueOperand()->getType();
3173 unsigned Sz = DL->getTypeSizeInBits(StoreTy);
3174 unsigned VF = MinVecRegSize / Sz;
3176 if (!isPowerOf2_32(Sz) || VF < 2)
3179 // Keep track of values that were deleted by vectorizing in the loop below.
3180 SmallVector<WeakVH, 8> TrackValues(Chain.begin(), Chain.end());
3182 bool Changed = false;
3183 // Look for profitable vectorizable trees at all offsets, starting at zero.
3184 for (unsigned i = 0, e = ChainLen; i < e; ++i) {
3188 // Check that a previous iteration of this loop did not delete the Value.
3189 if (hasValueBeenRAUWed(Chain, TrackValues, i, VF))
3192 DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
3194 ArrayRef<Value *> Operands = Chain.slice(i, VF);
3196 R.buildTree(Operands);
3198 int Cost = R.getTreeCost();
3200 DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
3201 if (Cost < CostThreshold) {
3202 DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
3205 // Move to the next bundle.
3214 bool SLPVectorizer::vectorizeStores(ArrayRef<StoreInst *> Stores,
3215 int costThreshold, BoUpSLP &R) {
3216 SetVector<Value *> Heads, Tails;
3217 SmallDenseMap<Value *, Value *> ConsecutiveChain;
3219 // We may run into multiple chains that merge into a single chain. We mark the
3220 // stores that we vectorized so that we don't visit the same store twice.
3221 BoUpSLP::ValueSet VectorizedStores;
3222 bool Changed = false;
3224 // Do a quadratic search on all of the given stores and find
3225 // all of the pairs of stores that follow each other.
3226 for (unsigned i = 0, e = Stores.size(); i < e; ++i) {
3227 for (unsigned j = 0; j < e; ++j) {
3231 if (R.isConsecutiveAccess(Stores[i], Stores[j])) {
3232 Tails.insert(Stores[j]);
3233 Heads.insert(Stores[i]);
3234 ConsecutiveChain[Stores[i]] = Stores[j];
3239 // For stores that start but don't end a link in the chain:
3240 for (SetVector<Value *>::iterator it = Heads.begin(), e = Heads.end();
3242 if (Tails.count(*it))
3245 // We found a store instr that starts a chain. Now follow the chain and try
3247 BoUpSLP::ValueList Operands;
3249 // Collect the chain into a list.
3250 while (Tails.count(I) || Heads.count(I)) {
3251 if (VectorizedStores.count(I))
3253 Operands.push_back(I);
3254 // Move to the next value in the chain.
3255 I = ConsecutiveChain[I];
3258 bool Vectorized = vectorizeStoreChain(Operands, costThreshold, R);
3260 // Mark the vectorized stores so that we don't vectorize them again.
3262 VectorizedStores.insert(Operands.begin(), Operands.end());
3263 Changed |= Vectorized;
3270 unsigned SLPVectorizer::collectStores(BasicBlock *BB, BoUpSLP &R) {
3273 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
3274 StoreInst *SI = dyn_cast<StoreInst>(it);
3278 // Don't touch volatile stores.
3279 if (!SI->isSimple())
3282 // Check that the pointer points to scalars.
3283 Type *Ty = SI->getValueOperand()->getType();
3284 if (Ty->isAggregateType() || Ty->isVectorTy())
3287 // Find the base pointer.
3288 Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), DL);
3290 // Save the store locations.
3291 StoreRefs[Ptr].push_back(SI);
3297 bool SLPVectorizer::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
3300 Value *VL[] = { A, B };
3301 return tryToVectorizeList(VL, R, None, true);
3304 bool SLPVectorizer::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
3305 ArrayRef<Value *> BuildVector,
3306 bool allowReorder) {
3310 DEBUG(dbgs() << "SLP: Vectorizing a list of length = " << VL.size() << ".\n");
3312 // Check that all of the parts are scalar instructions of the same type.
3313 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
3317 unsigned Opcode0 = I0->getOpcode();
3319 Type *Ty0 = I0->getType();
3320 unsigned Sz = DL->getTypeSizeInBits(Ty0);
3321 unsigned VF = MinVecRegSize / Sz;
3323 for (int i = 0, e = VL.size(); i < e; ++i) {
3324 Type *Ty = VL[i]->getType();
3325 if (Ty->isAggregateType() || Ty->isVectorTy())
3327 Instruction *Inst = dyn_cast<Instruction>(VL[i]);
3328 if (!Inst || Inst->getOpcode() != Opcode0)
3332 bool Changed = false;
3334 // Keep track of values that were deleted by vectorizing in the loop below.
3335 SmallVector<WeakVH, 8> TrackValues(VL.begin(), VL.end());
3337 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
3338 unsigned OpsWidth = 0;
3345 if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
3348 // Check that a previous iteration of this loop did not delete the Value.
3349 if (hasValueBeenRAUWed(VL, TrackValues, i, OpsWidth))
3352 DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
3354 ArrayRef<Value *> Ops = VL.slice(i, OpsWidth);
3356 ArrayRef<Value *> BuildVectorSlice;
3357 if (!BuildVector.empty())
3358 BuildVectorSlice = BuildVector.slice(i, OpsWidth);
3360 R.buildTree(Ops, BuildVectorSlice);
3361 // TODO: check if we can allow reordering also for other cases than
3362 // tryToVectorizePair()
3363 if (allowReorder && R.shouldReorder()) {
3364 assert(Ops.size() == 2);
3365 assert(BuildVectorSlice.empty());
3366 Value *ReorderedOps[] = { Ops[1], Ops[0] };
3367 R.buildTree(ReorderedOps, None);
3369 int Cost = R.getTreeCost();
3371 if (Cost < -SLPCostThreshold) {
3372 DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
3373 Value *VectorizedRoot = R.vectorizeTree();
3375 // Reconstruct the build vector by extracting the vectorized root. This
3376 // way we handle the case where some elements of the vector are undefined.
3377 // (return (inserelt <4 xi32> (insertelt undef (opd0) 0) (opd1) 2))
3378 if (!BuildVectorSlice.empty()) {
3379 // The insert point is the last build vector instruction. The vectorized
3380 // root will precede it. This guarantees that we get an instruction. The
3381 // vectorized tree could have been constant folded.
3382 Instruction *InsertAfter = cast<Instruction>(BuildVectorSlice.back());
3383 unsigned VecIdx = 0;
3384 for (auto &V : BuildVectorSlice) {
3385 IRBuilder<true, NoFolder> Builder(
3386 ++BasicBlock::iterator(InsertAfter));
3387 InsertElementInst *IE = cast<InsertElementInst>(V);
3388 Instruction *Extract = cast<Instruction>(Builder.CreateExtractElement(
3389 VectorizedRoot, Builder.getInt32(VecIdx++)));
3390 IE->setOperand(1, Extract);
3391 IE->removeFromParent();
3392 IE->insertAfter(Extract);
3396 // Move to the next bundle.
3405 bool SLPVectorizer::tryToVectorize(BinaryOperator *V, BoUpSLP &R) {
3409 // Try to vectorize V.
3410 if (tryToVectorizePair(V->getOperand(0), V->getOperand(1), R))
3413 BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0));
3414 BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1));
3416 if (B && B->hasOneUse()) {
3417 BinaryOperator *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
3418 BinaryOperator *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
3419 if (tryToVectorizePair(A, B0, R)) {
3422 if (tryToVectorizePair(A, B1, R)) {
3428 if (A && A->hasOneUse()) {
3429 BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
3430 BinaryOperator *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
3431 if (tryToVectorizePair(A0, B, R)) {
3434 if (tryToVectorizePair(A1, B, R)) {
3441 /// \brief Generate a shuffle mask to be used in a reduction tree.
3443 /// \param VecLen The length of the vector to be reduced.
3444 /// \param NumEltsToRdx The number of elements that should be reduced in the
3446 /// \param IsPairwise Whether the reduction is a pairwise or splitting
3447 /// reduction. A pairwise reduction will generate a mask of
3448 /// <0,2,...> or <1,3,..> while a splitting reduction will generate
3449 /// <2,3, undef,undef> for a vector of 4 and NumElts = 2.
3450 /// \param IsLeft True will generate a mask of even elements, odd otherwise.
3451 static Value *createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx,
3452 bool IsPairwise, bool IsLeft,
3453 IRBuilder<> &Builder) {
3454 assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask");
3456 SmallVector<Constant *, 32> ShuffleMask(
3457 VecLen, UndefValue::get(Builder.getInt32Ty()));
3460 // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
3461 for (unsigned i = 0; i != NumEltsToRdx; ++i)
3462 ShuffleMask[i] = Builder.getInt32(2 * i + !IsLeft);
3464 // Move the upper half of the vector to the lower half.
3465 for (unsigned i = 0; i != NumEltsToRdx; ++i)
3466 ShuffleMask[i] = Builder.getInt32(NumEltsToRdx + i);
3468 return ConstantVector::get(ShuffleMask);
3472 /// Model horizontal reductions.
3474 /// A horizontal reduction is a tree of reduction operations (currently add and
3475 /// fadd) that has operations that can be put into a vector as its leaf.
3476 /// For example, this tree:
3483 /// This tree has "mul" as its reduced values and "+" as its reduction
3484 /// operations. A reduction might be feeding into a store or a binary operation
3499 class HorizontalReduction {
3500 SmallVector<Value *, 16> ReductionOps;
3501 SmallVector<Value *, 32> ReducedVals;
3503 BinaryOperator *ReductionRoot;
3504 PHINode *ReductionPHI;
3506 /// The opcode of the reduction.
3507 unsigned ReductionOpcode;
3508 /// The opcode of the values we perform a reduction on.
3509 unsigned ReducedValueOpcode;
3510 /// The width of one full horizontal reduction operation.
3511 unsigned ReduxWidth;
3512 /// Should we model this reduction as a pairwise reduction tree or a tree that
3513 /// splits the vector in halves and adds those halves.
3514 bool IsPairwiseReduction;
3517 HorizontalReduction()
3518 : ReductionRoot(nullptr), ReductionPHI(nullptr), ReductionOpcode(0),
3519 ReducedValueOpcode(0), ReduxWidth(0), IsPairwiseReduction(false) {}
3521 /// \brief Try to find a reduction tree.
3522 bool matchAssociativeReduction(PHINode *Phi, BinaryOperator *B,
3523 const DataLayout *DL) {
3525 std::find(Phi->op_begin(), Phi->op_end(), B) != Phi->op_end()) &&
3526 "Thi phi needs to use the binary operator");
3528 // We could have a initial reductions that is not an add.
3529 // r *= v1 + v2 + v3 + v4
3530 // In such a case start looking for a tree rooted in the first '+'.
3532 if (B->getOperand(0) == Phi) {
3534 B = dyn_cast<BinaryOperator>(B->getOperand(1));
3535 } else if (B->getOperand(1) == Phi) {
3537 B = dyn_cast<BinaryOperator>(B->getOperand(0));
3544 Type *Ty = B->getType();
3545 if (Ty->isVectorTy())
3548 ReductionOpcode = B->getOpcode();
3549 ReducedValueOpcode = 0;
3550 ReduxWidth = MinVecRegSize / DL->getTypeSizeInBits(Ty);
3557 // We currently only support adds.
3558 if (ReductionOpcode != Instruction::Add &&
3559 ReductionOpcode != Instruction::FAdd)
3562 // Post order traverse the reduction tree starting at B. We only handle true
3563 // trees containing only binary operators.
3564 SmallVector<std::pair<BinaryOperator *, unsigned>, 32> Stack;
3565 Stack.push_back(std::make_pair(B, 0));
3566 while (!Stack.empty()) {
3567 BinaryOperator *TreeN = Stack.back().first;
3568 unsigned EdgeToVist = Stack.back().second++;
3569 bool IsReducedValue = TreeN->getOpcode() != ReductionOpcode;
3571 // Only handle trees in the current basic block.
3572 if (TreeN->getParent() != B->getParent())
3575 // Each tree node needs to have one user except for the ultimate
3577 if (!TreeN->hasOneUse() && TreeN != B)
3581 if (EdgeToVist == 2 || IsReducedValue) {
3582 if (IsReducedValue) {
3583 // Make sure that the opcodes of the operations that we are going to
3585 if (!ReducedValueOpcode)
3586 ReducedValueOpcode = TreeN->getOpcode();
3587 else if (ReducedValueOpcode != TreeN->getOpcode())
3589 ReducedVals.push_back(TreeN);
3591 // We need to be able to reassociate the adds.
3592 if (!TreeN->isAssociative())
3594 ReductionOps.push_back(TreeN);
3601 // Visit left or right.
3602 Value *NextV = TreeN->getOperand(EdgeToVist);
3603 BinaryOperator *Next = dyn_cast<BinaryOperator>(NextV);
3605 Stack.push_back(std::make_pair(Next, 0));
3606 else if (NextV != Phi)
3612 /// \brief Attempt to vectorize the tree found by
3613 /// matchAssociativeReduction.
3614 bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
3615 if (ReducedVals.empty())
3618 unsigned NumReducedVals = ReducedVals.size();
3619 if (NumReducedVals < ReduxWidth)
3622 Value *VectorizedTree = nullptr;
3623 IRBuilder<> Builder(ReductionRoot);
3624 FastMathFlags Unsafe;
3625 Unsafe.setUnsafeAlgebra();
3626 Builder.SetFastMathFlags(Unsafe);
3629 for (; i < NumReducedVals - ReduxWidth + 1; i += ReduxWidth) {
3630 V.buildTree(makeArrayRef(&ReducedVals[i], ReduxWidth), ReductionOps);
3633 int Cost = V.getTreeCost() + getReductionCost(TTI, ReducedVals[i]);
3634 if (Cost >= -SLPCostThreshold)
3637 DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" << Cost
3640 // Vectorize a tree.
3641 DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
3642 Value *VectorizedRoot = V.vectorizeTree();
3644 // Emit a reduction.
3645 Value *ReducedSubTree = emitReduction(VectorizedRoot, Builder);
3646 if (VectorizedTree) {
3647 Builder.SetCurrentDebugLocation(Loc);
3648 VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
3649 ReducedSubTree, "bin.rdx");
3651 VectorizedTree = ReducedSubTree;
3654 if (VectorizedTree) {
3655 // Finish the reduction.
3656 for (; i < NumReducedVals; ++i) {
3657 Builder.SetCurrentDebugLocation(
3658 cast<Instruction>(ReducedVals[i])->getDebugLoc());
3659 VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
3664 assert(ReductionRoot && "Need a reduction operation");
3665 ReductionRoot->setOperand(0, VectorizedTree);
3666 ReductionRoot->setOperand(1, ReductionPHI);
3668 ReductionRoot->replaceAllUsesWith(VectorizedTree);
3670 return VectorizedTree != nullptr;
3675 /// \brief Calcuate the cost of a reduction.
3676 int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal) {
3677 Type *ScalarTy = FirstReducedVal->getType();
3678 Type *VecTy = VectorType::get(ScalarTy, ReduxWidth);
3680 int PairwiseRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, true);
3681 int SplittingRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, false);
3683 IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
3684 int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
3686 int ScalarReduxCost =
3687 ReduxWidth * TTI->getArithmeticInstrCost(ReductionOpcode, VecTy);
3689 DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost
3690 << " for reduction that starts with " << *FirstReducedVal
3692 << (IsPairwiseReduction ? "pairwise" : "splitting")
3693 << " reduction)\n");
3695 return VecReduxCost - ScalarReduxCost;
3698 static Value *createBinOp(IRBuilder<> &Builder, unsigned Opcode, Value *L,
3699 Value *R, const Twine &Name = "") {
3700 if (Opcode == Instruction::FAdd)
3701 return Builder.CreateFAdd(L, R, Name);
3702 return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, L, R, Name);
3705 /// \brief Emit a horizontal reduction of the vectorized value.
3706 Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder) {
3707 assert(VectorizedValue && "Need to have a vectorized tree node");
3708 assert(isPowerOf2_32(ReduxWidth) &&
3709 "We only handle power-of-two reductions for now");
3711 Value *TmpVec = VectorizedValue;
3712 for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
3713 if (IsPairwiseReduction) {
3715 createRdxShuffleMask(ReduxWidth, i, true, true, Builder);
3717 createRdxShuffleMask(ReduxWidth, i, true, false, Builder);
3719 Value *LeftShuf = Builder.CreateShuffleVector(
3720 TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l");
3721 Value *RightShuf = Builder.CreateShuffleVector(
3722 TmpVec, UndefValue::get(TmpVec->getType()), (RightMask),
3724 TmpVec = createBinOp(Builder, ReductionOpcode, LeftShuf, RightShuf,
3728 createRdxShuffleMask(ReduxWidth, i, false, false, Builder);
3729 Value *Shuf = Builder.CreateShuffleVector(
3730 TmpVec, UndefValue::get(TmpVec->getType()), UpperHalf, "rdx.shuf");
3731 TmpVec = createBinOp(Builder, ReductionOpcode, TmpVec, Shuf, "bin.rdx");
3735 // The result is in the first element of the vector.
3736 return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
3740 /// \brief Recognize construction of vectors like
3741 /// %ra = insertelement <4 x float> undef, float %s0, i32 0
3742 /// %rb = insertelement <4 x float> %ra, float %s1, i32 1
3743 /// %rc = insertelement <4 x float> %rb, float %s2, i32 2
3744 /// %rd = insertelement <4 x float> %rc, float %s3, i32 3
3746 /// Returns true if it matches
3748 static bool findBuildVector(InsertElementInst *FirstInsertElem,
3749 SmallVectorImpl<Value *> &BuildVector,
3750 SmallVectorImpl<Value *> &BuildVectorOpds) {
3751 if (!isa<UndefValue>(FirstInsertElem->getOperand(0)))
3754 InsertElementInst *IE = FirstInsertElem;
3756 BuildVector.push_back(IE);
3757 BuildVectorOpds.push_back(IE->getOperand(1));
3759 if (IE->use_empty())
3762 InsertElementInst *NextUse = dyn_cast<InsertElementInst>(IE->user_back());
3766 // If this isn't the final use, make sure the next insertelement is the only
3767 // use. It's OK if the final constructed vector is used multiple times
3768 if (!IE->hasOneUse())
3777 static bool PhiTypeSorterFunc(Value *V, Value *V2) {
3778 return V->getType() < V2->getType();
3781 bool SLPVectorizer::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
3782 bool Changed = false;
3783 SmallVector<Value *, 4> Incoming;
3784 SmallSet<Value *, 16> VisitedInstrs;
3786 bool HaveVectorizedPhiNodes = true;
3787 while (HaveVectorizedPhiNodes) {
3788 HaveVectorizedPhiNodes = false;
3790 // Collect the incoming values from the PHIs.
3792 for (BasicBlock::iterator instr = BB->begin(), ie = BB->end(); instr != ie;
3794 PHINode *P = dyn_cast<PHINode>(instr);
3798 if (!VisitedInstrs.count(P))
3799 Incoming.push_back(P);
3803 std::stable_sort(Incoming.begin(), Incoming.end(), PhiTypeSorterFunc);
3805 // Try to vectorize elements base on their type.
3806 for (SmallVector<Value *, 4>::iterator IncIt = Incoming.begin(),
3810 // Look for the next elements with the same type.
3811 SmallVector<Value *, 4>::iterator SameTypeIt = IncIt;
3812 while (SameTypeIt != E &&
3813 (*SameTypeIt)->getType() == (*IncIt)->getType()) {
3814 VisitedInstrs.insert(*SameTypeIt);
3818 // Try to vectorize them.
3819 unsigned NumElts = (SameTypeIt - IncIt);
3820 DEBUG(errs() << "SLP: Trying to vectorize starting at PHIs (" << NumElts << ")\n");
3821 if (NumElts > 1 && tryToVectorizeList(makeArrayRef(IncIt, NumElts), R)) {
3822 // Success start over because instructions might have been changed.
3823 HaveVectorizedPhiNodes = true;
3828 // Start over at the next instruction of a different type (or the end).
3833 VisitedInstrs.clear();
3835 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) {
3836 // We may go through BB multiple times so skip the one we have checked.
3837 if (!VisitedInstrs.insert(it).second)
3840 if (isa<DbgInfoIntrinsic>(it))
3843 // Try to vectorize reductions that use PHINodes.
3844 if (PHINode *P = dyn_cast<PHINode>(it)) {
3845 // Check that the PHI is a reduction PHI.
3846 if (P->getNumIncomingValues() != 2)
3849 (P->getIncomingBlock(0) == BB
3850 ? (P->getIncomingValue(0))
3851 : (P->getIncomingBlock(1) == BB ? P->getIncomingValue(1)
3853 // Check if this is a Binary Operator.
3854 BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx);
3858 // Try to match and vectorize a horizontal reduction.
3859 HorizontalReduction HorRdx;
3860 if (ShouldVectorizeHor &&
3861 HorRdx.matchAssociativeReduction(P, BI, DL) &&
3862 HorRdx.tryToReduce(R, TTI)) {
3869 Value *Inst = BI->getOperand(0);
3871 Inst = BI->getOperand(1);
3873 if (tryToVectorize(dyn_cast<BinaryOperator>(Inst), R)) {
3874 // We would like to start over since some instructions are deleted
3875 // and the iterator may become invalid value.
3885 // Try to vectorize horizontal reductions feeding into a store.
3886 if (ShouldStartVectorizeHorAtStore)
3887 if (StoreInst *SI = dyn_cast<StoreInst>(it))
3888 if (BinaryOperator *BinOp =
3889 dyn_cast<BinaryOperator>(SI->getValueOperand())) {
3890 HorizontalReduction HorRdx;
3891 if (((HorRdx.matchAssociativeReduction(nullptr, BinOp, DL) &&
3892 HorRdx.tryToReduce(R, TTI)) ||
3893 tryToVectorize(BinOp, R))) {
3901 // Try to vectorize horizontal reductions feeding into a return.
3902 if (ReturnInst *RI = dyn_cast<ReturnInst>(it))
3903 if (RI->getNumOperands() != 0)
3904 if (BinaryOperator *BinOp =
3905 dyn_cast<BinaryOperator>(RI->getOperand(0))) {
3906 DEBUG(dbgs() << "SLP: Found a return to vectorize.\n");
3907 if (tryToVectorizePair(BinOp->getOperand(0),
3908 BinOp->getOperand(1), R)) {
3916 // Try to vectorize trees that start at compare instructions.
3917 if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
3918 if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) {
3920 // We would like to start over since some instructions are deleted
3921 // and the iterator may become invalid value.
3927 for (int i = 0; i < 2; ++i) {
3928 if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i))) {
3929 if (tryToVectorizePair(BI->getOperand(0), BI->getOperand(1), R)) {
3931 // We would like to start over since some instructions are deleted
3932 // and the iterator may become invalid value.
3941 // Try to vectorize trees that start at insertelement instructions.
3942 if (InsertElementInst *FirstInsertElem = dyn_cast<InsertElementInst>(it)) {
3943 SmallVector<Value *, 16> BuildVector;
3944 SmallVector<Value *, 16> BuildVectorOpds;
3945 if (!findBuildVector(FirstInsertElem, BuildVector, BuildVectorOpds))
3948 // Vectorize starting with the build vector operands ignoring the
3949 // BuildVector instructions for the purpose of scheduling and user
3951 if (tryToVectorizeList(BuildVectorOpds, R, BuildVector)) {
3964 bool SLPVectorizer::vectorizeStoreChains(BoUpSLP &R) {
3965 bool Changed = false;
3966 // Attempt to sort and vectorize each of the store-groups.
3967 for (StoreListMap::iterator it = StoreRefs.begin(), e = StoreRefs.end();
3969 if (it->second.size() < 2)
3972 DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
3973 << it->second.size() << ".\n");
3975 // Process the stores in chunks of 16.
3976 for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI+=16) {
3977 unsigned Len = std::min<unsigned>(CE - CI, 16);
3978 Changed |= vectorizeStores(makeArrayRef(&it->second[CI], Len),
3979 -SLPCostThreshold, R);
3985 } // end anonymous namespace
3987 char SLPVectorizer::ID = 0;
3988 static const char lv_name[] = "SLP Vectorizer";
3989 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
3990 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3991 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
3992 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
3993 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
3994 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
3995 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
3998 Pass *createSLPVectorizerPass() { return new SLPVectorizer(); }