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