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