6837e51c9a672b6a68e2a175582d9ad990ece9c3
[oota-llvm.git] / lib / Transforms / Vectorize / SLPVectorizer.cpp
1 //===- SLPVectorizer.cpp - A bottom up SLP Vectorizer ---------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
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.
13 //
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.
16 //
17 //===----------------------------------------------------------------------===//
18 #define SV_NAME "slp-vectorizer"
19 #define DEBUG_TYPE "SLP"
20
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"
43 #include <algorithm>
44 #include <map>
45
46 using namespace llvm;
47
48 static cl::opt<int>
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)"));
52 namespace {
53
54 static const unsigned MinVecRegSize = 128;
55
56 static const unsigned RecursionMaxDepth = 12;
57
58 /// RAII pattern to save the insertion point of the IR builder.
59 class BuilderLocGuard {
60 public:
61   BuilderLocGuard(IRBuilder<> &B) : Builder(B), Loc(B.GetInsertPoint()) {}
62   ~BuilderLocGuard() { Builder.SetInsertPoint(Loc); }
63
64 private:
65   // Prevent copying.
66   BuilderLocGuard(const BuilderLocGuard &);
67   BuilderLocGuard &operator=(const BuilderLocGuard &);
68   IRBuilder<> &Builder;
69   BasicBlock::iterator Loc;
70 };
71
72 /// A helper class for numbering instructions in multible blocks.
73 /// Numbers starts at zero for each basic block.
74 struct BlockNumbering {
75
76   BlockNumbering(BasicBlock *Bb) : BB(Bb), Valid(false) {}
77
78   BlockNumbering() : BB(0), Valid(false) {}
79
80   void numberInstructions() {
81     unsigned Loc = 0;
82     InstrIdx.clear();
83     InstrVec.clear();
84     // Number the instructions in the block.
85     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
86       InstrIdx[it] = Loc++;
87       InstrVec.push_back(it);
88       assert(InstrVec[InstrIdx[it]] == it && "Invalid allocation");
89     }
90     Valid = true;
91   }
92
93   int getIndex(Instruction *I) {
94     if (!Valid)
95       numberInstructions();
96     assert(InstrIdx.count(I) && "Unknown instruction");
97     return InstrIdx[I];
98   }
99
100   Instruction *getInstruction(unsigned loc) {
101     if (!Valid)
102       numberInstructions();
103     assert(InstrVec.size() > loc && "Invalid Index");
104     return InstrVec[loc];
105   }
106
107   void forget() { Valid = false; }
108
109 private:
110   /// The block we are numbering.
111   BasicBlock *BB;
112   /// Is the block numbered.
113   bool Valid;
114   /// Maps instructions to numbers and back.
115   SmallDenseMap<Instruction *, int> InstrIdx;
116   /// Maps integers to Instructions.
117   std::vector<Instruction *> InstrVec;
118 };
119
120 class FuncSLP {
121   typedef SmallVector<Value *, 8> ValueList;
122   typedef SmallVector<Instruction *, 16> InstrList;
123   typedef SmallPtrSet<Value *, 16> ValueSet;
124   typedef SmallVector<StoreInst *, 8> StoreList;
125
126 public:
127   static const int MAX_COST = INT_MIN;
128
129   FuncSLP(Function *Func, ScalarEvolution *Se, DataLayout *Dl,
130           TargetTransformInfo *Tti, AliasAnalysis *Aa, LoopInfo *Li, 
131           DominatorTree *Dt) :
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) {
135       BasicBlock *BB = it;
136       BlocksNumbers[BB] = BlockNumbering(BB);
137     }
138   }
139
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);
143
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);
147
148   /// \returns true if the memory operations A and B are consecutive.
149   bool isConsecutiveAccess(Value *A, Value *B);
150
151   /// \brief Vectorize the tree that starts with the elements in \p VL.
152   /// \returns the vectorized value.
153   Value *vectorizeTree(ArrayRef<Value *> VL);
154
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);
158
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);
163
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);
168
169   /// \brief Vectorize a group of scalars into a vector tree.
170   /// \returns the vectorized value.
171   Value *vectorizeArith(ArrayRef<Value *> Operands);
172
173   /// \brief This method contains the recursive part of getTreeCost.
174   int getTreeCost_rec(ArrayRef<Value *> VL, unsigned Depth);
175
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);
180
181   /// \brief This method contains the recursive part of vectorizeTree.
182   Value *vectorizeTree_rec(ArrayRef<Value *> VL);
183
184   ///  \brief Vectorize a sorted sequence of stores.
185   bool vectorizeStoreChain(ArrayRef<Value *> Chain, int CostThreshold);
186
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);
190
191   /// \returns the AA location that is being access by the instruction.
192   AliasAnalysis::Location getLocation(Instruction *I);
193
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);
198
199   /// \returns the index of the last instrucion in the BB from \p VL.
200   int getLastIndex(ArrayRef<Value *> VL);
201
202   /// \returns the Instrucion in the bundle \p VL.
203   Instruction *getLastInstruction(ArrayRef<Value *> VL);
204
205   /// \returns the Instruction at index \p Index which is in Block \p BB.
206   Instruction *getInstructionForIndex(unsigned Index, BasicBlock *BB);
207
208   /// \returns the index of the first User of \p VL.
209   int getFirstUserIndex(ArrayRef<Value *> VL);
210
211   /// \returns a vector from a collection of scalars in \p VL.
212   Value *Gather(ArrayRef<Value *> VL, VectorType *Ty);
213
214   /// \brief Perform LICM and CSE on the newly generated gather sequences.
215   void optimizeGatherSequence();
216
217   bool needToGatherAny(ArrayRef<Value *> VL) {
218     for (int i = 0, e = VL.size(); i < e; ++i)
219       if (MustGather.count(VL[i]))
220         return true;
221     return false;
222   }
223
224   /// -- Vectorization State --
225
226   /// Maps values in the tree to the vector lanes that uses them. This map must
227   /// be reset between runs of getCost.
228   std::map<Value *, int> LaneMap;
229   /// A list of instructions to ignore while sinking
230   /// memory instructions. This map must be reset between runs of getCost.
231   ValueSet MemBarrierIgnoreList;
232
233   /// Maps between the first scalar to the vector. This map must be reset
234   /// between runs.
235   DenseMap<Value *, Value *> VectorizedValues;
236
237   /// Contains values that must be gathered because they are used
238   /// by multiple lanes, or by users outside the tree.
239   /// NOTICE: The vectorization methods also use this set.
240   ValueSet MustGather;
241
242   /// Contains a list of values that are used outside the current tree. This
243   /// set must be reset between runs.
244   SetVector<Value *> MultiUserVals;
245
246   /// Holds all of the instructions that we gathered.
247   SetVector<Instruction *> GatherSeq;
248
249   /// Numbers instructions in different blocks.
250   std::map<BasicBlock *, BlockNumbering> BlocksNumbers;
251
252   // Analysis and block reference.
253   Function *F;
254   ScalarEvolution *SE;
255   DataLayout *DL;
256   TargetTransformInfo *TTI;
257   AliasAnalysis *AA;
258   LoopInfo *LI;
259   DominatorTree *DT;
260   /// Instruction builder to construct the vectorized tree.
261   IRBuilder<> Builder;
262 };
263
264 int FuncSLP::getGatherCost(Type *Ty) {
265   int Cost = 0;
266   for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
267     Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
268   return Cost;
269 }
270
271 int FuncSLP::getGatherCost(ArrayRef<Value *> VL) {
272   // Find the type of the operands in VL.
273   Type *ScalarTy = VL[0]->getType();
274   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
275     ScalarTy = SI->getValueOperand()->getType();
276   VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
277   // Find the cost of inserting/extracting values from the vector.
278   return getGatherCost(VecTy);
279 }
280
281 AliasAnalysis::Location FuncSLP::getLocation(Instruction *I) {
282   if (StoreInst *SI = dyn_cast<StoreInst>(I))
283     return AA->getLocation(SI);
284   if (LoadInst *LI = dyn_cast<LoadInst>(I))
285     return AA->getLocation(LI);
286   return AliasAnalysis::Location();
287 }
288
289 Value *FuncSLP::getPointerOperand(Value *I) {
290   if (LoadInst *LI = dyn_cast<LoadInst>(I))
291     return LI->getPointerOperand();
292   if (StoreInst *SI = dyn_cast<StoreInst>(I))
293     return SI->getPointerOperand();
294   return 0;
295 }
296
297 unsigned FuncSLP::getAddressSpaceOperand(Value *I) {
298   if (LoadInst *L = dyn_cast<LoadInst>(I))
299     return L->getPointerAddressSpace();
300   if (StoreInst *S = dyn_cast<StoreInst>(I))
301     return S->getPointerAddressSpace();
302   return -1;
303 }
304
305 bool FuncSLP::isConsecutiveAccess(Value *A, Value *B) {
306   Value *PtrA = getPointerOperand(A);
307   Value *PtrB = getPointerOperand(B);
308   unsigned ASA = getAddressSpaceOperand(A);
309   unsigned ASB = getAddressSpaceOperand(B);
310
311   // Check that the address spaces match and that the pointers are valid.
312   if (!PtrA || !PtrB || (ASA != ASB))
313     return false;
314
315   // Check that A and B are of the same type.
316   if (PtrA->getType() != PtrB->getType())
317     return false;
318
319   // Calculate the distance.
320   const SCEV *PtrSCEVA = SE->getSCEV(PtrA);
321   const SCEV *PtrSCEVB = SE->getSCEV(PtrB);
322   const SCEV *OffsetSCEV = SE->getMinusSCEV(PtrSCEVA, PtrSCEVB);
323   const SCEVConstant *ConstOffSCEV = dyn_cast<SCEVConstant>(OffsetSCEV);
324
325   // Non constant distance.
326   if (!ConstOffSCEV)
327     return false;
328
329   int64_t Offset = ConstOffSCEV->getValue()->getSExtValue();
330   Type *Ty = cast<PointerType>(PtrA->getType())->getElementType();
331   // The Instructions are connsecutive if the size of the first load/store is
332   // the same as the offset.
333   int64_t Sz = DL->getTypeStoreSize(Ty);
334   return ((-Offset) == Sz);
335 }
336
337 Value *FuncSLP::getSinkBarrier(Instruction *Src, Instruction *Dst) {
338   assert(Src->getParent() == Dst->getParent() && "Not the same BB");
339   BasicBlock::iterator I = Src, E = Dst;
340   /// Scan all of the instruction from SRC to DST and check if
341   /// the source may alias.
342   for (++I; I != E; ++I) {
343     // Ignore store instructions that are marked as 'ignore'.
344     if (MemBarrierIgnoreList.count(I))
345       continue;
346     if (Src->mayWriteToMemory()) /* Write */ {
347       if (!I->mayReadOrWriteMemory())
348         continue;
349     } else /* Read */ {
350       if (!I->mayWriteToMemory())
351         continue;
352     }
353     AliasAnalysis::Location A = getLocation(&*I);
354     AliasAnalysis::Location B = getLocation(Src);
355
356     if (!A.Ptr || !B.Ptr || AA->alias(A, B))
357       return I;
358   }
359   return 0;
360 }
361
362 static BasicBlock *getSameBlock(ArrayRef<Value *> VL) {
363   BasicBlock *BB = 0;
364   for (int i = 0, e = VL.size(); i < e; i++) {
365     Instruction *I = dyn_cast<Instruction>(VL[i]);
366     if (!I)
367       return 0;
368
369     if (!BB) {
370       BB = I->getParent();
371       continue;
372     }
373
374     if (BB != I->getParent())
375       return 0;
376   }
377   return BB;
378 }
379
380 static bool allConstant(ArrayRef<Value *> VL) {
381   for (unsigned i = 0, e = VL.size(); i < e; ++i)
382     if (!isa<Constant>(VL[i]))
383       return false;
384   return true;
385 }
386
387 static bool isSplat(ArrayRef<Value *> VL) {
388   for (unsigned i = 1, e = VL.size(); i < e; ++i)
389     if (VL[i] != VL[0])
390       return false;
391   return true;
392 }
393
394 static unsigned getSameOpcode(ArrayRef<Value *> VL) {
395   unsigned Opcode = 0;
396   for (int i = 0, e = VL.size(); i < e; i++) {
397     if (Instruction *I = dyn_cast<Instruction>(VL[i])) {
398       if (!Opcode) {
399         Opcode = I->getOpcode();
400         continue;
401       }
402       if (Opcode != I->getOpcode())
403         return 0;
404     }
405   }
406   return Opcode;
407 }
408
409 static bool CanReuseExtract(ArrayRef<Value *> VL, unsigned VF,
410                             VectorType *VecTy) {
411   assert(Instruction::ExtractElement == getSameOpcode(VL) && "Invalid opcode");
412   // Check if all of the extracts come from the same vector and from the
413   // correct offset.
414   Value *VL0 = VL[0];
415   ExtractElementInst *E0 = cast<ExtractElementInst>(VL0);
416   Value *Vec = E0->getOperand(0);
417
418   // We have to extract from the same vector type.
419   if (Vec->getType() != VecTy)
420     return false;
421
422   // Check that all of the indices extract from the correct offset.
423   ConstantInt *CI = dyn_cast<ConstantInt>(E0->getOperand(1));
424   if (!CI || CI->getZExtValue())
425     return false;
426
427   for (unsigned i = 1, e = VF; i < e; ++i) {
428     ExtractElementInst *E = cast<ExtractElementInst>(VL[i]);
429     ConstantInt *CI = dyn_cast<ConstantInt>(E->getOperand(1));
430
431     if (!CI || CI->getZExtValue() != i || E->getOperand(0) != Vec)
432       return false;
433   }
434
435   return true;
436 }
437
438 void FuncSLP::getTreeUses_rec(ArrayRef<Value *> VL, unsigned Depth) {
439   if (Depth == RecursionMaxDepth)
440     return MustGather.insert(VL.begin(), VL.end());
441
442   // Don't handle vectors.
443   if (VL[0]->getType()->isVectorTy())
444     return;
445
446   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
447     if (SI->getValueOperand()->getType()->isVectorTy())
448       return;
449
450   // If all of the operands are identical or constant we have a simple solution.
451   if (allConstant(VL) || isSplat(VL) || !getSameBlock(VL))
452     return MustGather.insert(VL.begin(), VL.end());
453
454   // Stop the scan at unknown IR.
455   Instruction *VL0 = dyn_cast<Instruction>(VL[0]);
456   assert(VL0 && "Invalid instruction");
457
458   // Mark instructions with multiple users.
459   for (unsigned i = 0, e = VL.size(); i < e; ++i) {
460     Instruction *I = dyn_cast<Instruction>(VL[i]);
461     // Remember to check if all of the users of this instruction are vectorized
462     // within our tree. At depth zero we have no local users, only external
463     // users that we don't care about.
464     if (Depth && I && I->getNumUses() > 1) {
465       DEBUG(dbgs() << "SLP: Adding to MultiUserVals "
466                       "because it has multiple users:" << *I << " \n");
467       MultiUserVals.insert(I);
468     }
469   }
470
471   // Check that the instruction is only used within one lane.
472   for (int i = 0, e = VL.size(); i < e; ++i) {
473     if (LaneMap.count(VL[i]) && LaneMap[VL[i]] != i) {
474       DEBUG(dbgs() << "SLP: Value used by multiple lanes:" << *VL[i] << "\n");
475       return MustGather.insert(VL.begin(), VL.end());
476     }
477     // Make this instruction as 'seen' and remember the lane.
478     LaneMap[VL[i]] = i;
479   }
480
481   unsigned Opcode = getSameOpcode(VL);
482   if (!Opcode)
483     return MustGather.insert(VL.begin(), VL.end());
484
485   switch (Opcode) {
486   case Instruction::ExtractElement: {
487     VectorType *VecTy = VectorType::get(VL[0]->getType(), VL.size());
488     // No need to follow ExtractElements that are going to be optimized away.
489     if (CanReuseExtract(VL, VL.size(), VecTy))
490       return;
491     // Fall through.
492   }
493   case Instruction::Load:
494     return;
495   case Instruction::ZExt:
496   case Instruction::SExt:
497   case Instruction::FPToUI:
498   case Instruction::FPToSI:
499   case Instruction::FPExt:
500   case Instruction::PtrToInt:
501   case Instruction::IntToPtr:
502   case Instruction::SIToFP:
503   case Instruction::UIToFP:
504   case Instruction::Trunc:
505   case Instruction::FPTrunc:
506   case Instruction::BitCast:
507   case Instruction::Select:
508   case Instruction::ICmp:
509   case Instruction::FCmp:
510   case Instruction::Add:
511   case Instruction::FAdd:
512   case Instruction::Sub:
513   case Instruction::FSub:
514   case Instruction::Mul:
515   case Instruction::FMul:
516   case Instruction::UDiv:
517   case Instruction::SDiv:
518   case Instruction::FDiv:
519   case Instruction::URem:
520   case Instruction::SRem:
521   case Instruction::FRem:
522   case Instruction::Shl:
523   case Instruction::LShr:
524   case Instruction::AShr:
525   case Instruction::And:
526   case Instruction::Or:
527   case Instruction::Xor: {
528     for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
529       ValueList Operands;
530       // Prepare the operand vector.
531       for (unsigned j = 0; j < VL.size(); ++j)
532         Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
533
534       getTreeUses_rec(Operands, Depth + 1);
535     }
536     return;
537   }
538   case Instruction::Store: {
539     ValueList Operands;
540     for (unsigned j = 0; j < VL.size(); ++j)
541       Operands.push_back(cast<Instruction>(VL[j])->getOperand(0));
542     getTreeUses_rec(Operands, Depth + 1);
543     return;
544   }
545   default:
546     return MustGather.insert(VL.begin(), VL.end());
547   }
548 }
549
550 int FuncSLP::getLastIndex(ArrayRef<Value *> VL) {
551   BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
552   assert(BB == getSameBlock(VL) && BlocksNumbers.count(BB) && "Invalid block");
553   BlockNumbering &BN = BlocksNumbers[BB];
554
555   int MaxIdx = BN.getIndex(BB->getFirstNonPHI());
556   for (unsigned i = 0, e = VL.size(); i < e; ++i)
557     MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
558   return MaxIdx;
559 }
560
561 Instruction *FuncSLP::getLastInstruction(ArrayRef<Value *> VL) {
562   BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
563   assert(BB == getSameBlock(VL) && BlocksNumbers.count(BB) && "Invalid block");
564   BlockNumbering &BN = BlocksNumbers[BB];
565
566   int MaxIdx = BN.getIndex(cast<Instruction>(VL[0]));
567   for (unsigned i = 1, e = VL.size(); i < e; ++i)
568     MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
569   return BN.getInstruction(MaxIdx);
570 }
571
572 Instruction *FuncSLP::getInstructionForIndex(unsigned Index, BasicBlock *BB) {
573   BlockNumbering &BN = BlocksNumbers[BB];
574   return BN.getInstruction(Index);
575 }
576
577 int FuncSLP::getFirstUserIndex(ArrayRef<Value *> VL) {
578   BasicBlock *BB = getSameBlock(VL);
579   assert(BB && "All instructions must come from the same block");
580   BlockNumbering &BN = BlocksNumbers[BB];
581
582   // Find the first user of the values.
583   int FirstUser = BN.getIndex(BB->getTerminator());
584   for (unsigned i = 0, e = VL.size(); i < e; ++i) {
585     for (Value::use_iterator U = VL[i]->use_begin(), UE = VL[i]->use_end();
586          U != UE; ++U) {
587       Instruction *Instr = dyn_cast<Instruction>(*U);
588
589       if (!Instr || Instr->getParent() != BB)
590         continue;
591
592       FirstUser = std::min(FirstUser, BN.getIndex(Instr));
593     }
594   }
595   return FirstUser;
596 }
597
598 int FuncSLP::getTreeCost_rec(ArrayRef<Value *> VL, unsigned Depth) {
599   Type *ScalarTy = VL[0]->getType();
600
601   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
602     ScalarTy = SI->getValueOperand()->getType();
603
604   /// Don't mess with vectors.
605   if (ScalarTy->isVectorTy())
606     return FuncSLP::MAX_COST;
607
608   if (allConstant(VL))
609     return 0;
610
611   VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
612
613   if (isSplat(VL))
614     return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
615
616   int GatherCost = getGatherCost(VecTy);
617   if (Depth == RecursionMaxDepth || needToGatherAny(VL))
618     return GatherCost;
619
620   BasicBlock *BB = getSameBlock(VL);
621   unsigned Opcode = getSameOpcode(VL);
622   assert(Opcode && BB && "Invalid Instruction Value");
623
624   // Check if it is safe to sink the loads or the stores.
625   if (Opcode == Instruction::Load || Opcode == Instruction::Store) {
626     int MaxIdx = getLastIndex(VL);
627     Instruction *Last = getInstructionForIndex(MaxIdx, BB);
628
629     for (unsigned i = 0, e = VL.size(); i < e; ++i) {
630       if (VL[i] == Last)
631         continue;
632       Value *Barrier = getSinkBarrier(cast<Instruction>(VL[i]), Last);
633       if (Barrier) {
634         DEBUG(dbgs() << "SLP: Can't sink " << *VL[i] << "\n down to " << *Last
635                      << "\n because of " << *Barrier << "\n");
636         return MAX_COST;
637       }
638     }
639   }
640
641   Instruction *VL0 = cast<Instruction>(VL[0]);
642   switch (Opcode) {
643   case Instruction::ExtractElement: {
644     if (CanReuseExtract(VL, VL.size(), VecTy))
645       return 0;
646     return getGatherCost(VecTy);
647   }
648   case Instruction::ZExt:
649   case Instruction::SExt:
650   case Instruction::FPToUI:
651   case Instruction::FPToSI:
652   case Instruction::FPExt:
653   case Instruction::PtrToInt:
654   case Instruction::IntToPtr:
655   case Instruction::SIToFP:
656   case Instruction::UIToFP:
657   case Instruction::Trunc:
658   case Instruction::FPTrunc:
659   case Instruction::BitCast: {
660     ValueList Operands;
661     Type *SrcTy = VL0->getOperand(0)->getType();
662     // Prepare the operand vector.
663     for (unsigned j = 0; j < VL.size(); ++j) {
664       Operands.push_back(cast<Instruction>(VL[j])->getOperand(0));
665       // Check that the casted type is the same for all users.
666       if (cast<Instruction>(VL[j])->getOperand(0)->getType() != SrcTy)
667         return getGatherCost(VecTy);
668     }
669
670     int Cost = getTreeCost_rec(Operands, Depth + 1);
671     if (Cost == FuncSLP::MAX_COST)
672       return Cost;
673
674     // Calculate the cost of this instruction.
675     int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(),
676                                                        VL0->getType(), SrcTy);
677
678     VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
679     int VecCost = TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy);
680     Cost += (VecCost - ScalarCost);
681
682     if (Cost > GatherCost) {
683       MustGather.insert(VL.begin(), VL.end());
684       return GatherCost;
685     }
686
687     return Cost;
688   }
689   case Instruction::FCmp:
690   case Instruction::ICmp: {
691     // Check that all of the compares have the same predicate.
692     CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
693     for (unsigned i = 1, e = VL.size(); i < e; ++i) {
694       CmpInst *Cmp = cast<CmpInst>(VL[i]);
695       if (Cmp->getPredicate() != P0)
696         return getGatherCost(VecTy);
697     }
698     // Fall through.
699   }
700   case Instruction::Select:
701   case Instruction::Add:
702   case Instruction::FAdd:
703   case Instruction::Sub:
704   case Instruction::FSub:
705   case Instruction::Mul:
706   case Instruction::FMul:
707   case Instruction::UDiv:
708   case Instruction::SDiv:
709   case Instruction::FDiv:
710   case Instruction::URem:
711   case Instruction::SRem:
712   case Instruction::FRem:
713   case Instruction::Shl:
714   case Instruction::LShr:
715   case Instruction::AShr:
716   case Instruction::And:
717   case Instruction::Or:
718   case Instruction::Xor: {
719     int TotalCost = 0;
720     // Calculate the cost of all of the operands.
721     for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
722       ValueList Operands;
723       // Prepare the operand vector.
724       for (unsigned j = 0; j < VL.size(); ++j)
725         Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
726
727       int Cost = getTreeCost_rec(Operands, Depth + 1);
728       if (Cost == MAX_COST)
729         return MAX_COST;
730       TotalCost += TotalCost;
731     }
732
733     // Calculate the cost of this instruction.
734     int ScalarCost = 0;
735     int VecCost = 0;
736     if (Opcode == Instruction::FCmp || Opcode == Instruction::ICmp ||
737         Opcode == Instruction::Select) {
738       VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
739       ScalarCost =
740           VecTy->getNumElements() *
741           TTI->getCmpSelInstrCost(Opcode, ScalarTy, Builder.getInt1Ty());
742       VecCost = TTI->getCmpSelInstrCost(Opcode, VecTy, MaskTy);
743     } else {
744       ScalarCost = VecTy->getNumElements() *
745                    TTI->getArithmeticInstrCost(Opcode, ScalarTy);
746       VecCost = TTI->getArithmeticInstrCost(Opcode, VecTy);
747     }
748     TotalCost += (VecCost - ScalarCost);
749
750     if (TotalCost > GatherCost) {
751       MustGather.insert(VL.begin(), VL.end());
752       return GatherCost;
753     }
754
755     return TotalCost;
756   }
757   case Instruction::Load: {
758     // If we are scalarize the loads, add the cost of forming the vector.
759     for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
760       if (!isConsecutiveAccess(VL[i], VL[i + 1]))
761         return getGatherCost(VecTy);
762
763     // Cost of wide load - cost of scalar loads.
764     int ScalarLdCost = VecTy->getNumElements() *
765                        TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
766     int VecLdCost = TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
767     int TotalCost = VecLdCost - ScalarLdCost;
768
769     if (TotalCost > GatherCost) {
770       MustGather.insert(VL.begin(), VL.end());
771       return GatherCost;
772     }
773
774     return TotalCost;
775   }
776   case Instruction::Store: {
777     // We know that we can merge the stores. Calculate the cost.
778     int ScalarStCost = VecTy->getNumElements() *
779                        TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
780     int VecStCost = TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
781     int StoreCost = VecStCost - ScalarStCost;
782
783     ValueList Operands;
784     for (unsigned j = 0; j < VL.size(); ++j) {
785       Operands.push_back(cast<Instruction>(VL[j])->getOperand(0));
786       MemBarrierIgnoreList.insert(VL[j]);
787     }
788
789     int Cost = getTreeCost_rec(Operands, Depth + 1);
790     if (Cost == MAX_COST)
791       return MAX_COST;
792
793     int TotalCost = StoreCost + Cost;
794     return TotalCost;
795   }
796   default:
797     // Unable to vectorize unknown instructions.
798     return getGatherCost(VecTy);
799   }
800 }
801
802 int FuncSLP::getTreeCost(ArrayRef<Value *> VL) {
803   // Get rid of the list of stores that were removed, and from the
804   // lists of instructions with multiple users.
805   MemBarrierIgnoreList.clear();
806   LaneMap.clear();
807   MultiUserVals.clear();
808   MustGather.clear();
809
810   if (!getSameBlock(VL))
811     return MAX_COST;
812
813   // Find the location of the last root.
814   int LastRootIndex = getLastIndex(VL);
815   int FirstUserIndex = getFirstUserIndex(VL);
816
817   // Don't vectorize if there are users of the tree roots inside the tree
818   // itself.
819   if (LastRootIndex > FirstUserIndex)
820     return MAX_COST;
821
822   // Scan the tree and find which value is used by which lane, and which values
823   // must be scalarized.
824   getTreeUses_rec(VL, 0);
825
826   // Check that instructions with multiple users can be vectorized. Mark unsafe
827   // instructions.
828   for (SetVector<Value *>::iterator it = MultiUserVals.begin(),
829                                     e = MultiUserVals.end();
830        it != e; ++it) {
831     // Check that all of the users of this instr are within the tree.
832     for (Value::use_iterator I = (*it)->use_begin(), E = (*it)->use_end();
833          I != E; ++I) {
834       if (LaneMap.find(*I) == LaneMap.end()) {
835         DEBUG(dbgs() << "SLP: Adding to MustExtract "
836                         "because of an out of tree usage.\n");
837         MustGather.insert(*it);
838         continue;
839       }
840     }
841   }
842
843   // Now calculate the cost of vectorizing the tree.
844   return getTreeCost_rec(VL, 0);
845 }
846 bool FuncSLP::vectorizeStoreChain(ArrayRef<Value *> Chain, int CostThreshold) {
847   unsigned ChainLen = Chain.size();
848   DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
849                << "\n");
850   Type *StoreTy = cast<StoreInst>(Chain[0])->getValueOperand()->getType();
851   unsigned Sz = DL->getTypeSizeInBits(StoreTy);
852   unsigned VF = MinVecRegSize / Sz;
853
854   if (!isPowerOf2_32(Sz) || VF < 2)
855     return false;
856
857   bool Changed = false;
858   // Look for profitable vectorizable trees at all offsets, starting at zero.
859   for (unsigned i = 0, e = ChainLen; i < e; ++i) {
860     if (i + VF > e)
861       break;
862     DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
863                  << "\n");
864     ArrayRef<Value *> Operands = Chain.slice(i, VF);
865
866     int Cost = getTreeCost(Operands);
867     if (Cost == FuncSLP::MAX_COST)
868       continue;
869     DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
870     if (Cost < CostThreshold) {
871       DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
872       vectorizeTree(Operands);
873
874       // Remove the scalar stores.
875       for (int j = 0, e = VF; j < e; ++j)
876         cast<Instruction>(Operands[j])->eraseFromParent();
877
878       // Move to the next bundle.
879       i += VF - 1;
880       Changed = true;
881     }
882   }
883
884   if (Changed || ChainLen > VF)
885     return Changed;
886
887   // Handle short chains. This helps us catch types such as <3 x float> that
888   // are smaller than vector size.
889   int Cost = getTreeCost(Chain);
890   if (Cost == FuncSLP::MAX_COST)
891     return false;
892   if (Cost < CostThreshold) {
893     DEBUG(dbgs() << "SLP: Found store chain cost = " << Cost
894                  << " for size = " << ChainLen << "\n");
895     vectorizeTree(Chain);
896
897     // Remove all of the scalar stores.
898     for (int i = 0, e = Chain.size(); i < e; ++i)
899       cast<Instruction>(Chain[i])->eraseFromParent();
900
901     return true;
902   }
903
904   return false;
905 }
906
907 bool FuncSLP::vectorizeStores(ArrayRef<StoreInst *> Stores, int costThreshold) {
908   SetVector<Value *> Heads, Tails;
909   SmallDenseMap<Value *, Value *> ConsecutiveChain;
910
911   // We may run into multiple chains that merge into a single chain. We mark the
912   // stores that we vectorized so that we don't visit the same store twice.
913   ValueSet VectorizedStores;
914   bool Changed = false;
915
916   // Do a quadratic search on all of the given stores and find
917   // all of the pairs of loads that follow each other.
918   for (unsigned i = 0, e = Stores.size(); i < e; ++i)
919     for (unsigned j = 0; j < e; ++j) {
920       if (i == j)
921         continue;
922
923       if (isConsecutiveAccess(Stores[i], Stores[j])) {
924         Tails.insert(Stores[j]);
925         Heads.insert(Stores[i]);
926         ConsecutiveChain[Stores[i]] = Stores[j];
927       }
928     }
929
930   // For stores that start but don't end a link in the chain:
931   for (SetVector<Value *>::iterator it = Heads.begin(), e = Heads.end();
932        it != e; ++it) {
933     if (Tails.count(*it))
934       continue;
935
936     // We found a store instr that starts a chain. Now follow the chain and try
937     // to vectorize it.
938     ValueList Operands;
939     Value *I = *it;
940     // Collect the chain into a list.
941     while (Tails.count(I) || Heads.count(I)) {
942       if (VectorizedStores.count(I))
943         break;
944       Operands.push_back(I);
945       // Move to the next value in the chain.
946       I = ConsecutiveChain[I];
947     }
948
949     bool Vectorized = vectorizeStoreChain(Operands, costThreshold);
950
951     // Mark the vectorized stores so that we don't vectorize them again.
952     if (Vectorized)
953       VectorizedStores.insert(Operands.begin(), Operands.end());
954     Changed |= Vectorized;
955   }
956
957   return Changed;
958 }
959
960 Value *FuncSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
961   Value *Vec = UndefValue::get(Ty);
962   // Generate the 'InsertElement' instruction.
963   for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
964     Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
965     if (Instruction *I = dyn_cast<Instruction>(Vec))
966       GatherSeq.insert(I);
967   }
968
969   return Vec;
970 }
971
972 Value *FuncSLP::vectorizeTree_rec(ArrayRef<Value *> VL) {
973   BuilderLocGuard Guard(Builder);
974
975   Type *ScalarTy = VL[0]->getType();
976   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
977     ScalarTy = SI->getValueOperand()->getType();
978   VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
979
980   if (needToGatherAny(VL))
981     return Gather(VL, VecTy);
982
983   if (VectorizedValues.count(VL[0])) {
984     DEBUG(dbgs() << "SLP: Diamond merged at depth.\n");
985     return VectorizedValues[VL[0]];
986   }
987
988   Instruction *VL0 = cast<Instruction>(VL[0]);
989   unsigned Opcode = VL0->getOpcode();
990   assert(Opcode == getSameOpcode(VL) && "Invalid opcode");
991
992   switch (Opcode) {
993   case Instruction::ExtractElement: {
994     if (CanReuseExtract(VL, VL.size(), VecTy))
995       return VL0->getOperand(0);
996     return Gather(VL, VecTy);
997   }
998   case Instruction::ZExt:
999   case Instruction::SExt:
1000   case Instruction::FPToUI:
1001   case Instruction::FPToSI:
1002   case Instruction::FPExt:
1003   case Instruction::PtrToInt:
1004   case Instruction::IntToPtr:
1005   case Instruction::SIToFP:
1006   case Instruction::UIToFP:
1007   case Instruction::Trunc:
1008   case Instruction::FPTrunc:
1009   case Instruction::BitCast: {
1010     ValueList INVL;
1011     for (int i = 0, e = VL.size(); i < e; ++i)
1012       INVL.push_back(cast<Instruction>(VL[i])->getOperand(0));
1013
1014     Builder.SetInsertPoint(getLastInstruction(VL));
1015     Value *InVec = vectorizeTree_rec(INVL);
1016     CastInst *CI = dyn_cast<CastInst>(VL0);
1017     Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
1018     VectorizedValues[VL0] = V;
1019     return V;
1020   }
1021   case Instruction::FCmp:
1022   case Instruction::ICmp: {
1023     // Check that all of the compares have the same predicate.
1024     CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
1025     for (unsigned i = 1, e = VL.size(); i < e; ++i) {
1026       CmpInst *Cmp = cast<CmpInst>(VL[i]);
1027       if (Cmp->getPredicate() != P0)
1028         return Gather(VL, VecTy);
1029     }
1030
1031     ValueList LHSV, RHSV;
1032     for (int i = 0, e = VL.size(); i < e; ++i) {
1033       LHSV.push_back(cast<Instruction>(VL[i])->getOperand(0));
1034       RHSV.push_back(cast<Instruction>(VL[i])->getOperand(1));
1035     }
1036
1037     Builder.SetInsertPoint(getLastInstruction(VL));
1038     Value *L = vectorizeTree_rec(LHSV);
1039     Value *R = vectorizeTree_rec(RHSV);
1040     Value *V;
1041
1042     if (Opcode == Instruction::FCmp)
1043       V = Builder.CreateFCmp(P0, L, R);
1044     else
1045       V = Builder.CreateICmp(P0, L, R);
1046
1047     VectorizedValues[VL0] = V;
1048     return V;
1049   }
1050   case Instruction::Select: {
1051     ValueList TrueVec, FalseVec, CondVec;
1052     for (int i = 0, e = VL.size(); i < e; ++i) {
1053       CondVec.push_back(cast<Instruction>(VL[i])->getOperand(0));
1054       TrueVec.push_back(cast<Instruction>(VL[i])->getOperand(1));
1055       FalseVec.push_back(cast<Instruction>(VL[i])->getOperand(2));
1056     }
1057
1058     Builder.SetInsertPoint(getLastInstruction(VL));
1059     Value *True = vectorizeTree_rec(TrueVec);
1060     Value *False = vectorizeTree_rec(FalseVec);
1061     Value *Cond = vectorizeTree_rec(CondVec);
1062     Value *V = Builder.CreateSelect(Cond, True, False);
1063     VectorizedValues[VL0] = V;
1064     return V;
1065   }
1066   case Instruction::Add:
1067   case Instruction::FAdd:
1068   case Instruction::Sub:
1069   case Instruction::FSub:
1070   case Instruction::Mul:
1071   case Instruction::FMul:
1072   case Instruction::UDiv:
1073   case Instruction::SDiv:
1074   case Instruction::FDiv:
1075   case Instruction::URem:
1076   case Instruction::SRem:
1077   case Instruction::FRem:
1078   case Instruction::Shl:
1079   case Instruction::LShr:
1080   case Instruction::AShr:
1081   case Instruction::And:
1082   case Instruction::Or:
1083   case Instruction::Xor: {
1084     ValueList LHSVL, RHSVL;
1085     for (int i = 0, e = VL.size(); i < e; ++i) {
1086       LHSVL.push_back(cast<Instruction>(VL[i])->getOperand(0));
1087       RHSVL.push_back(cast<Instruction>(VL[i])->getOperand(1));
1088     }
1089
1090     Builder.SetInsertPoint(getLastInstruction(VL));
1091     Value *LHS = vectorizeTree_rec(LHSVL);
1092     Value *RHS = vectorizeTree_rec(RHSVL);
1093
1094     if (LHS == RHS) {
1095       assert((VL0->getOperand(0) == VL0->getOperand(1)) && "Invalid order");
1096     }
1097
1098     BinaryOperator *BinOp = cast<BinaryOperator>(VL0);
1099     Value *V = Builder.CreateBinOp(BinOp->getOpcode(), LHS, RHS);
1100     VectorizedValues[VL0] = V;
1101     return V;
1102   }
1103   case Instruction::Load: {
1104     // Check if all of the loads are consecutive.
1105     for (unsigned i = 1, e = VL.size(); i < e; ++i)
1106       if (!isConsecutiveAccess(VL[i - 1], VL[i]))
1107         return Gather(VL, VecTy);
1108
1109     // Loads are inserted at the head of the tree because we don't want to
1110     // sink them all the way down past store instructions.
1111     Builder.SetInsertPoint(getLastInstruction(VL));
1112     LoadInst *LI = cast<LoadInst>(VL0);
1113     Value *VecPtr =
1114         Builder.CreateBitCast(LI->getPointerOperand(), VecTy->getPointerTo());
1115     unsigned Alignment = LI->getAlignment();
1116     LI = Builder.CreateLoad(VecPtr);
1117     LI->setAlignment(Alignment);
1118
1119     VectorizedValues[VL0] = LI;
1120     return LI;
1121   }
1122   case Instruction::Store: {
1123     StoreInst *SI = cast<StoreInst>(VL0);
1124     unsigned Alignment = SI->getAlignment();
1125
1126     ValueList ValueOp;
1127     for (int i = 0, e = VL.size(); i < e; ++i)
1128       ValueOp.push_back(cast<StoreInst>(VL[i])->getValueOperand());
1129
1130     Value *VecValue = vectorizeTree_rec(ValueOp);
1131
1132     Builder.SetInsertPoint(getLastInstruction(VL));
1133     Value *VecPtr =
1134         Builder.CreateBitCast(SI->getPointerOperand(), VecTy->getPointerTo());
1135     Builder.CreateStore(VecValue, VecPtr)->setAlignment(Alignment);
1136     return 0;
1137   }
1138   default:
1139     return Gather(VL, VecTy);
1140   }
1141 }
1142
1143 Value *FuncSLP::vectorizeTree(ArrayRef<Value *> VL) {
1144   Builder.SetInsertPoint(getLastInstruction(VL));
1145   Value *V = vectorizeTree_rec(VL);
1146
1147   // We moved some instructions around. We have to number them again
1148   // before we can do any analysis.
1149   for (Function::iterator it = F->begin(), e = F->end(); it != e; ++it)
1150     BlocksNumbers[it].forget();
1151   // Clear the state.
1152   MustGather.clear();
1153   VectorizedValues.clear();
1154   MemBarrierIgnoreList.clear();
1155   return V;
1156 }
1157
1158 Value *FuncSLP::vectorizeArith(ArrayRef<Value *> Operands) {
1159   Value *Vec = vectorizeTree(Operands);
1160   // After vectorizing the operands we need to generate extractelement
1161   // instructions and replace all of the uses of the scalar values with
1162   // the values that we extracted from the vectorized tree.
1163   for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
1164     Value *S = Builder.CreateExtractElement(Vec, Builder.getInt32(i));
1165     Operands[i]->replaceAllUsesWith(S);
1166   }
1167
1168   return Vec;
1169 }
1170
1171 void FuncSLP::optimizeGatherSequence() {
1172   // LICM InsertElementInst sequences.
1173   for (SetVector<Instruction *>::iterator it = GatherSeq.begin(),
1174        e = GatherSeq.end(); it != e; ++it) {
1175     InsertElementInst *Insert = dyn_cast<InsertElementInst>(*it);
1176
1177     if (!Insert)
1178       continue;
1179
1180     // Check if this block is inside a loop.
1181     Loop *L = LI->getLoopFor(Insert->getParent());
1182     if (!L)
1183       continue;
1184
1185     // Check if it has a preheader.
1186     BasicBlock *PreHeader = L->getLoopPreheader();
1187     if (!PreHeader)
1188       return;
1189
1190     // If the vector or the element that we insert into it are
1191     // instructions that are defined in this basic block then we can't
1192     // hoist this instruction.
1193     Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
1194     Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
1195     if (CurrVec && L->contains(CurrVec))
1196       continue;
1197     if (NewElem && L->contains(NewElem))
1198       continue;
1199
1200     // We can hoist this instruction. Move it to the pre-header.
1201     Insert->moveBefore(PreHeader->getTerminator());
1202   }
1203
1204   // Perform O(N^2) search over the gather sequences and merge identical
1205   // instructions. TODO: We can further optimize this scan if we split the
1206   // instructions into different buckets based on the insert lane.
1207   SmallPtrSet<Instruction*, 16> Visited;
1208   ReversePostOrderTraversal<Function*> RPOT(F);
1209   for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
1210        E = RPOT.end(); I != E; ++I) {
1211     BasicBlock *BB = *I;
1212     // For all instructions in the function:
1213     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1214       InsertElementInst *Insert = dyn_cast<InsertElementInst>(it);
1215       if (!Insert || !GatherSeq.count(Insert))
1216         continue;
1217
1218      // Check if we can replace this instruction with any of the
1219      // visited instructions.
1220       for (SmallPtrSet<Instruction*, 16>::iterator v = Visited.begin(),
1221            ve = Visited.end(); v != ve; ++v) {
1222         if (Insert->isIdenticalTo(*v) &&
1223           DT->dominates((*v)->getParent(), Insert->getParent())) {
1224           Insert->replaceAllUsesWith(*v);
1225           break;
1226         }
1227       }
1228       Visited.insert(Insert);
1229     }
1230   }
1231 }
1232
1233 /// The SLPVectorizer Pass.
1234 struct SLPVectorizer : public FunctionPass {
1235   typedef SmallVector<StoreInst *, 8> StoreList;
1236   typedef MapVector<Value *, StoreList> StoreListMap;
1237
1238   /// Pass identification, replacement for typeid
1239   static char ID;
1240
1241   explicit SLPVectorizer() : FunctionPass(ID) {
1242     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
1243   }
1244
1245   ScalarEvolution *SE;
1246   DataLayout *DL;
1247   TargetTransformInfo *TTI;
1248   AliasAnalysis *AA;
1249   LoopInfo *LI;
1250   DominatorTree *DT;
1251
1252   virtual bool runOnFunction(Function &F) {
1253     SE = &getAnalysis<ScalarEvolution>();
1254     DL = getAnalysisIfAvailable<DataLayout>();
1255     TTI = &getAnalysis<TargetTransformInfo>();
1256     AA = &getAnalysis<AliasAnalysis>();
1257     LI = &getAnalysis<LoopInfo>();
1258     DT = &getAnalysis<DominatorTree>();
1259
1260     StoreRefs.clear();
1261     bool Changed = false;
1262
1263     // Must have DataLayout. We can't require it because some tests run w/o
1264     // triple.
1265     if (!DL)
1266       return false;
1267
1268     DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
1269
1270     // Use the bollom up slp vectorizer to construct chains that start with
1271     // he store instructions.
1272     FuncSLP R(&F, SE, DL, TTI, AA, LI, DT);
1273
1274     for (Function::iterator it = F.begin(), e = F.end(); it != e; ++it) {
1275       BasicBlock *BB = it;
1276
1277       // Vectorize trees that end at reductions.
1278       Changed |= vectorizeChainsInBlock(BB, R);
1279
1280       // Vectorize trees that end at stores.
1281       if (unsigned count = collectStores(BB, R)) {
1282         (void)count;
1283         DEBUG(dbgs() << "SLP: Found " << count << " stores to vectorize.\n");
1284         Changed |= vectorizeStoreChains(R);
1285       }
1286     }
1287
1288     if (Changed) {
1289       R.optimizeGatherSequence();
1290       DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
1291       DEBUG(verifyFunction(F));
1292     }
1293     return Changed;
1294   }
1295
1296   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1297     FunctionPass::getAnalysisUsage(AU);
1298     AU.addRequired<ScalarEvolution>();
1299     AU.addRequired<AliasAnalysis>();
1300     AU.addRequired<TargetTransformInfo>();
1301     AU.addRequired<LoopInfo>();
1302     AU.addRequired<DominatorTree>();
1303   }
1304
1305 private:
1306
1307   /// \brief Collect memory references and sort them according to their base
1308   /// object. We sort the stores to their base objects to reduce the cost of the
1309   /// quadratic search on the stores. TODO: We can further reduce this cost
1310   /// if we flush the chain creation every time we run into a memory barrier.
1311   unsigned collectStores(BasicBlock *BB, FuncSLP &R);
1312
1313   /// \brief Try to vectorize a chain that starts at two arithmetic instrs.
1314   bool tryToVectorizePair(Value *A, Value *B, FuncSLP &R);
1315
1316   /// \brief Try to vectorize a list of operands. If \p NeedExtracts is true
1317   /// then we calculate the cost of extracting the scalars from the vector.
1318   /// \returns true if a value was vectorized.
1319   bool tryToVectorizeList(ArrayRef<Value *> VL, FuncSLP &R, bool NeedExtracts);
1320
1321   /// \brief Try to vectorize a chain that may start at the operands of \V;
1322   bool tryToVectorize(BinaryOperator *V, FuncSLP &R);
1323
1324   /// \brief Vectorize the stores that were collected in StoreRefs.
1325   bool vectorizeStoreChains(FuncSLP &R);
1326
1327   /// \brief Scan the basic block and look for patterns that are likely to start
1328   /// a vectorization chain.
1329   bool vectorizeChainsInBlock(BasicBlock *BB, FuncSLP &R);
1330
1331 private:
1332   StoreListMap StoreRefs;
1333 };
1334
1335 unsigned SLPVectorizer::collectStores(BasicBlock *BB, FuncSLP &R) {
1336   unsigned count = 0;
1337   StoreRefs.clear();
1338   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1339     StoreInst *SI = dyn_cast<StoreInst>(it);
1340     if (!SI)
1341       continue;
1342
1343     // Check that the pointer points to scalars.
1344     Type *Ty = SI->getValueOperand()->getType();
1345     if (Ty->isAggregateType() || Ty->isVectorTy())
1346       return 0;
1347
1348     // Find the base of the GEP.
1349     Value *Ptr = SI->getPointerOperand();
1350     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
1351       Ptr = GEP->getPointerOperand();
1352
1353     // Save the store locations.
1354     StoreRefs[Ptr].push_back(SI);
1355     count++;
1356   }
1357   return count;
1358 }
1359
1360 bool SLPVectorizer::tryToVectorizePair(Value *A, Value *B, FuncSLP &R) {
1361   if (!A || !B)
1362     return false;
1363   Value *VL[] = { A, B };
1364   return tryToVectorizeList(VL, R, true);
1365 }
1366
1367 bool SLPVectorizer::tryToVectorizeList(ArrayRef<Value *> VL, FuncSLP &R,
1368                                        bool NeedExtracts) {
1369   if (VL.size() < 2)
1370     return false;
1371
1372   DEBUG(dbgs() << "SLP: Vectorizing a list of length = " << VL.size() << ".\n");
1373
1374   // Check that all of the parts are scalar instructions of the same type.
1375   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
1376   if (!I0)
1377     return 0;
1378
1379   unsigned Opcode0 = I0->getOpcode();
1380
1381   for (int i = 0, e = VL.size(); i < e; ++i) {
1382     Type *Ty = VL[i]->getType();
1383     if (Ty->isAggregateType() || Ty->isVectorTy())
1384       return 0;
1385     Instruction *Inst = dyn_cast<Instruction>(VL[i]);
1386     if (!Inst || Inst->getOpcode() != Opcode0)
1387       return 0;
1388   }
1389
1390   int Cost = R.getTreeCost(VL);
1391   if (Cost == FuncSLP::MAX_COST)
1392     return false;
1393
1394   int ExtrCost = NeedExtracts ? R.getGatherCost(VL) : 0;
1395   DEBUG(dbgs() << "SLP: Cost of pair:" << Cost
1396                << " Cost of extract:" << ExtrCost << ".\n");
1397   if ((Cost + ExtrCost) >= -SLPCostThreshold)
1398     return false;
1399   DEBUG(dbgs() << "SLP: Vectorizing pair.\n");
1400   R.vectorizeArith(VL);
1401   return true;
1402 }
1403
1404 bool SLPVectorizer::tryToVectorize(BinaryOperator *V, FuncSLP &R) {
1405   if (!V)
1406     return false;
1407
1408   // Try to vectorize V.
1409   if (tryToVectorizePair(V->getOperand(0), V->getOperand(1), R))
1410     return true;
1411
1412   BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0));
1413   BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1));
1414   // Try to skip B.
1415   if (B && B->hasOneUse()) {
1416     BinaryOperator *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
1417     BinaryOperator *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
1418     if (tryToVectorizePair(A, B0, R)) {
1419       B->moveBefore(V);
1420       return true;
1421     }
1422     if (tryToVectorizePair(A, B1, R)) {
1423       B->moveBefore(V);
1424       return true;
1425     }
1426   }
1427
1428   // Try to skip A.
1429   if (A && A->hasOneUse()) {
1430     BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
1431     BinaryOperator *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
1432     if (tryToVectorizePair(A0, B, R)) {
1433       A->moveBefore(V);
1434       return true;
1435     }
1436     if (tryToVectorizePair(A1, B, R)) {
1437       A->moveBefore(V);
1438       return true;
1439     }
1440   }
1441   return 0;
1442 }
1443
1444 bool SLPVectorizer::vectorizeChainsInBlock(BasicBlock *BB, FuncSLP &R) {
1445   bool Changed = false;
1446   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1447     if (isa<DbgInfoIntrinsic>(it))
1448       continue;
1449
1450     // Try to vectorize reductions that use PHINodes.
1451     if (PHINode *P = dyn_cast<PHINode>(it)) {
1452       // Check that the PHI is a reduction PHI.
1453       if (P->getNumIncomingValues() != 2)
1454         return Changed;
1455       Value *Rdx =
1456           (P->getIncomingBlock(0) == BB
1457                ? (P->getIncomingValue(0))
1458                : (P->getIncomingBlock(1) == BB ? P->getIncomingValue(1) : 0));
1459       // Check if this is a Binary Operator.
1460       BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx);
1461       if (!BI)
1462         continue;
1463
1464       Value *Inst = BI->getOperand(0);
1465       if (Inst == P)
1466         Inst = BI->getOperand(1);
1467
1468       Changed |= tryToVectorize(dyn_cast<BinaryOperator>(Inst), R);
1469       continue;
1470     }
1471
1472     // Try to vectorize trees that start at compare instructions.
1473     if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
1474       if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) {
1475         Changed |= true;
1476         continue;
1477       }
1478       for (int i = 0; i < 2; ++i)
1479         if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i)))
1480           Changed |=
1481               tryToVectorizePair(BI->getOperand(0), BI->getOperand(1), R);
1482       continue;
1483     }
1484   }
1485
1486   // Scan the PHINodes in our successors in search for pairing hints.
1487   for (succ_iterator it = succ_begin(BB), e = succ_end(BB); it != e; ++it) {
1488     BasicBlock *Succ = *it;
1489     SmallVector<Value *, 4> Incoming;
1490
1491     // Collect the incoming values from the PHIs.
1492     for (BasicBlock::iterator instr = Succ->begin(), ie = Succ->end();
1493          instr != ie; ++instr) {
1494       PHINode *P = dyn_cast<PHINode>(instr);
1495
1496       if (!P)
1497         break;
1498
1499       Value *V = P->getIncomingValueForBlock(BB);
1500       if (Instruction *I = dyn_cast<Instruction>(V))
1501         if (I->getParent() == BB)
1502           Incoming.push_back(I);
1503     }
1504
1505     if (Incoming.size() > 1)
1506       Changed |= tryToVectorizeList(Incoming, R, true);
1507   }
1508
1509   return Changed;
1510 }
1511
1512 bool SLPVectorizer::vectorizeStoreChains(FuncSLP &R) {
1513   bool Changed = false;
1514   // Attempt to sort and vectorize each of the store-groups.
1515   for (StoreListMap::iterator it = StoreRefs.begin(), e = StoreRefs.end();
1516        it != e; ++it) {
1517     if (it->second.size() < 2)
1518       continue;
1519
1520     DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
1521                  << it->second.size() << ".\n");
1522
1523     Changed |= R.vectorizeStores(it->second, -SLPCostThreshold);
1524   }
1525   return Changed;
1526 }
1527
1528 } // end anonymous namespace
1529
1530 char SLPVectorizer::ID = 0;
1531 static const char lv_name[] = "SLP Vectorizer";
1532 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
1533 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
1534 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
1535 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1536 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
1537 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
1538
1539 namespace llvm {
1540 Pass *createSLPVectorizerPass() { return new SLPVectorizer(); }
1541 }