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