SLP Vectorizer: Add support for trees with external users.
[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   void forgetNumbering() {
225     for (Function::iterator it = F->begin(), e = F->end(); it != e; ++it)
226       BlocksNumbers[it].forget();
227   }
228
229   /// -- Vectorization State --
230
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;
237
238   /// Maps between the first scalar to the vector. This map must be reset
239   /// between runs.
240   DenseMap<Value *, Value *> VectorizedValues;
241
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.
245   ValueSet MustGather;
246
247   /// Contains PHINodes that are being processed. We use this data structure
248   /// to stop cycles in the graph.
249   ValueSet VisitedPHIs;
250
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.
254   struct UseInfo{
255     UseInfo(Instruction *VL0, int I) :
256       Leader(VL0), LastIndex(I) {}
257     UseInfo() : Leader(0), LastIndex(0) {}
258     /// The first element in the bundle.
259     Instruction *Leader;
260     /// The insertion index.
261     int LastIndex;
262   };
263   MapVector<Instruction*, UseInfo> MultiUserVals;
264   SetVector<Instruction*> ExtractedLane;
265
266   /// Holds all of the instructions that we gathered.
267   SetVector<Instruction *> GatherSeq;
268
269   /// Numbers instructions in different blocks.
270   std::map<BasicBlock *, BlockNumbering> BlocksNumbers;
271
272   // Analysis and block reference.
273   Function *F;
274   ScalarEvolution *SE;
275   DataLayout *DL;
276   TargetTransformInfo *TTI;
277   AliasAnalysis *AA;
278   LoopInfo *LI;
279   DominatorTree *DT;
280   /// Instruction builder to construct the vectorized tree.
281   IRBuilder<> Builder;
282 };
283
284 int FuncSLP::getGatherCost(Type *Ty) {
285   int Cost = 0;
286   for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
287     Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
288   return Cost;
289 }
290
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);
299 }
300
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();
307 }
308
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();
314   return 0;
315 }
316
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();
322   return -1;
323 }
324
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);
330
331   // Check that the address spaces match and that the pointers are valid.
332   if (!PtrA || !PtrB || (ASA != ASB))
333     return false;
334
335   // Check that A and B are of the same type.
336   if (PtrA->getType() != PtrB->getType())
337     return false;
338
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);
344
345   // Non constant distance.
346   if (!ConstOffSCEV)
347     return false;
348
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);
355 }
356
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))
365       continue;
366     if (Src->mayWriteToMemory()) /* Write */ {
367       if (!I->mayReadOrWriteMemory())
368         continue;
369     } else /* Read */ {
370       if (!I->mayWriteToMemory())
371         continue;
372     }
373     AliasAnalysis::Location A = getLocation(&*I);
374     AliasAnalysis::Location B = getLocation(Src);
375
376     if (!A.Ptr || !B.Ptr || AA->alias(A, B))
377       return I;
378   }
379   return 0;
380 }
381
382 static BasicBlock *getSameBlock(ArrayRef<Value *> VL) {
383   BasicBlock *BB = 0;
384   for (int i = 0, e = VL.size(); i < e; i++) {
385     Instruction *I = dyn_cast<Instruction>(VL[i]);
386     if (!I)
387       return 0;
388
389     if (!BB) {
390       BB = I->getParent();
391       continue;
392     }
393
394     if (BB != I->getParent())
395       return 0;
396   }
397   return BB;
398 }
399
400 static bool allConstant(ArrayRef<Value *> VL) {
401   for (unsigned i = 0, e = VL.size(); i < e; ++i)
402     if (!isa<Constant>(VL[i]))
403       return false;
404   return true;
405 }
406
407 static bool isSplat(ArrayRef<Value *> VL) {
408   for (unsigned i = 1, e = VL.size(); i < e; ++i)
409     if (VL[i] != VL[0])
410       return false;
411   return true;
412 }
413
414 static unsigned getSameOpcode(ArrayRef<Value *> VL) {
415   unsigned Opcode = 0;
416   for (int i = 0, e = VL.size(); i < e; i++) {
417     if (Instruction *I = dyn_cast<Instruction>(VL[i])) {
418       if (!Opcode) {
419         Opcode = I->getOpcode();
420         continue;
421       }
422       if (Opcode != I->getOpcode())
423         return 0;
424     }
425   }
426   return Opcode;
427 }
428
429 static bool CanReuseExtract(ArrayRef<Value *> VL, unsigned VF,
430                             VectorType *VecTy) {
431   assert(Instruction::ExtractElement == getSameOpcode(VL) && "Invalid opcode");
432   // Check if all of the extracts come from the same vector and from the
433   // correct offset.
434   Value *VL0 = VL[0];
435   ExtractElementInst *E0 = cast<ExtractElementInst>(VL0);
436   Value *Vec = E0->getOperand(0);
437
438   // We have to extract from the same vector type.
439   if (Vec->getType() != VecTy)
440     return false;
441
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())
445     return false;
446
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));
450
451     if (!CI || CI->getZExtValue() != i || E->getOperand(0) != Vec)
452       return false;
453   }
454
455   return true;
456 }
457
458 void FuncSLP::getTreeUses_rec(ArrayRef<Value *> VL, unsigned Depth) {
459   if (Depth == RecursionMaxDepth)
460     return MustGather.insert(VL.begin(), VL.end());
461
462   // Don't handle vectors.
463   if (VL[0]->getType()->isVectorTy())
464     return;
465
466   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
467     if (SI->getValueOperand()->getType()->isVectorTy())
468       return;
469
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());
473
474   // Stop the scan at unknown IR.
475   Instruction *VL0 = dyn_cast<Instruction>(VL[0]);
476   assert(VL0 && "Invalid instruction");
477
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();
485            U != UE; ++U) {
486         // Don't count self uses.
487         if (*U == PN)
488           continue;
489         NumUses++;
490       }
491       if (NumUses > 1) {
492         DEBUG(dbgs() << "SLP: Adding PHI to MultiUserVals "
493               "because it has " << NumUses << " users:" << *PN << " \n");
494         UseInfo UI(VL0, 0);
495         MultiUserVals[PN] = UI;
496       }
497       continue;
498     }
499
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;
509     }
510   }
511
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());
517     }
518     // Make this instruction as 'seen' and remember the lane.
519     LaneMap[VL[i]] = i;
520   }
521
522   unsigned Opcode = getSameOpcode(VL);
523   if (!Opcode)
524     return MustGather.insert(VL.begin(), VL.end());
525
526   switch (Opcode) {
527   case Instruction::PHI: {
528     PHINode *PH = dyn_cast<PHINode>(VL0);
529
530     // Stop self cycles.
531     if (VisitedPHIs.count(PH))
532         return;
533
534     VisitedPHIs.insert(PH);
535     for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
536       ValueList Operands;
537       // Prepare the operand vector.
538       for (unsigned j = 0; j < VL.size(); ++j)
539         Operands.push_back(cast<PHINode>(VL[j])->getIncomingValue(i));
540
541       getTreeUses_rec(Operands, Depth + 1);
542     }
543     return;
544   }
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))
549       return;
550     // Fall through.
551   }
552   case Instruction::Load:
553     return;
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) {
588       ValueList Operands;
589       // Prepare the operand vector.
590       for (unsigned j = 0; j < VL.size(); ++j)
591         Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
592
593       getTreeUses_rec(Operands, Depth + 1);
594     }
595     return;
596   }
597   case Instruction::Store: {
598     ValueList Operands;
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);
602     return;
603   }
604   default:
605     return MustGather.insert(VL.begin(), VL.end());
606   }
607 }
608
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];
613
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])));
617   return MaxIdx;
618 }
619
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];
624
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);
629 }
630
631 Instruction *FuncSLP::getInstructionForIndex(unsigned Index, BasicBlock *BB) {
632   BlockNumbering &BN = BlocksNumbers[BB];
633   return BN.getInstruction(Index);
634 }
635
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];
640
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();
645          U != UE; ++U) {
646       Instruction *Instr = dyn_cast<Instruction>(*U);
647
648       if (!Instr || Instr->getParent() != BB)
649         continue;
650
651       FirstUser = std::min(FirstUser, BN.getIndex(Instr));
652     }
653   }
654   return FirstUser;
655 }
656
657 int FuncSLP::getTreeCost_rec(ArrayRef<Value *> VL, unsigned Depth) {
658   Type *ScalarTy = VL[0]->getType();
659
660   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
661     ScalarTy = SI->getValueOperand()->getType();
662
663   /// Don't mess with vectors.
664   if (ScalarTy->isVectorTy())
665     return FuncSLP::MAX_COST;
666
667   if (allConstant(VL))
668     return 0;
669
670   VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
671
672   if (isSplat(VL))
673     return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
674
675   int GatherCost = getGatherCost(VecTy);
676   if (Depth == RecursionMaxDepth || needToGatherAny(VL))
677     return GatherCost;
678
679   BasicBlock *BB = getSameBlock(VL);
680   unsigned Opcode = getSameOpcode(VL);
681   assert(Opcode && BB && "Invalid Instruction Value");
682
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);
687
688     for (unsigned i = 0, e = VL.size(); i < e; ++i) {
689       if (VL[i] == Last)
690         continue;
691       Value *Barrier = getSinkBarrier(cast<Instruction>(VL[i]), Last);
692       if (Barrier) {
693         DEBUG(dbgs() << "SLP: Can't sink " << *VL[i] << "\n down to " << *Last
694                      << "\n because of " << *Barrier << "\n");
695         return MAX_COST;
696       }
697     }
698   }
699
700
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);
707
708   Instruction *VL0 = cast<Instruction>(VL[0]);
709   switch (Opcode) {
710   case Instruction::PHI: {
711     PHINode *PH = dyn_cast<PHINode>(VL0);
712
713     // Stop self cycles.
714     if (VisitedPHIs.count(PH))
715         return 0;
716
717     VisitedPHIs.insert(PH);
718     int TotalCost = 0;
719     // Calculate the cost of all of the operands.
720     for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {      
721       ValueList Operands;
722       // Prepare the operand vector.
723       for (unsigned j = 0; j < VL.size(); ++j)
724         Operands.push_back(cast<PHINode>(VL[j])->getIncomingValue(i));
725
726       int Cost = getTreeCost_rec(Operands, Depth + 1);
727       if (Cost == MAX_COST)
728         return MAX_COST;
729       TotalCost += TotalCost;
730     }
731
732     if (TotalCost > GatherCost) {
733       MustGather.insert(VL.begin(), VL.end());
734       return GatherCost;
735     }
736
737     return TotalCost + ExternalUserExtractCost;
738   }
739   case Instruction::ExtractElement: {
740     if (CanReuseExtract(VL, VL.size(), VecTy))
741       return 0;
742     return getGatherCost(VecTy);
743   }
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: {
756     ValueList Operands;
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);
764     }
765
766     int Cost = getTreeCost_rec(Operands, Depth + 1);
767     if (Cost == MAX_COST)
768       return MAX_COST;
769
770     // Calculate the cost of this instruction.
771     int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(),
772                                                        VL0->getType(), SrcTy);
773
774     VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
775     int VecCost = TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy);
776     Cost += (VecCost - ScalarCost);
777
778     if (Cost > GatherCost) {
779       MustGather.insert(VL.begin(), VL.end());
780       return GatherCost;
781     }
782
783     return Cost + ExternalUserExtractCost;
784   }
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);
793     }
794     // Fall through.
795   }
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: {
815     int TotalCost = 0;
816     // Calculate the cost of all of the operands.
817     for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
818       ValueList Operands;
819       // Prepare the operand vector.
820       for (unsigned j = 0; j < VL.size(); ++j)
821         Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
822
823       int Cost = getTreeCost_rec(Operands, Depth + 1);
824       if (Cost == MAX_COST)
825         return MAX_COST;
826       TotalCost += Cost;
827     }
828
829     // Calculate the cost of this instruction.
830     int ScalarCost = 0;
831     int VecCost = 0;
832     if (Opcode == Instruction::FCmp || Opcode == Instruction::ICmp ||
833         Opcode == Instruction::Select) {
834       VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
835       ScalarCost =
836           VecTy->getNumElements() *
837           TTI->getCmpSelInstrCost(Opcode, ScalarTy, Builder.getInt1Ty());
838       VecCost = TTI->getCmpSelInstrCost(Opcode, VecTy, MaskTy);
839     } else {
840       ScalarCost = VecTy->getNumElements() *
841                    TTI->getArithmeticInstrCost(Opcode, ScalarTy);
842       VecCost = TTI->getArithmeticInstrCost(Opcode, VecTy);
843     }
844     TotalCost += (VecCost - ScalarCost);
845
846     if (TotalCost > GatherCost) {
847       MustGather.insert(VL.begin(), VL.end());
848       return GatherCost;
849     }
850
851     return TotalCost + ExternalUserExtractCost;
852   }
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);
858
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;
864
865     if (TotalCost > GatherCost) {
866       MustGather.insert(VL.begin(), VL.end());
867       return GatherCost;
868     }
869
870     return TotalCost + ExternalUserExtractCost;
871   }
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;
878
879     ValueList Operands;
880     for (unsigned j = 0; j < VL.size(); ++j) {
881       Operands.push_back(cast<Instruction>(VL[j])->getOperand(0));
882       MemBarrierIgnoreList.insert(VL[j]);
883     }
884
885     int Cost = getTreeCost_rec(Operands, Depth + 1);
886     if (Cost == MAX_COST)
887       return MAX_COST;
888
889     int TotalCost = StoreCost + Cost;
890     return TotalCost + ExternalUserExtractCost;
891   }
892   default:
893     // Unable to vectorize unknown instructions.
894     return getGatherCost(VecTy);
895   }
896 }
897
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();
902   LaneMap.clear();
903   MultiUserVals.clear();
904   ExtractedLane.clear();
905   MustGather.clear();
906   VisitedPHIs.clear();
907
908   if (!getSameBlock(VL))
909     return MAX_COST;
910
911   // Find the location of the last root.
912   int LastRootIndex = getLastIndex(VL);
913   int FirstUserIndex = getFirstUserIndex(VL);
914
915   // Don't vectorize if there are users of the tree roots inside the tree
916   // itself.
917   if (LastRootIndex > FirstUserIndex)
918     return MAX_COST;
919
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);
923
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;
929
930     if (MustGather.count(Scalar))
931       continue;
932
933     assert(LaneMap.count(Scalar) && "Unknown scalar");
934     int ScalarLane = LaneMap[Scalar];
935
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);
947           break;
948         }
949         continue;
950       }
951
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);
963           break;
964         }
965       }
966       // We have an external user.
967       ExternalUse = true;
968     }
969
970     if (ExternalUse) {
971       // Items that are left in MultiUserVals are to be extracted.
972       // ExtractLane is used for the lookup.
973       ExtractedLane.insert(Scalar);
974     }
975
976   }
977
978   // Now calculate the cost of vectorizing the tree.
979   return getTreeCost_rec(VL, 0);
980 }
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
984                << "\n");
985   Type *StoreTy = cast<StoreInst>(Chain[0])->getValueOperand()->getType();
986   unsigned Sz = DL->getTypeSizeInBits(StoreTy);
987   unsigned VF = MinVecRegSize / Sz;
988
989   if (!isPowerOf2_32(Sz) || VF < 2)
990     return false;
991
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) {
995     if (i + VF > e)
996       break;
997     DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
998                  << "\n");
999     ArrayRef<Value *> Operands = Chain.slice(i, VF);
1000
1001     int Cost = getTreeCost(Operands);
1002     if (Cost == FuncSLP::MAX_COST)
1003       continue;
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);
1008
1009       // Remove the scalar stores.
1010       for (int j = 0, e = VF; j < e; ++j)
1011         cast<Instruction>(Operands[j])->eraseFromParent();
1012
1013       // Move to the next bundle.
1014       i += VF - 1;
1015       Changed = true;
1016     }
1017   }
1018
1019   if (Changed || ChainLen > VF)
1020     return Changed;
1021
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)
1026     return false;
1027   if (Cost < CostThreshold) {
1028     DEBUG(dbgs() << "SLP: Found store chain cost = " << Cost
1029                  << " for size = " << ChainLen << "\n");
1030     vectorizeTree(Chain);
1031
1032     // Remove all of the scalar stores.
1033     for (int i = 0, e = Chain.size(); i < e; ++i)
1034       cast<Instruction>(Chain[i])->eraseFromParent();
1035
1036     return true;
1037   }
1038
1039   return false;
1040 }
1041
1042 bool FuncSLP::vectorizeStores(ArrayRef<StoreInst *> Stores, int costThreshold) {
1043   SetVector<Value *> Heads, Tails;
1044   SmallDenseMap<Value *, Value *> ConsecutiveChain;
1045
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;
1050
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) {
1055       if (i == j)
1056         continue;
1057
1058       if (isConsecutiveAccess(Stores[i], Stores[j])) {
1059         Tails.insert(Stores[j]);
1060         Heads.insert(Stores[i]);
1061         ConsecutiveChain[Stores[i]] = Stores[j];
1062       }
1063     }
1064
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();
1067        it != e; ++it) {
1068     if (Tails.count(*it))
1069       continue;
1070
1071     // We found a store instr that starts a chain. Now follow the chain and try
1072     // to vectorize it.
1073     ValueList Operands;
1074     Value *I = *it;
1075     // Collect the chain into a list.
1076     while (Tails.count(I) || Heads.count(I)) {
1077       if (VectorizedStores.count(I))
1078         break;
1079       Operands.push_back(I);
1080       // Move to the next value in the chain.
1081       I = ConsecutiveChain[I];
1082     }
1083
1084     bool Vectorized = vectorizeStoreChain(Operands, costThreshold);
1085
1086     // Mark the vectorized stores so that we don't vectorize them again.
1087     if (Vectorized)
1088       VectorizedStores.insert(Operands.begin(), Operands.end());
1089     Changed |= Vectorized;
1090   }
1091
1092   return Changed;
1093 }
1094
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);
1102   }
1103
1104   return Vec;
1105 }
1106
1107 Value *FuncSLP::vectorizeTree_rec(ArrayRef<Value *> VL) {
1108   BuilderLocGuard Guard(Builder);
1109
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());
1114
1115   if (needToGatherAny(VL))
1116     return Gather(VL, VecTy);
1117
1118   if (VectorizedValues.count(VL[0])) {
1119     DEBUG(dbgs() << "SLP: Diamond merged at depth.\n");
1120     return VectorizedValues[VL[0]];
1121   }
1122
1123   Instruction *VL0 = cast<Instruction>(VL[0]);
1124   unsigned Opcode = VL0->getOpcode();
1125   assert(Opcode == getSameOpcode(VL) && "Invalid opcode");
1126
1127   switch (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;
1133
1134     for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1135       ValueList Operands;
1136       BasicBlock *IBB = PH->getIncomingBlock(i);
1137
1138       // Prepare the operand vector.
1139       for (unsigned j = 0; j < VL.size(); ++j)
1140         Operands.push_back(cast<PHINode>(VL[j])->getIncomingValueForBlock(IBB));
1141
1142       Builder.SetInsertPoint(IBB->getTerminator());
1143       Value *Vec = vectorizeTree_rec(Operands);
1144       NewPhi->addIncoming(Vec, IBB);
1145     }
1146
1147     assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
1148            "Invalid number of incoming values");
1149     return NewPhi;
1150   }
1151
1152   case Instruction::ExtractElement: {
1153     if (CanReuseExtract(VL, VL.size(), VecTy))
1154       return VL0->getOperand(0);
1155     return Gather(VL, VecTy);
1156   }
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: {
1169     ValueList INVL;
1170     for (int i = 0, e = VL.size(); i < e; ++i)
1171       INVL.push_back(cast<Instruction>(VL[i])->getOperand(0));
1172
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;
1178     return V;
1179   }
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);
1188     }
1189
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));
1194     }
1195
1196     Builder.SetInsertPoint(getLastInstruction(VL));
1197     Value *L = vectorizeTree_rec(LHSV);
1198     Value *R = vectorizeTree_rec(RHSV);
1199     Value *V;
1200
1201     if (Opcode == Instruction::FCmp)
1202       V = Builder.CreateFCmp(P0, L, R);
1203     else
1204       V = Builder.CreateICmp(P0, L, R);
1205
1206     VectorizedValues[VL0] = V;
1207     return V;
1208   }
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));
1215     }
1216
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;
1223     return V;
1224   }
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));
1247     }
1248
1249     Builder.SetInsertPoint(getLastInstruction(VL));
1250     Value *LHS = vectorizeTree_rec(LHSVL);
1251     Value *RHS = vectorizeTree_rec(RHSVL);
1252
1253     if (LHS == RHS) {
1254       assert((VL0->getOperand(0) == VL0->getOperand(1)) && "Invalid order");
1255     }
1256
1257     BinaryOperator *BinOp = cast<BinaryOperator>(VL0);
1258     Value *V = Builder.CreateBinOp(BinOp->getOpcode(), LHS, RHS);
1259     VectorizedValues[VL0] = V;
1260     return V;
1261   }
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);
1267
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);
1272     Value *VecPtr =
1273         Builder.CreateBitCast(LI->getPointerOperand(), VecTy->getPointerTo());
1274     unsigned Alignment = LI->getAlignment();
1275     LI = Builder.CreateLoad(VecPtr);
1276     LI->setAlignment(Alignment);
1277
1278     VectorizedValues[VL0] = LI;
1279     return LI;
1280   }
1281   case Instruction::Store: {
1282     StoreInst *SI = cast<StoreInst>(VL0);
1283     unsigned Alignment = SI->getAlignment();
1284
1285     ValueList ValueOp;
1286     for (int i = 0, e = VL.size(); i < e; ++i)
1287       ValueOp.push_back(cast<StoreInst>(VL[i])->getValueOperand());
1288
1289     Value *VecValue = vectorizeTree_rec(ValueOp);
1290
1291     Builder.SetInsertPoint(getLastInstruction(VL));
1292     Value *VecPtr =
1293         Builder.CreateBitCast(SI->getPointerOperand(), VecTy->getPointerTo());
1294     Builder.CreateStore(VecValue, VecPtr)->setAlignment(Alignment);
1295     return 0;
1296   }
1297   default:
1298     return Gather(VL, VecTy);
1299   }
1300 }
1301
1302 Value *FuncSLP::vectorizeTree(ArrayRef<Value *> VL) {
1303   Builder.SetInsertPoint(getLastInstruction(VL));
1304   Value *V = vectorizeTree_rec(VL);
1305
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);
1311
1312     if (!Scalar)
1313       continue;
1314
1315     Instruction *Loc = 0;
1316
1317     assert(MultiUserVals.count(Scalar) && "Can't find the lane to extract");
1318     Instruction *Leader = MultiUserVals[Scalar].Leader;
1319
1320     // This value is gathered so we don't need to extract from anywhere.
1321     if (!VectorizedValues.count(Leader))
1322       continue;
1323
1324     Value *Vec = VectorizedValues[Leader];
1325     if (PHINode *PN = dyn_cast<PHINode>(Vec)) {
1326       Loc = PN->getParent()->getFirstInsertionPt();
1327     } else {
1328       Instruction *I = cast<Instruction>(Vec);
1329       BasicBlock::iterator L = *I;
1330       Loc = ++L;
1331     }
1332
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);
1338
1339     bool Replaced = false;;
1340     for (Value::use_iterator U = Scalar->use_begin(), UE = Scalar->use_end();
1341          U != UE; ++U) {
1342       Instruction *UI = cast<Instruction>(*U);
1343       // No need to replace instructions that are inside our lane map.
1344       if (LaneMap.count(UI))
1345         continue;
1346
1347       UI->replaceUsesOfWith(Scalar ,Extract);
1348       Replaced = true;
1349     }
1350     assert(Replaced && "Must replace at least one outside user");
1351     (void)Replaced;
1352   }
1353
1354   // We moved some instructions around. We have to number them again
1355   // before we can do any analysis.
1356   forgetNumbering();
1357
1358   // Clear the state.
1359   MustGather.clear();
1360   VisitedPHIs.clear();
1361   VectorizedValues.clear();
1362   MemBarrierIgnoreList.clear();
1363   return V;
1364 }
1365
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);
1376   }
1377
1378   forgetNumbering();
1379   return Vec;
1380 }
1381
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);
1387
1388     if (!Insert)
1389       continue;
1390
1391     // Check if this block is inside a loop.
1392     Loop *L = LI->getLoopFor(Insert->getParent());
1393     if (!L)
1394       continue;
1395
1396     // Check if it has a preheader.
1397     BasicBlock *PreHeader = L->getLoopPreheader();
1398     if (!PreHeader)
1399       continue;
1400
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))
1407       continue;
1408     if (NewElem && L->contains(NewElem))
1409       continue;
1410
1411     // We can hoist this instruction. Move it to the pre-header.
1412     Insert->moveBefore(PreHeader->getTerminator());
1413   }
1414
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))
1428         continue;
1429
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);
1438           Insert = 0;
1439           break;
1440         }
1441       }
1442       if (Insert)
1443         Visited.insert(Insert);
1444     }
1445   }
1446
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();
1452   }
1453
1454   forgetNumbering();
1455 }
1456
1457 /// The SLPVectorizer Pass.
1458 struct SLPVectorizer : public FunctionPass {
1459   typedef SmallVector<StoreInst *, 8> StoreList;
1460   typedef MapVector<Value *, StoreList> StoreListMap;
1461
1462   /// Pass identification, replacement for typeid
1463   static char ID;
1464
1465   explicit SLPVectorizer() : FunctionPass(ID) {
1466     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
1467   }
1468
1469   ScalarEvolution *SE;
1470   DataLayout *DL;
1471   TargetTransformInfo *TTI;
1472   AliasAnalysis *AA;
1473   LoopInfo *LI;
1474   DominatorTree *DT;
1475
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>();
1483
1484     StoreRefs.clear();
1485     bool Changed = false;
1486
1487     // Must have DataLayout. We can't require it because some tests run w/o
1488     // triple.
1489     if (!DL)
1490       return false;
1491
1492     DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
1493
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);
1497
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;
1502
1503       // Vectorize trees that end at reductions.
1504       Changed |= vectorizeChainsInBlock(BB, R);
1505
1506       // Vectorize trees that end at stores.
1507       if (unsigned count = collectStores(BB, R)) {
1508         (void)count;
1509         DEBUG(dbgs() << "SLP: Found " << count << " stores to vectorize.\n");
1510         Changed |= vectorizeStoreChains(R);
1511       }
1512     }
1513
1514     if (Changed) {
1515       R.optimizeGatherSequence();
1516       DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
1517       DEBUG(verifyFunction(F));
1518     }
1519     return Changed;
1520   }
1521
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>();
1529   }
1530
1531 private:
1532
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);
1538
1539   /// \brief Try to vectorize a chain that starts at two arithmetic instrs.
1540   bool tryToVectorizePair(Value *A, Value *B, FuncSLP &R);
1541
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);
1546
1547   /// \brief Try to vectorize a chain that may start at the operands of \V;
1548   bool tryToVectorize(BinaryOperator *V, FuncSLP &R);
1549
1550   /// \brief Vectorize the stores that were collected in StoreRefs.
1551   bool vectorizeStoreChains(FuncSLP &R);
1552
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);
1556
1557 private:
1558   StoreListMap StoreRefs;
1559 };
1560
1561 unsigned SLPVectorizer::collectStores(BasicBlock *BB, FuncSLP &R) {
1562   unsigned count = 0;
1563   StoreRefs.clear();
1564   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1565     StoreInst *SI = dyn_cast<StoreInst>(it);
1566     if (!SI)
1567       continue;
1568
1569     // Check that the pointer points to scalars.
1570     Type *Ty = SI->getValueOperand()->getType();
1571     if (Ty->isAggregateType() || Ty->isVectorTy())
1572       return 0;
1573
1574     // Find the base of the GEP.
1575     Value *Ptr = SI->getPointerOperand();
1576     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
1577       Ptr = GEP->getPointerOperand();
1578
1579     // Save the store locations.
1580     StoreRefs[Ptr].push_back(SI);
1581     count++;
1582   }
1583   return count;
1584 }
1585
1586 bool SLPVectorizer::tryToVectorizePair(Value *A, Value *B, FuncSLP &R) {
1587   if (!A || !B)
1588     return false;
1589   Value *VL[] = { A, B };
1590   return tryToVectorizeList(VL, R, true);
1591 }
1592
1593 bool SLPVectorizer::tryToVectorizeList(ArrayRef<Value *> VL, FuncSLP &R,
1594                                        bool NeedExtracts) {
1595   if (VL.size() < 2)
1596     return false;
1597
1598   DEBUG(dbgs() << "SLP: Vectorizing a list of length = " << VL.size() << ".\n");
1599
1600   // Check that all of the parts are scalar instructions of the same type.
1601   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
1602   if (!I0)
1603     return 0;
1604
1605   unsigned Opcode0 = I0->getOpcode();
1606
1607   for (int i = 0, e = VL.size(); i < e; ++i) {
1608     Type *Ty = VL[i]->getType();
1609     if (Ty->isAggregateType() || Ty->isVectorTy())
1610       return 0;
1611     Instruction *Inst = dyn_cast<Instruction>(VL[i]);
1612     if (!Inst || Inst->getOpcode() != Opcode0)
1613       return 0;
1614   }
1615
1616   int Cost = R.getTreeCost(VL);
1617   if (Cost == FuncSLP::MAX_COST)
1618     return false;
1619
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)
1624     return false;
1625   DEBUG(dbgs() << "SLP: Vectorizing pair.\n");
1626   R.vectorizeArith(VL);
1627   return true;
1628 }
1629
1630 bool SLPVectorizer::tryToVectorize(BinaryOperator *V, FuncSLP &R) {
1631   if (!V)
1632     return false;
1633
1634   // Try to vectorize V.
1635   if (tryToVectorizePair(V->getOperand(0), V->getOperand(1), R))
1636     return true;
1637
1638   BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0));
1639   BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1));
1640   // Try to skip B.
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)) {
1645       B->moveBefore(V);
1646       return true;
1647     }
1648     if (tryToVectorizePair(A, B1, R)) {
1649       B->moveBefore(V);
1650       return true;
1651     }
1652   }
1653
1654   // Try to skip A.
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)) {
1659       A->moveBefore(V);
1660       return true;
1661     }
1662     if (tryToVectorizePair(A1, B, R)) {
1663       A->moveBefore(V);
1664       return true;
1665     }
1666   }
1667   return 0;
1668 }
1669
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))
1674       continue;
1675
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)
1680         return Changed;
1681       Value *Rdx =
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);
1687       if (!BI)
1688         continue;
1689
1690       Value *Inst = BI->getOperand(0);
1691       if (Inst == P)
1692         Inst = BI->getOperand(1);
1693
1694       Changed |= tryToVectorize(dyn_cast<BinaryOperator>(Inst), R);
1695       continue;
1696     }
1697
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)) {
1701         Changed |= true;
1702         continue;
1703       }
1704       for (int i = 0; i < 2; ++i)
1705         if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i)))
1706           Changed |=
1707               tryToVectorizePair(BI->getOperand(0), BI->getOperand(1), R);
1708       continue;
1709     }
1710   }
1711
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;
1716
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);
1721
1722       if (!P)
1723         break;
1724
1725       Value *V = P->getIncomingValueForBlock(BB);
1726       if (Instruction *I = dyn_cast<Instruction>(V))
1727         if (I->getParent() == BB)
1728           Incoming.push_back(I);
1729     }
1730
1731     if (Incoming.size() > 1)
1732       Changed |= tryToVectorizeList(Incoming, R, true);
1733   }
1734
1735   return Changed;
1736 }
1737
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();
1742        it != e; ++it) {
1743     if (it->second.size() < 2)
1744       continue;
1745
1746     DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
1747                  << it->second.size() << ".\n");
1748
1749     Changed |= R.vectorizeStores(it->second, -SLPCostThreshold);
1750   }
1751   return Changed;
1752 }
1753
1754 } // end anonymous namespace
1755
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)
1764
1765 namespace llvm {
1766 Pass *createSLPVectorizerPass() { return new SLPVectorizer(); }
1767 }