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