Transforms: Use getFirstNonPHI to set the insertion point for PHIs
[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 if you gain more than this "
51                               "number "));
52
53 static cl::opt<bool>
54 ShouldVectorizeHor("slp-vectorize-hor", cl::init(false), cl::Hidden,
55                    cl::desc("Attempt to vectorize horizontal reductions"));
56
57 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
58     "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
59     cl::desc(
60         "Attempt to vectorize horizontal reductions feeding into a store"));
61
62 namespace {
63
64 static const unsigned MinVecRegSize = 128;
65
66 static const unsigned RecursionMaxDepth = 12;
67
68 /// RAII pattern to save the insertion point of the IR builder.
69 class BuilderLocGuard {
70 public:
71   BuilderLocGuard(IRBuilder<> &B) : Builder(B), Loc(B.GetInsertPoint()),
72   DbgLoc(B.getCurrentDebugLocation()) {}
73   ~BuilderLocGuard() {
74     Builder.SetCurrentDebugLocation(DbgLoc);
75     if (Loc)
76       Builder.SetInsertPoint(Loc);
77   }
78
79 private:
80   // Prevent copying.
81   BuilderLocGuard(const BuilderLocGuard &);
82   BuilderLocGuard &operator=(const BuilderLocGuard &);
83   IRBuilder<> &Builder;
84   AssertingVH<Instruction> Loc;
85   DebugLoc DbgLoc;
86 };
87
88 /// A helper class for numbering instructions in multiple blocks.
89 /// Numbers start at zero for each basic block.
90 struct BlockNumbering {
91
92   BlockNumbering(BasicBlock *Bb) : BB(Bb), Valid(false) {}
93
94   BlockNumbering() : BB(0), Valid(false) {}
95
96   void numberInstructions() {
97     unsigned Loc = 0;
98     InstrIdx.clear();
99     InstrVec.clear();
100     // Number the instructions in the block.
101     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
102       InstrIdx[it] = Loc++;
103       InstrVec.push_back(it);
104       assert(InstrVec[InstrIdx[it]] == it && "Invalid allocation");
105     }
106     Valid = true;
107   }
108
109   int getIndex(Instruction *I) {
110     assert(I->getParent() == BB && "Invalid instruction");
111     if (!Valid)
112       numberInstructions();
113     assert(InstrIdx.count(I) && "Unknown instruction");
114     return InstrIdx[I];
115   }
116
117   Instruction *getInstruction(unsigned loc) {
118     if (!Valid)
119       numberInstructions();
120     assert(InstrVec.size() > loc && "Invalid Index");
121     return InstrVec[loc];
122   }
123
124   void forget() { Valid = false; }
125
126 private:
127   /// The block we are numbering.
128   BasicBlock *BB;
129   /// Is the block numbered.
130   bool Valid;
131   /// Maps instructions to numbers and back.
132   SmallDenseMap<Instruction *, int> InstrIdx;
133   /// Maps integers to Instructions.
134   SmallVector<Instruction *, 32> InstrVec;
135 };
136
137 /// \returns the parent basic block if all of the instructions in \p VL
138 /// are in the same block or null otherwise.
139 static BasicBlock *getSameBlock(ArrayRef<Value *> VL) {
140   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
141   if (!I0)
142     return 0;
143   BasicBlock *BB = I0->getParent();
144   for (int i = 1, e = VL.size(); i < e; i++) {
145     Instruction *I = dyn_cast<Instruction>(VL[i]);
146     if (!I)
147       return 0;
148
149     if (BB != I->getParent())
150       return 0;
151   }
152   return BB;
153 }
154
155 /// \returns True if all of the values in \p VL are constants.
156 static bool allConstant(ArrayRef<Value *> VL) {
157   for (unsigned i = 0, e = VL.size(); i < e; ++i)
158     if (!isa<Constant>(VL[i]))
159       return false;
160   return true;
161 }
162
163 /// \returns True if all of the values in \p VL are identical.
164 static bool isSplat(ArrayRef<Value *> VL) {
165   for (unsigned i = 1, e = VL.size(); i < e; ++i)
166     if (VL[i] != VL[0])
167       return false;
168   return true;
169 }
170
171 /// \returns The opcode if all of the Instructions in \p VL have the same
172 /// opcode, or zero.
173 static unsigned getSameOpcode(ArrayRef<Value *> VL) {
174   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
175   if (!I0)
176     return 0;
177   unsigned Opcode = I0->getOpcode();
178   for (int i = 1, e = VL.size(); i < e; i++) {
179     Instruction *I = dyn_cast<Instruction>(VL[i]);
180     if (!I || Opcode != I->getOpcode())
181       return 0;
182   }
183   return Opcode;
184 }
185
186 /// \returns The type that all of the values in \p VL have or null if there
187 /// are different types.
188 static Type* getSameType(ArrayRef<Value *> VL) {
189   Type *Ty = VL[0]->getType();
190   for (int i = 1, e = VL.size(); i < e; i++)
191     if (VL[i]->getType() != Ty)
192       return 0;
193
194   return Ty;
195 }
196
197 /// \returns True if the ExtractElement instructions in VL can be vectorized
198 /// to use the original vector.
199 static bool CanReuseExtract(ArrayRef<Value *> VL) {
200   assert(Instruction::ExtractElement == getSameOpcode(VL) && "Invalid opcode");
201   // Check if all of the extracts come from the same vector and from the
202   // correct offset.
203   Value *VL0 = VL[0];
204   ExtractElementInst *E0 = cast<ExtractElementInst>(VL0);
205   Value *Vec = E0->getOperand(0);
206
207   // We have to extract from the same vector type.
208   unsigned NElts = Vec->getType()->getVectorNumElements();
209
210   if (NElts != VL.size())
211     return false;
212
213   // Check that all of the indices extract from the correct offset.
214   ConstantInt *CI = dyn_cast<ConstantInt>(E0->getOperand(1));
215   if (!CI || CI->getZExtValue())
216     return false;
217
218   for (unsigned i = 1, e = VL.size(); i < e; ++i) {
219     ExtractElementInst *E = cast<ExtractElementInst>(VL[i]);
220     ConstantInt *CI = dyn_cast<ConstantInt>(E->getOperand(1));
221
222     if (!CI || CI->getZExtValue() != i || E->getOperand(0) != Vec)
223       return false;
224   }
225
226   return true;
227 }
228
229 /// Bottom Up SLP Vectorizer.
230 class BoUpSLP {
231 public:
232   typedef SmallVector<Value *, 8> ValueList;
233   typedef SmallVector<Instruction *, 16> InstrList;
234   typedef SmallPtrSet<Value *, 16> ValueSet;
235   typedef SmallVector<StoreInst *, 8> StoreList;
236
237   BoUpSLP(Function *Func, ScalarEvolution *Se, DataLayout *Dl,
238           TargetTransformInfo *Tti, AliasAnalysis *Aa, LoopInfo *Li,
239           DominatorTree *Dt) :
240     F(Func), SE(Se), DL(Dl), TTI(Tti), AA(Aa), LI(Li), DT(Dt),
241     Builder(Se->getContext()) {
242       // Setup the block numbering utility for all of the blocks in the
243       // function.
244       for (Function::iterator it = F->begin(), e = F->end(); it != e; ++it) {
245         BasicBlock *BB = it;
246         BlocksNumbers[BB] = BlockNumbering(BB);
247       }
248     }
249
250   /// \brief Vectorize the tree that starts with the elements in \p VL.
251   /// Returns the vectorized root.
252   Value *vectorizeTree();
253
254   /// \returns the vectorization cost of the subtree that starts at \p VL.
255   /// A negative number means that this is profitable.
256   int getTreeCost();
257
258   /// Construct a vectorizable tree that starts at \p Roots and is possibly
259   /// used by a reduction of \p RdxOps.
260   void buildTree(ArrayRef<Value *> Roots, ValueSet *RdxOps = 0);
261
262   /// Clear the internal data structures that are created by 'buildTree'.
263   void deleteTree() {
264     RdxOps = 0;
265     VectorizableTree.clear();
266     ScalarToTreeEntry.clear();
267     MustGather.clear();
268     ExternalUses.clear();
269     MemBarrierIgnoreList.clear();
270   }
271
272   /// \returns true if the memory operations A and B are consecutive.
273   bool isConsecutiveAccess(Value *A, Value *B);
274
275   /// \brief Perform LICM and CSE on the newly generated gather sequences.
276   void optimizeGatherSequence();
277 private:
278   struct TreeEntry;
279
280   /// \returns the cost of the vectorizable entry.
281   int getEntryCost(TreeEntry *E);
282
283   /// This is the recursive part of buildTree.
284   void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth);
285
286   /// Vectorize a single entry in the tree.
287   Value *vectorizeTree(TreeEntry *E);
288
289   /// Vectorize a single entry in the tree, starting in \p VL.
290   Value *vectorizeTree(ArrayRef<Value *> VL);
291
292   /// \returns the pointer to the vectorized value if \p VL is already
293   /// vectorized, or NULL. They may happen in cycles.
294   Value *alreadyVectorized(ArrayRef<Value *> VL) const;
295
296   /// \brief Take the pointer operand from the Load/Store instruction.
297   /// \returns NULL if this is not a valid Load/Store instruction.
298   static Value *getPointerOperand(Value *I);
299
300   /// \brief Take the address space operand from the Load/Store instruction.
301   /// \returns -1 if this is not a valid Load/Store instruction.
302   static unsigned getAddressSpaceOperand(Value *I);
303
304   /// \returns the scalarization cost for this type. Scalarization in this
305   /// context means the creation of vectors from a group of scalars.
306   int getGatherCost(Type *Ty);
307
308   /// \returns the scalarization cost for this list of values. Assuming that
309   /// this subtree gets vectorized, we may need to extract the values from the
310   /// roots. This method calculates the cost of extracting the values.
311   int getGatherCost(ArrayRef<Value *> VL);
312
313   /// \returns the AA location that is being access by the instruction.
314   AliasAnalysis::Location getLocation(Instruction *I);
315
316   /// \brief Checks if it is possible to sink an instruction from
317   /// \p Src to \p Dst.
318   /// \returns the pointer to the barrier instruction if we can't sink.
319   Value *getSinkBarrier(Instruction *Src, Instruction *Dst);
320
321   /// \returns the index of the last instrucion in the BB from \p VL.
322   int getLastIndex(ArrayRef<Value *> VL);
323
324   /// \returns the Instruction in the bundle \p VL.
325   Instruction *getLastInstruction(ArrayRef<Value *> VL);
326
327   /// \brief Set the Builder insert point to one after the last instruction in
328   /// the bundle
329   void setInsertPointAfterBundle(ArrayRef<Value *> VL);
330
331   /// \returns a vector from a collection of scalars in \p VL.
332   Value *Gather(ArrayRef<Value *> VL, VectorType *Ty);
333
334   struct TreeEntry {
335     TreeEntry() : Scalars(), VectorizedValue(0), LastScalarIndex(0),
336     NeedToGather(0) {}
337
338     /// \returns true if the scalars in VL are equal to this entry.
339     bool isSame(ArrayRef<Value *> VL) const {
340       assert(VL.size() == Scalars.size() && "Invalid size");
341       for (int i = 0, e = VL.size(); i != e; ++i)
342         if (VL[i] != Scalars[i])
343           return false;
344       return true;
345     }
346
347     /// A vector of scalars.
348     ValueList Scalars;
349
350     /// The Scalars are vectorized into this value. It is initialized to Null.
351     Value *VectorizedValue;
352
353     /// The index in the basic block of the last scalar.
354     int LastScalarIndex;
355
356     /// Do we need to gather this sequence ?
357     bool NeedToGather;
358   };
359
360   /// Create a new VectorizableTree entry.
361   TreeEntry *newTreeEntry(ArrayRef<Value *> VL, bool Vectorized) {
362     VectorizableTree.push_back(TreeEntry());
363     int idx = VectorizableTree.size() - 1;
364     TreeEntry *Last = &VectorizableTree[idx];
365     Last->Scalars.insert(Last->Scalars.begin(), VL.begin(), VL.end());
366     Last->NeedToGather = !Vectorized;
367     if (Vectorized) {
368       Last->LastScalarIndex = getLastIndex(VL);
369       for (int i = 0, e = VL.size(); i != e; ++i) {
370         assert(!ScalarToTreeEntry.count(VL[i]) && "Scalar already in tree!");
371         ScalarToTreeEntry[VL[i]] = idx;
372       }
373     } else {
374       Last->LastScalarIndex = 0;
375       MustGather.insert(VL.begin(), VL.end());
376     }
377     return Last;
378   }
379
380   /// -- Vectorization State --
381   /// Holds all of the tree entries.
382   std::vector<TreeEntry> VectorizableTree;
383
384   /// Maps a specific scalar to its tree entry.
385   SmallDenseMap<Value*, int> ScalarToTreeEntry;
386
387   /// A list of scalars that we found that we need to keep as scalars.
388   ValueSet MustGather;
389
390   /// This POD struct describes one external user in the vectorized tree.
391   struct ExternalUser {
392     ExternalUser (Value *S, llvm::User *U, int L) :
393       Scalar(S), User(U), Lane(L){};
394     // Which scalar in our function.
395     Value *Scalar;
396     // Which user that uses the scalar.
397     llvm::User *User;
398     // Which lane does the scalar belong to.
399     int Lane;
400   };
401   typedef SmallVector<ExternalUser, 16> UserList;
402
403   /// A list of values that need to extracted out of the tree.
404   /// This list holds pairs of (Internal Scalar : External User).
405   UserList ExternalUses;
406
407   /// A list of instructions to ignore while sinking
408   /// memory instructions. This map must be reset between runs of getCost.
409   ValueSet MemBarrierIgnoreList;
410
411   /// Holds all of the instructions that we gathered.
412   SetVector<Instruction *> GatherSeq;
413
414   /// Numbers instructions in different blocks.
415   DenseMap<BasicBlock *, BlockNumbering> BlocksNumbers;
416
417   /// Reduction operators.
418   ValueSet *RdxOps;
419
420   // Analysis and block reference.
421   Function *F;
422   ScalarEvolution *SE;
423   DataLayout *DL;
424   TargetTransformInfo *TTI;
425   AliasAnalysis *AA;
426   LoopInfo *LI;
427   DominatorTree *DT;
428   /// Instruction builder to construct the vectorized tree.
429   IRBuilder<> Builder;
430 };
431
432 void BoUpSLP::buildTree(ArrayRef<Value *> Roots, ValueSet *Rdx) {
433   deleteTree();
434   RdxOps = Rdx;
435   if (!getSameType(Roots))
436     return;
437   buildTree_rec(Roots, 0);
438
439   // Collect the values that we need to extract from the tree.
440   for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
441     TreeEntry *Entry = &VectorizableTree[EIdx];
442
443     // For each lane:
444     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
445       Value *Scalar = Entry->Scalars[Lane];
446
447       // No need to handle users of gathered values.
448       if (Entry->NeedToGather)
449         continue;
450
451       for (Value::use_iterator User = Scalar->use_begin(),
452            UE = Scalar->use_end(); User != UE; ++User) {
453         DEBUG(dbgs() << "SLP: Checking user:" << **User << ".\n");
454
455         bool Gathered = MustGather.count(*User);
456
457         // Skip in-tree scalars that become vectors.
458         if (ScalarToTreeEntry.count(*User) && !Gathered) {
459           DEBUG(dbgs() << "SLP: \tInternal user will be removed:" <<
460                 **User << ".\n");
461           int Idx = ScalarToTreeEntry[*User]; (void) Idx;
462           assert(!VectorizableTree[Idx].NeedToGather && "Bad state");
463           continue;
464         }
465         Instruction *UserInst = dyn_cast<Instruction>(*User);
466         if (!UserInst)
467           continue;
468
469         // Ignore uses that are part of the reduction.
470         if (Rdx && std::find(Rdx->begin(), Rdx->end(), UserInst) != Rdx->end())
471           continue;
472
473         DEBUG(dbgs() << "SLP: Need to extract:" << **User << " from lane " <<
474               Lane << " from " << *Scalar << ".\n");
475         ExternalUses.push_back(ExternalUser(Scalar, *User, Lane));
476       }
477     }
478   }
479 }
480
481
482 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth) {
483   bool SameTy = getSameType(VL); (void)SameTy;
484   assert(SameTy && "Invalid types!");
485
486   if (Depth == RecursionMaxDepth) {
487     DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
488     newTreeEntry(VL, false);
489     return;
490   }
491
492   // Don't handle vectors.
493   if (VL[0]->getType()->isVectorTy()) {
494     DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
495     newTreeEntry(VL, false);
496     return;
497   }
498
499   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
500     if (SI->getValueOperand()->getType()->isVectorTy()) {
501       DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
502       newTreeEntry(VL, false);
503       return;
504     }
505
506   // If all of the operands are identical or constant we have a simple solution.
507   if (allConstant(VL) || isSplat(VL) || !getSameBlock(VL) ||
508       !getSameOpcode(VL)) {
509     DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
510     newTreeEntry(VL, false);
511     return;
512   }
513
514   // We now know that this is a vector of instructions of the same type from
515   // the same block.
516
517   // Check if this is a duplicate of another entry.
518   if (ScalarToTreeEntry.count(VL[0])) {
519     int Idx = ScalarToTreeEntry[VL[0]];
520     TreeEntry *E = &VectorizableTree[Idx];
521     for (unsigned i = 0, e = VL.size(); i != e; ++i) {
522       DEBUG(dbgs() << "SLP: \tChecking bundle: " << *VL[i] << ".\n");
523       if (E->Scalars[i] != VL[i]) {
524         DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
525         newTreeEntry(VL, false);
526         return;
527       }
528     }
529     DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *VL[0] << ".\n");
530     return;
531   }
532
533   // Check that none of the instructions in the bundle are already in the tree.
534   for (unsigned i = 0, e = VL.size(); i != e; ++i) {
535     if (ScalarToTreeEntry.count(VL[i])) {
536       DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
537             ") is already in tree.\n");
538       newTreeEntry(VL, false);
539       return;
540     }
541   }
542
543   // If any of the scalars appears in the table OR it is marked as a value that
544   // needs to stat scalar then we need to gather the scalars.
545   for (unsigned i = 0, e = VL.size(); i != e; ++i) {
546     if (ScalarToTreeEntry.count(VL[i]) || MustGather.count(VL[i])) {
547       DEBUG(dbgs() << "SLP: Gathering due to gathered scalar. \n");
548       newTreeEntry(VL, false);
549       return;
550     }
551   }
552
553   // Check that all of the users of the scalars that we want to vectorize are
554   // schedulable.
555   Instruction *VL0 = cast<Instruction>(VL[0]);
556   int MyLastIndex = getLastIndex(VL);
557   BasicBlock *BB = cast<Instruction>(VL0)->getParent();
558
559   for (unsigned i = 0, e = VL.size(); i != e; ++i) {
560     Instruction *Scalar = cast<Instruction>(VL[i]);
561     DEBUG(dbgs() << "SLP: Checking users of  " << *Scalar << ". \n");
562     for (Value::use_iterator U = Scalar->use_begin(), UE = Scalar->use_end();
563          U != UE; ++U) {
564       DEBUG(dbgs() << "SLP: \tUser " << **U << ". \n");
565       Instruction *User = dyn_cast<Instruction>(*U);
566       if (!User) {
567         DEBUG(dbgs() << "SLP: Gathering due unknown user. \n");
568         newTreeEntry(VL, false);
569         return;
570       }
571
572       // We don't care if the user is in a different basic block.
573       BasicBlock *UserBlock = User->getParent();
574       if (UserBlock != BB) {
575         DEBUG(dbgs() << "SLP: User from a different basic block "
576               << *User << ". \n");
577         continue;
578       }
579
580       // If this is a PHINode within this basic block then we can place the
581       // extract wherever we want.
582       if (isa<PHINode>(*User)) {
583         DEBUG(dbgs() << "SLP: \tWe can schedule PHIs:" << *User << ". \n");
584         continue;
585       }
586
587       // Check if this is a safe in-tree user.
588       if (ScalarToTreeEntry.count(User)) {
589         int Idx = ScalarToTreeEntry[User];
590         int VecLocation = VectorizableTree[Idx].LastScalarIndex;
591         if (VecLocation <= MyLastIndex) {
592           DEBUG(dbgs() << "SLP: Gathering due to unschedulable vector. \n");
593           newTreeEntry(VL, false);
594           return;
595         }
596         DEBUG(dbgs() << "SLP: In-tree user (" << *User << ") at #" <<
597               VecLocation << " vector value (" << *Scalar << ") at #"
598               << MyLastIndex << ".\n");
599         continue;
600       }
601
602       // This user is part of the reduction.
603       if (RdxOps && RdxOps->count(User))
604         continue;
605
606       // Make sure that we can schedule this unknown user.
607       BlockNumbering &BN = BlocksNumbers[BB];
608       int UserIndex = BN.getIndex(User);
609       if (UserIndex < MyLastIndex) {
610
611         DEBUG(dbgs() << "SLP: Can't schedule extractelement for "
612               << *User << ". \n");
613         newTreeEntry(VL, false);
614         return;
615       }
616     }
617   }
618
619   // Check that every instructions appears once in this bundle.
620   for (unsigned i = 0, e = VL.size(); i < e; ++i)
621     for (unsigned j = i+1; j < e; ++j)
622       if (VL[i] == VL[j]) {
623         DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
624         newTreeEntry(VL, false);
625         return;
626       }
627
628   // Check that instructions in this bundle don't reference other instructions.
629   // The runtime of this check is O(N * N-1 * uses(N)) and a typical N is 4.
630   for (unsigned i = 0, e = VL.size(); i < e; ++i) {
631     for (Value::use_iterator U = VL[i]->use_begin(), UE = VL[i]->use_end();
632          U != UE; ++U) {
633       for (unsigned j = 0; j < e; ++j) {
634         if (i != j && *U == VL[j]) {
635           DEBUG(dbgs() << "SLP: Intra-bundle dependencies!" << **U << ". \n");
636           newTreeEntry(VL, false);
637           return;
638         }
639       }
640     }
641   }
642
643   DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
644
645   unsigned Opcode = getSameOpcode(VL);
646
647   // Check if it is safe to sink the loads or the stores.
648   if (Opcode == Instruction::Load || Opcode == Instruction::Store) {
649     Instruction *Last = getLastInstruction(VL);
650
651     for (unsigned i = 0, e = VL.size(); i < e; ++i) {
652       if (VL[i] == Last)
653         continue;
654       Value *Barrier = getSinkBarrier(cast<Instruction>(VL[i]), Last);
655       if (Barrier) {
656         DEBUG(dbgs() << "SLP: Can't sink " << *VL[i] << "\n down to " << *Last
657               << "\n because of " << *Barrier << ".  Gathering.\n");
658         newTreeEntry(VL, false);
659         return;
660       }
661     }
662   }
663
664   switch (Opcode) {
665     case Instruction::PHI: {
666       PHINode *PH = dyn_cast<PHINode>(VL0);
667
668       // Check for terminator values (e.g. invoke).
669       for (unsigned j = 0; j < VL.size(); ++j)
670         for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
671           TerminatorInst *Term = dyn_cast<TerminatorInst>(cast<PHINode>(VL[j])->getIncomingValue(i));
672           if (Term) {
673             DEBUG(dbgs() << "SLP: Need to swizzle PHINodes (TerminatorInst use).\n");
674             newTreeEntry(VL, false);
675             return;
676           }
677         }
678
679       newTreeEntry(VL, true);
680       DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
681
682       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
683         ValueList Operands;
684         // Prepare the operand vector.
685         for (unsigned j = 0; j < VL.size(); ++j)
686           Operands.push_back(cast<PHINode>(VL[j])->getIncomingValue(i));
687
688         buildTree_rec(Operands, Depth + 1);
689       }
690       return;
691     }
692     case Instruction::ExtractElement: {
693       bool Reuse = CanReuseExtract(VL);
694       if (Reuse) {
695         DEBUG(dbgs() << "SLP: Reusing extract sequence.\n");
696       }
697       newTreeEntry(VL, Reuse);
698       return;
699     }
700     case Instruction::Load: {
701       // Check if the loads are consecutive or of we need to swizzle them.
702       for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
703         if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
704           newTreeEntry(VL, false);
705           DEBUG(dbgs() << "SLP: Need to swizzle loads.\n");
706           return;
707         }
708
709       newTreeEntry(VL, true);
710       DEBUG(dbgs() << "SLP: added a vector of loads.\n");
711       return;
712     }
713     case Instruction::ZExt:
714     case Instruction::SExt:
715     case Instruction::FPToUI:
716     case Instruction::FPToSI:
717     case Instruction::FPExt:
718     case Instruction::PtrToInt:
719     case Instruction::IntToPtr:
720     case Instruction::SIToFP:
721     case Instruction::UIToFP:
722     case Instruction::Trunc:
723     case Instruction::FPTrunc:
724     case Instruction::BitCast: {
725       Type *SrcTy = VL0->getOperand(0)->getType();
726       for (unsigned i = 0; i < VL.size(); ++i) {
727         Type *Ty = cast<Instruction>(VL[i])->getOperand(0)->getType();
728         if (Ty != SrcTy || Ty->isAggregateType() || Ty->isVectorTy()) {
729           newTreeEntry(VL, false);
730           DEBUG(dbgs() << "SLP: Gathering casts with different src types.\n");
731           return;
732         }
733       }
734       newTreeEntry(VL, true);
735       DEBUG(dbgs() << "SLP: added a vector of casts.\n");
736
737       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
738         ValueList Operands;
739         // Prepare the operand vector.
740         for (unsigned j = 0; j < VL.size(); ++j)
741           Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
742
743         buildTree_rec(Operands, Depth+1);
744       }
745       return;
746     }
747     case Instruction::ICmp:
748     case Instruction::FCmp: {
749       // Check that all of the compares have the same predicate.
750       CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
751       Type *ComparedTy = cast<Instruction>(VL[0])->getOperand(0)->getType();
752       for (unsigned i = 1, e = VL.size(); i < e; ++i) {
753         CmpInst *Cmp = cast<CmpInst>(VL[i]);
754         if (Cmp->getPredicate() != P0 ||
755             Cmp->getOperand(0)->getType() != ComparedTy) {
756           newTreeEntry(VL, false);
757           DEBUG(dbgs() << "SLP: Gathering cmp with different predicate.\n");
758           return;
759         }
760       }
761
762       newTreeEntry(VL, true);
763       DEBUG(dbgs() << "SLP: added a vector of compares.\n");
764
765       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
766         ValueList Operands;
767         // Prepare the operand vector.
768         for (unsigned j = 0; j < VL.size(); ++j)
769           Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
770
771         buildTree_rec(Operands, Depth+1);
772       }
773       return;
774     }
775     case Instruction::Select:
776     case Instruction::Add:
777     case Instruction::FAdd:
778     case Instruction::Sub:
779     case Instruction::FSub:
780     case Instruction::Mul:
781     case Instruction::FMul:
782     case Instruction::UDiv:
783     case Instruction::SDiv:
784     case Instruction::FDiv:
785     case Instruction::URem:
786     case Instruction::SRem:
787     case Instruction::FRem:
788     case Instruction::Shl:
789     case Instruction::LShr:
790     case Instruction::AShr:
791     case Instruction::And:
792     case Instruction::Or:
793     case Instruction::Xor: {
794       newTreeEntry(VL, true);
795       DEBUG(dbgs() << "SLP: added a vector of bin op.\n");
796
797       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
798         ValueList Operands;
799         // Prepare the operand vector.
800         for (unsigned j = 0; j < VL.size(); ++j)
801           Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
802
803         buildTree_rec(Operands, Depth+1);
804       }
805       return;
806     }
807     case Instruction::Store: {
808       // Check if the stores are consecutive or of we need to swizzle them.
809       for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
810         if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
811           newTreeEntry(VL, false);
812           DEBUG(dbgs() << "SLP: Non consecutive store.\n");
813           return;
814         }
815
816       newTreeEntry(VL, true);
817       DEBUG(dbgs() << "SLP: added a vector of stores.\n");
818
819       ValueList Operands;
820       for (unsigned j = 0; j < VL.size(); ++j)
821         Operands.push_back(cast<Instruction>(VL[j])->getOperand(0));
822
823       // We can ignore these values because we are sinking them down.
824       MemBarrierIgnoreList.insert(VL.begin(), VL.end());
825       buildTree_rec(Operands, Depth + 1);
826       return;
827     }
828     default:
829       newTreeEntry(VL, false);
830       DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
831       return;
832   }
833 }
834
835 int BoUpSLP::getEntryCost(TreeEntry *E) {
836   ArrayRef<Value*> VL = E->Scalars;
837
838   Type *ScalarTy = VL[0]->getType();
839   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
840     ScalarTy = SI->getValueOperand()->getType();
841   VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
842
843   if (E->NeedToGather) {
844     if (allConstant(VL))
845       return 0;
846     if (isSplat(VL)) {
847       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
848     }
849     return getGatherCost(E->Scalars);
850   }
851
852   assert(getSameOpcode(VL) && getSameType(VL) && getSameBlock(VL) &&
853          "Invalid VL");
854   Instruction *VL0 = cast<Instruction>(VL[0]);
855   unsigned Opcode = VL0->getOpcode();
856   switch (Opcode) {
857     case Instruction::PHI: {
858       return 0;
859     }
860     case Instruction::ExtractElement: {
861       if (CanReuseExtract(VL))
862         return 0;
863       return getGatherCost(VecTy);
864     }
865     case Instruction::ZExt:
866     case Instruction::SExt:
867     case Instruction::FPToUI:
868     case Instruction::FPToSI:
869     case Instruction::FPExt:
870     case Instruction::PtrToInt:
871     case Instruction::IntToPtr:
872     case Instruction::SIToFP:
873     case Instruction::UIToFP:
874     case Instruction::Trunc:
875     case Instruction::FPTrunc:
876     case Instruction::BitCast: {
877       Type *SrcTy = VL0->getOperand(0)->getType();
878
879       // Calculate the cost of this instruction.
880       int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(),
881                                                          VL0->getType(), SrcTy);
882
883       VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
884       int VecCost = TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy);
885       return VecCost - ScalarCost;
886     }
887     case Instruction::FCmp:
888     case Instruction::ICmp:
889     case Instruction::Select:
890     case Instruction::Add:
891     case Instruction::FAdd:
892     case Instruction::Sub:
893     case Instruction::FSub:
894     case Instruction::Mul:
895     case Instruction::FMul:
896     case Instruction::UDiv:
897     case Instruction::SDiv:
898     case Instruction::FDiv:
899     case Instruction::URem:
900     case Instruction::SRem:
901     case Instruction::FRem:
902     case Instruction::Shl:
903     case Instruction::LShr:
904     case Instruction::AShr:
905     case Instruction::And:
906     case Instruction::Or:
907     case Instruction::Xor: {
908       // Calculate the cost of this instruction.
909       int ScalarCost = 0;
910       int VecCost = 0;
911       if (Opcode == Instruction::FCmp || Opcode == Instruction::ICmp ||
912           Opcode == Instruction::Select) {
913         VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
914         ScalarCost = VecTy->getNumElements() *
915         TTI->getCmpSelInstrCost(Opcode, ScalarTy, Builder.getInt1Ty());
916         VecCost = TTI->getCmpSelInstrCost(Opcode, VecTy, MaskTy);
917       } else {
918         ScalarCost = VecTy->getNumElements() *
919         TTI->getArithmeticInstrCost(Opcode, ScalarTy);
920         VecCost = TTI->getArithmeticInstrCost(Opcode, VecTy);
921       }
922       return VecCost - ScalarCost;
923     }
924     case Instruction::Load: {
925       // Cost of wide load - cost of scalar loads.
926       int ScalarLdCost = VecTy->getNumElements() *
927       TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
928       int VecLdCost = TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
929       return VecLdCost - ScalarLdCost;
930     }
931     case Instruction::Store: {
932       // We know that we can merge the stores. Calculate the cost.
933       int ScalarStCost = VecTy->getNumElements() *
934       TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
935       int VecStCost = TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
936       return VecStCost - ScalarStCost;
937     }
938     default:
939       llvm_unreachable("Unknown instruction");
940   }
941 }
942
943 int BoUpSLP::getTreeCost() {
944   int Cost = 0;
945   DEBUG(dbgs() << "SLP: Calculating cost for tree of size " <<
946         VectorizableTree.size() << ".\n");
947
948   // Don't vectorize tiny trees. Small load/store chains or consecutive stores
949   // of constants will be vectoried in SelectionDAG in MergeConsecutiveStores.
950   // The SelectionDAG vectorizer can only handle pairs (trees of height = 2).
951   if (VectorizableTree.size() < 3) {
952     if (!VectorizableTree.size()) {
953       assert(!ExternalUses.size() && "We should not have any external users");
954     }
955     return INT_MAX;
956   }
957
958   unsigned BundleWidth = VectorizableTree[0].Scalars.size();
959
960   for (unsigned i = 0, e = VectorizableTree.size(); i != e; ++i) {
961     int C = getEntryCost(&VectorizableTree[i]);
962     DEBUG(dbgs() << "SLP: Adding cost " << C << " for bundle that starts with "
963           << *VectorizableTree[i].Scalars[0] << " .\n");
964     Cost += C;
965   }
966
967   int ExtractCost = 0;
968   for (UserList::iterator I = ExternalUses.begin(), E = ExternalUses.end();
969        I != E; ++I) {
970
971     VectorType *VecTy = VectorType::get(I->Scalar->getType(), BundleWidth);
972     ExtractCost += TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy,
973                                            I->Lane);
974   }
975
976
977   DEBUG(dbgs() << "SLP: Total Cost " << Cost + ExtractCost<< ".\n");
978   return  Cost + ExtractCost;
979 }
980
981 int BoUpSLP::getGatherCost(Type *Ty) {
982   int Cost = 0;
983   for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
984     Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
985   return Cost;
986 }
987
988 int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) {
989   // Find the type of the operands in VL.
990   Type *ScalarTy = VL[0]->getType();
991   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
992     ScalarTy = SI->getValueOperand()->getType();
993   VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
994   // Find the cost of inserting/extracting values from the vector.
995   return getGatherCost(VecTy);
996 }
997
998 AliasAnalysis::Location BoUpSLP::getLocation(Instruction *I) {
999   if (StoreInst *SI = dyn_cast<StoreInst>(I))
1000     return AA->getLocation(SI);
1001   if (LoadInst *LI = dyn_cast<LoadInst>(I))
1002     return AA->getLocation(LI);
1003   return AliasAnalysis::Location();
1004 }
1005
1006 Value *BoUpSLP::getPointerOperand(Value *I) {
1007   if (LoadInst *LI = dyn_cast<LoadInst>(I))
1008     return LI->getPointerOperand();
1009   if (StoreInst *SI = dyn_cast<StoreInst>(I))
1010     return SI->getPointerOperand();
1011   return 0;
1012 }
1013
1014 unsigned BoUpSLP::getAddressSpaceOperand(Value *I) {
1015   if (LoadInst *L = dyn_cast<LoadInst>(I))
1016     return L->getPointerAddressSpace();
1017   if (StoreInst *S = dyn_cast<StoreInst>(I))
1018     return S->getPointerAddressSpace();
1019   return -1;
1020 }
1021
1022 bool BoUpSLP::isConsecutiveAccess(Value *A, Value *B) {
1023   Value *PtrA = getPointerOperand(A);
1024   Value *PtrB = getPointerOperand(B);
1025   unsigned ASA = getAddressSpaceOperand(A);
1026   unsigned ASB = getAddressSpaceOperand(B);
1027
1028   // Check that the address spaces match and that the pointers are valid.
1029   if (!PtrA || !PtrB || (ASA != ASB))
1030     return false;
1031
1032   // Make sure that A and B are different pointers of the same type.
1033   if (PtrA == PtrB || PtrA->getType() != PtrB->getType())
1034     return false;
1035
1036   unsigned PtrBitWidth = DL->getPointerSizeInBits(ASA);
1037   Type *Ty = cast<PointerType>(PtrA->getType())->getElementType();
1038   APInt Size(PtrBitWidth, DL->getTypeStoreSize(Ty));
1039
1040   APInt OffsetA(PtrBitWidth, 0), OffsetB(PtrBitWidth, 0);
1041   PtrA = PtrA->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetA);
1042   PtrB = PtrB->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetB);
1043
1044   APInt OffsetDelta = OffsetB - OffsetA;
1045
1046   // Check if they are based on the same pointer. That makes the offsets
1047   // sufficient.
1048   if (PtrA == PtrB)
1049     return OffsetDelta == Size;
1050
1051   // Compute the necessary base pointer delta to have the necessary final delta
1052   // equal to the size.
1053   APInt BaseDelta = Size - OffsetDelta;
1054
1055   // Otherwise compute the distance with SCEV between the base pointers.
1056   const SCEV *PtrSCEVA = SE->getSCEV(PtrA);
1057   const SCEV *PtrSCEVB = SE->getSCEV(PtrB);
1058   const SCEV *C = SE->getConstant(BaseDelta);
1059   const SCEV *X = SE->getAddExpr(PtrSCEVA, C);
1060   return X == PtrSCEVB;
1061 }
1062
1063 Value *BoUpSLP::getSinkBarrier(Instruction *Src, Instruction *Dst) {
1064   assert(Src->getParent() == Dst->getParent() && "Not the same BB");
1065   BasicBlock::iterator I = Src, E = Dst;
1066   /// Scan all of the instruction from SRC to DST and check if
1067   /// the source may alias.
1068   for (++I; I != E; ++I) {
1069     // Ignore store instructions that are marked as 'ignore'.
1070     if (MemBarrierIgnoreList.count(I))
1071       continue;
1072     if (Src->mayWriteToMemory()) /* Write */ {
1073       if (!I->mayReadOrWriteMemory())
1074         continue;
1075     } else /* Read */ {
1076       if (!I->mayWriteToMemory())
1077         continue;
1078     }
1079     AliasAnalysis::Location A = getLocation(&*I);
1080     AliasAnalysis::Location B = getLocation(Src);
1081
1082     if (!A.Ptr || !B.Ptr || AA->alias(A, B))
1083       return I;
1084   }
1085   return 0;
1086 }
1087
1088 int BoUpSLP::getLastIndex(ArrayRef<Value *> VL) {
1089   BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
1090   assert(BB == getSameBlock(VL) && BlocksNumbers.count(BB) && "Invalid block");
1091   BlockNumbering &BN = BlocksNumbers[BB];
1092
1093   int MaxIdx = BN.getIndex(BB->getFirstNonPHI());
1094   for (unsigned i = 0, e = VL.size(); i < e; ++i)
1095     MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
1096   return MaxIdx;
1097 }
1098
1099 Instruction *BoUpSLP::getLastInstruction(ArrayRef<Value *> VL) {
1100   BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
1101   assert(BB == getSameBlock(VL) && BlocksNumbers.count(BB) && "Invalid block");
1102   BlockNumbering &BN = BlocksNumbers[BB];
1103
1104   int MaxIdx = BN.getIndex(cast<Instruction>(VL[0]));
1105   for (unsigned i = 1, e = VL.size(); i < e; ++i)
1106     MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
1107   Instruction *I = BN.getInstruction(MaxIdx);
1108   assert(I && "bad location");
1109   return I;
1110 }
1111
1112 void BoUpSLP::setInsertPointAfterBundle(ArrayRef<Value *> VL) {
1113   Instruction *VL0 = cast<Instruction>(VL[0]);
1114   Instruction *LastInst = getLastInstruction(VL);
1115   BasicBlock::iterator NextInst = LastInst;
1116   ++NextInst;
1117   Builder.SetInsertPoint(VL0->getParent(), NextInst);
1118   Builder.SetCurrentDebugLocation(VL0->getDebugLoc());
1119 }
1120
1121 Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
1122   Value *Vec = UndefValue::get(Ty);
1123   // Generate the 'InsertElement' instruction.
1124   for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
1125     Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
1126     if (Instruction *Insrt = dyn_cast<Instruction>(Vec)) {
1127       GatherSeq.insert(Insrt);
1128
1129       // Add to our 'need-to-extract' list.
1130       if (ScalarToTreeEntry.count(VL[i])) {
1131         int Idx = ScalarToTreeEntry[VL[i]];
1132         TreeEntry *E = &VectorizableTree[Idx];
1133         // Find which lane we need to extract.
1134         int FoundLane = -1;
1135         for (unsigned Lane = 0, LE = VL.size(); Lane != LE; ++Lane) {
1136           // Is this the lane of the scalar that we are looking for ?
1137           if (E->Scalars[Lane] == VL[i]) {
1138             FoundLane = Lane;
1139             break;
1140           }
1141         }
1142         assert(FoundLane >= 0 && "Could not find the correct lane");
1143         ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
1144       }
1145     }
1146   }
1147
1148   return Vec;
1149 }
1150
1151 Value *BoUpSLP::alreadyVectorized(ArrayRef<Value *> VL) const {
1152   SmallDenseMap<Value*, int>::const_iterator Entry
1153     = ScalarToTreeEntry.find(VL[0]);
1154   if (Entry != ScalarToTreeEntry.end()) {
1155     int Idx = Entry->second;
1156     const TreeEntry *En = &VectorizableTree[Idx];
1157     if (En->isSame(VL) && En->VectorizedValue)
1158       return En->VectorizedValue;
1159   }
1160   return 0;
1161 }
1162
1163 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
1164   if (ScalarToTreeEntry.count(VL[0])) {
1165     int Idx = ScalarToTreeEntry[VL[0]];
1166     TreeEntry *E = &VectorizableTree[Idx];
1167     if (E->isSame(VL))
1168       return vectorizeTree(E);
1169   }
1170
1171   Type *ScalarTy = VL[0]->getType();
1172   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1173     ScalarTy = SI->getValueOperand()->getType();
1174   VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1175
1176   return Gather(VL, VecTy);
1177 }
1178
1179 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
1180   BuilderLocGuard Guard(Builder);
1181
1182   if (E->VectorizedValue) {
1183     DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
1184     return E->VectorizedValue;
1185   }
1186
1187   Instruction *VL0 = cast<Instruction>(E->Scalars[0]);
1188   Type *ScalarTy = VL0->getType();
1189   if (StoreInst *SI = dyn_cast<StoreInst>(VL0))
1190     ScalarTy = SI->getValueOperand()->getType();
1191   VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size());
1192
1193   if (E->NeedToGather) {
1194     setInsertPointAfterBundle(E->Scalars);
1195     return Gather(E->Scalars, VecTy);
1196   }
1197
1198   unsigned Opcode = VL0->getOpcode();
1199   assert(Opcode == getSameOpcode(E->Scalars) && "Invalid opcode");
1200
1201   switch (Opcode) {
1202     case Instruction::PHI: {
1203       PHINode *PH = dyn_cast<PHINode>(VL0);
1204       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
1205       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1206       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
1207       E->VectorizedValue = NewPhi;
1208
1209       // PHINodes may have multiple entries from the same block. We want to
1210       // visit every block once.
1211       SmallSet<BasicBlock*, 4> VisitedBBs;
1212
1213       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1214         ValueList Operands;
1215         BasicBlock *IBB = PH->getIncomingBlock(i);
1216
1217         if (!VisitedBBs.insert(IBB)) {
1218           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
1219           continue;
1220         }
1221
1222         // Prepare the operand vector.
1223         for (unsigned j = 0; j < E->Scalars.size(); ++j)
1224           Operands.push_back(cast<PHINode>(E->Scalars[j])->
1225                              getIncomingValueForBlock(IBB));
1226
1227         Builder.SetInsertPoint(IBB->getTerminator());
1228         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1229         Value *Vec = vectorizeTree(Operands);
1230         NewPhi->addIncoming(Vec, IBB);
1231       }
1232
1233       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
1234              "Invalid number of incoming values");
1235       return NewPhi;
1236     }
1237
1238     case Instruction::ExtractElement: {
1239       if (CanReuseExtract(E->Scalars)) {
1240         Value *V = VL0->getOperand(0);
1241         E->VectorizedValue = V;
1242         return V;
1243       }
1244       return Gather(E->Scalars, VecTy);
1245     }
1246     case Instruction::ZExt:
1247     case Instruction::SExt:
1248     case Instruction::FPToUI:
1249     case Instruction::FPToSI:
1250     case Instruction::FPExt:
1251     case Instruction::PtrToInt:
1252     case Instruction::IntToPtr:
1253     case Instruction::SIToFP:
1254     case Instruction::UIToFP:
1255     case Instruction::Trunc:
1256     case Instruction::FPTrunc:
1257     case Instruction::BitCast: {
1258       ValueList INVL;
1259       for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1260         INVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1261
1262       setInsertPointAfterBundle(E->Scalars);
1263
1264       Value *InVec = vectorizeTree(INVL);
1265
1266       if (Value *V = alreadyVectorized(E->Scalars))
1267         return V;
1268
1269       CastInst *CI = dyn_cast<CastInst>(VL0);
1270       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
1271       E->VectorizedValue = V;
1272       return V;
1273     }
1274     case Instruction::FCmp:
1275     case Instruction::ICmp: {
1276       ValueList LHSV, RHSV;
1277       for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1278         LHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1279         RHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1280       }
1281
1282       setInsertPointAfterBundle(E->Scalars);
1283
1284       Value *L = vectorizeTree(LHSV);
1285       Value *R = vectorizeTree(RHSV);
1286
1287       if (Value *V = alreadyVectorized(E->Scalars))
1288         return V;
1289
1290       CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
1291       Value *V;
1292       if (Opcode == Instruction::FCmp)
1293         V = Builder.CreateFCmp(P0, L, R);
1294       else
1295         V = Builder.CreateICmp(P0, L, R);
1296
1297       E->VectorizedValue = V;
1298       return V;
1299     }
1300     case Instruction::Select: {
1301       ValueList TrueVec, FalseVec, CondVec;
1302       for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1303         CondVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1304         TrueVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1305         FalseVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(2));
1306       }
1307
1308       setInsertPointAfterBundle(E->Scalars);
1309
1310       Value *Cond = vectorizeTree(CondVec);
1311       Value *True = vectorizeTree(TrueVec);
1312       Value *False = vectorizeTree(FalseVec);
1313
1314       if (Value *V = alreadyVectorized(E->Scalars))
1315         return V;
1316
1317       Value *V = Builder.CreateSelect(Cond, True, False);
1318       E->VectorizedValue = V;
1319       return V;
1320     }
1321     case Instruction::Add:
1322     case Instruction::FAdd:
1323     case Instruction::Sub:
1324     case Instruction::FSub:
1325     case Instruction::Mul:
1326     case Instruction::FMul:
1327     case Instruction::UDiv:
1328     case Instruction::SDiv:
1329     case Instruction::FDiv:
1330     case Instruction::URem:
1331     case Instruction::SRem:
1332     case Instruction::FRem:
1333     case Instruction::Shl:
1334     case Instruction::LShr:
1335     case Instruction::AShr:
1336     case Instruction::And:
1337     case Instruction::Or:
1338     case Instruction::Xor: {
1339       ValueList LHSVL, RHSVL;
1340       for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1341         LHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1342         RHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1343       }
1344
1345       setInsertPointAfterBundle(E->Scalars);
1346
1347       Value *LHS = vectorizeTree(LHSVL);
1348       Value *RHS = vectorizeTree(RHSVL);
1349
1350       if (LHS == RHS && isa<Instruction>(LHS)) {
1351         assert((VL0->getOperand(0) == VL0->getOperand(1)) && "Invalid order");
1352       }
1353
1354       if (Value *V = alreadyVectorized(E->Scalars))
1355         return V;
1356
1357       BinaryOperator *BinOp = cast<BinaryOperator>(VL0);
1358       Value *V = Builder.CreateBinOp(BinOp->getOpcode(), LHS, RHS);
1359       E->VectorizedValue = V;
1360       return V;
1361     }
1362     case Instruction::Load: {
1363       // Loads are inserted at the head of the tree because we don't want to
1364       // sink them all the way down past store instructions.
1365       setInsertPointAfterBundle(E->Scalars);
1366
1367       LoadInst *LI = cast<LoadInst>(VL0);
1368       Value *VecPtr =
1369       Builder.CreateBitCast(LI->getPointerOperand(), VecTy->getPointerTo());
1370       unsigned Alignment = LI->getAlignment();
1371       LI = Builder.CreateLoad(VecPtr);
1372       LI->setAlignment(Alignment);
1373       E->VectorizedValue = LI;
1374       return LI;
1375     }
1376     case Instruction::Store: {
1377       StoreInst *SI = cast<StoreInst>(VL0);
1378       unsigned Alignment = SI->getAlignment();
1379
1380       ValueList ValueOp;
1381       for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1382         ValueOp.push_back(cast<StoreInst>(E->Scalars[i])->getValueOperand());
1383
1384       setInsertPointAfterBundle(E->Scalars);
1385
1386       Value *VecValue = vectorizeTree(ValueOp);
1387       Value *VecPtr =
1388       Builder.CreateBitCast(SI->getPointerOperand(), VecTy->getPointerTo());
1389       StoreInst *S = Builder.CreateStore(VecValue, VecPtr);
1390       S->setAlignment(Alignment);
1391       E->VectorizedValue = S;
1392       return S;
1393     }
1394     default:
1395     llvm_unreachable("unknown inst");
1396   }
1397   return 0;
1398 }
1399
1400 Value *BoUpSLP::vectorizeTree() {
1401   Builder.SetInsertPoint(F->getEntryBlock().begin());
1402   vectorizeTree(&VectorizableTree[0]);
1403
1404   DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() << " values .\n");
1405
1406   // Extract all of the elements with the external uses.
1407   for (UserList::iterator it = ExternalUses.begin(), e = ExternalUses.end();
1408        it != e; ++it) {
1409     Value *Scalar = it->Scalar;
1410     llvm::User *User = it->User;
1411
1412     // Skip users that we already RAUW. This happens when one instruction
1413     // has multiple uses of the same value.
1414     if (std::find(Scalar->use_begin(), Scalar->use_end(), User) ==
1415         Scalar->use_end())
1416       continue;
1417     assert(ScalarToTreeEntry.count(Scalar) && "Invalid scalar");
1418
1419     int Idx = ScalarToTreeEntry[Scalar];
1420     TreeEntry *E = &VectorizableTree[Idx];
1421     assert(!E->NeedToGather && "Extracting from a gather list");
1422
1423     Value *Vec = E->VectorizedValue;
1424     assert(Vec && "Can't find vectorizable value");
1425
1426     Value *Lane = Builder.getInt32(it->Lane);
1427     // Generate extracts for out-of-tree users.
1428     // Find the insertion point for the extractelement lane.
1429     if (PHINode *PN = dyn_cast<PHINode>(Vec)) {
1430       Builder.SetInsertPoint(PN->getParent()->getFirstInsertionPt());
1431       Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1432       User->replaceUsesOfWith(Scalar, Ex);
1433     } else if (isa<Instruction>(Vec)){
1434       if (PHINode *PH = dyn_cast<PHINode>(User)) {
1435         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
1436           if (PH->getIncomingValue(i) == Scalar) {
1437             Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
1438             Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1439             PH->setOperand(i, Ex);
1440           }
1441         }
1442       } else {
1443         Builder.SetInsertPoint(cast<Instruction>(User));
1444         Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1445         User->replaceUsesOfWith(Scalar, Ex);
1446      }
1447     } else {
1448       Builder.SetInsertPoint(F->getEntryBlock().begin());
1449       Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1450       User->replaceUsesOfWith(Scalar, Ex);
1451     }
1452
1453     DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
1454   }
1455
1456   // For each vectorized value:
1457   for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
1458     TreeEntry *Entry = &VectorizableTree[EIdx];
1459
1460     // For each lane:
1461     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
1462       Value *Scalar = Entry->Scalars[Lane];
1463
1464       // No need to handle users of gathered values.
1465       if (Entry->NeedToGather)
1466         continue;
1467
1468       assert(Entry->VectorizedValue && "Can't find vectorizable value");
1469
1470       Type *Ty = Scalar->getType();
1471       if (!Ty->isVoidTy()) {
1472         for (Value::use_iterator User = Scalar->use_begin(),
1473              UE = Scalar->use_end(); User != UE; ++User) {
1474           DEBUG(dbgs() << "SLP: \tvalidating user:" << **User << ".\n");
1475           assert(!MustGather.count(*User) &&
1476                  "Replacing gathered value with undef");
1477
1478           assert((ScalarToTreeEntry.count(*User) ||
1479                   // It is legal to replace the reduction users by undef.
1480                   (RdxOps && RdxOps->count(*User))) &&
1481                  "Replacing out-of-tree value with undef");
1482         }
1483         Value *Undef = UndefValue::get(Ty);
1484         Scalar->replaceAllUsesWith(Undef);
1485       }
1486       DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
1487       cast<Instruction>(Scalar)->eraseFromParent();
1488     }
1489   }
1490
1491   for (Function::iterator it = F->begin(), e = F->end(); it != e; ++it) {
1492     BlocksNumbers[it].forget();
1493   }
1494   Builder.ClearInsertionPoint();
1495
1496   return VectorizableTree[0].VectorizedValue;
1497 }
1498
1499 void BoUpSLP::optimizeGatherSequence() {
1500   DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
1501         << " gather sequences instructions.\n");
1502   // LICM InsertElementInst sequences.
1503   for (SetVector<Instruction *>::iterator it = GatherSeq.begin(),
1504        e = GatherSeq.end(); it != e; ++it) {
1505     InsertElementInst *Insert = dyn_cast<InsertElementInst>(*it);
1506
1507     if (!Insert)
1508       continue;
1509
1510     // Check if this block is inside a loop.
1511     Loop *L = LI->getLoopFor(Insert->getParent());
1512     if (!L)
1513       continue;
1514
1515     // Check if it has a preheader.
1516     BasicBlock *PreHeader = L->getLoopPreheader();
1517     if (!PreHeader)
1518       continue;
1519
1520     // If the vector or the element that we insert into it are
1521     // instructions that are defined in this basic block then we can't
1522     // hoist this instruction.
1523     Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
1524     Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
1525     if (CurrVec && L->contains(CurrVec))
1526       continue;
1527     if (NewElem && L->contains(NewElem))
1528       continue;
1529
1530     // We can hoist this instruction. Move it to the pre-header.
1531     Insert->moveBefore(PreHeader->getTerminator());
1532   }
1533
1534   // Perform O(N^2) search over the gather sequences and merge identical
1535   // instructions. TODO: We can further optimize this scan if we split the
1536   // instructions into different buckets based on the insert lane.
1537   SmallPtrSet<Instruction*, 16> Visited;
1538   SmallVector<Instruction*, 16> ToRemove;
1539   ReversePostOrderTraversal<Function*> RPOT(F);
1540   for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
1541        E = RPOT.end(); I != E; ++I) {
1542     BasicBlock *BB = *I;
1543     // For all instructions in the function:
1544     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1545       Instruction *In = it;
1546       if ((!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In)) ||
1547           !GatherSeq.count(In))
1548         continue;
1549
1550       // Check if we can replace this instruction with any of the
1551       // visited instructions.
1552       for (SmallPtrSet<Instruction*, 16>::iterator v = Visited.begin(),
1553            ve = Visited.end(); v != ve; ++v) {
1554         if (In->isIdenticalTo(*v) &&
1555             DT->dominates((*v)->getParent(), In->getParent())) {
1556           In->replaceAllUsesWith(*v);
1557           ToRemove.push_back(In);
1558           In = 0;
1559           break;
1560         }
1561       }
1562       if (In)
1563         Visited.insert(In);
1564     }
1565   }
1566
1567   // Erase all of the instructions that we RAUWed.
1568   for (SmallVectorImpl<Instruction *>::iterator v = ToRemove.begin(),
1569        ve = ToRemove.end(); v != ve; ++v) {
1570     assert((*v)->getNumUses() == 0 && "Can't remove instructions with uses");
1571     (*v)->eraseFromParent();
1572   }
1573 }
1574
1575 /// The SLPVectorizer Pass.
1576 struct SLPVectorizer : public FunctionPass {
1577   typedef SmallVector<StoreInst *, 8> StoreList;
1578   typedef MapVector<Value *, StoreList> StoreListMap;
1579
1580   /// Pass identification, replacement for typeid
1581   static char ID;
1582
1583   explicit SLPVectorizer() : FunctionPass(ID) {
1584     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
1585   }
1586
1587   ScalarEvolution *SE;
1588   DataLayout *DL;
1589   TargetTransformInfo *TTI;
1590   AliasAnalysis *AA;
1591   LoopInfo *LI;
1592   DominatorTree *DT;
1593
1594   virtual bool runOnFunction(Function &F) {
1595     SE = &getAnalysis<ScalarEvolution>();
1596     DL = getAnalysisIfAvailable<DataLayout>();
1597     TTI = &getAnalysis<TargetTransformInfo>();
1598     AA = &getAnalysis<AliasAnalysis>();
1599     LI = &getAnalysis<LoopInfo>();
1600     DT = &getAnalysis<DominatorTree>();
1601
1602     StoreRefs.clear();
1603     bool Changed = false;
1604
1605     // If the target claims to have no vector registers don't attempt
1606     // vectorization.
1607     if (!TTI->getNumberOfRegisters(true))
1608       return false;
1609
1610     // Must have DataLayout. We can't require it because some tests run w/o
1611     // triple.
1612     if (!DL)
1613       return false;
1614
1615     // Don't vectorize when the attribute NoImplicitFloat is used.
1616     if (F.hasFnAttribute(Attribute::NoImplicitFloat))
1617       return false;
1618
1619     DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
1620
1621     // Use the bollom up slp vectorizer to construct chains that start with
1622     // he store instructions.
1623     BoUpSLP R(&F, SE, DL, TTI, AA, LI, DT);
1624
1625     // Scan the blocks in the function in post order.
1626     for (po_iterator<BasicBlock*> it = po_begin(&F.getEntryBlock()),
1627          e = po_end(&F.getEntryBlock()); it != e; ++it) {
1628       BasicBlock *BB = *it;
1629
1630       // Vectorize trees that end at stores.
1631       if (unsigned count = collectStores(BB, R)) {
1632         (void)count;
1633         DEBUG(dbgs() << "SLP: Found " << count << " stores to vectorize.\n");
1634         Changed |= vectorizeStoreChains(R);
1635       }
1636
1637       // Vectorize trees that end at reductions.
1638       Changed |= vectorizeChainsInBlock(BB, R);
1639     }
1640
1641     if (Changed) {
1642       R.optimizeGatherSequence();
1643       DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
1644       DEBUG(verifyFunction(F));
1645     }
1646     return Changed;
1647   }
1648
1649   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1650     FunctionPass::getAnalysisUsage(AU);
1651     AU.addRequired<ScalarEvolution>();
1652     AU.addRequired<AliasAnalysis>();
1653     AU.addRequired<TargetTransformInfo>();
1654     AU.addRequired<LoopInfo>();
1655     AU.addRequired<DominatorTree>();
1656     AU.addPreserved<LoopInfo>();
1657     AU.addPreserved<DominatorTree>();
1658     AU.setPreservesCFG();
1659   }
1660
1661 private:
1662
1663   /// \brief Collect memory references and sort them according to their base
1664   /// object. We sort the stores to their base objects to reduce the cost of the
1665   /// quadratic search on the stores. TODO: We can further reduce this cost
1666   /// if we flush the chain creation every time we run into a memory barrier.
1667   unsigned collectStores(BasicBlock *BB, BoUpSLP &R);
1668
1669   /// \brief Try to vectorize a chain that starts at two arithmetic instrs.
1670   bool tryToVectorizePair(Value *A, Value *B, BoUpSLP &R);
1671
1672   /// \brief Try to vectorize a list of operands.
1673   /// \returns true if a value was vectorized.
1674   bool tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R);
1675
1676   /// \brief Try to vectorize a chain that may start at the operands of \V;
1677   bool tryToVectorize(BinaryOperator *V, BoUpSLP &R);
1678
1679   /// \brief Vectorize the stores that were collected in StoreRefs.
1680   bool vectorizeStoreChains(BoUpSLP &R);
1681
1682   /// \brief Scan the basic block and look for patterns that are likely to start
1683   /// a vectorization chain.
1684   bool vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R);
1685
1686   bool vectorizeStoreChain(ArrayRef<Value *> Chain, int CostThreshold,
1687                            BoUpSLP &R);
1688
1689   bool vectorizeStores(ArrayRef<StoreInst *> Stores, int costThreshold,
1690                        BoUpSLP &R);
1691 private:
1692   StoreListMap StoreRefs;
1693 };
1694
1695 bool SLPVectorizer::vectorizeStoreChain(ArrayRef<Value *> Chain,
1696                                           int CostThreshold, BoUpSLP &R) {
1697   unsigned ChainLen = Chain.size();
1698   DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
1699         << "\n");
1700   Type *StoreTy = cast<StoreInst>(Chain[0])->getValueOperand()->getType();
1701   unsigned Sz = DL->getTypeSizeInBits(StoreTy);
1702   unsigned VF = MinVecRegSize / Sz;
1703
1704   if (!isPowerOf2_32(Sz) || VF < 2)
1705     return false;
1706
1707   bool Changed = false;
1708   // Look for profitable vectorizable trees at all offsets, starting at zero.
1709   for (unsigned i = 0, e = ChainLen; i < e; ++i) {
1710     if (i + VF > e)
1711       break;
1712     DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
1713           << "\n");
1714     ArrayRef<Value *> Operands = Chain.slice(i, VF);
1715
1716     R.buildTree(Operands);
1717
1718     int Cost = R.getTreeCost();
1719
1720     DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
1721     if (Cost < CostThreshold) {
1722       DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
1723       R.vectorizeTree();
1724
1725       // Move to the next bundle.
1726       i += VF - 1;
1727       Changed = true;
1728     }
1729   }
1730
1731     return Changed;
1732 }
1733
1734 bool SLPVectorizer::vectorizeStores(ArrayRef<StoreInst *> Stores,
1735                                     int costThreshold, BoUpSLP &R) {
1736   SetVector<Value *> Heads, Tails;
1737   SmallDenseMap<Value *, Value *> ConsecutiveChain;
1738
1739   // We may run into multiple chains that merge into a single chain. We mark the
1740   // stores that we vectorized so that we don't visit the same store twice.
1741   BoUpSLP::ValueSet VectorizedStores;
1742   bool Changed = false;
1743
1744   // Do a quadratic search on all of the given stores and find
1745   // all of the pairs of stores that follow each other.
1746   for (unsigned i = 0, e = Stores.size(); i < e; ++i) {
1747     for (unsigned j = 0; j < e; ++j) {
1748       if (i == j)
1749         continue;
1750
1751       if (R.isConsecutiveAccess(Stores[i], Stores[j])) {
1752         Tails.insert(Stores[j]);
1753         Heads.insert(Stores[i]);
1754         ConsecutiveChain[Stores[i]] = Stores[j];
1755       }
1756     }
1757   }
1758
1759   // For stores that start but don't end a link in the chain:
1760   for (SetVector<Value *>::iterator it = Heads.begin(), e = Heads.end();
1761        it != e; ++it) {
1762     if (Tails.count(*it))
1763       continue;
1764
1765     // We found a store instr that starts a chain. Now follow the chain and try
1766     // to vectorize it.
1767     BoUpSLP::ValueList Operands;
1768     Value *I = *it;
1769     // Collect the chain into a list.
1770     while (Tails.count(I) || Heads.count(I)) {
1771       if (VectorizedStores.count(I))
1772         break;
1773       Operands.push_back(I);
1774       // Move to the next value in the chain.
1775       I = ConsecutiveChain[I];
1776     }
1777
1778     bool Vectorized = vectorizeStoreChain(Operands, costThreshold, R);
1779
1780     // Mark the vectorized stores so that we don't vectorize them again.
1781     if (Vectorized)
1782       VectorizedStores.insert(Operands.begin(), Operands.end());
1783     Changed |= Vectorized;
1784   }
1785
1786   return Changed;
1787 }
1788
1789
1790 unsigned SLPVectorizer::collectStores(BasicBlock *BB, BoUpSLP &R) {
1791   unsigned count = 0;
1792   StoreRefs.clear();
1793   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1794     StoreInst *SI = dyn_cast<StoreInst>(it);
1795     if (!SI)
1796       continue;
1797
1798     // Check that the pointer points to scalars.
1799     Type *Ty = SI->getValueOperand()->getType();
1800     if (Ty->isAggregateType() || Ty->isVectorTy())
1801       return 0;
1802
1803     // Find the base of the GEP.
1804     Value *Ptr = SI->getPointerOperand();
1805     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
1806       Ptr = GEP->getPointerOperand();
1807
1808     // Save the store locations.
1809     StoreRefs[Ptr].push_back(SI);
1810     count++;
1811   }
1812   return count;
1813 }
1814
1815 bool SLPVectorizer::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
1816   if (!A || !B)
1817     return false;
1818   Value *VL[] = { A, B };
1819   return tryToVectorizeList(VL, R);
1820 }
1821
1822 bool SLPVectorizer::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R) {
1823   if (VL.size() < 2)
1824     return false;
1825
1826   DEBUG(dbgs() << "SLP: Vectorizing a list of length = " << VL.size() << ".\n");
1827
1828   // Check that all of the parts are scalar instructions of the same type.
1829   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
1830   if (!I0)
1831     return false;
1832
1833   unsigned Opcode0 = I0->getOpcode();
1834   
1835   Type *Ty0 = I0->getType();
1836   unsigned Sz = DL->getTypeSizeInBits(Ty0);
1837   unsigned VF = MinVecRegSize / Sz;
1838
1839   for (int i = 0, e = VL.size(); i < e; ++i) {
1840     Type *Ty = VL[i]->getType();
1841     if (Ty->isAggregateType() || Ty->isVectorTy())
1842       return false;
1843     Instruction *Inst = dyn_cast<Instruction>(VL[i]);
1844     if (!Inst || Inst->getOpcode() != Opcode0)
1845       return false;
1846   }
1847
1848   bool Changed = false;
1849     
1850   for (unsigned i = 0, e = VL.size(); i < e; ++i) {
1851     unsigned OpsWidth = 0;
1852       
1853     if (i + VF > e) 
1854       OpsWidth = e - i;
1855     else
1856       OpsWidth = VF;
1857
1858     if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
1859       break;
1860
1861     DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations " << "\n");
1862     ArrayRef<Value *> Ops = VL.slice(i, OpsWidth);
1863       
1864     R.buildTree(Ops);
1865     int Cost = R.getTreeCost();
1866        
1867     if (Cost < -SLPCostThreshold) {
1868       DEBUG(dbgs() << "SLP: Vectorizing pair at cost:" << Cost << ".\n");
1869       R.vectorizeTree();
1870         
1871       // Move to the next bundle.
1872       i += VF - 1;
1873       Changed = true;
1874     }
1875   }
1876     
1877   return Changed; 
1878 }
1879
1880 bool SLPVectorizer::tryToVectorize(BinaryOperator *V, BoUpSLP &R) {
1881   if (!V)
1882     return false;
1883
1884   // Try to vectorize V.
1885   if (tryToVectorizePair(V->getOperand(0), V->getOperand(1), R))
1886     return true;
1887
1888   BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0));
1889   BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1));
1890   // Try to skip B.
1891   if (B && B->hasOneUse()) {
1892     BinaryOperator *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
1893     BinaryOperator *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
1894     if (tryToVectorizePair(A, B0, R)) {
1895       B->moveBefore(V);
1896       return true;
1897     }
1898     if (tryToVectorizePair(A, B1, R)) {
1899       B->moveBefore(V);
1900       return true;
1901     }
1902   }
1903
1904   // Try to skip A.
1905   if (A && A->hasOneUse()) {
1906     BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
1907     BinaryOperator *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
1908     if (tryToVectorizePair(A0, B, R)) {
1909       A->moveBefore(V);
1910       return true;
1911     }
1912     if (tryToVectorizePair(A1, B, R)) {
1913       A->moveBefore(V);
1914       return true;
1915     }
1916   }
1917   return 0;
1918 }
1919
1920 /// \brief Generate a shuffle mask to be used in a reduction tree.
1921 ///
1922 /// \param VecLen The length of the vector to be reduced.
1923 /// \param NumEltsToRdx The number of elements that should be reduced in the
1924 ///        vector.
1925 /// \param IsPairwise Whether the reduction is a pairwise or splitting
1926 ///        reduction. A pairwise reduction will generate a mask of 
1927 ///        <0,2,...> or <1,3,..> while a splitting reduction will generate
1928 ///        <2,3, undef,undef> for a vector of 4 and NumElts = 2.
1929 /// \param IsLeft True will generate a mask of even elements, odd otherwise.
1930 static Value *createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx,
1931                                    bool IsPairwise, bool IsLeft,
1932                                    IRBuilder<> &Builder) {
1933   assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask");
1934
1935   SmallVector<Constant *, 32> ShuffleMask(
1936       VecLen, UndefValue::get(Builder.getInt32Ty()));
1937
1938   if (IsPairwise)
1939     // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
1940     for (unsigned i = 0; i != NumEltsToRdx; ++i)
1941       ShuffleMask[i] = Builder.getInt32(2 * i + !IsLeft);
1942   else
1943     // Move the upper half of the vector to the lower half.
1944     for (unsigned i = 0; i != NumEltsToRdx; ++i)
1945       ShuffleMask[i] = Builder.getInt32(NumEltsToRdx + i);
1946
1947   return ConstantVector::get(ShuffleMask);
1948 }
1949
1950
1951 /// Model horizontal reductions.
1952 ///
1953 /// A horizontal reduction is a tree of reduction operations (currently add and
1954 /// fadd) that has operations that can be put into a vector as its leaf.
1955 /// For example, this tree:
1956 ///
1957 /// mul mul mul mul
1958 ///  \  /    \  /
1959 ///   +       +
1960 ///    \     /
1961 ///       +
1962 /// This tree has "mul" as its reduced values and "+" as its reduction
1963 /// operations. A reduction might be feeding into a store or a binary operation
1964 /// feeding a phi.
1965 ///    ...
1966 ///    \  /
1967 ///     +
1968 ///     |
1969 ///  phi +=
1970 ///
1971 ///  Or:
1972 ///    ...
1973 ///    \  /
1974 ///     +
1975 ///     |
1976 ///   *p =
1977 ///
1978 class HorizontalReduction {
1979   SmallPtrSet<Value *, 16> ReductionOps;
1980   SmallVector<Value *, 32> ReducedVals;
1981
1982   BinaryOperator *ReductionRoot;
1983   PHINode *ReductionPHI;
1984
1985   /// The opcode of the reduction.
1986   unsigned ReductionOpcode;
1987   /// The opcode of the values we perform a reduction on.
1988   unsigned ReducedValueOpcode;
1989   /// The width of one full horizontal reduction operation.
1990   unsigned ReduxWidth;
1991   /// Should we model this reduction as a pairwise reduction tree or a tree that
1992   /// splits the vector in halves and adds those halves.
1993   bool IsPairwiseReduction;
1994
1995 public:
1996   HorizontalReduction()
1997     : ReductionRoot(0), ReductionPHI(0), ReductionOpcode(0),
1998     ReducedValueOpcode(0), ReduxWidth(0), IsPairwiseReduction(false) {}
1999
2000   /// \brief Try to find a reduction tree.
2001   bool matchAssociativeReduction(PHINode *Phi, BinaryOperator *B,
2002                                  DataLayout *DL) {
2003     assert((!Phi ||
2004             std::find(Phi->op_begin(), Phi->op_end(), B) != Phi->op_end()) &&
2005            "Thi phi needs to use the binary operator");
2006
2007     // We could have a initial reductions that is not an add.
2008     //  r *= v1 + v2 + v3 + v4
2009     // In such a case start looking for a tree rooted in the first '+'.
2010     if (Phi) {
2011       if (B->getOperand(0) == Phi) {
2012         Phi = 0;
2013         B = dyn_cast<BinaryOperator>(B->getOperand(1));
2014       } else if (B->getOperand(1) == Phi) {
2015         Phi = 0;
2016         B = dyn_cast<BinaryOperator>(B->getOperand(0));
2017       }
2018     }
2019
2020     if (!B)
2021       return false;
2022
2023     Type *Ty = B->getType();
2024     if (Ty->isVectorTy())
2025       return false;
2026
2027     ReductionOpcode = B->getOpcode();
2028     ReducedValueOpcode = 0;
2029     ReduxWidth = MinVecRegSize / DL->getTypeSizeInBits(Ty);
2030     ReductionRoot = B;
2031     ReductionPHI = Phi;
2032
2033     if (ReduxWidth < 4)
2034       return false;
2035
2036     // We currently only support adds.
2037     if (ReductionOpcode != Instruction::Add &&
2038         ReductionOpcode != Instruction::FAdd)
2039       return false;
2040
2041     // Post order traverse the reduction tree starting at B. We only handle true
2042     // trees containing only binary operators.
2043     SmallVector<std::pair<BinaryOperator *, unsigned>, 32> Stack;
2044     Stack.push_back(std::make_pair(B, 0));
2045     while (!Stack.empty()) {
2046       BinaryOperator *TreeN = Stack.back().first;
2047       unsigned EdgeToVist = Stack.back().second++;
2048       bool IsReducedValue = TreeN->getOpcode() != ReductionOpcode;
2049
2050       // Only handle trees in the current basic block.
2051       if (TreeN->getParent() != B->getParent())
2052         return false;
2053
2054       // Each tree node needs to have one user except for the ultimate
2055       // reduction.
2056       if (!TreeN->hasOneUse() && TreeN != B)
2057         return false;
2058
2059       // Postorder vist.
2060       if (EdgeToVist == 2 || IsReducedValue) {
2061         if (IsReducedValue) {
2062           // Make sure that the opcodes of the operations that we are going to
2063           // reduce match.
2064           if (!ReducedValueOpcode)
2065             ReducedValueOpcode = TreeN->getOpcode();
2066           else if (ReducedValueOpcode != TreeN->getOpcode())
2067             return false;
2068           ReducedVals.push_back(TreeN);
2069         } else {
2070           // We need to be able to reassociate the adds.
2071           if (!TreeN->isAssociative())
2072             return false;
2073           ReductionOps.insert(TreeN);
2074         }
2075         // Retract.
2076         Stack.pop_back();
2077         continue;
2078       }
2079
2080       // Visit left or right.
2081       Value *NextV = TreeN->getOperand(EdgeToVist);
2082       BinaryOperator *Next = dyn_cast<BinaryOperator>(NextV);
2083       if (Next)
2084         Stack.push_back(std::make_pair(Next, 0));
2085       else if (NextV != Phi)
2086         return false;
2087     }
2088     return true;
2089   }
2090
2091   /// \brief Attempt to vectorize the tree found by
2092   /// matchAssociativeReduction.
2093   bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
2094     if (ReducedVals.empty())
2095       return false;
2096
2097     unsigned NumReducedVals = ReducedVals.size();
2098     if (NumReducedVals < ReduxWidth)
2099       return false;
2100
2101     Value *VectorizedTree = 0;
2102     IRBuilder<> Builder(ReductionRoot);
2103     FastMathFlags Unsafe;
2104     Unsafe.setUnsafeAlgebra();
2105     Builder.SetFastMathFlags(Unsafe);
2106     unsigned i = 0;
2107
2108     for (; i < NumReducedVals - ReduxWidth + 1; i += ReduxWidth) {
2109       ArrayRef<Value *> ValsToReduce(&ReducedVals[i], ReduxWidth);
2110       V.buildTree(ValsToReduce, &ReductionOps);
2111
2112       // Estimate cost.
2113       int Cost = V.getTreeCost() + getReductionCost(TTI, ReducedVals[i]);
2114       if (Cost >= -SLPCostThreshold)
2115         break;
2116
2117       DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" << Cost
2118                    << ". (HorRdx)\n");
2119
2120       // Vectorize a tree.
2121       DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
2122       Value *VectorizedRoot = V.vectorizeTree();
2123
2124       // Emit a reduction.
2125       Value *ReducedSubTree = emitReduction(VectorizedRoot, Builder);
2126       if (VectorizedTree) {
2127         Builder.SetCurrentDebugLocation(Loc);
2128         VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
2129                                      ReducedSubTree, "bin.rdx");
2130       } else
2131         VectorizedTree = ReducedSubTree;
2132     }
2133
2134     if (VectorizedTree) {
2135       // Finish the reduction.
2136       for (; i < NumReducedVals; ++i) {
2137         Builder.SetCurrentDebugLocation(
2138           cast<Instruction>(ReducedVals[i])->getDebugLoc());
2139         VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
2140                                      ReducedVals[i]);
2141       }
2142       // Update users.
2143       if (ReductionPHI) {
2144         assert(ReductionRoot != NULL && "Need a reduction operation");
2145         ReductionRoot->setOperand(0, VectorizedTree);
2146         ReductionRoot->setOperand(1, ReductionPHI);
2147       } else
2148         ReductionRoot->replaceAllUsesWith(VectorizedTree);
2149     }
2150     return VectorizedTree != 0;
2151   }
2152
2153 private:
2154
2155   /// \brief Calcuate the cost of a reduction.
2156   int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal) {
2157     Type *ScalarTy = FirstReducedVal->getType();
2158     Type *VecTy = VectorType::get(ScalarTy, ReduxWidth);
2159
2160     int PairwiseRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, true);
2161     int SplittingRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, false);
2162
2163     IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
2164     int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
2165
2166     int ScalarReduxCost =
2167         ReduxWidth * TTI->getArithmeticInstrCost(ReductionOpcode, VecTy);
2168
2169     DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost
2170                  << " for reduction that starts with " << *FirstReducedVal
2171                  << " (It is a "
2172                  << (IsPairwiseReduction ? "pairwise" : "splitting")
2173                  << " reduction)\n");
2174
2175     return VecReduxCost - ScalarReduxCost;
2176   }
2177
2178   static Value *createBinOp(IRBuilder<> &Builder, unsigned Opcode, Value *L,
2179                             Value *R, const Twine &Name = "") {
2180     if (Opcode == Instruction::FAdd)
2181       return Builder.CreateFAdd(L, R, Name);
2182     return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, L, R, Name);
2183   }
2184
2185   /// \brief Emit a horizontal reduction of the vectorized value.
2186   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder) {
2187     assert(VectorizedValue && "Need to have a vectorized tree node");
2188     Instruction *ValToReduce = dyn_cast<Instruction>(VectorizedValue);
2189     assert(isPowerOf2_32(ReduxWidth) &&
2190            "We only handle power-of-two reductions for now");
2191
2192     SmallVector<Constant *, 32> ShuffleMask(ReduxWidth, 0);
2193     Value *TmpVec = ValToReduce;
2194     for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
2195       if (IsPairwiseReduction) {
2196         Value *LeftMask =
2197           createRdxShuffleMask(ReduxWidth, i, true, true, Builder);
2198         Value *RightMask =
2199           createRdxShuffleMask(ReduxWidth, i, true, false, Builder);
2200
2201         Value *LeftShuf = Builder.CreateShuffleVector(
2202           TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l");
2203         Value *RightShuf = Builder.CreateShuffleVector(
2204           TmpVec, UndefValue::get(TmpVec->getType()), (RightMask),
2205           "rdx.shuf.r");
2206         TmpVec = createBinOp(Builder, ReductionOpcode, LeftShuf, RightShuf,
2207                              "bin.rdx");
2208       } else {
2209         Value *UpperHalf =
2210           createRdxShuffleMask(ReduxWidth, i, false, false, Builder);
2211         Value *Shuf = Builder.CreateShuffleVector(
2212           TmpVec, UndefValue::get(TmpVec->getType()), UpperHalf, "rdx.shuf");
2213         TmpVec = createBinOp(Builder, ReductionOpcode, TmpVec, Shuf, "bin.rdx");
2214       }
2215     }
2216
2217     // The result is in the first element of the vector.
2218     return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
2219   }
2220 };
2221
2222 /// \brief Recognize construction of vectors like
2223 ///  %ra = insertelement <4 x float> undef, float %s0, i32 0
2224 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
2225 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
2226 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
2227 ///
2228 /// Returns true if it matches
2229 ///
2230 static bool findBuildVector(InsertElementInst *IE,
2231                             SmallVectorImpl<Value *> &Ops) {
2232   if (!isa<UndefValue>(IE->getOperand(0)))
2233     return false;
2234
2235   while (true) {
2236     Ops.push_back(IE->getOperand(1));
2237
2238     if (IE->use_empty())
2239       return false;
2240
2241     InsertElementInst *NextUse = dyn_cast<InsertElementInst>(IE->use_back());
2242     if (!NextUse)
2243       return true;
2244
2245     // If this isn't the final use, make sure the next insertelement is the only
2246     // use. It's OK if the final constructed vector is used multiple times
2247     if (!IE->hasOneUse())
2248       return false;
2249
2250     IE = NextUse;
2251   }
2252
2253   return false;
2254 }
2255
2256 bool SLPVectorizer::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
2257   bool Changed = false;
2258   SmallVector<Value *, 4> Incoming;
2259   SmallSet<Instruction *, 16> VisitedInstrs;
2260
2261   // Collect the incoming values from the PHIs.
2262   for (BasicBlock::iterator instr = BB->begin(), ie = BB->end(); instr != ie;
2263        ++instr) {
2264     PHINode *P = dyn_cast<PHINode>(instr);
2265
2266     if (!P)
2267       break;
2268
2269     // We may go through BB multiple times so skip the one we have checked.
2270     if (!VisitedInstrs.insert(instr))
2271       continue;
2272
2273     // Stop constructing the list when you reach a different type.
2274     if (Incoming.size() && P->getType() != Incoming[0]->getType()) {
2275       if (tryToVectorizeList(Incoming, R)) {
2276         // We would like to start over since some instructions are deleted
2277         // and the iterator may become invalid value.
2278         Changed = true;
2279         instr = BB->begin();
2280         ie = BB->end();
2281       }
2282
2283       Incoming.clear();
2284     }
2285
2286     Incoming.push_back(P);
2287   }
2288
2289   if (Incoming.size() > 1)
2290     Changed |= tryToVectorizeList(Incoming, R);
2291
2292   VisitedInstrs.clear();
2293
2294   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) {
2295     // We may go through BB multiple times so skip the one we have checked.
2296     if (!VisitedInstrs.insert(it))
2297       continue;
2298
2299     if (isa<DbgInfoIntrinsic>(it))
2300       continue;
2301
2302     // Try to vectorize reductions that use PHINodes.
2303     if (PHINode *P = dyn_cast<PHINode>(it)) {
2304       // Check that the PHI is a reduction PHI.
2305       if (P->getNumIncomingValues() != 2)
2306         return Changed;
2307       Value *Rdx =
2308           (P->getIncomingBlock(0) == BB
2309                ? (P->getIncomingValue(0))
2310                : (P->getIncomingBlock(1) == BB ? P->getIncomingValue(1) : 0));
2311       // Check if this is a Binary Operator.
2312       BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx);
2313       if (!BI)
2314         continue;
2315
2316       // Try to match and vectorize a horizontal reduction.
2317       HorizontalReduction HorRdx;
2318       if (ShouldVectorizeHor &&
2319           HorRdx.matchAssociativeReduction(P, BI, DL) &&
2320           HorRdx.tryToReduce(R, TTI)) {
2321         Changed = true;
2322         it = BB->begin();
2323         e = BB->end();
2324         continue;
2325       }
2326
2327      Value *Inst = BI->getOperand(0);
2328       if (Inst == P)
2329         Inst = BI->getOperand(1);
2330
2331       if (tryToVectorize(dyn_cast<BinaryOperator>(Inst), R)) {
2332         // We would like to start over since some instructions are deleted
2333         // and the iterator may become invalid value.
2334         Changed = true;
2335         it = BB->begin();
2336         e = BB->end();
2337         continue;
2338       }
2339
2340       continue;
2341     }
2342
2343     // Try to vectorize horizontal reductions feeding into a store.
2344     if (ShouldStartVectorizeHorAtStore)
2345       if (StoreInst *SI = dyn_cast<StoreInst>(it))
2346         if (BinaryOperator *BinOp =
2347                 dyn_cast<BinaryOperator>(SI->getValueOperand())) {
2348           HorizontalReduction HorRdx;
2349           if (((HorRdx.matchAssociativeReduction(0, BinOp, DL) &&
2350                 HorRdx.tryToReduce(R, TTI)) ||
2351                tryToVectorize(BinOp, R))) {
2352             Changed = true;
2353             it = BB->begin();
2354             e = BB->end();
2355             continue;
2356           }
2357         }
2358
2359     // Try to vectorize trees that start at compare instructions.
2360     if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
2361       if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) {
2362         Changed = true;
2363         // We would like to start over since some instructions are deleted
2364         // and the iterator may become invalid value.
2365         it = BB->begin();
2366         e = BB->end();
2367         continue;
2368       }
2369
2370       for (int i = 0; i < 2; ++i) {
2371          if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i))) {
2372             if (tryToVectorizePair(BI->getOperand(0), BI->getOperand(1), R)) {
2373               Changed = true;
2374               // We would like to start over since some instructions are deleted
2375               // and the iterator may become invalid value.
2376               it = BB->begin();
2377               e = BB->end();
2378             }
2379          }
2380       }
2381       continue;
2382     }
2383
2384     // Try to vectorize trees that start at insertelement instructions.
2385     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(it)) {
2386       SmallVector<Value *, 8> Ops;
2387       if (!findBuildVector(IE, Ops))
2388         continue;
2389
2390       if (tryToVectorizeList(Ops, R)) {
2391         Changed = true;
2392         it = BB->begin();
2393         e = BB->end();
2394       }
2395
2396       continue;
2397     }
2398   }
2399
2400   return Changed;
2401 }
2402
2403 bool SLPVectorizer::vectorizeStoreChains(BoUpSLP &R) {
2404   bool Changed = false;
2405   // Attempt to sort and vectorize each of the store-groups.
2406   for (StoreListMap::iterator it = StoreRefs.begin(), e = StoreRefs.end();
2407        it != e; ++it) {
2408     if (it->second.size() < 2)
2409       continue;
2410
2411     DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
2412           << it->second.size() << ".\n");
2413
2414     // Process the stores in chunks of 16.
2415     for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI+=16) {
2416       unsigned Len = std::min<unsigned>(CE - CI, 16);
2417       ArrayRef<StoreInst *> Chunk(&it->second[CI], Len);
2418       Changed |= vectorizeStores(Chunk, -SLPCostThreshold, R);
2419     }
2420   }
2421   return Changed;
2422 }
2423
2424 } // end anonymous namespace
2425
2426 char SLPVectorizer::ID = 0;
2427 static const char lv_name[] = "SLP Vectorizer";
2428 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
2429 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
2430 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
2431 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
2432 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
2433 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
2434
2435 namespace llvm {
2436 Pass *createSLPVectorizerPass() { return new SLPVectorizer(); }
2437 }