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