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