fixed typo in comment as my test commit
[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     default:
951       newTreeEntry(VL, false);
952       DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
953       return;
954   }
955 }
956
957 int BoUpSLP::getEntryCost(TreeEntry *E) {
958   ArrayRef<Value*> VL = E->Scalars;
959
960   Type *ScalarTy = VL[0]->getType();
961   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
962     ScalarTy = SI->getValueOperand()->getType();
963   VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
964
965   if (E->NeedToGather) {
966     if (allConstant(VL))
967       return 0;
968     if (isSplat(VL)) {
969       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
970     }
971     return getGatherCost(E->Scalars);
972   }
973
974   assert(getSameOpcode(VL) && getSameType(VL) && getSameBlock(VL) &&
975          "Invalid VL");
976   Instruction *VL0 = cast<Instruction>(VL[0]);
977   unsigned Opcode = VL0->getOpcode();
978   switch (Opcode) {
979     case Instruction::PHI: {
980       return 0;
981     }
982     case Instruction::ExtractElement: {
983       if (CanReuseExtract(VL))
984         return 0;
985       return getGatherCost(VecTy);
986     }
987     case Instruction::ZExt:
988     case Instruction::SExt:
989     case Instruction::FPToUI:
990     case Instruction::FPToSI:
991     case Instruction::FPExt:
992     case Instruction::PtrToInt:
993     case Instruction::IntToPtr:
994     case Instruction::SIToFP:
995     case Instruction::UIToFP:
996     case Instruction::Trunc:
997     case Instruction::FPTrunc:
998     case Instruction::BitCast: {
999       Type *SrcTy = VL0->getOperand(0)->getType();
1000
1001       // Calculate the cost of this instruction.
1002       int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(),
1003                                                          VL0->getType(), SrcTy);
1004
1005       VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
1006       int VecCost = TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy);
1007       return VecCost - ScalarCost;
1008     }
1009     case Instruction::FCmp:
1010     case Instruction::ICmp:
1011     case Instruction::Select:
1012     case Instruction::Add:
1013     case Instruction::FAdd:
1014     case Instruction::Sub:
1015     case Instruction::FSub:
1016     case Instruction::Mul:
1017     case Instruction::FMul:
1018     case Instruction::UDiv:
1019     case Instruction::SDiv:
1020     case Instruction::FDiv:
1021     case Instruction::URem:
1022     case Instruction::SRem:
1023     case Instruction::FRem:
1024     case Instruction::Shl:
1025     case Instruction::LShr:
1026     case Instruction::AShr:
1027     case Instruction::And:
1028     case Instruction::Or:
1029     case Instruction::Xor: {
1030       // Calculate the cost of this instruction.
1031       int ScalarCost = 0;
1032       int VecCost = 0;
1033       if (Opcode == Instruction::FCmp || Opcode == Instruction::ICmp ||
1034           Opcode == Instruction::Select) {
1035         VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
1036         ScalarCost = VecTy->getNumElements() *
1037         TTI->getCmpSelInstrCost(Opcode, ScalarTy, Builder.getInt1Ty());
1038         VecCost = TTI->getCmpSelInstrCost(Opcode, VecTy, MaskTy);
1039       } else {
1040         // Certain instructions can be cheaper to vectorize if they have a
1041         // constant second vector operand.
1042         TargetTransformInfo::OperandValueKind Op1VK =
1043             TargetTransformInfo::OK_AnyValue;
1044         TargetTransformInfo::OperandValueKind Op2VK =
1045             TargetTransformInfo::OK_UniformConstantValue;
1046
1047         // If all operands are exactly the same ConstantInt then set the
1048         // operand kind to OK_UniformConstantValue.
1049         // If instead not all operands are constants, then set the operand kind
1050         // to OK_AnyValue. If all operands are constants but not the same,
1051         // then set the operand kind to OK_NonUniformConstantValue.
1052         ConstantInt *CInt = NULL;
1053         for (unsigned i = 0; i < VL.size(); ++i) {
1054           const Instruction *I = cast<Instruction>(VL[i]);
1055           if (!isa<ConstantInt>(I->getOperand(1))) {
1056             Op2VK = TargetTransformInfo::OK_AnyValue;
1057             break;
1058           }
1059           if (i == 0) {
1060             CInt = cast<ConstantInt>(I->getOperand(1));
1061             continue;
1062           }
1063           if (Op2VK == TargetTransformInfo::OK_UniformConstantValue &&
1064               CInt != cast<ConstantInt>(I->getOperand(1)))
1065             Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
1066         }
1067
1068         ScalarCost =
1069             VecTy->getNumElements() *
1070             TTI->getArithmeticInstrCost(Opcode, ScalarTy, Op1VK, Op2VK);
1071         VecCost = TTI->getArithmeticInstrCost(Opcode, VecTy, Op1VK, Op2VK);
1072       }
1073       return VecCost - ScalarCost;
1074     }
1075     case Instruction::Load: {
1076       // Cost of wide load - cost of scalar loads.
1077       int ScalarLdCost = VecTy->getNumElements() *
1078       TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
1079       int VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, 1, 0);
1080       return VecLdCost - ScalarLdCost;
1081     }
1082     case Instruction::Store: {
1083       // We know that we can merge the stores. Calculate the cost.
1084       int ScalarStCost = VecTy->getNumElements() *
1085       TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
1086       int VecStCost = TTI->getMemoryOpCost(Instruction::Store, VecTy, 1, 0);
1087       return VecStCost - ScalarStCost;
1088     }
1089     default:
1090       llvm_unreachable("Unknown instruction");
1091   }
1092 }
1093
1094 bool BoUpSLP::isFullyVectorizableTinyTree() {
1095   DEBUG(dbgs() << "SLP: Check whether the tree with height " <<
1096         VectorizableTree.size() << " is fully vectorizable .\n");
1097
1098   // We only handle trees of height 2.
1099   if (VectorizableTree.size() != 2)
1100     return false;
1101
1102   // Gathering cost would be too much for tiny trees.
1103   if (VectorizableTree[0].NeedToGather || VectorizableTree[1].NeedToGather) 
1104     return false; 
1105
1106   return true; 
1107 }
1108
1109 int BoUpSLP::getTreeCost() {
1110   int Cost = 0;
1111   DEBUG(dbgs() << "SLP: Calculating cost for tree of size " <<
1112         VectorizableTree.size() << ".\n");
1113
1114   // We only vectorize tiny trees if it is fully vectorizable.
1115   if (VectorizableTree.size() < 3 && !isFullyVectorizableTinyTree()) {
1116     if (!VectorizableTree.size()) {
1117       assert(!ExternalUses.size() && "We should not have any external users");
1118     }
1119     return INT_MAX;
1120   }
1121
1122   unsigned BundleWidth = VectorizableTree[0].Scalars.size();
1123
1124   for (unsigned i = 0, e = VectorizableTree.size(); i != e; ++i) {
1125     int C = getEntryCost(&VectorizableTree[i]);
1126     DEBUG(dbgs() << "SLP: Adding cost " << C << " for bundle that starts with "
1127           << *VectorizableTree[i].Scalars[0] << " .\n");
1128     Cost += C;
1129   }
1130
1131   SmallSet<Value *, 16> ExtractCostCalculated;
1132   int ExtractCost = 0;
1133   for (UserList::iterator I = ExternalUses.begin(), E = ExternalUses.end();
1134        I != E; ++I) {
1135     // We only add extract cost once for the same scalar.
1136     if (!ExtractCostCalculated.insert(I->Scalar))
1137       continue;
1138
1139     VectorType *VecTy = VectorType::get(I->Scalar->getType(), BundleWidth);
1140     ExtractCost += TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy,
1141                                            I->Lane);
1142   }
1143
1144   DEBUG(dbgs() << "SLP: Total Cost " << Cost + ExtractCost<< ".\n");
1145   return  Cost + ExtractCost;
1146 }
1147
1148 int BoUpSLP::getGatherCost(Type *Ty) {
1149   int Cost = 0;
1150   for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
1151     Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
1152   return Cost;
1153 }
1154
1155 int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) {
1156   // Find the type of the operands in VL.
1157   Type *ScalarTy = VL[0]->getType();
1158   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1159     ScalarTy = SI->getValueOperand()->getType();
1160   VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1161   // Find the cost of inserting/extracting values from the vector.
1162   return getGatherCost(VecTy);
1163 }
1164
1165 AliasAnalysis::Location BoUpSLP::getLocation(Instruction *I) {
1166   if (StoreInst *SI = dyn_cast<StoreInst>(I))
1167     return AA->getLocation(SI);
1168   if (LoadInst *LI = dyn_cast<LoadInst>(I))
1169     return AA->getLocation(LI);
1170   return AliasAnalysis::Location();
1171 }
1172
1173 Value *BoUpSLP::getPointerOperand(Value *I) {
1174   if (LoadInst *LI = dyn_cast<LoadInst>(I))
1175     return LI->getPointerOperand();
1176   if (StoreInst *SI = dyn_cast<StoreInst>(I))
1177     return SI->getPointerOperand();
1178   return 0;
1179 }
1180
1181 unsigned BoUpSLP::getAddressSpaceOperand(Value *I) {
1182   if (LoadInst *L = dyn_cast<LoadInst>(I))
1183     return L->getPointerAddressSpace();
1184   if (StoreInst *S = dyn_cast<StoreInst>(I))
1185     return S->getPointerAddressSpace();
1186   return -1;
1187 }
1188
1189 bool BoUpSLP::isConsecutiveAccess(Value *A, Value *B) {
1190   Value *PtrA = getPointerOperand(A);
1191   Value *PtrB = getPointerOperand(B);
1192   unsigned ASA = getAddressSpaceOperand(A);
1193   unsigned ASB = getAddressSpaceOperand(B);
1194
1195   // Check that the address spaces match and that the pointers are valid.
1196   if (!PtrA || !PtrB || (ASA != ASB))
1197     return false;
1198
1199   // Make sure that A and B are different pointers of the same type.
1200   if (PtrA == PtrB || PtrA->getType() != PtrB->getType())
1201     return false;
1202
1203   unsigned PtrBitWidth = DL->getPointerSizeInBits(ASA);
1204   Type *Ty = cast<PointerType>(PtrA->getType())->getElementType();
1205   APInt Size(PtrBitWidth, DL->getTypeStoreSize(Ty));
1206
1207   APInt OffsetA(PtrBitWidth, 0), OffsetB(PtrBitWidth, 0);
1208   PtrA = PtrA->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetA);
1209   PtrB = PtrB->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetB);
1210
1211   APInt OffsetDelta = OffsetB - OffsetA;
1212
1213   // Check if they are based on the same pointer. That makes the offsets
1214   // sufficient.
1215   if (PtrA == PtrB)
1216     return OffsetDelta == Size;
1217
1218   // Compute the necessary base pointer delta to have the necessary final delta
1219   // equal to the size.
1220   APInt BaseDelta = Size - OffsetDelta;
1221
1222   // Otherwise compute the distance with SCEV between the base pointers.
1223   const SCEV *PtrSCEVA = SE->getSCEV(PtrA);
1224   const SCEV *PtrSCEVB = SE->getSCEV(PtrB);
1225   const SCEV *C = SE->getConstant(BaseDelta);
1226   const SCEV *X = SE->getAddExpr(PtrSCEVA, C);
1227   return X == PtrSCEVB;
1228 }
1229
1230 Value *BoUpSLP::getSinkBarrier(Instruction *Src, Instruction *Dst) {
1231   assert(Src->getParent() == Dst->getParent() && "Not the same BB");
1232   BasicBlock::iterator I = Src, E = Dst;
1233   /// Scan all of the instruction from SRC to DST and check if
1234   /// the source may alias.
1235   for (++I; I != E; ++I) {
1236     // Ignore store instructions that are marked as 'ignore'.
1237     if (MemBarrierIgnoreList.count(I))
1238       continue;
1239     if (Src->mayWriteToMemory()) /* Write */ {
1240       if (!I->mayReadOrWriteMemory())
1241         continue;
1242     } else /* Read */ {
1243       if (!I->mayWriteToMemory())
1244         continue;
1245     }
1246     AliasAnalysis::Location A = getLocation(&*I);
1247     AliasAnalysis::Location B = getLocation(Src);
1248
1249     if (!A.Ptr || !B.Ptr || AA->alias(A, B))
1250       return I;
1251   }
1252   return 0;
1253 }
1254
1255 int BoUpSLP::getLastIndex(ArrayRef<Value *> VL) {
1256   BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
1257   assert(BB == getSameBlock(VL) && BlocksNumbers.count(BB) && "Invalid block");
1258   BlockNumbering &BN = BlocksNumbers[BB];
1259
1260   int MaxIdx = BN.getIndex(BB->getFirstNonPHI());
1261   for (unsigned i = 0, e = VL.size(); i < e; ++i)
1262     MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
1263   return MaxIdx;
1264 }
1265
1266 Instruction *BoUpSLP::getLastInstruction(ArrayRef<Value *> VL) {
1267   BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
1268   assert(BB == getSameBlock(VL) && BlocksNumbers.count(BB) && "Invalid block");
1269   BlockNumbering &BN = BlocksNumbers[BB];
1270
1271   int MaxIdx = BN.getIndex(cast<Instruction>(VL[0]));
1272   for (unsigned i = 1, e = VL.size(); i < e; ++i)
1273     MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
1274   Instruction *I = BN.getInstruction(MaxIdx);
1275   assert(I && "bad location");
1276   return I;
1277 }
1278
1279 void BoUpSLP::setInsertPointAfterBundle(ArrayRef<Value *> VL) {
1280   Instruction *VL0 = cast<Instruction>(VL[0]);
1281   Instruction *LastInst = getLastInstruction(VL);
1282   BasicBlock::iterator NextInst = LastInst;
1283   ++NextInst;
1284   Builder.SetInsertPoint(VL0->getParent(), NextInst);
1285   Builder.SetCurrentDebugLocation(VL0->getDebugLoc());
1286 }
1287
1288 Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
1289   Value *Vec = UndefValue::get(Ty);
1290   // Generate the 'InsertElement' instruction.
1291   for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
1292     Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
1293     if (Instruction *Insrt = dyn_cast<Instruction>(Vec)) {
1294       GatherSeq.insert(Insrt);
1295       CSEBlocks.insert(Insrt->getParent());
1296
1297       // Add to our 'need-to-extract' list.
1298       if (ScalarToTreeEntry.count(VL[i])) {
1299         int Idx = ScalarToTreeEntry[VL[i]];
1300         TreeEntry *E = &VectorizableTree[Idx];
1301         // Find which lane we need to extract.
1302         int FoundLane = -1;
1303         for (unsigned Lane = 0, LE = VL.size(); Lane != LE; ++Lane) {
1304           // Is this the lane of the scalar that we are looking for ?
1305           if (E->Scalars[Lane] == VL[i]) {
1306             FoundLane = Lane;
1307             break;
1308           }
1309         }
1310         assert(FoundLane >= 0 && "Could not find the correct lane");
1311         ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
1312       }
1313     }
1314   }
1315
1316   return Vec;
1317 }
1318
1319 Value *BoUpSLP::alreadyVectorized(ArrayRef<Value *> VL) const {
1320   SmallDenseMap<Value*, int>::const_iterator Entry
1321     = ScalarToTreeEntry.find(VL[0]);
1322   if (Entry != ScalarToTreeEntry.end()) {
1323     int Idx = Entry->second;
1324     const TreeEntry *En = &VectorizableTree[Idx];
1325     if (En->isSame(VL) && En->VectorizedValue)
1326       return En->VectorizedValue;
1327   }
1328   return 0;
1329 }
1330
1331 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
1332   if (ScalarToTreeEntry.count(VL[0])) {
1333     int Idx = ScalarToTreeEntry[VL[0]];
1334     TreeEntry *E = &VectorizableTree[Idx];
1335     if (E->isSame(VL))
1336       return vectorizeTree(E);
1337   }
1338
1339   Type *ScalarTy = VL[0]->getType();
1340   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1341     ScalarTy = SI->getValueOperand()->getType();
1342   VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1343
1344   return Gather(VL, VecTy);
1345 }
1346
1347 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
1348   IRBuilder<>::InsertPointGuard Guard(Builder);
1349
1350   if (E->VectorizedValue) {
1351     DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
1352     return E->VectorizedValue;
1353   }
1354
1355   Instruction *VL0 = cast<Instruction>(E->Scalars[0]);
1356   Type *ScalarTy = VL0->getType();
1357   if (StoreInst *SI = dyn_cast<StoreInst>(VL0))
1358     ScalarTy = SI->getValueOperand()->getType();
1359   VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size());
1360
1361   if (E->NeedToGather) {
1362     setInsertPointAfterBundle(E->Scalars);
1363     return Gather(E->Scalars, VecTy);
1364   }
1365
1366   unsigned Opcode = VL0->getOpcode();
1367   assert(Opcode == getSameOpcode(E->Scalars) && "Invalid opcode");
1368
1369   switch (Opcode) {
1370     case Instruction::PHI: {
1371       PHINode *PH = dyn_cast<PHINode>(VL0);
1372       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
1373       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1374       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
1375       E->VectorizedValue = NewPhi;
1376
1377       // PHINodes may have multiple entries from the same block. We want to
1378       // visit every block once.
1379       SmallSet<BasicBlock*, 4> VisitedBBs;
1380
1381       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1382         ValueList Operands;
1383         BasicBlock *IBB = PH->getIncomingBlock(i);
1384
1385         if (!VisitedBBs.insert(IBB)) {
1386           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
1387           continue;
1388         }
1389
1390         // Prepare the operand vector.
1391         for (unsigned j = 0; j < E->Scalars.size(); ++j)
1392           Operands.push_back(cast<PHINode>(E->Scalars[j])->
1393                              getIncomingValueForBlock(IBB));
1394
1395         Builder.SetInsertPoint(IBB->getTerminator());
1396         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1397         Value *Vec = vectorizeTree(Operands);
1398         NewPhi->addIncoming(Vec, IBB);
1399       }
1400
1401       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
1402              "Invalid number of incoming values");
1403       return NewPhi;
1404     }
1405
1406     case Instruction::ExtractElement: {
1407       if (CanReuseExtract(E->Scalars)) {
1408         Value *V = VL0->getOperand(0);
1409         E->VectorizedValue = V;
1410         return V;
1411       }
1412       return Gather(E->Scalars, VecTy);
1413     }
1414     case Instruction::ZExt:
1415     case Instruction::SExt:
1416     case Instruction::FPToUI:
1417     case Instruction::FPToSI:
1418     case Instruction::FPExt:
1419     case Instruction::PtrToInt:
1420     case Instruction::IntToPtr:
1421     case Instruction::SIToFP:
1422     case Instruction::UIToFP:
1423     case Instruction::Trunc:
1424     case Instruction::FPTrunc:
1425     case Instruction::BitCast: {
1426       ValueList INVL;
1427       for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1428         INVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1429
1430       setInsertPointAfterBundle(E->Scalars);
1431
1432       Value *InVec = vectorizeTree(INVL);
1433
1434       if (Value *V = alreadyVectorized(E->Scalars))
1435         return V;
1436
1437       CastInst *CI = dyn_cast<CastInst>(VL0);
1438       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
1439       E->VectorizedValue = V;
1440       return V;
1441     }
1442     case Instruction::FCmp:
1443     case Instruction::ICmp: {
1444       ValueList LHSV, RHSV;
1445       for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1446         LHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1447         RHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1448       }
1449
1450       setInsertPointAfterBundle(E->Scalars);
1451
1452       Value *L = vectorizeTree(LHSV);
1453       Value *R = vectorizeTree(RHSV);
1454
1455       if (Value *V = alreadyVectorized(E->Scalars))
1456         return V;
1457
1458       CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
1459       Value *V;
1460       if (Opcode == Instruction::FCmp)
1461         V = Builder.CreateFCmp(P0, L, R);
1462       else
1463         V = Builder.CreateICmp(P0, L, R);
1464
1465       E->VectorizedValue = V;
1466       return V;
1467     }
1468     case Instruction::Select: {
1469       ValueList TrueVec, FalseVec, CondVec;
1470       for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1471         CondVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1472         TrueVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1473         FalseVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(2));
1474       }
1475
1476       setInsertPointAfterBundle(E->Scalars);
1477
1478       Value *Cond = vectorizeTree(CondVec);
1479       Value *True = vectorizeTree(TrueVec);
1480       Value *False = vectorizeTree(FalseVec);
1481
1482       if (Value *V = alreadyVectorized(E->Scalars))
1483         return V;
1484
1485       Value *V = Builder.CreateSelect(Cond, True, False);
1486       E->VectorizedValue = V;
1487       return V;
1488     }
1489     case Instruction::Add:
1490     case Instruction::FAdd:
1491     case Instruction::Sub:
1492     case Instruction::FSub:
1493     case Instruction::Mul:
1494     case Instruction::FMul:
1495     case Instruction::UDiv:
1496     case Instruction::SDiv:
1497     case Instruction::FDiv:
1498     case Instruction::URem:
1499     case Instruction::SRem:
1500     case Instruction::FRem:
1501     case Instruction::Shl:
1502     case Instruction::LShr:
1503     case Instruction::AShr:
1504     case Instruction::And:
1505     case Instruction::Or:
1506     case Instruction::Xor: {
1507       ValueList LHSVL, RHSVL;
1508       if (isa<BinaryOperator>(VL0) && VL0->isCommutative())
1509         reorderInputsAccordingToOpcode(E->Scalars, LHSVL, RHSVL);
1510       else
1511         for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1512           LHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1513           RHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1514         }
1515
1516       setInsertPointAfterBundle(E->Scalars);
1517
1518       Value *LHS = vectorizeTree(LHSVL);
1519       Value *RHS = vectorizeTree(RHSVL);
1520
1521       if (LHS == RHS && isa<Instruction>(LHS)) {
1522         assert((VL0->getOperand(0) == VL0->getOperand(1)) && "Invalid order");
1523       }
1524
1525       if (Value *V = alreadyVectorized(E->Scalars))
1526         return V;
1527
1528       BinaryOperator *BinOp = cast<BinaryOperator>(VL0);
1529       Value *V = Builder.CreateBinOp(BinOp->getOpcode(), LHS, RHS);
1530       E->VectorizedValue = V;
1531
1532       if (Instruction *I = dyn_cast<Instruction>(V))
1533         return propagateMetadata(I, E->Scalars);
1534
1535       return V;
1536     }
1537     case Instruction::Load: {
1538       // Loads are inserted at the head of the tree because we don't want to
1539       // sink them all the way down past store instructions.
1540       setInsertPointAfterBundle(E->Scalars);
1541
1542       LoadInst *LI = cast<LoadInst>(VL0);
1543       unsigned AS = LI->getPointerAddressSpace();
1544
1545       Value *VecPtr = Builder.CreateBitCast(LI->getPointerOperand(),
1546                                             VecTy->getPointerTo(AS));
1547       unsigned Alignment = LI->getAlignment();
1548       LI = Builder.CreateLoad(VecPtr);
1549       LI->setAlignment(Alignment);
1550       E->VectorizedValue = LI;
1551       return propagateMetadata(LI, E->Scalars);
1552     }
1553     case Instruction::Store: {
1554       StoreInst *SI = cast<StoreInst>(VL0);
1555       unsigned Alignment = SI->getAlignment();
1556       unsigned AS = SI->getPointerAddressSpace();
1557
1558       ValueList ValueOp;
1559       for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1560         ValueOp.push_back(cast<StoreInst>(E->Scalars[i])->getValueOperand());
1561
1562       setInsertPointAfterBundle(E->Scalars);
1563
1564       Value *VecValue = vectorizeTree(ValueOp);
1565       Value *VecPtr = Builder.CreateBitCast(SI->getPointerOperand(),
1566                                             VecTy->getPointerTo(AS));
1567       StoreInst *S = Builder.CreateStore(VecValue, VecPtr);
1568       S->setAlignment(Alignment);
1569       E->VectorizedValue = S;
1570       return propagateMetadata(S, E->Scalars);
1571     }
1572     default:
1573     llvm_unreachable("unknown inst");
1574   }
1575   return 0;
1576 }
1577
1578 Value *BoUpSLP::vectorizeTree() {
1579   Builder.SetInsertPoint(F->getEntryBlock().begin());
1580   vectorizeTree(&VectorizableTree[0]);
1581
1582   DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() << " values .\n");
1583
1584   // Extract all of the elements with the external uses.
1585   for (UserList::iterator it = ExternalUses.begin(), e = ExternalUses.end();
1586        it != e; ++it) {
1587     Value *Scalar = it->Scalar;
1588     llvm::User *User = it->User;
1589
1590     // Skip users that we already RAUW. This happens when one instruction
1591     // has multiple uses of the same value.
1592     if (std::find(Scalar->use_begin(), Scalar->use_end(), User) ==
1593         Scalar->use_end())
1594       continue;
1595     assert(ScalarToTreeEntry.count(Scalar) && "Invalid scalar");
1596
1597     int Idx = ScalarToTreeEntry[Scalar];
1598     TreeEntry *E = &VectorizableTree[Idx];
1599     assert(!E->NeedToGather && "Extracting from a gather list");
1600
1601     Value *Vec = E->VectorizedValue;
1602     assert(Vec && "Can't find vectorizable value");
1603
1604     Value *Lane = Builder.getInt32(it->Lane);
1605     // Generate extracts for out-of-tree users.
1606     // Find the insertion point for the extractelement lane.
1607     if (PHINode *PN = dyn_cast<PHINode>(Vec)) {
1608       Builder.SetInsertPoint(PN->getParent()->getFirstInsertionPt());
1609       Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1610       CSEBlocks.insert(PN->getParent());
1611       User->replaceUsesOfWith(Scalar, Ex);
1612     } else if (isa<Instruction>(Vec)){
1613       if (PHINode *PH = dyn_cast<PHINode>(User)) {
1614         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
1615           if (PH->getIncomingValue(i) == Scalar) {
1616             Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
1617             Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1618             CSEBlocks.insert(PH->getIncomingBlock(i));
1619             PH->setOperand(i, Ex);
1620           }
1621         }
1622       } else {
1623         Builder.SetInsertPoint(cast<Instruction>(User));
1624         Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1625         CSEBlocks.insert(cast<Instruction>(User)->getParent());
1626         User->replaceUsesOfWith(Scalar, Ex);
1627      }
1628     } else {
1629       Builder.SetInsertPoint(F->getEntryBlock().begin());
1630       Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1631       CSEBlocks.insert(&F->getEntryBlock());
1632       User->replaceUsesOfWith(Scalar, Ex);
1633     }
1634
1635     DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
1636   }
1637
1638   // For each vectorized value:
1639   for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
1640     TreeEntry *Entry = &VectorizableTree[EIdx];
1641
1642     // For each lane:
1643     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
1644       Value *Scalar = Entry->Scalars[Lane];
1645
1646       // No need to handle users of gathered values.
1647       if (Entry->NeedToGather)
1648         continue;
1649
1650       assert(Entry->VectorizedValue && "Can't find vectorizable value");
1651
1652       Type *Ty = Scalar->getType();
1653       if (!Ty->isVoidTy()) {
1654         for (Value::use_iterator User = Scalar->use_begin(),
1655              UE = Scalar->use_end(); User != UE; ++User) {
1656           DEBUG(dbgs() << "SLP: \tvalidating user:" << **User << ".\n");
1657
1658           assert((ScalarToTreeEntry.count(*User) ||
1659                   // It is legal to replace the reduction users by undef.
1660                   (RdxOps && RdxOps->count(*User))) &&
1661                  "Replacing out-of-tree value with undef");
1662         }
1663         Value *Undef = UndefValue::get(Ty);
1664         Scalar->replaceAllUsesWith(Undef);
1665       }
1666       DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
1667       cast<Instruction>(Scalar)->eraseFromParent();
1668     }
1669   }
1670
1671   for (Function::iterator it = F->begin(), e = F->end(); it != e; ++it) {
1672     BlocksNumbers[it].forget();
1673   }
1674   Builder.ClearInsertionPoint();
1675
1676   return VectorizableTree[0].VectorizedValue;
1677 }
1678
1679 class DTCmp {
1680   const DominatorTree *DT;
1681
1682 public:
1683   DTCmp(const DominatorTree *DT) : DT(DT) {}
1684   bool operator()(const BasicBlock *A, const BasicBlock *B) const {
1685     return DT->properlyDominates(A, B);
1686   }
1687 };
1688
1689 void BoUpSLP::optimizeGatherSequence() {
1690   DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
1691         << " gather sequences instructions.\n");
1692   // LICM InsertElementInst sequences.
1693   for (SetVector<Instruction *>::iterator it = GatherSeq.begin(),
1694        e = GatherSeq.end(); it != e; ++it) {
1695     InsertElementInst *Insert = dyn_cast<InsertElementInst>(*it);
1696
1697     if (!Insert)
1698       continue;
1699
1700     // Check if this block is inside a loop.
1701     Loop *L = LI->getLoopFor(Insert->getParent());
1702     if (!L)
1703       continue;
1704
1705     // Check if it has a preheader.
1706     BasicBlock *PreHeader = L->getLoopPreheader();
1707     if (!PreHeader)
1708       continue;
1709
1710     // If the vector or the element that we insert into it are
1711     // instructions that are defined in this basic block then we can't
1712     // hoist this instruction.
1713     Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
1714     Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
1715     if (CurrVec && L->contains(CurrVec))
1716       continue;
1717     if (NewElem && L->contains(NewElem))
1718       continue;
1719
1720     // We can hoist this instruction. Move it to the pre-header.
1721     Insert->moveBefore(PreHeader->getTerminator());
1722   }
1723
1724   // Sort blocks by domination. This ensures we visit a block after all blocks
1725   // dominating it are visited.
1726   SmallVector<BasicBlock *, 8> CSEWorkList(CSEBlocks.begin(), CSEBlocks.end());
1727   std::stable_sort(CSEWorkList.begin(), CSEWorkList.end(), DTCmp(DT));
1728
1729   // Perform O(N^2) search over the gather sequences and merge identical
1730   // instructions. TODO: We can further optimize this scan if we split the
1731   // instructions into different buckets based on the insert lane.
1732   SmallVector<Instruction *, 16> Visited;
1733   for (SmallVectorImpl<BasicBlock *>::iterator I = CSEWorkList.begin(),
1734                                                E = CSEWorkList.end();
1735        I != E; ++I) {
1736     assert((I == CSEWorkList.begin() || !DT->dominates(*I, *llvm::prior(I))) &&
1737            "Worklist not sorted properly!");
1738     BasicBlock *BB = *I;
1739     // For all instructions in blocks containing gather sequences:
1740     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) {
1741       Instruction *In = it++;
1742       if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In))
1743         continue;
1744
1745       // Check if we can replace this instruction with any of the
1746       // visited instructions.
1747       for (SmallVectorImpl<Instruction *>::iterator v = Visited.begin(),
1748                                                     ve = Visited.end();
1749            v != ve; ++v) {
1750         if (In->isIdenticalTo(*v) &&
1751             DT->dominates((*v)->getParent(), In->getParent())) {
1752           In->replaceAllUsesWith(*v);
1753           In->eraseFromParent();
1754           In = 0;
1755           break;
1756         }
1757       }
1758       if (In) {
1759         assert(std::find(Visited.begin(), Visited.end(), In) == Visited.end());
1760         Visited.push_back(In);
1761       }
1762     }
1763   }
1764   CSEBlocks.clear();
1765   GatherSeq.clear();
1766 }
1767
1768 /// The SLPVectorizer Pass.
1769 struct SLPVectorizer : public FunctionPass {
1770   typedef SmallVector<StoreInst *, 8> StoreList;
1771   typedef MapVector<Value *, StoreList> StoreListMap;
1772
1773   /// Pass identification, replacement for typeid
1774   static char ID;
1775
1776   explicit SLPVectorizer() : FunctionPass(ID) {
1777     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
1778   }
1779
1780   ScalarEvolution *SE;
1781   DataLayout *DL;
1782   TargetTransformInfo *TTI;
1783   AliasAnalysis *AA;
1784   LoopInfo *LI;
1785   DominatorTree *DT;
1786
1787   virtual bool runOnFunction(Function &F) {
1788     if (skipOptnoneFunction(F))
1789       return false;
1790
1791     SE = &getAnalysis<ScalarEvolution>();
1792     DL = getAnalysisIfAvailable<DataLayout>();
1793     TTI = &getAnalysis<TargetTransformInfo>();
1794     AA = &getAnalysis<AliasAnalysis>();
1795     LI = &getAnalysis<LoopInfo>();
1796     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1797
1798     StoreRefs.clear();
1799     bool Changed = false;
1800
1801     // If the target claims to have no vector registers don't attempt
1802     // vectorization.
1803     if (!TTI->getNumberOfRegisters(true))
1804       return false;
1805
1806     // Must have DataLayout. We can't require it because some tests run w/o
1807     // triple.
1808     if (!DL)
1809       return false;
1810
1811     // Don't vectorize when the attribute NoImplicitFloat is used.
1812     if (F.hasFnAttribute(Attribute::NoImplicitFloat))
1813       return false;
1814
1815     DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
1816
1817     // Use the bottom up slp vectorizer to construct chains that start with
1818     // he store instructions.
1819     BoUpSLP R(&F, SE, DL, TTI, AA, LI, DT);
1820
1821     // Scan the blocks in the function in post order.
1822     for (po_iterator<BasicBlock*> it = po_begin(&F.getEntryBlock()),
1823          e = po_end(&F.getEntryBlock()); it != e; ++it) {
1824       BasicBlock *BB = *it;
1825
1826       // Vectorize trees that end at stores.
1827       if (unsigned count = collectStores(BB, R)) {
1828         (void)count;
1829         DEBUG(dbgs() << "SLP: Found " << count << " stores to vectorize.\n");
1830         Changed |= vectorizeStoreChains(R);
1831       }
1832
1833       // Vectorize trees that end at reductions.
1834       Changed |= vectorizeChainsInBlock(BB, R);
1835     }
1836
1837     if (Changed) {
1838       R.optimizeGatherSequence();
1839       DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
1840       DEBUG(verifyFunction(F));
1841     }
1842     return Changed;
1843   }
1844
1845   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1846     FunctionPass::getAnalysisUsage(AU);
1847     AU.addRequired<ScalarEvolution>();
1848     AU.addRequired<AliasAnalysis>();
1849     AU.addRequired<TargetTransformInfo>();
1850     AU.addRequired<LoopInfo>();
1851     AU.addRequired<DominatorTreeWrapperPass>();
1852     AU.addPreserved<LoopInfo>();
1853     AU.addPreserved<DominatorTreeWrapperPass>();
1854     AU.setPreservesCFG();
1855   }
1856
1857 private:
1858
1859   /// \brief Collect memory references and sort them according to their base
1860   /// object. We sort the stores to their base objects to reduce the cost of the
1861   /// quadratic search on the stores. TODO: We can further reduce this cost
1862   /// if we flush the chain creation every time we run into a memory barrier.
1863   unsigned collectStores(BasicBlock *BB, BoUpSLP &R);
1864
1865   /// \brief Try to vectorize a chain that starts at two arithmetic instrs.
1866   bool tryToVectorizePair(Value *A, Value *B, BoUpSLP &R);
1867
1868   /// \brief Try to vectorize a list of operands.
1869   /// \returns true if a value was vectorized.
1870   bool tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R);
1871
1872   /// \brief Try to vectorize a chain that may start at the operands of \V;
1873   bool tryToVectorize(BinaryOperator *V, BoUpSLP &R);
1874
1875   /// \brief Vectorize the stores that were collected in StoreRefs.
1876   bool vectorizeStoreChains(BoUpSLP &R);
1877
1878   /// \brief Scan the basic block and look for patterns that are likely to start
1879   /// a vectorization chain.
1880   bool vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R);
1881
1882   bool vectorizeStoreChain(ArrayRef<Value *> Chain, int CostThreshold,
1883                            BoUpSLP &R);
1884
1885   bool vectorizeStores(ArrayRef<StoreInst *> Stores, int costThreshold,
1886                        BoUpSLP &R);
1887 private:
1888   StoreListMap StoreRefs;
1889 };
1890
1891 /// \brief Check that the Values in the slice in VL array are still existent in
1892 /// the WeakVH array.
1893 /// Vectorization of part of the VL array may cause later values in the VL array
1894 /// to become invalid. We track when this has happened in the WeakVH array.
1895 static bool hasValueBeenRAUWed(ArrayRef<Value *> &VL,
1896                                SmallVectorImpl<WeakVH> &VH,
1897                                unsigned SliceBegin,
1898                                unsigned SliceSize) {
1899   for (unsigned i = SliceBegin; i < SliceBegin + SliceSize; ++i)
1900     if (VH[i] != VL[i])
1901       return true;
1902
1903   return false;
1904 }
1905
1906 bool SLPVectorizer::vectorizeStoreChain(ArrayRef<Value *> Chain,
1907                                           int CostThreshold, BoUpSLP &R) {
1908   unsigned ChainLen = Chain.size();
1909   DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
1910         << "\n");
1911   Type *StoreTy = cast<StoreInst>(Chain[0])->getValueOperand()->getType();
1912   unsigned Sz = DL->getTypeSizeInBits(StoreTy);
1913   unsigned VF = MinVecRegSize / Sz;
1914
1915   if (!isPowerOf2_32(Sz) || VF < 2)
1916     return false;
1917
1918   // Keep track of values that were delete by vectorizing in the loop below.
1919   SmallVector<WeakVH, 8> TrackValues(Chain.begin(), Chain.end());
1920
1921   bool Changed = false;
1922   // Look for profitable vectorizable trees at all offsets, starting at zero.
1923   for (unsigned i = 0, e = ChainLen; i < e; ++i) {
1924     if (i + VF > e)
1925       break;
1926
1927     // Check that a previous iteration of this loop did not delete the Value.
1928     if (hasValueBeenRAUWed(Chain, TrackValues, i, VF))
1929       continue;
1930
1931     DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
1932           << "\n");
1933     ArrayRef<Value *> Operands = Chain.slice(i, VF);
1934
1935     R.buildTree(Operands);
1936
1937     int Cost = R.getTreeCost();
1938
1939     DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
1940     if (Cost < CostThreshold) {
1941       DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
1942       R.vectorizeTree();
1943
1944       // Move to the next bundle.
1945       i += VF - 1;
1946       Changed = true;
1947     }
1948   }
1949
1950   return Changed;
1951 }
1952
1953 bool SLPVectorizer::vectorizeStores(ArrayRef<StoreInst *> Stores,
1954                                     int costThreshold, BoUpSLP &R) {
1955   SetVector<Value *> Heads, Tails;
1956   SmallDenseMap<Value *, Value *> ConsecutiveChain;
1957
1958   // We may run into multiple chains that merge into a single chain. We mark the
1959   // stores that we vectorized so that we don't visit the same store twice.
1960   BoUpSLP::ValueSet VectorizedStores;
1961   bool Changed = false;
1962
1963   // Do a quadratic search on all of the given stores and find
1964   // all of the pairs of stores that follow each other.
1965   for (unsigned i = 0, e = Stores.size(); i < e; ++i) {
1966     for (unsigned j = 0; j < e; ++j) {
1967       if (i == j)
1968         continue;
1969
1970       if (R.isConsecutiveAccess(Stores[i], Stores[j])) {
1971         Tails.insert(Stores[j]);
1972         Heads.insert(Stores[i]);
1973         ConsecutiveChain[Stores[i]] = Stores[j];
1974       }
1975     }
1976   }
1977
1978   // For stores that start but don't end a link in the chain:
1979   for (SetVector<Value *>::iterator it = Heads.begin(), e = Heads.end();
1980        it != e; ++it) {
1981     if (Tails.count(*it))
1982       continue;
1983
1984     // We found a store instr that starts a chain. Now follow the chain and try
1985     // to vectorize it.
1986     BoUpSLP::ValueList Operands;
1987     Value *I = *it;
1988     // Collect the chain into a list.
1989     while (Tails.count(I) || Heads.count(I)) {
1990       if (VectorizedStores.count(I))
1991         break;
1992       Operands.push_back(I);
1993       // Move to the next value in the chain.
1994       I = ConsecutiveChain[I];
1995     }
1996
1997     bool Vectorized = vectorizeStoreChain(Operands, costThreshold, R);
1998
1999     // Mark the vectorized stores so that we don't vectorize them again.
2000     if (Vectorized)
2001       VectorizedStores.insert(Operands.begin(), Operands.end());
2002     Changed |= Vectorized;
2003   }
2004
2005   return Changed;
2006 }
2007
2008
2009 unsigned SLPVectorizer::collectStores(BasicBlock *BB, BoUpSLP &R) {
2010   unsigned count = 0;
2011   StoreRefs.clear();
2012   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2013     StoreInst *SI = dyn_cast<StoreInst>(it);
2014     if (!SI)
2015       continue;
2016
2017     // Don't touch volatile stores.
2018     if (!SI->isSimple())
2019       continue;
2020
2021     // Check that the pointer points to scalars.
2022     Type *Ty = SI->getValueOperand()->getType();
2023     if (Ty->isAggregateType() || Ty->isVectorTy())
2024       return 0;
2025
2026     // Find the base pointer.
2027     Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), DL);
2028
2029     // Save the store locations.
2030     StoreRefs[Ptr].push_back(SI);
2031     count++;
2032   }
2033   return count;
2034 }
2035
2036 bool SLPVectorizer::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
2037   if (!A || !B)
2038     return false;
2039   Value *VL[] = { A, B };
2040   return tryToVectorizeList(VL, R);
2041 }
2042
2043 bool SLPVectorizer::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R) {
2044   if (VL.size() < 2)
2045     return false;
2046
2047   DEBUG(dbgs() << "SLP: Vectorizing a list of length = " << VL.size() << ".\n");
2048
2049   // Check that all of the parts are scalar instructions of the same type.
2050   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
2051   if (!I0)
2052     return false;
2053
2054   unsigned Opcode0 = I0->getOpcode();
2055
2056   Type *Ty0 = I0->getType();
2057   unsigned Sz = DL->getTypeSizeInBits(Ty0);
2058   unsigned VF = MinVecRegSize / Sz;
2059
2060   for (int i = 0, e = VL.size(); i < e; ++i) {
2061     Type *Ty = VL[i]->getType();
2062     if (Ty->isAggregateType() || Ty->isVectorTy())
2063       return false;
2064     Instruction *Inst = dyn_cast<Instruction>(VL[i]);
2065     if (!Inst || Inst->getOpcode() != Opcode0)
2066       return false;
2067   }
2068
2069   bool Changed = false;
2070
2071   // Keep track of values that were delete by vectorizing in the loop below.
2072   SmallVector<WeakVH, 8> TrackValues(VL.begin(), VL.end());
2073
2074   for (unsigned i = 0, e = VL.size(); i < e; ++i) {
2075     unsigned OpsWidth = 0;
2076
2077     if (i + VF > e)
2078       OpsWidth = e - i;
2079     else
2080       OpsWidth = VF;
2081
2082     if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
2083       break;
2084
2085     // Check that a previous iteration of this loop did not delete the Value.
2086     if (hasValueBeenRAUWed(VL, TrackValues, i, OpsWidth))
2087       continue;
2088
2089     DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
2090                  << "\n");
2091     ArrayRef<Value *> Ops = VL.slice(i, OpsWidth);
2092
2093     R.buildTree(Ops);
2094     int Cost = R.getTreeCost();
2095
2096     if (Cost < -SLPCostThreshold) {
2097       DEBUG(dbgs() << "SLP: Vectorizing pair at cost:" << Cost << ".\n");
2098       R.vectorizeTree();
2099
2100       // Move to the next bundle.
2101       i += VF - 1;
2102       Changed = true;
2103     }
2104   }
2105
2106   return Changed;
2107 }
2108
2109 bool SLPVectorizer::tryToVectorize(BinaryOperator *V, BoUpSLP &R) {
2110   if (!V)
2111     return false;
2112
2113   // Try to vectorize V.
2114   if (tryToVectorizePair(V->getOperand(0), V->getOperand(1), R))
2115     return true;
2116
2117   BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0));
2118   BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1));
2119   // Try to skip B.
2120   if (B && B->hasOneUse()) {
2121     BinaryOperator *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
2122     BinaryOperator *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
2123     if (tryToVectorizePair(A, B0, R)) {
2124       B->moveBefore(V);
2125       return true;
2126     }
2127     if (tryToVectorizePair(A, B1, R)) {
2128       B->moveBefore(V);
2129       return true;
2130     }
2131   }
2132
2133   // Try to skip A.
2134   if (A && A->hasOneUse()) {
2135     BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
2136     BinaryOperator *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
2137     if (tryToVectorizePair(A0, B, R)) {
2138       A->moveBefore(V);
2139       return true;
2140     }
2141     if (tryToVectorizePair(A1, B, R)) {
2142       A->moveBefore(V);
2143       return true;
2144     }
2145   }
2146   return 0;
2147 }
2148
2149 /// \brief Generate a shuffle mask to be used in a reduction tree.
2150 ///
2151 /// \param VecLen The length of the vector to be reduced.
2152 /// \param NumEltsToRdx The number of elements that should be reduced in the
2153 ///        vector.
2154 /// \param IsPairwise Whether the reduction is a pairwise or splitting
2155 ///        reduction. A pairwise reduction will generate a mask of 
2156 ///        <0,2,...> or <1,3,..> while a splitting reduction will generate
2157 ///        <2,3, undef,undef> for a vector of 4 and NumElts = 2.
2158 /// \param IsLeft True will generate a mask of even elements, odd otherwise.
2159 static Value *createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx,
2160                                    bool IsPairwise, bool IsLeft,
2161                                    IRBuilder<> &Builder) {
2162   assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask");
2163
2164   SmallVector<Constant *, 32> ShuffleMask(
2165       VecLen, UndefValue::get(Builder.getInt32Ty()));
2166
2167   if (IsPairwise)
2168     // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
2169     for (unsigned i = 0; i != NumEltsToRdx; ++i)
2170       ShuffleMask[i] = Builder.getInt32(2 * i + !IsLeft);
2171   else
2172     // Move the upper half of the vector to the lower half.
2173     for (unsigned i = 0; i != NumEltsToRdx; ++i)
2174       ShuffleMask[i] = Builder.getInt32(NumEltsToRdx + i);
2175
2176   return ConstantVector::get(ShuffleMask);
2177 }
2178
2179
2180 /// Model horizontal reductions.
2181 ///
2182 /// A horizontal reduction is a tree of reduction operations (currently add and
2183 /// fadd) that has operations that can be put into a vector as its leaf.
2184 /// For example, this tree:
2185 ///
2186 /// mul mul mul mul
2187 ///  \  /    \  /
2188 ///   +       +
2189 ///    \     /
2190 ///       +
2191 /// This tree has "mul" as its reduced values and "+" as its reduction
2192 /// operations. A reduction might be feeding into a store or a binary operation
2193 /// feeding a phi.
2194 ///    ...
2195 ///    \  /
2196 ///     +
2197 ///     |
2198 ///  phi +=
2199 ///
2200 ///  Or:
2201 ///    ...
2202 ///    \  /
2203 ///     +
2204 ///     |
2205 ///   *p =
2206 ///
2207 class HorizontalReduction {
2208   SmallPtrSet<Value *, 16> ReductionOps;
2209   SmallVector<Value *, 32> ReducedVals;
2210
2211   BinaryOperator *ReductionRoot;
2212   PHINode *ReductionPHI;
2213
2214   /// The opcode of the reduction.
2215   unsigned ReductionOpcode;
2216   /// The opcode of the values we perform a reduction on.
2217   unsigned ReducedValueOpcode;
2218   /// The width of one full horizontal reduction operation.
2219   unsigned ReduxWidth;
2220   /// Should we model this reduction as a pairwise reduction tree or a tree that
2221   /// splits the vector in halves and adds those halves.
2222   bool IsPairwiseReduction;
2223
2224 public:
2225   HorizontalReduction()
2226     : ReductionRoot(0), ReductionPHI(0), ReductionOpcode(0),
2227     ReducedValueOpcode(0), ReduxWidth(0), IsPairwiseReduction(false) {}
2228
2229   /// \brief Try to find a reduction tree.
2230   bool matchAssociativeReduction(PHINode *Phi, BinaryOperator *B,
2231                                  DataLayout *DL) {
2232     assert((!Phi ||
2233             std::find(Phi->op_begin(), Phi->op_end(), B) != Phi->op_end()) &&
2234            "Thi phi needs to use the binary operator");
2235
2236     // We could have a initial reductions that is not an add.
2237     //  r *= v1 + v2 + v3 + v4
2238     // In such a case start looking for a tree rooted in the first '+'.
2239     if (Phi) {
2240       if (B->getOperand(0) == Phi) {
2241         Phi = 0;
2242         B = dyn_cast<BinaryOperator>(B->getOperand(1));
2243       } else if (B->getOperand(1) == Phi) {
2244         Phi = 0;
2245         B = dyn_cast<BinaryOperator>(B->getOperand(0));
2246       }
2247     }
2248
2249     if (!B)
2250       return false;
2251
2252     Type *Ty = B->getType();
2253     if (Ty->isVectorTy())
2254       return false;
2255
2256     ReductionOpcode = B->getOpcode();
2257     ReducedValueOpcode = 0;
2258     ReduxWidth = MinVecRegSize / DL->getTypeSizeInBits(Ty);
2259     ReductionRoot = B;
2260     ReductionPHI = Phi;
2261
2262     if (ReduxWidth < 4)
2263       return false;
2264
2265     // We currently only support adds.
2266     if (ReductionOpcode != Instruction::Add &&
2267         ReductionOpcode != Instruction::FAdd)
2268       return false;
2269
2270     // Post order traverse the reduction tree starting at B. We only handle true
2271     // trees containing only binary operators.
2272     SmallVector<std::pair<BinaryOperator *, unsigned>, 32> Stack;
2273     Stack.push_back(std::make_pair(B, 0));
2274     while (!Stack.empty()) {
2275       BinaryOperator *TreeN = Stack.back().first;
2276       unsigned EdgeToVist = Stack.back().second++;
2277       bool IsReducedValue = TreeN->getOpcode() != ReductionOpcode;
2278
2279       // Only handle trees in the current basic block.
2280       if (TreeN->getParent() != B->getParent())
2281         return false;
2282
2283       // Each tree node needs to have one user except for the ultimate
2284       // reduction.
2285       if (!TreeN->hasOneUse() && TreeN != B)
2286         return false;
2287
2288       // Postorder vist.
2289       if (EdgeToVist == 2 || IsReducedValue) {
2290         if (IsReducedValue) {
2291           // Make sure that the opcodes of the operations that we are going to
2292           // reduce match.
2293           if (!ReducedValueOpcode)
2294             ReducedValueOpcode = TreeN->getOpcode();
2295           else if (ReducedValueOpcode != TreeN->getOpcode())
2296             return false;
2297           ReducedVals.push_back(TreeN);
2298         } else {
2299           // We need to be able to reassociate the adds.
2300           if (!TreeN->isAssociative())
2301             return false;
2302           ReductionOps.insert(TreeN);
2303         }
2304         // Retract.
2305         Stack.pop_back();
2306         continue;
2307       }
2308
2309       // Visit left or right.
2310       Value *NextV = TreeN->getOperand(EdgeToVist);
2311       BinaryOperator *Next = dyn_cast<BinaryOperator>(NextV);
2312       if (Next)
2313         Stack.push_back(std::make_pair(Next, 0));
2314       else if (NextV != Phi)
2315         return false;
2316     }
2317     return true;
2318   }
2319
2320   /// \brief Attempt to vectorize the tree found by
2321   /// matchAssociativeReduction.
2322   bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
2323     if (ReducedVals.empty())
2324       return false;
2325
2326     unsigned NumReducedVals = ReducedVals.size();
2327     if (NumReducedVals < ReduxWidth)
2328       return false;
2329
2330     Value *VectorizedTree = 0;
2331     IRBuilder<> Builder(ReductionRoot);
2332     FastMathFlags Unsafe;
2333     Unsafe.setUnsafeAlgebra();
2334     Builder.SetFastMathFlags(Unsafe);
2335     unsigned i = 0;
2336
2337     for (; i < NumReducedVals - ReduxWidth + 1; i += ReduxWidth) {
2338       ArrayRef<Value *> ValsToReduce(&ReducedVals[i], ReduxWidth);
2339       V.buildTree(ValsToReduce, &ReductionOps);
2340
2341       // Estimate cost.
2342       int Cost = V.getTreeCost() + getReductionCost(TTI, ReducedVals[i]);
2343       if (Cost >= -SLPCostThreshold)
2344         break;
2345
2346       DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" << Cost
2347                    << ". (HorRdx)\n");
2348
2349       // Vectorize a tree.
2350       DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
2351       Value *VectorizedRoot = V.vectorizeTree();
2352
2353       // Emit a reduction.
2354       Value *ReducedSubTree = emitReduction(VectorizedRoot, Builder);
2355       if (VectorizedTree) {
2356         Builder.SetCurrentDebugLocation(Loc);
2357         VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
2358                                      ReducedSubTree, "bin.rdx");
2359       } else
2360         VectorizedTree = ReducedSubTree;
2361     }
2362
2363     if (VectorizedTree) {
2364       // Finish the reduction.
2365       for (; i < NumReducedVals; ++i) {
2366         Builder.SetCurrentDebugLocation(
2367           cast<Instruction>(ReducedVals[i])->getDebugLoc());
2368         VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
2369                                      ReducedVals[i]);
2370       }
2371       // Update users.
2372       if (ReductionPHI) {
2373         assert(ReductionRoot != NULL && "Need a reduction operation");
2374         ReductionRoot->setOperand(0, VectorizedTree);
2375         ReductionRoot->setOperand(1, ReductionPHI);
2376       } else
2377         ReductionRoot->replaceAllUsesWith(VectorizedTree);
2378     }
2379     return VectorizedTree != 0;
2380   }
2381
2382 private:
2383
2384   /// \brief Calcuate the cost of a reduction.
2385   int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal) {
2386     Type *ScalarTy = FirstReducedVal->getType();
2387     Type *VecTy = VectorType::get(ScalarTy, ReduxWidth);
2388
2389     int PairwiseRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, true);
2390     int SplittingRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, false);
2391
2392     IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
2393     int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
2394
2395     int ScalarReduxCost =
2396         ReduxWidth * TTI->getArithmeticInstrCost(ReductionOpcode, VecTy);
2397
2398     DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost
2399                  << " for reduction that starts with " << *FirstReducedVal
2400                  << " (It is a "
2401                  << (IsPairwiseReduction ? "pairwise" : "splitting")
2402                  << " reduction)\n");
2403
2404     return VecReduxCost - ScalarReduxCost;
2405   }
2406
2407   static Value *createBinOp(IRBuilder<> &Builder, unsigned Opcode, Value *L,
2408                             Value *R, const Twine &Name = "") {
2409     if (Opcode == Instruction::FAdd)
2410       return Builder.CreateFAdd(L, R, Name);
2411     return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, L, R, Name);
2412   }
2413
2414   /// \brief Emit a horizontal reduction of the vectorized value.
2415   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder) {
2416     assert(VectorizedValue && "Need to have a vectorized tree node");
2417     Instruction *ValToReduce = dyn_cast<Instruction>(VectorizedValue);
2418     assert(isPowerOf2_32(ReduxWidth) &&
2419            "We only handle power-of-two reductions for now");
2420
2421     Value *TmpVec = ValToReduce;
2422     for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
2423       if (IsPairwiseReduction) {
2424         Value *LeftMask =
2425           createRdxShuffleMask(ReduxWidth, i, true, true, Builder);
2426         Value *RightMask =
2427           createRdxShuffleMask(ReduxWidth, i, true, false, Builder);
2428
2429         Value *LeftShuf = Builder.CreateShuffleVector(
2430           TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l");
2431         Value *RightShuf = Builder.CreateShuffleVector(
2432           TmpVec, UndefValue::get(TmpVec->getType()), (RightMask),
2433           "rdx.shuf.r");
2434         TmpVec = createBinOp(Builder, ReductionOpcode, LeftShuf, RightShuf,
2435                              "bin.rdx");
2436       } else {
2437         Value *UpperHalf =
2438           createRdxShuffleMask(ReduxWidth, i, false, false, Builder);
2439         Value *Shuf = Builder.CreateShuffleVector(
2440           TmpVec, UndefValue::get(TmpVec->getType()), UpperHalf, "rdx.shuf");
2441         TmpVec = createBinOp(Builder, ReductionOpcode, TmpVec, Shuf, "bin.rdx");
2442       }
2443     }
2444
2445     // The result is in the first element of the vector.
2446     return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
2447   }
2448 };
2449
2450 /// \brief Recognize construction of vectors like
2451 ///  %ra = insertelement <4 x float> undef, float %s0, i32 0
2452 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
2453 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
2454 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
2455 ///
2456 /// Returns true if it matches
2457 ///
2458 static bool findBuildVector(InsertElementInst *IE,
2459                             SmallVectorImpl<Value *> &Ops) {
2460   if (!isa<UndefValue>(IE->getOperand(0)))
2461     return false;
2462
2463   while (true) {
2464     Ops.push_back(IE->getOperand(1));
2465
2466     if (IE->use_empty())
2467       return false;
2468
2469     InsertElementInst *NextUse = dyn_cast<InsertElementInst>(IE->use_back());
2470     if (!NextUse)
2471       return true;
2472
2473     // If this isn't the final use, make sure the next insertelement is the only
2474     // use. It's OK if the final constructed vector is used multiple times
2475     if (!IE->hasOneUse())
2476       return false;
2477
2478     IE = NextUse;
2479   }
2480
2481   return false;
2482 }
2483
2484 static bool PhiTypeSorterFunc(Value *V, Value *V2) {
2485   return V->getType() < V2->getType();
2486 }
2487
2488 bool SLPVectorizer::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
2489   bool Changed = false;
2490   SmallVector<Value *, 4> Incoming;
2491   SmallSet<Value *, 16> VisitedInstrs;
2492
2493   bool HaveVectorizedPhiNodes = true;
2494   while (HaveVectorizedPhiNodes) {
2495     HaveVectorizedPhiNodes = false;
2496
2497     // Collect the incoming values from the PHIs.
2498     Incoming.clear();
2499     for (BasicBlock::iterator instr = BB->begin(), ie = BB->end(); instr != ie;
2500          ++instr) {
2501       PHINode *P = dyn_cast<PHINode>(instr);
2502       if (!P)
2503         break;
2504
2505       if (!VisitedInstrs.count(P))
2506         Incoming.push_back(P);
2507     }
2508
2509     // Sort by type.
2510     std::stable_sort(Incoming.begin(), Incoming.end(), PhiTypeSorterFunc);
2511
2512     // Try to vectorize elements base on their type.
2513     for (SmallVector<Value *, 4>::iterator IncIt = Incoming.begin(),
2514                                            E = Incoming.end();
2515          IncIt != E;) {
2516
2517       // Look for the next elements with the same type.
2518       SmallVector<Value *, 4>::iterator SameTypeIt = IncIt;
2519       while (SameTypeIt != E &&
2520              (*SameTypeIt)->getType() == (*IncIt)->getType()) {
2521         VisitedInstrs.insert(*SameTypeIt);
2522         ++SameTypeIt;
2523       }
2524
2525       // Try to vectorize them.
2526       unsigned NumElts = (SameTypeIt - IncIt);
2527       DEBUG(errs() << "SLP: Trying to vectorize starting at PHIs (" << NumElts << ")\n");
2528       if (NumElts > 1 &&
2529           tryToVectorizeList(ArrayRef<Value *>(IncIt, NumElts), R)) {
2530         // Success start over because instructions might have been changed.
2531         HaveVectorizedPhiNodes = true;
2532         Changed = true;
2533         break;
2534       }
2535
2536       // Start over at the next instruction of a different type (or the end).
2537       IncIt = SameTypeIt;
2538     }
2539   }
2540
2541   VisitedInstrs.clear();
2542
2543   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) {
2544     // We may go through BB multiple times so skip the one we have checked.
2545     if (!VisitedInstrs.insert(it))
2546       continue;
2547
2548     if (isa<DbgInfoIntrinsic>(it))
2549       continue;
2550
2551     // Try to vectorize reductions that use PHINodes.
2552     if (PHINode *P = dyn_cast<PHINode>(it)) {
2553       // Check that the PHI is a reduction PHI.
2554       if (P->getNumIncomingValues() != 2)
2555         return Changed;
2556       Value *Rdx =
2557           (P->getIncomingBlock(0) == BB
2558                ? (P->getIncomingValue(0))
2559                : (P->getIncomingBlock(1) == BB ? P->getIncomingValue(1) : 0));
2560       // Check if this is a Binary Operator.
2561       BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx);
2562       if (!BI)
2563         continue;
2564
2565       // Try to match and vectorize a horizontal reduction.
2566       HorizontalReduction HorRdx;
2567       if (ShouldVectorizeHor &&
2568           HorRdx.matchAssociativeReduction(P, BI, DL) &&
2569           HorRdx.tryToReduce(R, TTI)) {
2570         Changed = true;
2571         it = BB->begin();
2572         e = BB->end();
2573         continue;
2574       }
2575
2576      Value *Inst = BI->getOperand(0);
2577       if (Inst == P)
2578         Inst = BI->getOperand(1);
2579
2580       if (tryToVectorize(dyn_cast<BinaryOperator>(Inst), R)) {
2581         // We would like to start over since some instructions are deleted
2582         // and the iterator may become invalid value.
2583         Changed = true;
2584         it = BB->begin();
2585         e = BB->end();
2586         continue;
2587       }
2588
2589       continue;
2590     }
2591
2592     // Try to vectorize horizontal reductions feeding into a store.
2593     if (ShouldStartVectorizeHorAtStore)
2594       if (StoreInst *SI = dyn_cast<StoreInst>(it))
2595         if (BinaryOperator *BinOp =
2596                 dyn_cast<BinaryOperator>(SI->getValueOperand())) {
2597           HorizontalReduction HorRdx;
2598           if (((HorRdx.matchAssociativeReduction(0, BinOp, DL) &&
2599                 HorRdx.tryToReduce(R, TTI)) ||
2600                tryToVectorize(BinOp, R))) {
2601             Changed = true;
2602             it = BB->begin();
2603             e = BB->end();
2604             continue;
2605           }
2606         }
2607
2608     // Try to vectorize trees that start at compare instructions.
2609     if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
2610       if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) {
2611         Changed = true;
2612         // We would like to start over since some instructions are deleted
2613         // and the iterator may become invalid value.
2614         it = BB->begin();
2615         e = BB->end();
2616         continue;
2617       }
2618
2619       for (int i = 0; i < 2; ++i) {
2620          if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i))) {
2621             if (tryToVectorizePair(BI->getOperand(0), BI->getOperand(1), R)) {
2622               Changed = true;
2623               // We would like to start over since some instructions are deleted
2624               // and the iterator may become invalid value.
2625               it = BB->begin();
2626               e = BB->end();
2627             }
2628          }
2629       }
2630       continue;
2631     }
2632
2633     // Try to vectorize trees that start at insertelement instructions.
2634     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(it)) {
2635       SmallVector<Value *, 8> Ops;
2636       if (!findBuildVector(IE, Ops))
2637         continue;
2638
2639       if (tryToVectorizeList(Ops, R)) {
2640         Changed = true;
2641         it = BB->begin();
2642         e = BB->end();
2643       }
2644
2645       continue;
2646     }
2647   }
2648
2649   return Changed;
2650 }
2651
2652 bool SLPVectorizer::vectorizeStoreChains(BoUpSLP &R) {
2653   bool Changed = false;
2654   // Attempt to sort and vectorize each of the store-groups.
2655   for (StoreListMap::iterator it = StoreRefs.begin(), e = StoreRefs.end();
2656        it != e; ++it) {
2657     if (it->second.size() < 2)
2658       continue;
2659
2660     DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
2661           << it->second.size() << ".\n");
2662
2663     // Process the stores in chunks of 16.
2664     for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI+=16) {
2665       unsigned Len = std::min<unsigned>(CE - CI, 16);
2666       ArrayRef<StoreInst *> Chunk(&it->second[CI], Len);
2667       Changed |= vectorizeStores(Chunk, -SLPCostThreshold, R);
2668     }
2669   }
2670   return Changed;
2671 }
2672
2673 } // end anonymous namespace
2674
2675 char SLPVectorizer::ID = 0;
2676 static const char lv_name[] = "SLP Vectorizer";
2677 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
2678 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
2679 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
2680 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
2681 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
2682 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
2683
2684 namespace llvm {
2685 Pass *createSLPVectorizerPass() { return new SLPVectorizer(); }
2686 }