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