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 #define SV_NAME "slp-vectorizer"
19 #define DEBUG_TYPE "SLP"
21 #include "llvm/Transforms/Vectorize.h"
22 #include "llvm/ADT/MapVector.h"
23 #include "llvm/ADT/PostOrderIterator.h"
24 #include "llvm/ADT/SetVector.h"
25 #include "llvm/Analysis/AliasAnalysis.h"
26 #include "llvm/Analysis/ScalarEvolution.h"
27 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
28 #include "llvm/Analysis/AliasAnalysis.h"
29 #include "llvm/Analysis/TargetTransformInfo.h"
30 #include "llvm/Analysis/Verifier.h"
31 #include "llvm/Analysis/LoopInfo.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/Instructions.h"
34 #include "llvm/IR/IntrinsicInst.h"
35 #include "llvm/IR/IRBuilder.h"
36 #include "llvm/IR/Module.h"
37 #include "llvm/IR/Type.h"
38 #include "llvm/IR/Value.h"
39 #include "llvm/Pass.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/raw_ostream.h"
49 SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
50 cl::desc("Only vectorize trees if the gain is above this "
51 "number. (gain = -cost of vectorization)"));
54 static const unsigned MinVecRegSize = 128;
56 static const unsigned RecursionMaxDepth = 12;
58 /// RAII pattern to save the insertion point of the IR builder.
59 class BuilderLocGuard {
61 BuilderLocGuard(IRBuilder<> &B) : Builder(B), Loc(B.GetInsertPoint()) {}
62 ~BuilderLocGuard() { Builder.SetInsertPoint(Loc); }
66 BuilderLocGuard(const BuilderLocGuard &);
67 BuilderLocGuard &operator=(const BuilderLocGuard &);
69 BasicBlock::iterator Loc;
72 /// A helper class for numbering instructions in multible blocks.
73 /// Numbers starts at zero for each basic block.
74 struct BlockNumbering {
76 BlockNumbering(BasicBlock *Bb) : BB(Bb), Valid(false) {}
78 BlockNumbering() : BB(0), Valid(false) {}
80 void numberInstructions() {
84 // Number the instructions in the block.
85 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
87 InstrVec.push_back(it);
88 assert(InstrVec[InstrIdx[it]] == it && "Invalid allocation");
93 int getIndex(Instruction *I) {
96 assert(InstrIdx.count(I) && "Unknown instruction");
100 Instruction *getInstruction(unsigned loc) {
102 numberInstructions();
103 assert(InstrVec.size() > loc && "Invalid Index");
104 return InstrVec[loc];
107 void forget() { Valid = false; }
110 /// The block we are numbering.
112 /// Is the block numbered.
114 /// Maps instructions to numbers and back.
115 SmallDenseMap<Instruction *, int> InstrIdx;
116 /// Maps integers to Instructions.
117 std::vector<Instruction *> InstrVec;
121 typedef SmallVector<Value *, 8> ValueList;
122 typedef SmallVector<Instruction *, 16> InstrList;
123 typedef SmallPtrSet<Value *, 16> ValueSet;
124 typedef SmallVector<StoreInst *, 8> StoreList;
127 static const int MAX_COST = INT_MIN;
129 FuncSLP(Function *Func, ScalarEvolution *Se, DataLayout *Dl,
130 TargetTransformInfo *Tti, AliasAnalysis *Aa, LoopInfo *Li,
132 F(Func), SE(Se), DL(Dl), TTI(Tti), AA(Aa), LI(Li), DT(Dt),
133 Builder(Se->getContext()) {
134 for (Function::iterator it = F->begin(), e = F->end(); it != e; ++it) {
136 BlocksNumbers[BB] = BlockNumbering(BB);
140 /// \brief Take the pointer operand from the Load/Store instruction.
141 /// \returns NULL if this is not a valid Load/Store instruction.
142 static Value *getPointerOperand(Value *I);
144 /// \brief Take the address space operand from the Load/Store instruction.
145 /// \returns -1 if this is not a valid Load/Store instruction.
146 static unsigned getAddressSpaceOperand(Value *I);
148 /// \returns true if the memory operations A and B are consecutive.
149 bool isConsecutiveAccess(Value *A, Value *B);
151 /// \brief Vectorize the tree that starts with the elements in \p VL.
152 /// \returns the vectorized value.
153 Value *vectorizeTree(ArrayRef<Value *> VL);
155 /// \returns the vectorization cost of the subtree that starts at \p VL.
156 /// A negative number means that this is profitable.
157 int getTreeCost(ArrayRef<Value *> VL);
159 /// \returns the scalarization cost for this list of values. Assuming that
160 /// this subtree gets vectorized, we may need to extract the values from the
161 /// roots. This method calculates the cost of extracting the values.
162 int getGatherCost(ArrayRef<Value *> VL);
164 /// \brief Attempts to order and vectorize a sequence of stores. This
165 /// function does a quadratic scan of the given stores.
166 /// \returns true if the basic block was modified.
167 bool vectorizeStores(ArrayRef<StoreInst *> Stores, int costThreshold);
169 /// \brief Vectorize a group of scalars into a vector tree.
170 /// \returns the vectorized value.
171 Value *vectorizeArith(ArrayRef<Value *> Operands);
173 /// \brief This method contains the recursive part of getTreeCost.
174 int getTreeCost_rec(ArrayRef<Value *> VL, unsigned Depth);
176 /// \brief This recursive method looks for vectorization hazards such as
177 /// values that are used by multiple users and checks that values are used
178 /// by only one vector lane. It updates the variables LaneMap, MultiUserVals.
179 void getTreeUses_rec(ArrayRef<Value *> VL, unsigned Depth);
181 /// \brief This method contains the recursive part of vectorizeTree.
182 Value *vectorizeTree_rec(ArrayRef<Value *> VL);
184 /// \brief Vectorize a sorted sequence of stores.
185 bool vectorizeStoreChain(ArrayRef<Value *> Chain, int CostThreshold);
187 /// \returns the scalarization cost for this type. Scalarization in this
188 /// context means the creation of vectors from a group of scalars.
189 int getGatherCost(Type *Ty);
191 /// \returns the AA location that is being access by the instruction.
192 AliasAnalysis::Location getLocation(Instruction *I);
194 /// \brief Checks if it is possible to sink an instruction from
195 /// \p Src to \p Dst.
196 /// \returns the pointer to the barrier instruction if we can't sink.
197 Value *getSinkBarrier(Instruction *Src, Instruction *Dst);
199 /// \returns the index of the last instrucion in the BB from \p VL.
200 int getLastIndex(ArrayRef<Value *> VL);
202 /// \returns the Instrucion in the bundle \p VL.
203 Instruction *getLastInstruction(ArrayRef<Value *> VL);
205 /// \returns the Instruction at index \p Index which is in Block \p BB.
206 Instruction *getInstructionForIndex(unsigned Index, BasicBlock *BB);
208 /// \returns the index of the first User of \p VL.
209 int getFirstUserIndex(ArrayRef<Value *> VL);
211 /// \returns a vector from a collection of scalars in \p VL.
212 Value *Gather(ArrayRef<Value *> VL, VectorType *Ty);
214 /// \brief Perform LICM and CSE on the newly generated gather sequences.
215 void optimizeGatherSequence();
217 bool needToGatherAny(ArrayRef<Value *> VL) {
218 for (int i = 0, e = VL.size(); i < e; ++i)
219 if (MustGather.count(VL[i]))
224 void forgetNumbering() {
225 for (Function::iterator it = F->begin(), e = F->end(); it != e; ++it)
226 BlocksNumbers[it].forget();
229 /// -- Vectorization State --
231 /// Maps values in the tree to the vector lanes that uses them. This map must
232 /// be reset between runs of getCost.
233 std::map<Value *, int> LaneMap;
234 /// A list of instructions to ignore while sinking
235 /// memory instructions. This map must be reset between runs of getCost.
236 ValueSet MemBarrierIgnoreList;
238 /// Maps between the first scalar to the vector. This map must be reset
240 DenseMap<Value *, Value *> VectorizedValues;
242 /// Contains values that must be gathered because they are used
243 /// by multiple lanes, or by users outside the tree.
244 /// NOTICE: The vectorization methods also use this set.
247 /// Contains PHINodes that are being processed. We use this data structure
248 /// to stop cycles in the graph.
249 ValueSet VisitedPHIs;
251 /// Contains a list of values that are used outside the current tree, the
252 /// first element in the bundle and the insertion point for extracts. This
253 /// set must be reset between runs.
255 UseInfo(Instruction *VL0, int I) :
256 Leader(VL0), LastIndex(I) {}
257 UseInfo() : Leader(0), LastIndex(0) {}
258 /// The first element in the bundle.
260 /// The insertion index.
263 MapVector<Instruction*, UseInfo> MultiUserVals;
264 SetVector<Instruction*> ExtractedLane;
266 /// Holds all of the instructions that we gathered.
267 SetVector<Instruction *> GatherSeq;
269 /// Numbers instructions in different blocks.
270 std::map<BasicBlock *, BlockNumbering> BlocksNumbers;
272 // Analysis and block reference.
276 TargetTransformInfo *TTI;
280 /// Instruction builder to construct the vectorized tree.
284 int FuncSLP::getGatherCost(Type *Ty) {
286 for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
287 Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
291 int FuncSLP::getGatherCost(ArrayRef<Value *> VL) {
292 // Find the type of the operands in VL.
293 Type *ScalarTy = VL[0]->getType();
294 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
295 ScalarTy = SI->getValueOperand()->getType();
296 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
297 // Find the cost of inserting/extracting values from the vector.
298 return getGatherCost(VecTy);
301 AliasAnalysis::Location FuncSLP::getLocation(Instruction *I) {
302 if (StoreInst *SI = dyn_cast<StoreInst>(I))
303 return AA->getLocation(SI);
304 if (LoadInst *LI = dyn_cast<LoadInst>(I))
305 return AA->getLocation(LI);
306 return AliasAnalysis::Location();
309 Value *FuncSLP::getPointerOperand(Value *I) {
310 if (LoadInst *LI = dyn_cast<LoadInst>(I))
311 return LI->getPointerOperand();
312 if (StoreInst *SI = dyn_cast<StoreInst>(I))
313 return SI->getPointerOperand();
317 unsigned FuncSLP::getAddressSpaceOperand(Value *I) {
318 if (LoadInst *L = dyn_cast<LoadInst>(I))
319 return L->getPointerAddressSpace();
320 if (StoreInst *S = dyn_cast<StoreInst>(I))
321 return S->getPointerAddressSpace();
325 bool FuncSLP::isConsecutiveAccess(Value *A, Value *B) {
326 Value *PtrA = getPointerOperand(A);
327 Value *PtrB = getPointerOperand(B);
328 unsigned ASA = getAddressSpaceOperand(A);
329 unsigned ASB = getAddressSpaceOperand(B);
331 // Check that the address spaces match and that the pointers are valid.
332 if (!PtrA || !PtrB || (ASA != ASB))
335 // Check that A and B are of the same type.
336 if (PtrA->getType() != PtrB->getType())
339 // Calculate the distance.
340 const SCEV *PtrSCEVA = SE->getSCEV(PtrA);
341 const SCEV *PtrSCEVB = SE->getSCEV(PtrB);
342 const SCEV *OffsetSCEV = SE->getMinusSCEV(PtrSCEVA, PtrSCEVB);
343 const SCEVConstant *ConstOffSCEV = dyn_cast<SCEVConstant>(OffsetSCEV);
345 // Non constant distance.
349 int64_t Offset = ConstOffSCEV->getValue()->getSExtValue();
350 Type *Ty = cast<PointerType>(PtrA->getType())->getElementType();
351 // The Instructions are connsecutive if the size of the first load/store is
352 // the same as the offset.
353 int64_t Sz = DL->getTypeStoreSize(Ty);
354 return ((-Offset) == Sz);
357 Value *FuncSLP::getSinkBarrier(Instruction *Src, Instruction *Dst) {
358 assert(Src->getParent() == Dst->getParent() && "Not the same BB");
359 BasicBlock::iterator I = Src, E = Dst;
360 /// Scan all of the instruction from SRC to DST and check if
361 /// the source may alias.
362 for (++I; I != E; ++I) {
363 // Ignore store instructions that are marked as 'ignore'.
364 if (MemBarrierIgnoreList.count(I))
366 if (Src->mayWriteToMemory()) /* Write */ {
367 if (!I->mayReadOrWriteMemory())
370 if (!I->mayWriteToMemory())
373 AliasAnalysis::Location A = getLocation(&*I);
374 AliasAnalysis::Location B = getLocation(Src);
376 if (!A.Ptr || !B.Ptr || AA->alias(A, B))
382 static BasicBlock *getSameBlock(ArrayRef<Value *> VL) {
384 for (int i = 0, e = VL.size(); i < e; i++) {
385 Instruction *I = dyn_cast<Instruction>(VL[i]);
394 if (BB != I->getParent())
400 static bool allConstant(ArrayRef<Value *> VL) {
401 for (unsigned i = 0, e = VL.size(); i < e; ++i)
402 if (!isa<Constant>(VL[i]))
407 static bool isSplat(ArrayRef<Value *> VL) {
408 for (unsigned i = 1, e = VL.size(); i < e; ++i)
414 static unsigned getSameOpcode(ArrayRef<Value *> VL) {
416 for (int i = 0, e = VL.size(); i < e; i++) {
417 if (Instruction *I = dyn_cast<Instruction>(VL[i])) {
419 Opcode = I->getOpcode();
422 if (Opcode != I->getOpcode())
429 static bool CanReuseExtract(ArrayRef<Value *> VL, unsigned VF,
431 assert(Instruction::ExtractElement == getSameOpcode(VL) && "Invalid opcode");
432 // Check if all of the extracts come from the same vector and from the
435 ExtractElementInst *E0 = cast<ExtractElementInst>(VL0);
436 Value *Vec = E0->getOperand(0);
438 // We have to extract from the same vector type.
439 if (Vec->getType() != VecTy)
442 // Check that all of the indices extract from the correct offset.
443 ConstantInt *CI = dyn_cast<ConstantInt>(E0->getOperand(1));
444 if (!CI || CI->getZExtValue())
447 for (unsigned i = 1, e = VF; i < e; ++i) {
448 ExtractElementInst *E = cast<ExtractElementInst>(VL[i]);
449 ConstantInt *CI = dyn_cast<ConstantInt>(E->getOperand(1));
451 if (!CI || CI->getZExtValue() != i || E->getOperand(0) != Vec)
458 void FuncSLP::getTreeUses_rec(ArrayRef<Value *> VL, unsigned Depth) {
459 if (Depth == RecursionMaxDepth)
460 return MustGather.insert(VL.begin(), VL.end());
462 // Don't handle vectors.
463 if (VL[0]->getType()->isVectorTy())
466 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
467 if (SI->getValueOperand()->getType()->isVectorTy())
470 // If all of the operands are identical or constant we have a simple solution.
471 if (allConstant(VL) || isSplat(VL) || !getSameBlock(VL))
472 return MustGather.insert(VL.begin(), VL.end());
474 // Stop the scan at unknown IR.
475 Instruction *VL0 = dyn_cast<Instruction>(VL[0]);
476 assert(VL0 && "Invalid instruction");
478 // Mark instructions with multiple users.
479 int LastIndex = getLastIndex(VL);
480 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
481 if (PHINode *PN = dyn_cast<PHINode>(VL[i])) {
482 unsigned NumUses = 0;
483 // Check that PHINodes have only one external (non-self) use.
484 for (Value::use_iterator U = VL[i]->use_begin(), UE = VL[i]->use_end();
486 // Don't count self uses.
492 DEBUG(dbgs() << "SLP: Adding PHI to MultiUserVals "
493 "because it has " << NumUses << " users:" << *PN << " \n");
495 MultiUserVals[PN] = UI;
500 Instruction *I = dyn_cast<Instruction>(VL[i]);
501 // Remember to check if all of the users of this instruction are vectorized
502 // within our tree. At depth zero we have no local users, only external
503 // users that we don't care about.
504 if (Depth && I && I->getNumUses() > 1) {
505 DEBUG(dbgs() << "SLP: Adding to MultiUserVals "
506 "because it has " << I->getNumUses() << " users:" << *I << " \n");
507 UseInfo UI(VL0, LastIndex);
508 MultiUserVals[I] = UI;
512 // Check that the instruction is only used within one lane.
513 for (int i = 0, e = VL.size(); i < e; ++i) {
514 if (LaneMap.count(VL[i]) && LaneMap[VL[i]] != i) {
515 DEBUG(dbgs() << "SLP: Value used by multiple lanes:" << *VL[i] << "\n");
516 return MustGather.insert(VL.begin(), VL.end());
518 // Make this instruction as 'seen' and remember the lane.
522 unsigned Opcode = getSameOpcode(VL);
524 return MustGather.insert(VL.begin(), VL.end());
527 case Instruction::PHI: {
528 PHINode *PH = dyn_cast<PHINode>(VL0);
531 if (VisitedPHIs.count(PH))
534 VisitedPHIs.insert(PH);
535 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
537 // Prepare the operand vector.
538 for (unsigned j = 0; j < VL.size(); ++j)
539 Operands.push_back(cast<PHINode>(VL[j])->getIncomingValue(i));
541 getTreeUses_rec(Operands, Depth + 1);
545 case Instruction::ExtractElement: {
546 VectorType *VecTy = VectorType::get(VL[0]->getType(), VL.size());
547 // No need to follow ExtractElements that are going to be optimized away.
548 if (CanReuseExtract(VL, VL.size(), VecTy))
552 case Instruction::Load:
554 case Instruction::ZExt:
555 case Instruction::SExt:
556 case Instruction::FPToUI:
557 case Instruction::FPToSI:
558 case Instruction::FPExt:
559 case Instruction::PtrToInt:
560 case Instruction::IntToPtr:
561 case Instruction::SIToFP:
562 case Instruction::UIToFP:
563 case Instruction::Trunc:
564 case Instruction::FPTrunc:
565 case Instruction::BitCast:
566 case Instruction::Select:
567 case Instruction::ICmp:
568 case Instruction::FCmp:
569 case Instruction::Add:
570 case Instruction::FAdd:
571 case Instruction::Sub:
572 case Instruction::FSub:
573 case Instruction::Mul:
574 case Instruction::FMul:
575 case Instruction::UDiv:
576 case Instruction::SDiv:
577 case Instruction::FDiv:
578 case Instruction::URem:
579 case Instruction::SRem:
580 case Instruction::FRem:
581 case Instruction::Shl:
582 case Instruction::LShr:
583 case Instruction::AShr:
584 case Instruction::And:
585 case Instruction::Or:
586 case Instruction::Xor: {
587 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
589 // Prepare the operand vector.
590 for (unsigned j = 0; j < VL.size(); ++j)
591 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
593 getTreeUses_rec(Operands, Depth + 1);
597 case Instruction::Store: {
599 for (unsigned j = 0; j < VL.size(); ++j)
600 Operands.push_back(cast<Instruction>(VL[j])->getOperand(0));
601 getTreeUses_rec(Operands, Depth + 1);
605 return MustGather.insert(VL.begin(), VL.end());
609 int FuncSLP::getLastIndex(ArrayRef<Value *> VL) {
610 BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
611 assert(BB == getSameBlock(VL) && BlocksNumbers.count(BB) && "Invalid block");
612 BlockNumbering &BN = BlocksNumbers[BB];
614 int MaxIdx = BN.getIndex(BB->getFirstNonPHI());
615 for (unsigned i = 0, e = VL.size(); i < e; ++i)
616 MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
620 Instruction *FuncSLP::getLastInstruction(ArrayRef<Value *> VL) {
621 BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
622 assert(BB == getSameBlock(VL) && BlocksNumbers.count(BB) && "Invalid block");
623 BlockNumbering &BN = BlocksNumbers[BB];
625 int MaxIdx = BN.getIndex(cast<Instruction>(VL[0]));
626 for (unsigned i = 1, e = VL.size(); i < e; ++i)
627 MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
628 return BN.getInstruction(MaxIdx);
631 Instruction *FuncSLP::getInstructionForIndex(unsigned Index, BasicBlock *BB) {
632 BlockNumbering &BN = BlocksNumbers[BB];
633 return BN.getInstruction(Index);
636 int FuncSLP::getFirstUserIndex(ArrayRef<Value *> VL) {
637 BasicBlock *BB = getSameBlock(VL);
638 assert(BB && "All instructions must come from the same block");
639 BlockNumbering &BN = BlocksNumbers[BB];
641 // Find the first user of the values.
642 int FirstUser = BN.getIndex(BB->getTerminator());
643 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
644 for (Value::use_iterator U = VL[i]->use_begin(), UE = VL[i]->use_end();
646 Instruction *Instr = dyn_cast<Instruction>(*U);
648 if (!Instr || Instr->getParent() != BB)
651 FirstUser = std::min(FirstUser, BN.getIndex(Instr));
657 int FuncSLP::getTreeCost_rec(ArrayRef<Value *> VL, unsigned Depth) {
658 Type *ScalarTy = VL[0]->getType();
660 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
661 ScalarTy = SI->getValueOperand()->getType();
663 /// Don't mess with vectors.
664 if (ScalarTy->isVectorTy())
665 return FuncSLP::MAX_COST;
670 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
673 return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
675 int GatherCost = getGatherCost(VecTy);
676 if (Depth == RecursionMaxDepth || needToGatherAny(VL))
679 BasicBlock *BB = getSameBlock(VL);
680 unsigned Opcode = getSameOpcode(VL);
681 assert(Opcode && BB && "Invalid Instruction Value");
683 // Check if it is safe to sink the loads or the stores.
684 if (Opcode == Instruction::Load || Opcode == Instruction::Store) {
685 int MaxIdx = getLastIndex(VL);
686 Instruction *Last = getInstructionForIndex(MaxIdx, BB);
688 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
691 Value *Barrier = getSinkBarrier(cast<Instruction>(VL[i]), Last);
693 DEBUG(dbgs() << "SLP: Can't sink " << *VL[i] << "\n down to " << *Last
694 << "\n because of " << *Barrier << "\n");
701 // Calculate the extract cost.
702 unsigned ExternalUserExtractCost = 0;
703 for (unsigned i = 0, e = VL.size(); i < e; ++i)
704 if (ExtractedLane.count(cast<Instruction>(VL[i])))
705 ExternalUserExtractCost +=
706 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, i);
708 Instruction *VL0 = cast<Instruction>(VL[0]);
710 case Instruction::PHI: {
711 PHINode *PH = dyn_cast<PHINode>(VL0);
714 if (VisitedPHIs.count(PH))
717 VisitedPHIs.insert(PH);
719 // Calculate the cost of all of the operands.
720 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
722 // Prepare the operand vector.
723 for (unsigned j = 0; j < VL.size(); ++j)
724 Operands.push_back(cast<PHINode>(VL[j])->getIncomingValue(i));
726 int Cost = getTreeCost_rec(Operands, Depth + 1);
727 if (Cost == MAX_COST)
729 TotalCost += TotalCost;
732 if (TotalCost > GatherCost) {
733 MustGather.insert(VL.begin(), VL.end());
737 return TotalCost + ExternalUserExtractCost;
739 case Instruction::ExtractElement: {
740 if (CanReuseExtract(VL, VL.size(), VecTy))
742 return getGatherCost(VecTy);
744 case Instruction::ZExt:
745 case Instruction::SExt:
746 case Instruction::FPToUI:
747 case Instruction::FPToSI:
748 case Instruction::FPExt:
749 case Instruction::PtrToInt:
750 case Instruction::IntToPtr:
751 case Instruction::SIToFP:
752 case Instruction::UIToFP:
753 case Instruction::Trunc:
754 case Instruction::FPTrunc:
755 case Instruction::BitCast: {
757 Type *SrcTy = VL0->getOperand(0)->getType();
758 // Prepare the operand vector.
759 for (unsigned j = 0; j < VL.size(); ++j) {
760 Operands.push_back(cast<Instruction>(VL[j])->getOperand(0));
761 // Check that the casted type is the same for all users.
762 if (cast<Instruction>(VL[j])->getOperand(0)->getType() != SrcTy)
763 return getGatherCost(VecTy);
766 int Cost = getTreeCost_rec(Operands, Depth + 1);
767 if (Cost == MAX_COST)
770 // Calculate the cost of this instruction.
771 int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(),
772 VL0->getType(), SrcTy);
774 VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
775 int VecCost = TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy);
776 Cost += (VecCost - ScalarCost);
778 if (Cost > GatherCost) {
779 MustGather.insert(VL.begin(), VL.end());
783 return Cost + ExternalUserExtractCost;
785 case Instruction::FCmp:
786 case Instruction::ICmp: {
787 // Check that all of the compares have the same predicate.
788 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
789 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
790 CmpInst *Cmp = cast<CmpInst>(VL[i]);
791 if (Cmp->getPredicate() != P0)
792 return getGatherCost(VecTy);
796 case Instruction::Select:
797 case Instruction::Add:
798 case Instruction::FAdd:
799 case Instruction::Sub:
800 case Instruction::FSub:
801 case Instruction::Mul:
802 case Instruction::FMul:
803 case Instruction::UDiv:
804 case Instruction::SDiv:
805 case Instruction::FDiv:
806 case Instruction::URem:
807 case Instruction::SRem:
808 case Instruction::FRem:
809 case Instruction::Shl:
810 case Instruction::LShr:
811 case Instruction::AShr:
812 case Instruction::And:
813 case Instruction::Or:
814 case Instruction::Xor: {
816 // Calculate the cost of all of the operands.
817 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
819 // Prepare the operand vector.
820 for (unsigned j = 0; j < VL.size(); ++j)
821 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
823 int Cost = getTreeCost_rec(Operands, Depth + 1);
824 if (Cost == MAX_COST)
829 // Calculate the cost of this instruction.
832 if (Opcode == Instruction::FCmp || Opcode == Instruction::ICmp ||
833 Opcode == Instruction::Select) {
834 VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
836 VecTy->getNumElements() *
837 TTI->getCmpSelInstrCost(Opcode, ScalarTy, Builder.getInt1Ty());
838 VecCost = TTI->getCmpSelInstrCost(Opcode, VecTy, MaskTy);
840 ScalarCost = VecTy->getNumElements() *
841 TTI->getArithmeticInstrCost(Opcode, ScalarTy);
842 VecCost = TTI->getArithmeticInstrCost(Opcode, VecTy);
844 TotalCost += (VecCost - ScalarCost);
846 if (TotalCost > GatherCost) {
847 MustGather.insert(VL.begin(), VL.end());
851 return TotalCost + ExternalUserExtractCost;
853 case Instruction::Load: {
854 // If we are scalarize the loads, add the cost of forming the vector.
855 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
856 if (!isConsecutiveAccess(VL[i], VL[i + 1]))
857 return getGatherCost(VecTy);
859 // Cost of wide load - cost of scalar loads.
860 int ScalarLdCost = VecTy->getNumElements() *
861 TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
862 int VecLdCost = TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
863 int TotalCost = VecLdCost - ScalarLdCost;
865 if (TotalCost > GatherCost) {
866 MustGather.insert(VL.begin(), VL.end());
870 return TotalCost + ExternalUserExtractCost;
872 case Instruction::Store: {
873 // We know that we can merge the stores. Calculate the cost.
874 int ScalarStCost = VecTy->getNumElements() *
875 TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
876 int VecStCost = TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
877 int StoreCost = VecStCost - ScalarStCost;
880 for (unsigned j = 0; j < VL.size(); ++j) {
881 Operands.push_back(cast<Instruction>(VL[j])->getOperand(0));
882 MemBarrierIgnoreList.insert(VL[j]);
885 int Cost = getTreeCost_rec(Operands, Depth + 1);
886 if (Cost == MAX_COST)
889 int TotalCost = StoreCost + Cost;
890 return TotalCost + ExternalUserExtractCost;
893 // Unable to vectorize unknown instructions.
894 return getGatherCost(VecTy);
898 int FuncSLP::getTreeCost(ArrayRef<Value *> VL) {
899 // Get rid of the list of stores that were removed, and from the
900 // lists of instructions with multiple users.
901 MemBarrierIgnoreList.clear();
903 MultiUserVals.clear();
904 ExtractedLane.clear();
908 if (!getSameBlock(VL))
911 // Find the location of the last root.
912 int LastRootIndex = getLastIndex(VL);
913 int FirstUserIndex = getFirstUserIndex(VL);
915 // Don't vectorize if there are users of the tree roots inside the tree
917 if (LastRootIndex > FirstUserIndex)
920 // Scan the tree and find which value is used by which lane, and which values
921 // must be scalarized.
922 getTreeUses_rec(VL, 0);
924 // Check that instructions with multiple users can be vectorized. Mark
925 // unsafe instructions.
926 for (MapVector<Instruction *, UseInfo>::iterator UI = MultiUserVals.begin(),
927 e = MultiUserVals.end(); UI != e; ++UI) {
928 Instruction *Scalar = UI->first;
930 if (MustGather.count(Scalar))
933 assert(LaneMap.count(Scalar) && "Unknown scalar");
934 int ScalarLane = LaneMap[Scalar];
936 bool ExternalUse = false;
937 // Check that all of the users of this instr are within the tree.
938 for (Value::use_iterator Usr = Scalar->use_begin(),
939 UE = Scalar->use_end(); Usr != UE; ++Usr) {
940 // If this user is within the tree, make sure it is from the same lane.
941 // Notice that we have both in-tree and out-of-tree users.
942 if (LaneMap.count(*Usr)) {
943 if (LaneMap[*Usr] != ScalarLane) {
944 DEBUG(dbgs() << "SLP: Adding to MustExtract "
945 "because of an out-of-lane usage.\n");
946 MustGather.insert(Scalar);
952 // We have an out-of-tree user. Check if we can place an 'extract'.
953 Instruction *User = cast<Instruction>(*Usr);
954 // We care about the order only if the user is in the same block.
955 if (User->getParent() == Scalar->getParent()) {
956 int LastLoc = UI->second.LastIndex;
957 BlockNumbering &BN = BlocksNumbers[User->getParent()];
958 int UserIdx = BN.getIndex(User);
959 if (UserIdx <= LastLoc) {
960 DEBUG(dbgs() << "SLP: Adding to MustExtract because of an external "
961 "user that we can't schedule.\n");
962 MustGather.insert(Scalar);
966 // We have an external user.
971 // Items that are left in MultiUserVals are to be extracted.
972 // ExtractLane is used for the lookup.
973 ExtractedLane.insert(Scalar);
978 // Now calculate the cost of vectorizing the tree.
979 return getTreeCost_rec(VL, 0);
981 bool FuncSLP::vectorizeStoreChain(ArrayRef<Value *> Chain, int CostThreshold) {
982 unsigned ChainLen = Chain.size();
983 DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
985 Type *StoreTy = cast<StoreInst>(Chain[0])->getValueOperand()->getType();
986 unsigned Sz = DL->getTypeSizeInBits(StoreTy);
987 unsigned VF = MinVecRegSize / Sz;
989 if (!isPowerOf2_32(Sz) || VF < 2)
992 bool Changed = false;
993 // Look for profitable vectorizable trees at all offsets, starting at zero.
994 for (unsigned i = 0, e = ChainLen; i < e; ++i) {
997 DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
999 ArrayRef<Value *> Operands = Chain.slice(i, VF);
1001 int Cost = getTreeCost(Operands);
1002 if (Cost == FuncSLP::MAX_COST)
1004 DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
1005 if (Cost < CostThreshold) {
1006 DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
1007 vectorizeTree(Operands);
1009 // Remove the scalar stores.
1010 for (int j = 0, e = VF; j < e; ++j)
1011 cast<Instruction>(Operands[j])->eraseFromParent();
1013 // Move to the next bundle.
1019 if (Changed || ChainLen > VF)
1022 // Handle short chains. This helps us catch types such as <3 x float> that
1023 // are smaller than vector size.
1024 int Cost = getTreeCost(Chain);
1025 if (Cost == FuncSLP::MAX_COST)
1027 if (Cost < CostThreshold) {
1028 DEBUG(dbgs() << "SLP: Found store chain cost = " << Cost
1029 << " for size = " << ChainLen << "\n");
1030 vectorizeTree(Chain);
1032 // Remove all of the scalar stores.
1033 for (int i = 0, e = Chain.size(); i < e; ++i)
1034 cast<Instruction>(Chain[i])->eraseFromParent();
1042 bool FuncSLP::vectorizeStores(ArrayRef<StoreInst *> Stores, int costThreshold) {
1043 SetVector<Value *> Heads, Tails;
1044 SmallDenseMap<Value *, Value *> ConsecutiveChain;
1046 // We may run into multiple chains that merge into a single chain. We mark the
1047 // stores that we vectorized so that we don't visit the same store twice.
1048 ValueSet VectorizedStores;
1049 bool Changed = false;
1051 // Do a quadratic search on all of the given stores and find
1052 // all of the pairs of loads that follow each other.
1053 for (unsigned i = 0, e = Stores.size(); i < e; ++i)
1054 for (unsigned j = 0; j < e; ++j) {
1058 if (isConsecutiveAccess(Stores[i], Stores[j])) {
1059 Tails.insert(Stores[j]);
1060 Heads.insert(Stores[i]);
1061 ConsecutiveChain[Stores[i]] = Stores[j];
1065 // For stores that start but don't end a link in the chain:
1066 for (SetVector<Value *>::iterator it = Heads.begin(), e = Heads.end();
1068 if (Tails.count(*it))
1071 // We found a store instr that starts a chain. Now follow the chain and try
1075 // Collect the chain into a list.
1076 while (Tails.count(I) || Heads.count(I)) {
1077 if (VectorizedStores.count(I))
1079 Operands.push_back(I);
1080 // Move to the next value in the chain.
1081 I = ConsecutiveChain[I];
1084 bool Vectorized = vectorizeStoreChain(Operands, costThreshold);
1086 // Mark the vectorized stores so that we don't vectorize them again.
1088 VectorizedStores.insert(Operands.begin(), Operands.end());
1089 Changed |= Vectorized;
1095 Value *FuncSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
1096 Value *Vec = UndefValue::get(Ty);
1097 // Generate the 'InsertElement' instruction.
1098 for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
1099 Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
1100 if (Instruction *I = dyn_cast<Instruction>(Vec))
1101 GatherSeq.insert(I);
1107 Value *FuncSLP::vectorizeTree_rec(ArrayRef<Value *> VL) {
1108 BuilderLocGuard Guard(Builder);
1110 Type *ScalarTy = VL[0]->getType();
1111 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1112 ScalarTy = SI->getValueOperand()->getType();
1113 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1115 if (needToGatherAny(VL))
1116 return Gather(VL, VecTy);
1118 if (VectorizedValues.count(VL[0])) {
1119 DEBUG(dbgs() << "SLP: Diamond merged at depth.\n");
1120 return VectorizedValues[VL[0]];
1123 Instruction *VL0 = cast<Instruction>(VL[0]);
1124 unsigned Opcode = VL0->getOpcode();
1125 assert(Opcode == getSameOpcode(VL) && "Invalid opcode");
1128 case Instruction::PHI: {
1129 PHINode *PH = dyn_cast<PHINode>(VL0);
1130 Builder.SetInsertPoint(PH->getParent()->getFirstInsertionPt());
1131 PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
1132 VectorizedValues[VL0] = NewPhi;
1134 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1136 BasicBlock *IBB = PH->getIncomingBlock(i);
1138 // Prepare the operand vector.
1139 for (unsigned j = 0; j < VL.size(); ++j)
1140 Operands.push_back(cast<PHINode>(VL[j])->getIncomingValueForBlock(IBB));
1142 Builder.SetInsertPoint(IBB->getTerminator());
1143 Value *Vec = vectorizeTree_rec(Operands);
1144 NewPhi->addIncoming(Vec, IBB);
1147 assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
1148 "Invalid number of incoming values");
1152 case Instruction::ExtractElement: {
1153 if (CanReuseExtract(VL, VL.size(), VecTy))
1154 return VL0->getOperand(0);
1155 return Gather(VL, VecTy);
1157 case Instruction::ZExt:
1158 case Instruction::SExt:
1159 case Instruction::FPToUI:
1160 case Instruction::FPToSI:
1161 case Instruction::FPExt:
1162 case Instruction::PtrToInt:
1163 case Instruction::IntToPtr:
1164 case Instruction::SIToFP:
1165 case Instruction::UIToFP:
1166 case Instruction::Trunc:
1167 case Instruction::FPTrunc:
1168 case Instruction::BitCast: {
1170 for (int i = 0, e = VL.size(); i < e; ++i)
1171 INVL.push_back(cast<Instruction>(VL[i])->getOperand(0));
1173 Builder.SetInsertPoint(getLastInstruction(VL));
1174 Value *InVec = vectorizeTree_rec(INVL);
1175 CastInst *CI = dyn_cast<CastInst>(VL0);
1176 Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
1177 VectorizedValues[VL0] = V;
1180 case Instruction::FCmp:
1181 case Instruction::ICmp: {
1182 // Check that all of the compares have the same predicate.
1183 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
1184 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
1185 CmpInst *Cmp = cast<CmpInst>(VL[i]);
1186 if (Cmp->getPredicate() != P0)
1187 return Gather(VL, VecTy);
1190 ValueList LHSV, RHSV;
1191 for (int i = 0, e = VL.size(); i < e; ++i) {
1192 LHSV.push_back(cast<Instruction>(VL[i])->getOperand(0));
1193 RHSV.push_back(cast<Instruction>(VL[i])->getOperand(1));
1196 Builder.SetInsertPoint(getLastInstruction(VL));
1197 Value *L = vectorizeTree_rec(LHSV);
1198 Value *R = vectorizeTree_rec(RHSV);
1201 if (Opcode == Instruction::FCmp)
1202 V = Builder.CreateFCmp(P0, L, R);
1204 V = Builder.CreateICmp(P0, L, R);
1206 VectorizedValues[VL0] = V;
1209 case Instruction::Select: {
1210 ValueList TrueVec, FalseVec, CondVec;
1211 for (int i = 0, e = VL.size(); i < e; ++i) {
1212 CondVec.push_back(cast<Instruction>(VL[i])->getOperand(0));
1213 TrueVec.push_back(cast<Instruction>(VL[i])->getOperand(1));
1214 FalseVec.push_back(cast<Instruction>(VL[i])->getOperand(2));
1217 Builder.SetInsertPoint(getLastInstruction(VL));
1218 Value *True = vectorizeTree_rec(TrueVec);
1219 Value *False = vectorizeTree_rec(FalseVec);
1220 Value *Cond = vectorizeTree_rec(CondVec);
1221 Value *V = Builder.CreateSelect(Cond, True, False);
1222 VectorizedValues[VL0] = V;
1225 case Instruction::Add:
1226 case Instruction::FAdd:
1227 case Instruction::Sub:
1228 case Instruction::FSub:
1229 case Instruction::Mul:
1230 case Instruction::FMul:
1231 case Instruction::UDiv:
1232 case Instruction::SDiv:
1233 case Instruction::FDiv:
1234 case Instruction::URem:
1235 case Instruction::SRem:
1236 case Instruction::FRem:
1237 case Instruction::Shl:
1238 case Instruction::LShr:
1239 case Instruction::AShr:
1240 case Instruction::And:
1241 case Instruction::Or:
1242 case Instruction::Xor: {
1243 ValueList LHSVL, RHSVL;
1244 for (int i = 0, e = VL.size(); i < e; ++i) {
1245 LHSVL.push_back(cast<Instruction>(VL[i])->getOperand(0));
1246 RHSVL.push_back(cast<Instruction>(VL[i])->getOperand(1));
1249 Builder.SetInsertPoint(getLastInstruction(VL));
1250 Value *LHS = vectorizeTree_rec(LHSVL);
1251 Value *RHS = vectorizeTree_rec(RHSVL);
1254 assert((VL0->getOperand(0) == VL0->getOperand(1)) && "Invalid order");
1257 BinaryOperator *BinOp = cast<BinaryOperator>(VL0);
1258 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), LHS, RHS);
1259 VectorizedValues[VL0] = V;
1262 case Instruction::Load: {
1263 // Check if all of the loads are consecutive.
1264 for (unsigned i = 1, e = VL.size(); i < e; ++i)
1265 if (!isConsecutiveAccess(VL[i - 1], VL[i]))
1266 return Gather(VL, VecTy);
1268 // Loads are inserted at the head of the tree because we don't want to
1269 // sink them all the way down past store instructions.
1270 Builder.SetInsertPoint(getLastInstruction(VL));
1271 LoadInst *LI = cast<LoadInst>(VL0);
1273 Builder.CreateBitCast(LI->getPointerOperand(), VecTy->getPointerTo());
1274 unsigned Alignment = LI->getAlignment();
1275 LI = Builder.CreateLoad(VecPtr);
1276 LI->setAlignment(Alignment);
1278 VectorizedValues[VL0] = LI;
1281 case Instruction::Store: {
1282 StoreInst *SI = cast<StoreInst>(VL0);
1283 unsigned Alignment = SI->getAlignment();
1286 for (int i = 0, e = VL.size(); i < e; ++i)
1287 ValueOp.push_back(cast<StoreInst>(VL[i])->getValueOperand());
1289 Value *VecValue = vectorizeTree_rec(ValueOp);
1291 Builder.SetInsertPoint(getLastInstruction(VL));
1293 Builder.CreateBitCast(SI->getPointerOperand(), VecTy->getPointerTo());
1294 Builder.CreateStore(VecValue, VecPtr)->setAlignment(Alignment);
1298 return Gather(VL, VecTy);
1302 Value *FuncSLP::vectorizeTree(ArrayRef<Value *> VL) {
1303 Builder.SetInsertPoint(getLastInstruction(VL));
1304 Value *V = vectorizeTree_rec(VL);
1306 DEBUG(dbgs() << "SLP: Placing 'extracts'\n");
1307 for (SetVector<Instruction*>::iterator it = ExtractedLane.begin(), e =
1308 ExtractedLane.end(); it != e; ++it) {
1309 Instruction *Scalar = *it;
1310 DEBUG(dbgs() << "SLP: Looking at " << *Scalar);
1315 Instruction *Loc = 0;
1317 assert(MultiUserVals.count(Scalar) && "Can't find the lane to extract");
1318 Instruction *Leader = MultiUserVals[Scalar].Leader;
1320 // This value is gathered so we don't need to extract from anywhere.
1321 if (!VectorizedValues.count(Leader))
1324 Value *Vec = VectorizedValues[Leader];
1325 if (PHINode *PN = dyn_cast<PHINode>(Vec)) {
1326 Loc = PN->getParent()->getFirstInsertionPt();
1328 Instruction *I = cast<Instruction>(Vec);
1329 BasicBlock::iterator L = *I;
1333 Builder.SetInsertPoint(Loc);
1334 assert(LaneMap.count(Scalar) && "Can't find the extracted lane.");
1335 int Lane = LaneMap[Scalar];
1336 Value *Idx = Builder.getInt32(Lane);
1337 Value *Extract = Builder.CreateExtractElement(Vec, Idx);
1339 bool Replaced = false;;
1340 for (Value::use_iterator U = Scalar->use_begin(), UE = Scalar->use_end();
1342 Instruction *UI = cast<Instruction>(*U);
1343 // No need to replace instructions that are inside our lane map.
1344 if (LaneMap.count(UI))
1347 UI->replaceUsesOfWith(Scalar ,Extract);
1350 assert(Replaced && "Must replace at least one outside user");
1354 // We moved some instructions around. We have to number them again
1355 // before we can do any analysis.
1360 VisitedPHIs.clear();
1361 VectorizedValues.clear();
1362 MemBarrierIgnoreList.clear();
1366 Value *FuncSLP::vectorizeArith(ArrayRef<Value *> Operands) {
1367 Instruction *LastInst = getLastInstruction(Operands);
1368 Value *Vec = vectorizeTree(Operands);
1369 // After vectorizing the operands we need to generate extractelement
1370 // instructions and replace all of the uses of the scalar values with
1371 // the values that we extracted from the vectorized tree.
1372 Builder.SetInsertPoint(LastInst);
1373 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
1374 Value *S = Builder.CreateExtractElement(Vec, Builder.getInt32(i));
1375 Operands[i]->replaceAllUsesWith(S);
1382 void FuncSLP::optimizeGatherSequence() {
1383 // LICM InsertElementInst sequences.
1384 for (SetVector<Instruction *>::iterator it = GatherSeq.begin(),
1385 e = GatherSeq.end(); it != e; ++it) {
1386 InsertElementInst *Insert = dyn_cast<InsertElementInst>(*it);
1391 // Check if this block is inside a loop.
1392 Loop *L = LI->getLoopFor(Insert->getParent());
1396 // Check if it has a preheader.
1397 BasicBlock *PreHeader = L->getLoopPreheader();
1401 // If the vector or the element that we insert into it are
1402 // instructions that are defined in this basic block then we can't
1403 // hoist this instruction.
1404 Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
1405 Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
1406 if (CurrVec && L->contains(CurrVec))
1408 if (NewElem && L->contains(NewElem))
1411 // We can hoist this instruction. Move it to the pre-header.
1412 Insert->moveBefore(PreHeader->getTerminator());
1415 // Perform O(N^2) search over the gather sequences and merge identical
1416 // instructions. TODO: We can further optimize this scan if we split the
1417 // instructions into different buckets based on the insert lane.
1418 SmallPtrSet<Instruction*, 16> Visited;
1419 SmallVector<Instruction*, 16> ToRemove;
1420 ReversePostOrderTraversal<Function*> RPOT(F);
1421 for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
1422 E = RPOT.end(); I != E; ++I) {
1423 BasicBlock *BB = *I;
1424 // For all instructions in the function:
1425 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1426 InsertElementInst *Insert = dyn_cast<InsertElementInst>(it);
1427 if (!Insert || !GatherSeq.count(Insert))
1430 // Check if we can replace this instruction with any of the
1431 // visited instructions.
1432 for (SmallPtrSet<Instruction*, 16>::iterator v = Visited.begin(),
1433 ve = Visited.end(); v != ve; ++v) {
1434 if (Insert->isIdenticalTo(*v) &&
1435 DT->dominates((*v)->getParent(), Insert->getParent())) {
1436 Insert->replaceAllUsesWith(*v);
1437 ToRemove.push_back(Insert);
1443 Visited.insert(Insert);
1447 // Erase all of the instructions that we RAUWed.
1448 for (SmallVector<Instruction*, 16>::iterator v = ToRemove.begin(),
1449 ve = ToRemove.end(); v != ve; ++v) {
1450 assert((*v)->getNumUses() == 0 && "Can't remove instructions with uses");
1451 (*v)->eraseFromParent();
1457 /// The SLPVectorizer Pass.
1458 struct SLPVectorizer : public FunctionPass {
1459 typedef SmallVector<StoreInst *, 8> StoreList;
1460 typedef MapVector<Value *, StoreList> StoreListMap;
1462 /// Pass identification, replacement for typeid
1465 explicit SLPVectorizer() : FunctionPass(ID) {
1466 initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
1469 ScalarEvolution *SE;
1471 TargetTransformInfo *TTI;
1476 virtual bool runOnFunction(Function &F) {
1477 SE = &getAnalysis<ScalarEvolution>();
1478 DL = getAnalysisIfAvailable<DataLayout>();
1479 TTI = &getAnalysis<TargetTransformInfo>();
1480 AA = &getAnalysis<AliasAnalysis>();
1481 LI = &getAnalysis<LoopInfo>();
1482 DT = &getAnalysis<DominatorTree>();
1485 bool Changed = false;
1487 // Must have DataLayout. We can't require it because some tests run w/o
1492 DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
1494 // Use the bollom up slp vectorizer to construct chains that start with
1495 // he store instructions.
1496 FuncSLP R(&F, SE, DL, TTI, AA, LI, DT);
1498 // Scan the blocks in the function in post order.
1499 for (po_iterator<BasicBlock*> it = po_begin(&F.getEntryBlock()),
1500 e = po_end(&F.getEntryBlock()); it != e; ++it) {
1501 BasicBlock *BB = *it;
1503 // Vectorize trees that end at reductions.
1504 Changed |= vectorizeChainsInBlock(BB, R);
1506 // Vectorize trees that end at stores.
1507 if (unsigned count = collectStores(BB, R)) {
1509 DEBUG(dbgs() << "SLP: Found " << count << " stores to vectorize.\n");
1510 Changed |= vectorizeStoreChains(R);
1515 R.optimizeGatherSequence();
1516 DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
1517 DEBUG(verifyFunction(F));
1522 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1523 FunctionPass::getAnalysisUsage(AU);
1524 AU.addRequired<ScalarEvolution>();
1525 AU.addRequired<AliasAnalysis>();
1526 AU.addRequired<TargetTransformInfo>();
1527 AU.addRequired<LoopInfo>();
1528 AU.addRequired<DominatorTree>();
1533 /// \brief Collect memory references and sort them according to their base
1534 /// object. We sort the stores to their base objects to reduce the cost of the
1535 /// quadratic search on the stores. TODO: We can further reduce this cost
1536 /// if we flush the chain creation every time we run into a memory barrier.
1537 unsigned collectStores(BasicBlock *BB, FuncSLP &R);
1539 /// \brief Try to vectorize a chain that starts at two arithmetic instrs.
1540 bool tryToVectorizePair(Value *A, Value *B, FuncSLP &R);
1542 /// \brief Try to vectorize a list of operands. If \p NeedExtracts is true
1543 /// then we calculate the cost of extracting the scalars from the vector.
1544 /// \returns true if a value was vectorized.
1545 bool tryToVectorizeList(ArrayRef<Value *> VL, FuncSLP &R, bool NeedExtracts);
1547 /// \brief Try to vectorize a chain that may start at the operands of \V;
1548 bool tryToVectorize(BinaryOperator *V, FuncSLP &R);
1550 /// \brief Vectorize the stores that were collected in StoreRefs.
1551 bool vectorizeStoreChains(FuncSLP &R);
1553 /// \brief Scan the basic block and look for patterns that are likely to start
1554 /// a vectorization chain.
1555 bool vectorizeChainsInBlock(BasicBlock *BB, FuncSLP &R);
1558 StoreListMap StoreRefs;
1561 unsigned SLPVectorizer::collectStores(BasicBlock *BB, FuncSLP &R) {
1564 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1565 StoreInst *SI = dyn_cast<StoreInst>(it);
1569 // Check that the pointer points to scalars.
1570 Type *Ty = SI->getValueOperand()->getType();
1571 if (Ty->isAggregateType() || Ty->isVectorTy())
1574 // Find the base of the GEP.
1575 Value *Ptr = SI->getPointerOperand();
1576 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
1577 Ptr = GEP->getPointerOperand();
1579 // Save the store locations.
1580 StoreRefs[Ptr].push_back(SI);
1586 bool SLPVectorizer::tryToVectorizePair(Value *A, Value *B, FuncSLP &R) {
1589 Value *VL[] = { A, B };
1590 return tryToVectorizeList(VL, R, true);
1593 bool SLPVectorizer::tryToVectorizeList(ArrayRef<Value *> VL, FuncSLP &R,
1594 bool NeedExtracts) {
1598 DEBUG(dbgs() << "SLP: Vectorizing a list of length = " << VL.size() << ".\n");
1600 // Check that all of the parts are scalar instructions of the same type.
1601 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
1605 unsigned Opcode0 = I0->getOpcode();
1607 for (int i = 0, e = VL.size(); i < e; ++i) {
1608 Type *Ty = VL[i]->getType();
1609 if (Ty->isAggregateType() || Ty->isVectorTy())
1611 Instruction *Inst = dyn_cast<Instruction>(VL[i]);
1612 if (!Inst || Inst->getOpcode() != Opcode0)
1616 int Cost = R.getTreeCost(VL);
1617 if (Cost == FuncSLP::MAX_COST)
1620 int ExtrCost = NeedExtracts ? R.getGatherCost(VL) : 0;
1621 DEBUG(dbgs() << "SLP: Cost of pair:" << Cost
1622 << " Cost of extract:" << ExtrCost << ".\n");
1623 if ((Cost + ExtrCost) >= -SLPCostThreshold)
1625 DEBUG(dbgs() << "SLP: Vectorizing pair.\n");
1626 R.vectorizeArith(VL);
1630 bool SLPVectorizer::tryToVectorize(BinaryOperator *V, FuncSLP &R) {
1634 // Try to vectorize V.
1635 if (tryToVectorizePair(V->getOperand(0), V->getOperand(1), R))
1638 BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0));
1639 BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1));
1641 if (B && B->hasOneUse()) {
1642 BinaryOperator *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
1643 BinaryOperator *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
1644 if (tryToVectorizePair(A, B0, R)) {
1648 if (tryToVectorizePair(A, B1, R)) {
1655 if (A && A->hasOneUse()) {
1656 BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
1657 BinaryOperator *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
1658 if (tryToVectorizePair(A0, B, R)) {
1662 if (tryToVectorizePair(A1, B, R)) {
1670 bool SLPVectorizer::vectorizeChainsInBlock(BasicBlock *BB, FuncSLP &R) {
1671 bool Changed = false;
1672 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1673 if (isa<DbgInfoIntrinsic>(it))
1676 // Try to vectorize reductions that use PHINodes.
1677 if (PHINode *P = dyn_cast<PHINode>(it)) {
1678 // Check that the PHI is a reduction PHI.
1679 if (P->getNumIncomingValues() != 2)
1682 (P->getIncomingBlock(0) == BB
1683 ? (P->getIncomingValue(0))
1684 : (P->getIncomingBlock(1) == BB ? P->getIncomingValue(1) : 0));
1685 // Check if this is a Binary Operator.
1686 BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx);
1690 Value *Inst = BI->getOperand(0);
1692 Inst = BI->getOperand(1);
1694 Changed |= tryToVectorize(dyn_cast<BinaryOperator>(Inst), R);
1698 // Try to vectorize trees that start at compare instructions.
1699 if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
1700 if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) {
1704 for (int i = 0; i < 2; ++i)
1705 if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i)))
1707 tryToVectorizePair(BI->getOperand(0), BI->getOperand(1), R);
1712 // Scan the PHINodes in our successors in search for pairing hints.
1713 for (succ_iterator it = succ_begin(BB), e = succ_end(BB); it != e; ++it) {
1714 BasicBlock *Succ = *it;
1715 SmallVector<Value *, 4> Incoming;
1717 // Collect the incoming values from the PHIs.
1718 for (BasicBlock::iterator instr = Succ->begin(), ie = Succ->end();
1719 instr != ie; ++instr) {
1720 PHINode *P = dyn_cast<PHINode>(instr);
1725 Value *V = P->getIncomingValueForBlock(BB);
1726 if (Instruction *I = dyn_cast<Instruction>(V))
1727 if (I->getParent() == BB)
1728 Incoming.push_back(I);
1731 if (Incoming.size() > 1)
1732 Changed |= tryToVectorizeList(Incoming, R, true);
1738 bool SLPVectorizer::vectorizeStoreChains(FuncSLP &R) {
1739 bool Changed = false;
1740 // Attempt to sort and vectorize each of the store-groups.
1741 for (StoreListMap::iterator it = StoreRefs.begin(), e = StoreRefs.end();
1743 if (it->second.size() < 2)
1746 DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
1747 << it->second.size() << ".\n");
1749 Changed |= R.vectorizeStores(it->second, -SLPCostThreshold);
1754 } // end anonymous namespace
1756 char SLPVectorizer::ID = 0;
1757 static const char lv_name[] = "SLP Vectorizer";
1758 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
1759 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
1760 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
1761 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1762 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
1763 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
1766 Pass *createSLPVectorizerPass() { return new SLPVectorizer(); }