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