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