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