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