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         buildTree_rec(Left, Depth + 1);
918         buildTree_rec(Right, Depth + 1);
919         return;
920       }
921 
922       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
923         ValueList Operands;
924         // Prepare the operand vector.
925         for (unsigned j = 0; j < VL.size(); ++j)
926           Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
927 
928         buildTree_rec(Operands, Depth+1);
929       }
930       return;
931     }
932     case Instruction::Store: {
933       // Check if the stores are consecutive or of we need to swizzle them.
934       for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
935         if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
936           newTreeEntry(VL, false);
937           DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
938           return;
939         }
940 
941       newTreeEntry(VL, true);
942       DEBUG(dbgs() << "SLP: added a vector of stores.\n");
943 
944       ValueList Operands;
945       for (unsigned j = 0; j < VL.size(); ++j)
946         Operands.push_back(cast<Instruction>(VL[j])->getOperand(0));
947 
948       // We can ignore these values because we are sinking them down.
949       MemBarrierIgnoreList.insert(VL.begin(), VL.end());
950       buildTree_rec(Operands, Depth + 1);
951       return;
952     }
953     case Instruction::Call: {
954       // Check if the calls are all to the same vectorizable intrinsic.
955       CallInst *CI = cast<CallInst>(VL[0]);
956       // Check if this is an Intrinsic call or something that can be
957       // represented by an intrinsic call
958       Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
959       if (!isTriviallyVectorizable(ID)) {
960         newTreeEntry(VL, false);
961         DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
962         return;
963       }
964       Function *Int = CI->getCalledFunction();
965       Value *A1I = nullptr;
966       if (hasVectorInstrinsicScalarOpd(ID, 1))
967         A1I = CI->getArgOperand(1);
968       for (unsigned i = 1, e = VL.size(); i != e; ++i) {
969         CallInst *CI2 = dyn_cast<CallInst>(VL[i]);
970         if (!CI2 || CI2->getCalledFunction() != Int ||
971             getIntrinsicIDForCall(CI2, TLI) != ID) {
972           newTreeEntry(VL, false);
973           DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *VL[i]
974                        << "\n");
975           return;
976         }
977         // ctlz,cttz and powi are special intrinsics whose second argument
978         // should be same in order for them to be vectorized.
979         if (hasVectorInstrinsicScalarOpd(ID, 1)) {
980           Value *A1J = CI2->getArgOperand(1);
981           if (A1I != A1J) {
982             newTreeEntry(VL, false);
983             DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
984                          << " argument "<< A1I<<"!=" << A1J
985                          << "\n");
986             return;
987           }
988         }
989       }
990 
991       newTreeEntry(VL, true);
992       for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i) {
993         ValueList Operands;
994         // Prepare the operand vector.
995         for (unsigned j = 0; j < VL.size(); ++j) {
996           CallInst *CI2 = dyn_cast<CallInst>(VL[j]);
997           Operands.push_back(CI2->getArgOperand(i));
998         }
999         buildTree_rec(Operands, Depth + 1);
1000       }
1001       return;
1002     }
1003     default:
1004       newTreeEntry(VL, false);
1005       DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
1006       return;
1007   }
1008 }
1009 
1010 int BoUpSLP::getEntryCost(TreeEntry *E) {
1011   ArrayRef<Value*> VL = E->Scalars;
1012 
1013   Type *ScalarTy = VL[0]->getType();
1014   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1015     ScalarTy = SI->getValueOperand()->getType();
1016   VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1017 
1018   if (E->NeedToGather) {
1019     if (allConstant(VL))
1020       return 0;
1021     if (isSplat(VL)) {
1022       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
1023     }
1024     return getGatherCost(E->Scalars);
1025   }
1026 
1027   assert(getSameOpcode(VL) && getSameType(VL) && getSameBlock(VL) &&
1028          "Invalid VL");
1029   Instruction *VL0 = cast<Instruction>(VL[0]);
1030   unsigned Opcode = VL0->getOpcode();
1031   switch (Opcode) {
1032     case Instruction::PHI: {
1033       return 0;
1034     }
1035     case Instruction::ExtractElement: {
1036       if (CanReuseExtract(VL)) {
1037         int DeadCost = 0;
1038         for (unsigned i = 0, e = VL.size(); i < e; ++i) {
1039           ExtractElementInst *E = cast<ExtractElementInst>(VL[i]);
1040           if (E->hasOneUse())
1041             // Take credit for instruction that will become dead.
1042             DeadCost +=
1043                 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, i);
1044         }
1045         return -DeadCost;
1046       }
1047       return getGatherCost(VecTy);
1048     }
1049     case Instruction::ZExt:
1050     case Instruction::SExt:
1051     case Instruction::FPToUI:
1052     case Instruction::FPToSI:
1053     case Instruction::FPExt:
1054     case Instruction::PtrToInt:
1055     case Instruction::IntToPtr:
1056     case Instruction::SIToFP:
1057     case Instruction::UIToFP:
1058     case Instruction::Trunc:
1059     case Instruction::FPTrunc:
1060     case Instruction::BitCast: {
1061       Type *SrcTy = VL0->getOperand(0)->getType();
1062 
1063       // Calculate the cost of this instruction.
1064       int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(),
1065                                                          VL0->getType(), SrcTy);
1066 
1067       VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
1068       int VecCost = TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy);
1069       return VecCost - ScalarCost;
1070     }
1071     case Instruction::FCmp:
1072     case Instruction::ICmp:
1073     case Instruction::Select:
1074     case Instruction::Add:
1075     case Instruction::FAdd:
1076     case Instruction::Sub:
1077     case Instruction::FSub:
1078     case Instruction::Mul:
1079     case Instruction::FMul:
1080     case Instruction::UDiv:
1081     case Instruction::SDiv:
1082     case Instruction::FDiv:
1083     case Instruction::URem:
1084     case Instruction::SRem:
1085     case Instruction::FRem:
1086     case Instruction::Shl:
1087     case Instruction::LShr:
1088     case Instruction::AShr:
1089     case Instruction::And:
1090     case Instruction::Or:
1091     case Instruction::Xor: {
1092       // Calculate the cost of this instruction.
1093       int ScalarCost = 0;
1094       int VecCost = 0;
1095       if (Opcode == Instruction::FCmp || Opcode == Instruction::ICmp ||
1096           Opcode == Instruction::Select) {
1097         VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
1098         ScalarCost = VecTy->getNumElements() *
1099         TTI->getCmpSelInstrCost(Opcode, ScalarTy, Builder.getInt1Ty());
1100         VecCost = TTI->getCmpSelInstrCost(Opcode, VecTy, MaskTy);
1101       } else {
1102         // Certain instructions can be cheaper to vectorize if they have a
1103         // constant second vector operand.
1104         TargetTransformInfo::OperandValueKind Op1VK =
1105             TargetTransformInfo::OK_AnyValue;
1106         TargetTransformInfo::OperandValueKind Op2VK =
1107             TargetTransformInfo::OK_UniformConstantValue;
1108 
1109         // If all operands are exactly the same ConstantInt then set the
1110         // operand kind to OK_UniformConstantValue.
1111         // If instead not all operands are constants, then set the operand kind
1112         // to OK_AnyValue. If all operands are constants but not the same,
1113         // then set the operand kind to OK_NonUniformConstantValue.
1114         ConstantInt *CInt = nullptr;
1115         for (unsigned i = 0; i < VL.size(); ++i) {
1116           const Instruction *I = cast<Instruction>(VL[i]);
1117           if (!isa<ConstantInt>(I->getOperand(1))) {
1118             Op2VK = TargetTransformInfo::OK_AnyValue;
1119             break;
1120           }
1121           if (i == 0) {
1122             CInt = cast<ConstantInt>(I->getOperand(1));
1123             continue;
1124           }
1125           if (Op2VK == TargetTransformInfo::OK_UniformConstantValue &&
1126               CInt != cast<ConstantInt>(I->getOperand(1)))
1127             Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
1128         }
1129 
1130         ScalarCost =
1131             VecTy->getNumElements() *
1132             TTI->getArithmeticInstrCost(Opcode, ScalarTy, Op1VK, Op2VK);
1133         VecCost = TTI->getArithmeticInstrCost(Opcode, VecTy, Op1VK, Op2VK);
1134       }
1135       return VecCost - ScalarCost;
1136     }
1137     case Instruction::Load: {
1138       // Cost of wide load - cost of scalar loads.
1139       int ScalarLdCost = VecTy->getNumElements() *
1140       TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
1141       int VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, 1, 0);
1142       return VecLdCost - ScalarLdCost;
1143     }
1144     case Instruction::Store: {
1145       // We know that we can merge the stores. Calculate the cost.
1146       int ScalarStCost = VecTy->getNumElements() *
1147       TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
1148       int VecStCost = TTI->getMemoryOpCost(Instruction::Store, VecTy, 1, 0);
1149       return VecStCost - ScalarStCost;
1150     }
1151     case Instruction::Call: {
1152       CallInst *CI = cast<CallInst>(VL0);
1153       Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
1154 
1155       // Calculate the cost of the scalar and vector calls.
1156       SmallVector<Type*, 4> ScalarTys, VecTys;
1157       for (unsigned op = 0, opc = CI->getNumArgOperands(); op!= opc; ++op) {
1158         ScalarTys.push_back(CI->getArgOperand(op)->getType());
1159         VecTys.push_back(VectorType::get(CI->getArgOperand(op)->getType(),
1160                                          VecTy->getNumElements()));
1161       }
1162 
1163       int ScalarCallCost = VecTy->getNumElements() *
1164           TTI->getIntrinsicInstrCost(ID, ScalarTy, ScalarTys);
1165 
1166       int VecCallCost = TTI->getIntrinsicInstrCost(ID, VecTy, VecTys);
1167 
1168       DEBUG(dbgs() << "SLP: Call cost "<< VecCallCost - ScalarCallCost
1169             << " (" << VecCallCost  << "-" <<  ScalarCallCost << ")"
1170             << " for " << *CI << "\n");
1171 
1172       return VecCallCost - ScalarCallCost;
1173     }
1174     default:
1175       llvm_unreachable("Unknown instruction");
1176   }
1177 }
1178 
1179 bool BoUpSLP::isFullyVectorizableTinyTree() {
1180   DEBUG(dbgs() << "SLP: Check whether the tree with height " <<
1181         VectorizableTree.size() << " is fully vectorizable .\n");
1182 
1183   // We only handle trees of height 2.
1184   if (VectorizableTree.size() != 2)
1185     return false;
1186 
1187   // Handle splat stores.
1188   if (!VectorizableTree[0].NeedToGather && isSplat(VectorizableTree[1].Scalars))
1189     return true;
1190 
1191   // Gathering cost would be too much for tiny trees.
1192   if (VectorizableTree[0].NeedToGather || VectorizableTree[1].NeedToGather)
1193     return false;
1194 
1195   return true;
1196 }
1197 
1198 int BoUpSLP::getTreeCost() {
1199   int Cost = 0;
1200   DEBUG(dbgs() << "SLP: Calculating cost for tree of size " <<
1201         VectorizableTree.size() << ".\n");
1202 
1203   // We only vectorize tiny trees if it is fully vectorizable.
1204   if (VectorizableTree.size() < 3 && !isFullyVectorizableTinyTree()) {
1205     if (!VectorizableTree.size()) {
1206       assert(!ExternalUses.size() && "We should not have any external users");
1207     }
1208     return INT_MAX;
1209   }
1210 
1211   unsigned BundleWidth = VectorizableTree[0].Scalars.size();
1212 
1213   for (unsigned i = 0, e = VectorizableTree.size(); i != e; ++i) {
1214     int C = getEntryCost(&VectorizableTree[i]);
1215     DEBUG(dbgs() << "SLP: Adding cost " << C << " for bundle that starts with "
1216           << *VectorizableTree[i].Scalars[0] << " .\n");
1217     Cost += C;
1218   }
1219 
1220   SmallSet<Value *, 16> ExtractCostCalculated;
1221   int ExtractCost = 0;
1222   for (UserList::iterator I = ExternalUses.begin(), E = ExternalUses.end();
1223        I != E; ++I) {
1224     // We only add extract cost once for the same scalar.
1225     if (!ExtractCostCalculated.insert(I->Scalar))
1226       continue;
1227 
1228     VectorType *VecTy = VectorType::get(I->Scalar->getType(), BundleWidth);
1229     ExtractCost += TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy,
1230                                            I->Lane);
1231   }
1232 
1233   DEBUG(dbgs() << "SLP: Total Cost " << Cost + ExtractCost<< ".\n");
1234   return  Cost + ExtractCost;
1235 }
1236 
1237 int BoUpSLP::getGatherCost(Type *Ty) {
1238   int Cost = 0;
1239   for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
1240     Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
1241   return Cost;
1242 }
1243 
1244 int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) {
1245   // Find the type of the operands in VL.
1246   Type *ScalarTy = VL[0]->getType();
1247   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1248     ScalarTy = SI->getValueOperand()->getType();
1249   VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1250   // Find the cost of inserting/extracting values from the vector.
1251   return getGatherCost(VecTy);
1252 }
1253 
1254 AliasAnalysis::Location BoUpSLP::getLocation(Instruction *I) {
1255   if (StoreInst *SI = dyn_cast<StoreInst>(I))
1256     return AA->getLocation(SI);
1257   if (LoadInst *LI = dyn_cast<LoadInst>(I))
1258     return AA->getLocation(LI);
1259   return AliasAnalysis::Location();
1260 }
1261 
1262 Value *BoUpSLP::getPointerOperand(Value *I) {
1263   if (LoadInst *LI = dyn_cast<LoadInst>(I))
1264     return LI->getPointerOperand();
1265   if (StoreInst *SI = dyn_cast<StoreInst>(I))
1266     return SI->getPointerOperand();
1267   return nullptr;
1268 }
1269 
1270 unsigned BoUpSLP::getAddressSpaceOperand(Value *I) {
1271   if (LoadInst *L = dyn_cast<LoadInst>(I))
1272     return L->getPointerAddressSpace();
1273   if (StoreInst *S = dyn_cast<StoreInst>(I))
1274     return S->getPointerAddressSpace();
1275   return -1;
1276 }
1277 
1278 bool BoUpSLP::isConsecutiveAccess(Value *A, Value *B) {
1279   Value *PtrA = getPointerOperand(A);
1280   Value *PtrB = getPointerOperand(B);
1281   unsigned ASA = getAddressSpaceOperand(A);
1282   unsigned ASB = getAddressSpaceOperand(B);
1283 
1284   // Check that the address spaces match and that the pointers are valid.
1285   if (!PtrA || !PtrB || (ASA != ASB))
1286     return false;
1287 
1288   // Make sure that A and B are different pointers of the same type.
1289   if (PtrA == PtrB || PtrA->getType() != PtrB->getType())
1290     return false;
1291 
1292   unsigned PtrBitWidth = DL->getPointerSizeInBits(ASA);
1293   Type *Ty = cast<PointerType>(PtrA->getType())->getElementType();
1294   APInt Size(PtrBitWidth, DL->getTypeStoreSize(Ty));
1295 
1296   APInt OffsetA(PtrBitWidth, 0), OffsetB(PtrBitWidth, 0);
1297   PtrA = PtrA->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetA);
1298   PtrB = PtrB->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetB);
1299 
1300   APInt OffsetDelta = OffsetB - OffsetA;
1301 
1302   // Check if they are based on the same pointer. That makes the offsets
1303   // sufficient.
1304   if (PtrA == PtrB)
1305     return OffsetDelta == Size;
1306 
1307   // Compute the necessary base pointer delta to have the necessary final delta
1308   // equal to the size.
1309   APInt BaseDelta = Size - OffsetDelta;
1310 
1311   // Otherwise compute the distance with SCEV between the base pointers.
1312   const SCEV *PtrSCEVA = SE->getSCEV(PtrA);
1313   const SCEV *PtrSCEVB = SE->getSCEV(PtrB);
1314   const SCEV *C = SE->getConstant(BaseDelta);
1315   const SCEV *X = SE->getAddExpr(PtrSCEVA, C);
1316   return X == PtrSCEVB;
1317 }
1318 
1319 Value *BoUpSLP::getSinkBarrier(Instruction *Src, Instruction *Dst) {
1320   assert(Src->getParent() == Dst->getParent() && "Not the same BB");
1321   BasicBlock::iterator I = Src, E = Dst;
1322   /// Scan all of the instruction from SRC to DST and check if
1323   /// the source may alias.
1324   for (++I; I != E; ++I) {
1325     // Ignore store instructions that are marked as 'ignore'.
1326     if (MemBarrierIgnoreList.count(I))
1327       continue;
1328     if (Src->mayWriteToMemory()) /* Write */ {
1329       if (!I->mayReadOrWriteMemory())
1330         continue;
1331     } else /* Read */ {
1332       if (!I->mayWriteToMemory())
1333         continue;
1334     }
1335     AliasAnalysis::Location A = getLocation(&*I);
1336     AliasAnalysis::Location B = getLocation(Src);
1337 
1338     if (!A.Ptr || !B.Ptr || AA->alias(A, B))
1339       return I;
1340   }
1341   return nullptr;
1342 }
1343 
1344 int BoUpSLP::getLastIndex(ArrayRef<Value *> VL) {
1345   BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
1346   assert(BB == getSameBlock(VL) && "Invalid block");
1347   BlockNumbering &BN = getBlockNumbering(BB);
1348 
1349   int MaxIdx = BN.getIndex(BB->getFirstNonPHI());
1350   for (unsigned i = 0, e = VL.size(); i < e; ++i)
1351     MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
1352   return MaxIdx;
1353 }
1354 
1355 Instruction *BoUpSLP::getLastInstruction(ArrayRef<Value *> VL) {
1356   BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
1357   assert(BB == getSameBlock(VL) && "Invalid block");
1358   BlockNumbering &BN = getBlockNumbering(BB);
1359 
1360   int MaxIdx = BN.getIndex(cast<Instruction>(VL[0]));
1361   for (unsigned i = 1, e = VL.size(); i < e; ++i)
1362     MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
1363   Instruction *I = BN.getInstruction(MaxIdx);
1364   assert(I && "bad location");
1365   return I;
1366 }
1367 
1368 void BoUpSLP::setInsertPointAfterBundle(ArrayRef<Value *> VL) {
1369   Instruction *VL0 = cast<Instruction>(VL[0]);
1370   Instruction *LastInst = getLastInstruction(VL);
1371   BasicBlock::iterator NextInst = LastInst;
1372   ++NextInst;
1373   Builder.SetInsertPoint(VL0->getParent(), NextInst);
1374   Builder.SetCurrentDebugLocation(VL0->getDebugLoc());
1375 }
1376 
1377 Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
1378   Value *Vec = UndefValue::get(Ty);
1379   // Generate the 'InsertElement' instruction.
1380   for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
1381     Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
1382     if (Instruction *Insrt = dyn_cast<Instruction>(Vec)) {
1383       GatherSeq.insert(Insrt);
1384       CSEBlocks.insert(Insrt->getParent());
1385 
1386       // Add to our 'need-to-extract' list.
1387       if (ScalarToTreeEntry.count(VL[i])) {
1388         int Idx = ScalarToTreeEntry[VL[i]];
1389         TreeEntry *E = &VectorizableTree[Idx];
1390         // Find which lane we need to extract.
1391         int FoundLane = -1;
1392         for (unsigned Lane = 0, LE = VL.size(); Lane != LE; ++Lane) {
1393           // Is this the lane of the scalar that we are looking for ?
1394           if (E->Scalars[Lane] == VL[i]) {
1395             FoundLane = Lane;
1396             break;
1397           }
1398         }
1399         assert(FoundLane >= 0 && "Could not find the correct lane");
1400         ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
1401       }
1402     }
1403   }
1404 
1405   return Vec;
1406 }
1407 
1408 Value *BoUpSLP::alreadyVectorized(ArrayRef<Value *> VL) const {
1409   SmallDenseMap<Value*, int>::const_iterator Entry
1410     = ScalarToTreeEntry.find(VL[0]);
1411   if (Entry != ScalarToTreeEntry.end()) {
1412     int Idx = Entry->second;
1413     const TreeEntry *En = &VectorizableTree[Idx];
1414     if (En->isSame(VL) && En->VectorizedValue)
1415       return En->VectorizedValue;
1416   }
1417   return nullptr;
1418 }
1419 
1420 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
1421   if (ScalarToTreeEntry.count(VL[0])) {
1422     int Idx = ScalarToTreeEntry[VL[0]];
1423     TreeEntry *E = &VectorizableTree[Idx];
1424     if (E->isSame(VL))
1425       return vectorizeTree(E);
1426   }
1427 
1428   Type *ScalarTy = VL[0]->getType();
1429   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1430     ScalarTy = SI->getValueOperand()->getType();
1431   VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1432 
1433   return Gather(VL, VecTy);
1434 }
1435 
1436 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
1437   IRBuilder<>::InsertPointGuard Guard(Builder);
1438 
1439   if (E->VectorizedValue) {
1440     DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
1441     return E->VectorizedValue;
1442   }
1443 
1444   Instruction *VL0 = cast<Instruction>(E->Scalars[0]);
1445   Type *ScalarTy = VL0->getType();
1446   if (StoreInst *SI = dyn_cast<StoreInst>(VL0))
1447     ScalarTy = SI->getValueOperand()->getType();
1448   VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size());
1449 
1450   if (E->NeedToGather) {
1451     setInsertPointAfterBundle(E->Scalars);
1452     return Gather(E->Scalars, VecTy);
1453   }
1454 
1455   unsigned Opcode = VL0->getOpcode();
1456   assert(Opcode == getSameOpcode(E->Scalars) && "Invalid opcode");
1457 
1458   switch (Opcode) {
1459     case Instruction::PHI: {
1460       PHINode *PH = dyn_cast<PHINode>(VL0);
1461       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
1462       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1463       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
1464       E->VectorizedValue = NewPhi;
1465 
1466       // PHINodes may have multiple entries from the same block. We want to
1467       // visit every block once.
1468       SmallSet<BasicBlock*, 4> VisitedBBs;
1469 
1470       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1471         ValueList Operands;
1472         BasicBlock *IBB = PH->getIncomingBlock(i);
1473 
1474         if (!VisitedBBs.insert(IBB)) {
1475           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
1476           continue;
1477         }
1478 
1479         // Prepare the operand vector.
1480         for (unsigned j = 0; j < E->Scalars.size(); ++j)
1481           Operands.push_back(cast<PHINode>(E->Scalars[j])->
1482                              getIncomingValueForBlock(IBB));
1483 
1484         Builder.SetInsertPoint(IBB->getTerminator());
1485         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1486         Value *Vec = vectorizeTree(Operands);
1487         NewPhi->addIncoming(Vec, IBB);
1488       }
1489 
1490       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
1491              "Invalid number of incoming values");
1492       return NewPhi;
1493     }
1494 
1495     case Instruction::ExtractElement: {
1496       if (CanReuseExtract(E->Scalars)) {
1497         Value *V = VL0->getOperand(0);
1498         E->VectorizedValue = V;
1499         return V;
1500       }
1501       return Gather(E->Scalars, VecTy);
1502     }
1503     case Instruction::ZExt:
1504     case Instruction::SExt:
1505     case Instruction::FPToUI:
1506     case Instruction::FPToSI:
1507     case Instruction::FPExt:
1508     case Instruction::PtrToInt:
1509     case Instruction::IntToPtr:
1510     case Instruction::SIToFP:
1511     case Instruction::UIToFP:
1512     case Instruction::Trunc:
1513     case Instruction::FPTrunc:
1514     case Instruction::BitCast: {
1515       ValueList INVL;
1516       for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1517         INVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1518 
1519       setInsertPointAfterBundle(E->Scalars);
1520 
1521       Value *InVec = vectorizeTree(INVL);
1522 
1523       if (Value *V = alreadyVectorized(E->Scalars))
1524         return V;
1525 
1526       CastInst *CI = dyn_cast<CastInst>(VL0);
1527       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
1528       E->VectorizedValue = V;
1529       return V;
1530     }
1531     case Instruction::FCmp:
1532     case Instruction::ICmp: {
1533       ValueList LHSV, RHSV;
1534       for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1535         LHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1536         RHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1537       }
1538 
1539       setInsertPointAfterBundle(E->Scalars);
1540 
1541       Value *L = vectorizeTree(LHSV);
1542       Value *R = vectorizeTree(RHSV);
1543 
1544       if (Value *V = alreadyVectorized(E->Scalars))
1545         return V;
1546 
1547       CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
1548       Value *V;
1549       if (Opcode == Instruction::FCmp)
1550         V = Builder.CreateFCmp(P0, L, R);
1551       else
1552         V = Builder.CreateICmp(P0, L, R);
1553 
1554       E->VectorizedValue = V;
1555       return V;
1556     }
1557     case Instruction::Select: {
1558       ValueList TrueVec, FalseVec, CondVec;
1559       for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1560         CondVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1561         TrueVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1562         FalseVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(2));
1563       }
1564 
1565       setInsertPointAfterBundle(E->Scalars);
1566 
1567       Value *Cond = vectorizeTree(CondVec);
1568       Value *True = vectorizeTree(TrueVec);
1569       Value *False = vectorizeTree(FalseVec);
1570 
1571       if (Value *V = alreadyVectorized(E->Scalars))
1572         return V;
1573 
1574       Value *V = Builder.CreateSelect(Cond, True, False);
1575       E->VectorizedValue = V;
1576       return V;
1577     }
1578     case Instruction::Add:
1579     case Instruction::FAdd:
1580     case Instruction::Sub:
1581     case Instruction::FSub:
1582     case Instruction::Mul:
1583     case Instruction::FMul:
1584     case Instruction::UDiv:
1585     case Instruction::SDiv:
1586     case Instruction::FDiv:
1587     case Instruction::URem:
1588     case Instruction::SRem:
1589     case Instruction::FRem:
1590     case Instruction::Shl:
1591     case Instruction::LShr:
1592     case Instruction::AShr:
1593     case Instruction::And:
1594     case Instruction::Or:
1595     case Instruction::Xor: {
1596       ValueList LHSVL, RHSVL;
1597       if (isa<BinaryOperator>(VL0) && VL0->isCommutative())
1598         reorderInputsAccordingToOpcode(E->Scalars, LHSVL, RHSVL);
1599       else
1600         for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1601           LHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1602           RHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1603         }
1604 
1605       setInsertPointAfterBundle(E->Scalars);
1606 
1607       Value *LHS = vectorizeTree(LHSVL);
1608       Value *RHS = vectorizeTree(RHSVL);
1609 
1610       if (LHS == RHS && isa<Instruction>(LHS)) {
1611         assert((VL0->getOperand(0) == VL0->getOperand(1)) && "Invalid order");
1612       }
1613 
1614       if (Value *V = alreadyVectorized(E->Scalars))
1615         return V;
1616 
1617       BinaryOperator *BinOp = cast<BinaryOperator>(VL0);
1618       Value *V = Builder.CreateBinOp(BinOp->getOpcode(), LHS, RHS);
1619       E->VectorizedValue = V;
1620 
1621       if (Instruction *I = dyn_cast<Instruction>(V))
1622         return propagateMetadata(I, E->Scalars);
1623 
1624       return V;
1625     }
1626     case Instruction::Load: {
1627       // Loads are inserted at the head of the tree because we don't want to
1628       // sink them all the way down past store instructions.
1629       setInsertPointAfterBundle(E->Scalars);
1630 
1631       LoadInst *LI = cast<LoadInst>(VL0);
1632       unsigned AS = LI->getPointerAddressSpace();
1633 
1634       Value *VecPtr = Builder.CreateBitCast(LI->getPointerOperand(),
1635                                             VecTy->getPointerTo(AS));
1636       unsigned Alignment = LI->getAlignment();
1637       LI = Builder.CreateLoad(VecPtr);
1638       if (!Alignment)
1639         Alignment = DL->getABITypeAlignment(LI->getPointerOperand()->getType());
1640       LI->setAlignment(Alignment);
1641       E->VectorizedValue = LI;
1642       return propagateMetadata(LI, E->Scalars);
1643     }
1644     case Instruction::Store: {
1645       StoreInst *SI = cast<StoreInst>(VL0);
1646       unsigned Alignment = SI->getAlignment();
1647       unsigned AS = SI->getPointerAddressSpace();
1648 
1649       ValueList ValueOp;
1650       for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1651         ValueOp.push_back(cast<StoreInst>(E->Scalars[i])->getValueOperand());
1652 
1653       setInsertPointAfterBundle(E->Scalars);
1654 
1655       Value *VecValue = vectorizeTree(ValueOp);
1656       Value *VecPtr = Builder.CreateBitCast(SI->getPointerOperand(),
1657                                             VecTy->getPointerTo(AS));
1658       StoreInst *S = Builder.CreateStore(VecValue, VecPtr);
1659       if (!Alignment)
1660         Alignment = DL->getABITypeAlignment(SI->getPointerOperand()->getType());
1661       S->setAlignment(Alignment);
1662       E->VectorizedValue = S;
1663       return propagateMetadata(S, E->Scalars);
1664     }
1665     case Instruction::Call: {
1666       CallInst *CI = cast<CallInst>(VL0);
1667       setInsertPointAfterBundle(E->Scalars);
1668       Function *FI;
1669       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
1670       if (CI && (FI = CI->getCalledFunction())) {
1671         IID = (Intrinsic::ID) FI->getIntrinsicID();
1672       }
1673       std::vector<Value *> OpVecs;
1674       for (int j = 0, e = CI->getNumArgOperands(); j < e; ++j) {
1675         ValueList OpVL;
1676         // ctlz,cttz and powi are special intrinsics whose second argument is
1677         // a scalar. This argument should not be vectorized.
1678         if (hasVectorInstrinsicScalarOpd(IID, 1) && j == 1) {
1679           CallInst *CEI = cast<CallInst>(E->Scalars[0]);
1680           OpVecs.push_back(CEI->getArgOperand(j));
1681           continue;
1682         }
1683         for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1684           CallInst *CEI = cast<CallInst>(E->Scalars[i]);
1685           OpVL.push_back(CEI->getArgOperand(j));
1686         }
1687 
1688         Value *OpVec = vectorizeTree(OpVL);
1689         DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
1690         OpVecs.push_back(OpVec);
1691       }
1692 
1693       Module *M = F->getParent();
1694       Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
1695       Type *Tys[] = { VectorType::get(CI->getType(), E->Scalars.size()) };
1696       Function *CF = Intrinsic::getDeclaration(M, ID, Tys);
1697       Value *V = Builder.CreateCall(CF, OpVecs);
1698       E->VectorizedValue = V;
1699       return V;
1700     }
1701     default:
1702     llvm_unreachable("unknown inst");
1703   }
1704   return nullptr;
1705 }
1706 
1707 Value *BoUpSLP::vectorizeTree() {
1708   Builder.SetInsertPoint(F->getEntryBlock().begin());
1709   vectorizeTree(&VectorizableTree[0]);
1710 
1711   DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() << " values .\n");
1712 
1713   // Extract all of the elements with the external uses.
1714   for (UserList::iterator it = ExternalUses.begin(), e = ExternalUses.end();
1715        it != e; ++it) {
1716     Value *Scalar = it->Scalar;
1717     llvm::User *User = it->User;
1718 
1719     // Skip users that we already RAUW. This happens when one instruction
1720     // has multiple uses of the same value.
1721     if (std::find(Scalar->user_begin(), Scalar->user_end(), User) ==
1722         Scalar->user_end())
1723       continue;
1724     assert(ScalarToTreeEntry.count(Scalar) && "Invalid scalar");
1725 
1726     int Idx = ScalarToTreeEntry[Scalar];
1727     TreeEntry *E = &VectorizableTree[Idx];
1728     assert(!E->NeedToGather && "Extracting from a gather list");
1729 
1730     Value *Vec = E->VectorizedValue;
1731     assert(Vec && "Can't find vectorizable value");
1732 
1733     Value *Lane = Builder.getInt32(it->Lane);
1734     // Generate extracts for out-of-tree users.
1735     // Find the insertion point for the extractelement lane.
1736     if (isa<Instruction>(Vec)){
1737       if (PHINode *PH = dyn_cast<PHINode>(User)) {
1738         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
1739           if (PH->getIncomingValue(i) == Scalar) {
1740             Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
1741             Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1742             CSEBlocks.insert(PH->getIncomingBlock(i));
1743             PH->setOperand(i, Ex);
1744           }
1745         }
1746       } else {
1747         Builder.SetInsertPoint(cast<Instruction>(User));
1748         Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1749         CSEBlocks.insert(cast<Instruction>(User)->getParent());
1750         User->replaceUsesOfWith(Scalar, Ex);
1751      }
1752     } else {
1753       Builder.SetInsertPoint(F->getEntryBlock().begin());
1754       Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1755       CSEBlocks.insert(&F->getEntryBlock());
1756       User->replaceUsesOfWith(Scalar, Ex);
1757     }
1758 
1759     DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
1760   }
1761 
1762   // For each vectorized value:
1763   for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
1764     TreeEntry *Entry = &VectorizableTree[EIdx];
1765 
1766     // For each lane:
1767     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
1768       Value *Scalar = Entry->Scalars[Lane];
1769 
1770       // No need to handle users of gathered values.
1771       if (Entry->NeedToGather)
1772         continue;
1773 
1774       assert(Entry->VectorizedValue && "Can't find vectorizable value");
1775 
1776       Type *Ty = Scalar->getType();
1777       if (!Ty->isVoidTy()) {
1778 #ifndef NDEBUG
1779         for (User *U : Scalar->users()) {
1780           DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
1781 
1782           assert((ScalarToTreeEntry.count(U) ||
1783                   // It is legal to replace users in the ignorelist by undef.
1784                   (std::find(UserIgnoreList.begin(), UserIgnoreList.end(), U) !=
1785                    UserIgnoreList.end())) &&
1786                  "Replacing out-of-tree value with undef");
1787         }
1788 #endif
1789         Value *Undef = UndefValue::get(Ty);
1790         Scalar->replaceAllUsesWith(Undef);
1791       }
1792       DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
1793       cast<Instruction>(Scalar)->eraseFromParent();
1794     }
1795   }
1796 
1797   for (auto &BN : BlocksNumbers)
1798     BN.second.forget();
1799 
1800   Builder.ClearInsertionPoint();
1801 
1802   return VectorizableTree[0].VectorizedValue;
1803 }
1804 
1805 void BoUpSLP::optimizeGatherSequence() {
1806   DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
1807         << " gather sequences instructions.\n");
1808   // LICM InsertElementInst sequences.
1809   for (SetVector<Instruction *>::iterator it = GatherSeq.begin(),
1810        e = GatherSeq.end(); it != e; ++it) {
1811     InsertElementInst *Insert = dyn_cast<InsertElementInst>(*it);
1812 
1813     if (!Insert)
1814       continue;
1815 
1816     // Check if this block is inside a loop.
1817     Loop *L = LI->getLoopFor(Insert->getParent());
1818     if (!L)
1819       continue;
1820 
1821     // Check if it has a preheader.
1822     BasicBlock *PreHeader = L->getLoopPreheader();
1823     if (!PreHeader)
1824       continue;
1825 
1826     // If the vector or the element that we insert into it are
1827     // instructions that are defined in this basic block then we can't
1828     // hoist this instruction.
1829     Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
1830     Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
1831     if (CurrVec && L->contains(CurrVec))
1832       continue;
1833     if (NewElem && L->contains(NewElem))
1834       continue;
1835 
1836     // We can hoist this instruction. Move it to the pre-header.
1837     Insert->moveBefore(PreHeader->getTerminator());
1838   }
1839 
1840   // Make a list of all reachable blocks in our CSE queue.
1841   SmallVector<const DomTreeNode *, 8> CSEWorkList;
1842   CSEWorkList.reserve(CSEBlocks.size());
1843   for (BasicBlock *BB : CSEBlocks)
1844     if (DomTreeNode *N = DT->getNode(BB)) {
1845       assert(DT->isReachableFromEntry(N));
1846       CSEWorkList.push_back(N);
1847     }
1848 
1849   // Sort blocks by domination. This ensures we visit a block after all blocks
1850   // dominating it are visited.
1851   std::stable_sort(CSEWorkList.begin(), CSEWorkList.end(),
1852                    [this](const DomTreeNode *A, const DomTreeNode *B) {
1853     return DT->properlyDominates(A, B);
1854   });
1855 
1856   // Perform O(N^2) search over the gather sequences and merge identical
1857   // instructions. TODO: We can further optimize this scan if we split the
1858   // instructions into different buckets based on the insert lane.
1859   SmallVector<Instruction *, 16> Visited;
1860   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
1861     assert((I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
1862            "Worklist not sorted properly!");
1863     BasicBlock *BB = (*I)->getBlock();
1864     // For all instructions in blocks containing gather sequences:
1865     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) {
1866       Instruction *In = it++;
1867       if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In))
1868         continue;
1869 
1870       // Check if we can replace this instruction with any of the
1871       // visited instructions.
1872       for (SmallVectorImpl<Instruction *>::iterator v = Visited.begin(),
1873                                                     ve = Visited.end();
1874            v != ve; ++v) {
1875         if (In->isIdenticalTo(*v) &&
1876             DT->dominates((*v)->getParent(), In->getParent())) {
1877           In->replaceAllUsesWith(*v);
1878           In->eraseFromParent();
1879           In = nullptr;
1880           break;
1881         }
1882       }
1883       if (In) {
1884         assert(std::find(Visited.begin(), Visited.end(), In) == Visited.end());
1885         Visited.push_back(In);
1886       }
1887     }
1888   }
1889   CSEBlocks.clear();
1890   GatherSeq.clear();
1891 }
1892 
1893 /// The SLPVectorizer Pass.
1894 struct SLPVectorizer : public FunctionPass {
1895   typedef SmallVector<StoreInst *, 8> StoreList;
1896   typedef MapVector<Value *, StoreList> StoreListMap;
1897 
1898   /// Pass identification, replacement for typeid
1899   static char ID;
1900 
1901   explicit SLPVectorizer() : FunctionPass(ID) {
1902     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
1903   }
1904 
1905   ScalarEvolution *SE;
1906   const DataLayout *DL;
1907   TargetTransformInfo *TTI;
1908   TargetLibraryInfo *TLI;
1909   AliasAnalysis *AA;
1910   LoopInfo *LI;
1911   DominatorTree *DT;
1912 
1913   bool runOnFunction(Function &F) override {
1914     if (skipOptnoneFunction(F))
1915       return false;
1916 
1917     SE = &getAnalysis<ScalarEvolution>();
1918     DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1919     DL = DLP ? &DLP->getDataLayout() : nullptr;
1920     TTI = &getAnalysis<TargetTransformInfo>();
1921     TLI = getAnalysisIfAvailable<TargetLibraryInfo>();
1922     AA = &getAnalysis<AliasAnalysis>();
1923     LI = &getAnalysis<LoopInfo>();
1924     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1925 
1926     StoreRefs.clear();
1927     bool Changed = false;
1928 
1929     // If the target claims to have no vector registers don't attempt
1930     // vectorization.
1931     if (!TTI->getNumberOfRegisters(true))
1932       return false;
1933 
1934     // Must have DataLayout. We can't require it because some tests run w/o
1935     // triple.
1936     if (!DL)
1937       return false;
1938 
1939     // Don't vectorize when the attribute NoImplicitFloat is used.
1940     if (F.hasFnAttribute(Attribute::NoImplicitFloat))
1941       return false;
1942 
1943     DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
1944 
1945     // Use the bottom up slp vectorizer to construct chains that start with
1946     // store instructions.
1947     BoUpSLP R(&F, SE, DL, TTI, TLI, AA, LI, DT);
1948 
1949     // Scan the blocks in the function in post order.
1950     for (po_iterator<BasicBlock*> it = po_begin(&F.getEntryBlock()),
1951          e = po_end(&F.getEntryBlock()); it != e; ++it) {
1952       BasicBlock *BB = *it;
1953 
1954       // Vectorize trees that end at stores.
1955       if (unsigned count = collectStores(BB, R)) {
1956         (void)count;
1957         DEBUG(dbgs() << "SLP: Found " << count << " stores to vectorize.\n");
1958         Changed |= vectorizeStoreChains(R);
1959       }
1960 
1961       // Vectorize trees that end at reductions.
1962       Changed |= vectorizeChainsInBlock(BB, R);
1963     }
1964 
1965     if (Changed) {
1966       R.optimizeGatherSequence();
1967       DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
1968       DEBUG(verifyFunction(F));
1969     }
1970     return Changed;
1971   }
1972 
1973   void getAnalysisUsage(AnalysisUsage &AU) const override {
1974     FunctionPass::getAnalysisUsage(AU);
1975     AU.addRequired<ScalarEvolution>();
1976     AU.addRequired<AliasAnalysis>();
1977     AU.addRequired<TargetTransformInfo>();
1978     AU.addRequired<LoopInfo>();
1979     AU.addRequired<DominatorTreeWrapperPass>();
1980     AU.addPreserved<LoopInfo>();
1981     AU.addPreserved<DominatorTreeWrapperPass>();
1982     AU.setPreservesCFG();
1983   }
1984 
1985 private:
1986 
1987   /// \brief Collect memory references and sort them according to their base
1988   /// object. We sort the stores to their base objects to reduce the cost of the
1989   /// quadratic search on the stores. TODO: We can further reduce this cost
1990   /// if we flush the chain creation every time we run into a memory barrier.
1991   unsigned collectStores(BasicBlock *BB, BoUpSLP &R);
1992 
1993   /// \brief Try to vectorize a chain that starts at two arithmetic instrs.
1994   bool tryToVectorizePair(Value *A, Value *B, BoUpSLP &R);
1995 
1996   /// \brief Try to vectorize a list of operands.
1997   /// \@param BuildVector A list of users to ignore for the purpose of
1998   ///                     scheduling and that don't need extracting.
1999   /// \returns true if a value was vectorized.
2000   bool tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
2001                           ArrayRef<Value *> BuildVector = None);
2002 
2003   /// \brief Try to vectorize a chain that may start at the operands of \V;
2004   bool tryToVectorize(BinaryOperator *V, BoUpSLP &R);
2005 
2006   /// \brief Vectorize the stores that were collected in StoreRefs.
2007   bool vectorizeStoreChains(BoUpSLP &R);
2008 
2009   /// \brief Scan the basic block and look for patterns that are likely to start
2010   /// a vectorization chain.
2011   bool vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R);
2012 
2013   bool vectorizeStoreChain(ArrayRef<Value *> Chain, int CostThreshold,
2014                            BoUpSLP &R);
2015 
2016   bool vectorizeStores(ArrayRef<StoreInst *> Stores, int costThreshold,
2017                        BoUpSLP &R);
2018 private:
2019   StoreListMap StoreRefs;
2020 };
2021 
2022 /// \brief Check that the Values in the slice in VL array are still existent in
2023 /// the WeakVH array.
2024 /// Vectorization of part of the VL array may cause later values in the VL array
2025 /// to become invalid. We track when this has happened in the WeakVH array.
2026 static bool hasValueBeenRAUWed(ArrayRef<Value *> &VL,
2027                                SmallVectorImpl<WeakVH> &VH,
2028                                unsigned SliceBegin,
2029                                unsigned SliceSize) {
2030   for (unsigned i = SliceBegin; i < SliceBegin + SliceSize; ++i)
2031     if (VH[i] != VL[i])
2032       return true;
2033 
2034   return false;
2035 }
2036 
2037 bool SLPVectorizer::vectorizeStoreChain(ArrayRef<Value *> Chain,
2038                                           int CostThreshold, BoUpSLP &R) {
2039   unsigned ChainLen = Chain.size();
2040   DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
2041         << "\n");
2042   Type *StoreTy = cast<StoreInst>(Chain[0])->getValueOperand()->getType();
2043   unsigned Sz = DL->getTypeSizeInBits(StoreTy);
2044   unsigned VF = MinVecRegSize / Sz;
2045 
2046   if (!isPowerOf2_32(Sz) || VF < 2)
2047     return false;
2048 
2049   // Keep track of values that were deleted by vectorizing in the loop below.
2050   SmallVector<WeakVH, 8> TrackValues(Chain.begin(), Chain.end());
2051 
2052   bool Changed = false;
2053   // Look for profitable vectorizable trees at all offsets, starting at zero.
2054   for (unsigned i = 0, e = ChainLen; i < e; ++i) {
2055     if (i + VF > e)
2056       break;
2057 
2058     // Check that a previous iteration of this loop did not delete the Value.
2059     if (hasValueBeenRAUWed(Chain, TrackValues, i, VF))
2060       continue;
2061 
2062     DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
2063           << "\n");
2064     ArrayRef<Value *> Operands = Chain.slice(i, VF);
2065 
2066     R.buildTree(Operands);
2067 
2068     int Cost = R.getTreeCost();
2069 
2070     DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
2071     if (Cost < CostThreshold) {
2072       DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
2073       R.vectorizeTree();
2074 
2075       // Move to the next bundle.
2076       i += VF - 1;
2077       Changed = true;
2078     }
2079   }
2080 
2081   return Changed;
2082 }
2083 
2084 bool SLPVectorizer::vectorizeStores(ArrayRef<StoreInst *> Stores,
2085                                     int costThreshold, BoUpSLP &R) {
2086   SetVector<Value *> Heads, Tails;
2087   SmallDenseMap<Value *, Value *> ConsecutiveChain;
2088 
2089   // We may run into multiple chains that merge into a single chain. We mark the
2090   // stores that we vectorized so that we don't visit the same store twice.
2091   BoUpSLP::ValueSet VectorizedStores;
2092   bool Changed = false;
2093 
2094   // Do a quadratic search on all of the given stores and find
2095   // all of the pairs of stores that follow each other.
2096   for (unsigned i = 0, e = Stores.size(); i < e; ++i) {
2097     for (unsigned j = 0; j < e; ++j) {
2098       if (i == j)
2099         continue;
2100 
2101       if (R.isConsecutiveAccess(Stores[i], Stores[j])) {
2102         Tails.insert(Stores[j]);
2103         Heads.insert(Stores[i]);
2104         ConsecutiveChain[Stores[i]] = Stores[j];
2105       }
2106     }
2107   }
2108 
2109   // For stores that start but don't end a link in the chain:
2110   for (SetVector<Value *>::iterator it = Heads.begin(), e = Heads.end();
2111        it != e; ++it) {
2112     if (Tails.count(*it))
2113       continue;
2114 
2115     // We found a store instr that starts a chain. Now follow the chain and try
2116     // to vectorize it.
2117     BoUpSLP::ValueList Operands;
2118     Value *I = *it;
2119     // Collect the chain into a list.
2120     while (Tails.count(I) || Heads.count(I)) {
2121       if (VectorizedStores.count(I))
2122         break;
2123       Operands.push_back(I);
2124       // Move to the next value in the chain.
2125       I = ConsecutiveChain[I];
2126     }
2127 
2128     bool Vectorized = vectorizeStoreChain(Operands, costThreshold, R);
2129 
2130     // Mark the vectorized stores so that we don't vectorize them again.
2131     if (Vectorized)
2132       VectorizedStores.insert(Operands.begin(), Operands.end());
2133     Changed |= Vectorized;
2134   }
2135 
2136   return Changed;
2137 }
2138 
2139 
2140 unsigned SLPVectorizer::collectStores(BasicBlock *BB, BoUpSLP &R) {
2141   unsigned count = 0;
2142   StoreRefs.clear();
2143   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2144     StoreInst *SI = dyn_cast<StoreInst>(it);
2145     if (!SI)
2146       continue;
2147 
2148     // Don't touch volatile stores.
2149     if (!SI->isSimple())
2150       continue;
2151 
2152     // Check that the pointer points to scalars.
2153     Type *Ty = SI->getValueOperand()->getType();
2154     if (Ty->isAggregateType() || Ty->isVectorTy())
2155       continue;
2156 
2157     // Find the base pointer.
2158     Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), DL);
2159 
2160     // Save the store locations.
2161     StoreRefs[Ptr].push_back(SI);
2162     count++;
2163   }
2164   return count;
2165 }
2166 
2167 bool SLPVectorizer::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
2168   if (!A || !B)
2169     return false;
2170   Value *VL[] = { A, B };
2171   return tryToVectorizeList(VL, R);
2172 }
2173 
2174 bool SLPVectorizer::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
2175                                        ArrayRef<Value *> BuildVector) {
2176   if (VL.size() < 2)
2177     return false;
2178 
2179   DEBUG(dbgs() << "SLP: Vectorizing a list of length = " << VL.size() << ".\n");
2180 
2181   // Check that all of the parts are scalar instructions of the same type.
2182   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
2183   if (!I0)
2184     return false;
2185 
2186   unsigned Opcode0 = I0->getOpcode();
2187 
2188   Type *Ty0 = I0->getType();
2189   unsigned Sz = DL->getTypeSizeInBits(Ty0);
2190   unsigned VF = MinVecRegSize / Sz;
2191 
2192   for (int i = 0, e = VL.size(); i < e; ++i) {
2193     Type *Ty = VL[i]->getType();
2194     if (Ty->isAggregateType() || Ty->isVectorTy())
2195       return false;
2196     Instruction *Inst = dyn_cast<Instruction>(VL[i]);
2197     if (!Inst || Inst->getOpcode() != Opcode0)
2198       return false;
2199   }
2200 
2201   bool Changed = false;
2202 
2203   // Keep track of values that were deleted by vectorizing in the loop below.
2204   SmallVector<WeakVH, 8> TrackValues(VL.begin(), VL.end());
2205 
2206   for (unsigned i = 0, e = VL.size(); i < e; ++i) {
2207     unsigned OpsWidth = 0;
2208 
2209     if (i + VF > e)
2210       OpsWidth = e - i;
2211     else
2212       OpsWidth = VF;
2213 
2214     if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
2215       break;
2216 
2217     // Check that a previous iteration of this loop did not delete the Value.
2218     if (hasValueBeenRAUWed(VL, TrackValues, i, OpsWidth))
2219       continue;
2220 
2221     DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
2222                  << "\n");
2223     ArrayRef<Value *> Ops = VL.slice(i, OpsWidth);
2224 
2225     ArrayRef<Value *> BuildVectorSlice;
2226     if (!BuildVector.empty())
2227       BuildVectorSlice = BuildVector.slice(i, OpsWidth);
2228 
2229     R.buildTree(Ops, BuildVectorSlice);
2230     int Cost = R.getTreeCost();
2231 
2232     if (Cost < -SLPCostThreshold) {
2233       DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
2234       Value *VectorizedRoot = R.vectorizeTree();
2235 
2236       // Reconstruct the build vector by extracting the vectorized root. This
2237       // way we handle the case where some elements of the vector are undefined.
2238       //  (return (inserelt <4 xi32> (insertelt undef (opd0) 0) (opd1) 2))
2239       if (!BuildVectorSlice.empty()) {
2240         // The insert point is the last build vector instruction. The vectorized
2241         // root will precede it. This guarantees that we get an instruction. The
2242         // vectorized tree could have been constant folded.
2243         Instruction *InsertAfter = cast<Instruction>(BuildVectorSlice.back());
2244         unsigned VecIdx = 0;
2245         for (auto &V : BuildVectorSlice) {
2246           IRBuilder<true, NoFolder> Builder(
2247               ++BasicBlock::iterator(InsertAfter));
2248           InsertElementInst *IE = cast<InsertElementInst>(V);
2249           Instruction *Extract = cast<Instruction>(Builder.CreateExtractElement(
2250               VectorizedRoot, Builder.getInt32(VecIdx++)));
2251           IE->setOperand(1, Extract);
2252           IE->removeFromParent();
2253           IE->insertAfter(Extract);
2254           InsertAfter = IE;
2255         }
2256       }
2257       // Move to the next bundle.
2258       i += VF - 1;
2259       Changed = true;
2260     }
2261   }
2262 
2263   return Changed;
2264 }
2265 
2266 bool SLPVectorizer::tryToVectorize(BinaryOperator *V, BoUpSLP &R) {
2267   if (!V)
2268     return false;
2269 
2270   // Try to vectorize V.
2271   if (tryToVectorizePair(V->getOperand(0), V->getOperand(1), R))
2272     return true;
2273 
2274   BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0));
2275   BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1));
2276   // Try to skip B.
2277   if (B && B->hasOneUse()) {
2278     BinaryOperator *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
2279     BinaryOperator *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
2280     if (tryToVectorizePair(A, B0, R)) {
2281       B->moveBefore(V);
2282       return true;
2283     }
2284     if (tryToVectorizePair(A, B1, R)) {
2285       B->moveBefore(V);
2286       return true;
2287     }
2288   }
2289 
2290   // Try to skip A.
2291   if (A && A->hasOneUse()) {
2292     BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
2293     BinaryOperator *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
2294     if (tryToVectorizePair(A0, B, R)) {
2295       A->moveBefore(V);
2296       return true;
2297     }
2298     if (tryToVectorizePair(A1, B, R)) {
2299       A->moveBefore(V);
2300       return true;
2301     }
2302   }
2303   return 0;
2304 }
2305 
2306 /// \brief Generate a shuffle mask to be used in a reduction tree.
2307 ///
2308 /// \param VecLen The length of the vector to be reduced.
2309 /// \param NumEltsToRdx The number of elements that should be reduced in the
2310 ///        vector.
2311 /// \param IsPairwise Whether the reduction is a pairwise or splitting
2312 ///        reduction. A pairwise reduction will generate a mask of
2313 ///        <0,2,...> or <1,3,..> while a splitting reduction will generate
2314 ///        <2,3, undef,undef> for a vector of 4 and NumElts = 2.
2315 /// \param IsLeft True will generate a mask of even elements, odd otherwise.
2316 static Value *createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx,
2317                                    bool IsPairwise, bool IsLeft,
2318                                    IRBuilder<> &Builder) {
2319   assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask");
2320 
2321   SmallVector<Constant *, 32> ShuffleMask(
2322       VecLen, UndefValue::get(Builder.getInt32Ty()));
2323 
2324   if (IsPairwise)
2325     // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
2326     for (unsigned i = 0; i != NumEltsToRdx; ++i)
2327       ShuffleMask[i] = Builder.getInt32(2 * i + !IsLeft);
2328   else
2329     // Move the upper half of the vector to the lower half.
2330     for (unsigned i = 0; i != NumEltsToRdx; ++i)
2331       ShuffleMask[i] = Builder.getInt32(NumEltsToRdx + i);
2332 
2333   return ConstantVector::get(ShuffleMask);
2334 }
2335 
2336 
2337 /// Model horizontal reductions.
2338 ///
2339 /// A horizontal reduction is a tree of reduction operations (currently add and
2340 /// fadd) that has operations that can be put into a vector as its leaf.
2341 /// For example, this tree:
2342 ///
2343 /// mul mul mul mul
2344 ///  \  /    \  /
2345 ///   +       +
2346 ///    \     /
2347 ///       +
2348 /// This tree has "mul" as its reduced values and "+" as its reduction
2349 /// operations. A reduction might be feeding into a store or a binary operation
2350 /// feeding a phi.
2351 ///    ...
2352 ///    \  /
2353 ///     +
2354 ///     |
2355 ///  phi +=
2356 ///
2357 ///  Or:
2358 ///    ...
2359 ///    \  /
2360 ///     +
2361 ///     |
2362 ///   *p =
2363 ///
2364 class HorizontalReduction {
2365   SmallVector<Value *, 16> ReductionOps;
2366   SmallVector<Value *, 32> ReducedVals;
2367 
2368   BinaryOperator *ReductionRoot;
2369   PHINode *ReductionPHI;
2370 
2371   /// The opcode of the reduction.
2372   unsigned ReductionOpcode;
2373   /// The opcode of the values we perform a reduction on.
2374   unsigned ReducedValueOpcode;
2375   /// The width of one full horizontal reduction operation.
2376   unsigned ReduxWidth;
2377   /// Should we model this reduction as a pairwise reduction tree or a tree that
2378   /// splits the vector in halves and adds those halves.
2379   bool IsPairwiseReduction;
2380 
2381 public:
2382   HorizontalReduction()
2383     : ReductionRoot(nullptr), ReductionPHI(nullptr), ReductionOpcode(0),
2384     ReducedValueOpcode(0), ReduxWidth(0), IsPairwiseReduction(false) {}
2385 
2386   /// \brief Try to find a reduction tree.
2387   bool matchAssociativeReduction(PHINode *Phi, BinaryOperator *B,
2388                                  const DataLayout *DL) {
2389     assert((!Phi ||
2390             std::find(Phi->op_begin(), Phi->op_end(), B) != Phi->op_end()) &&
2391            "Thi phi needs to use the binary operator");
2392 
2393     // We could have a initial reductions that is not an add.
2394     //  r *= v1 + v2 + v3 + v4
2395     // In such a case start looking for a tree rooted in the first '+'.
2396     if (Phi) {
2397       if (B->getOperand(0) == Phi) {
2398         Phi = nullptr;
2399         B = dyn_cast<BinaryOperator>(B->getOperand(1));
2400       } else if (B->getOperand(1) == Phi) {
2401         Phi = nullptr;
2402         B = dyn_cast<BinaryOperator>(B->getOperand(0));
2403       }
2404     }
2405 
2406     if (!B)
2407       return false;
2408 
2409     Type *Ty = B->getType();
2410     if (Ty->isVectorTy())
2411       return false;
2412 
2413     ReductionOpcode = B->getOpcode();
2414     ReducedValueOpcode = 0;
2415     ReduxWidth = MinVecRegSize / DL->getTypeSizeInBits(Ty);
2416     ReductionRoot = B;
2417     ReductionPHI = Phi;
2418 
2419     if (ReduxWidth < 4)
2420       return false;
2421 
2422     // We currently only support adds.
2423     if (ReductionOpcode != Instruction::Add &&
2424         ReductionOpcode != Instruction::FAdd)
2425       return false;
2426 
2427     // Post order traverse the reduction tree starting at B. We only handle true
2428     // trees containing only binary operators.
2429     SmallVector<std::pair<BinaryOperator *, unsigned>, 32> Stack;
2430     Stack.push_back(std::make_pair(B, 0));
2431     while (!Stack.empty()) {
2432       BinaryOperator *TreeN = Stack.back().first;
2433       unsigned EdgeToVist = Stack.back().second++;
2434       bool IsReducedValue = TreeN->getOpcode() != ReductionOpcode;
2435 
2436       // Only handle trees in the current basic block.
2437       if (TreeN->getParent() != B->getParent())
2438         return false;
2439 
2440       // Each tree node needs to have one user except for the ultimate
2441       // reduction.
2442       if (!TreeN->hasOneUse() && TreeN != B)
2443         return false;
2444 
2445       // Postorder vist.
2446       if (EdgeToVist == 2 || IsReducedValue) {
2447         if (IsReducedValue) {
2448           // Make sure that the opcodes of the operations that we are going to
2449           // reduce match.
2450           if (!ReducedValueOpcode)
2451             ReducedValueOpcode = TreeN->getOpcode();
2452           else if (ReducedValueOpcode != TreeN->getOpcode())
2453             return false;
2454           ReducedVals.push_back(TreeN);
2455         } else {
2456           // We need to be able to reassociate the adds.
2457           if (!TreeN->isAssociative())
2458             return false;
2459           ReductionOps.push_back(TreeN);
2460         }
2461         // Retract.
2462         Stack.pop_back();
2463         continue;
2464       }
2465 
2466       // Visit left or right.
2467       Value *NextV = TreeN->getOperand(EdgeToVist);
2468       BinaryOperator *Next = dyn_cast<BinaryOperator>(NextV);
2469       if (Next)
2470         Stack.push_back(std::make_pair(Next, 0));
2471       else if (NextV != Phi)
2472         return false;
2473     }
2474     return true;
2475   }
2476 
2477   /// \brief Attempt to vectorize the tree found by
2478   /// matchAssociativeReduction.
2479   bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
2480     if (ReducedVals.empty())
2481       return false;
2482 
2483     unsigned NumReducedVals = ReducedVals.size();
2484     if (NumReducedVals < ReduxWidth)
2485       return false;
2486 
2487     Value *VectorizedTree = nullptr;
2488     IRBuilder<> Builder(ReductionRoot);
2489     FastMathFlags Unsafe;
2490     Unsafe.setUnsafeAlgebra();
2491     Builder.SetFastMathFlags(Unsafe);
2492     unsigned i = 0;
2493 
2494     for (; i < NumReducedVals - ReduxWidth + 1; i += ReduxWidth) {
2495       ArrayRef<Value *> ValsToReduce(&ReducedVals[i], ReduxWidth);
2496       V.buildTree(ValsToReduce, ReductionOps);
2497 
2498       // Estimate cost.
2499       int Cost = V.getTreeCost() + getReductionCost(TTI, ReducedVals[i]);
2500       if (Cost >= -SLPCostThreshold)
2501         break;
2502 
2503       DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" << Cost
2504                    << ". (HorRdx)\n");
2505 
2506       // Vectorize a tree.
2507       DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
2508       Value *VectorizedRoot = V.vectorizeTree();
2509 
2510       // Emit a reduction.
2511       Value *ReducedSubTree = emitReduction(VectorizedRoot, Builder);
2512       if (VectorizedTree) {
2513         Builder.SetCurrentDebugLocation(Loc);
2514         VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
2515                                      ReducedSubTree, "bin.rdx");
2516       } else
2517         VectorizedTree = ReducedSubTree;
2518     }
2519 
2520     if (VectorizedTree) {
2521       // Finish the reduction.
2522       for (; i < NumReducedVals; ++i) {
2523         Builder.SetCurrentDebugLocation(
2524           cast<Instruction>(ReducedVals[i])->getDebugLoc());
2525         VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
2526                                      ReducedVals[i]);
2527       }
2528       // Update users.
2529       if (ReductionPHI) {
2530         assert(ReductionRoot && "Need a reduction operation");
2531         ReductionRoot->setOperand(0, VectorizedTree);
2532         ReductionRoot->setOperand(1, ReductionPHI);
2533       } else
2534         ReductionRoot->replaceAllUsesWith(VectorizedTree);
2535     }
2536     return VectorizedTree != nullptr;
2537   }
2538 
2539 private:
2540 
2541   /// \brief Calcuate the cost of a reduction.
2542   int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal) {
2543     Type *ScalarTy = FirstReducedVal->getType();
2544     Type *VecTy = VectorType::get(ScalarTy, ReduxWidth);
2545 
2546     int PairwiseRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, true);
2547     int SplittingRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, false);
2548 
2549     IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
2550     int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
2551 
2552     int ScalarReduxCost =
2553         ReduxWidth * TTI->getArithmeticInstrCost(ReductionOpcode, VecTy);
2554 
2555     DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost
2556                  << " for reduction that starts with " << *FirstReducedVal
2557                  << " (It is a "
2558                  << (IsPairwiseReduction ? "pairwise" : "splitting")
2559                  << " reduction)\n");
2560 
2561     return VecReduxCost - ScalarReduxCost;
2562   }
2563 
2564   static Value *createBinOp(IRBuilder<> &Builder, unsigned Opcode, Value *L,
2565                             Value *R, const Twine &Name = "") {
2566     if (Opcode == Instruction::FAdd)
2567       return Builder.CreateFAdd(L, R, Name);
2568     return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, L, R, Name);
2569   }
2570 
2571   /// \brief Emit a horizontal reduction of the vectorized value.
2572   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder) {
2573     assert(VectorizedValue && "Need to have a vectorized tree node");
2574     Instruction *ValToReduce = dyn_cast<Instruction>(VectorizedValue);
2575     assert(isPowerOf2_32(ReduxWidth) &&
2576            "We only handle power-of-two reductions for now");
2577 
2578     Value *TmpVec = ValToReduce;
2579     for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
2580       if (IsPairwiseReduction) {
2581         Value *LeftMask =
2582           createRdxShuffleMask(ReduxWidth, i, true, true, Builder);
2583         Value *RightMask =
2584           createRdxShuffleMask(ReduxWidth, i, true, false, Builder);
2585 
2586         Value *LeftShuf = Builder.CreateShuffleVector(
2587           TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l");
2588         Value *RightShuf = Builder.CreateShuffleVector(
2589           TmpVec, UndefValue::get(TmpVec->getType()), (RightMask),
2590           "rdx.shuf.r");
2591         TmpVec = createBinOp(Builder, ReductionOpcode, LeftShuf, RightShuf,
2592                              "bin.rdx");
2593       } else {
2594         Value *UpperHalf =
2595           createRdxShuffleMask(ReduxWidth, i, false, false, Builder);
2596         Value *Shuf = Builder.CreateShuffleVector(
2597           TmpVec, UndefValue::get(TmpVec->getType()), UpperHalf, "rdx.shuf");
2598         TmpVec = createBinOp(Builder, ReductionOpcode, TmpVec, Shuf, "bin.rdx");
2599       }
2600     }
2601 
2602     // The result is in the first element of the vector.
2603     return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
2604   }
2605 };
2606 
2607 /// \brief Recognize construction of vectors like
2608 ///  %ra = insertelement <4 x float> undef, float %s0, i32 0
2609 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
2610 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
2611 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
2612 ///
2613 /// Returns true if it matches
2614 ///
2615 static bool findBuildVector(InsertElementInst *FirstInsertElem,
2616                             SmallVectorImpl<Value *> &BuildVector,
2617                             SmallVectorImpl<Value *> &BuildVectorOpds) {
2618   if (!isa<UndefValue>(FirstInsertElem->getOperand(0)))
2619     return false;
2620 
2621   InsertElementInst *IE = FirstInsertElem;
2622   while (true) {
2623     BuildVector.push_back(IE);
2624     BuildVectorOpds.push_back(IE->getOperand(1));
2625 
2626     if (IE->use_empty())
2627       return false;
2628 
2629     InsertElementInst *NextUse = dyn_cast<InsertElementInst>(IE->user_back());
2630     if (!NextUse)
2631       return true;
2632 
2633     // If this isn't the final use, make sure the next insertelement is the only
2634     // use. It's OK if the final constructed vector is used multiple times
2635     if (!IE->hasOneUse())
2636       return false;
2637 
2638     IE = NextUse;
2639   }
2640 
2641   return false;
2642 }
2643 
2644 static bool PhiTypeSorterFunc(Value *V, Value *V2) {
2645   return V->getType() < V2->getType();
2646 }
2647 
2648 bool SLPVectorizer::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
2649   bool Changed = false;
2650   SmallVector<Value *, 4> Incoming;
2651   SmallSet<Value *, 16> VisitedInstrs;
2652 
2653   bool HaveVectorizedPhiNodes = true;
2654   while (HaveVectorizedPhiNodes) {
2655     HaveVectorizedPhiNodes = false;
2656 
2657     // Collect the incoming values from the PHIs.
2658     Incoming.clear();
2659     for (BasicBlock::iterator instr = BB->begin(), ie = BB->end(); instr != ie;
2660          ++instr) {
2661       PHINode *P = dyn_cast<PHINode>(instr);
2662       if (!P)
2663         break;
2664 
2665       if (!VisitedInstrs.count(P))
2666         Incoming.push_back(P);
2667     }
2668 
2669     // Sort by type.
2670     std::stable_sort(Incoming.begin(), Incoming.end(), PhiTypeSorterFunc);
2671 
2672     // Try to vectorize elements base on their type.
2673     for (SmallVector<Value *, 4>::iterator IncIt = Incoming.begin(),
2674                                            E = Incoming.end();
2675          IncIt != E;) {
2676 
2677       // Look for the next elements with the same type.
2678       SmallVector<Value *, 4>::iterator SameTypeIt = IncIt;
2679       while (SameTypeIt != E &&
2680              (*SameTypeIt)->getType() == (*IncIt)->getType()) {
2681         VisitedInstrs.insert(*SameTypeIt);
2682         ++SameTypeIt;
2683       }
2684 
2685       // Try to vectorize them.
2686       unsigned NumElts = (SameTypeIt - IncIt);
2687       DEBUG(errs() << "SLP: Trying to vectorize starting at PHIs (" << NumElts << ")\n");
2688       if (NumElts > 1 &&
2689           tryToVectorizeList(ArrayRef<Value *>(IncIt, NumElts), R)) {
2690         // Success start over because instructions might have been changed.
2691         HaveVectorizedPhiNodes = true;
2692         Changed = true;
2693         break;
2694       }
2695 
2696       // Start over at the next instruction of a different type (or the end).
2697       IncIt = SameTypeIt;
2698     }
2699   }
2700 
2701   VisitedInstrs.clear();
2702 
2703   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) {
2704     // We may go through BB multiple times so skip the one we have checked.
2705     if (!VisitedInstrs.insert(it))
2706       continue;
2707 
2708     if (isa<DbgInfoIntrinsic>(it))
2709       continue;
2710 
2711     // Try to vectorize reductions that use PHINodes.
2712     if (PHINode *P = dyn_cast<PHINode>(it)) {
2713       // Check that the PHI is a reduction PHI.
2714       if (P->getNumIncomingValues() != 2)
2715         return Changed;
2716       Value *Rdx =
2717           (P->getIncomingBlock(0) == BB
2718                ? (P->getIncomingValue(0))
2719                : (P->getIncomingBlock(1) == BB ? P->getIncomingValue(1)
2720                                                : nullptr));
2721       // Check if this is a Binary Operator.
2722       BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx);
2723       if (!BI)
2724         continue;
2725 
2726       // Try to match and vectorize a horizontal reduction.
2727       HorizontalReduction HorRdx;
2728       if (ShouldVectorizeHor &&
2729           HorRdx.matchAssociativeReduction(P, BI, DL) &&
2730           HorRdx.tryToReduce(R, TTI)) {
2731         Changed = true;
2732         it = BB->begin();
2733         e = BB->end();
2734         continue;
2735       }
2736 
2737      Value *Inst = BI->getOperand(0);
2738       if (Inst == P)
2739         Inst = BI->getOperand(1);
2740 
2741       if (tryToVectorize(dyn_cast<BinaryOperator>(Inst), R)) {
2742         // We would like to start over since some instructions are deleted
2743         // and the iterator may become invalid value.
2744         Changed = true;
2745         it = BB->begin();
2746         e = BB->end();
2747         continue;
2748       }
2749 
2750       continue;
2751     }
2752 
2753     // Try to vectorize horizontal reductions feeding into a store.
2754     if (ShouldStartVectorizeHorAtStore)
2755       if (StoreInst *SI = dyn_cast<StoreInst>(it))
2756         if (BinaryOperator *BinOp =
2757                 dyn_cast<BinaryOperator>(SI->getValueOperand())) {
2758           HorizontalReduction HorRdx;
2759           if (((HorRdx.matchAssociativeReduction(nullptr, BinOp, DL) &&
2760                 HorRdx.tryToReduce(R, TTI)) ||
2761                tryToVectorize(BinOp, R))) {
2762             Changed = true;
2763             it = BB->begin();
2764             e = BB->end();
2765             continue;
2766           }
2767         }
2768 
2769     // Try to vectorize trees that start at compare instructions.
2770     if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
2771       if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) {
2772         Changed = true;
2773         // We would like to start over since some instructions are deleted
2774         // and the iterator may become invalid value.
2775         it = BB->begin();
2776         e = BB->end();
2777         continue;
2778       }
2779 
2780       for (int i = 0; i < 2; ++i) {
2781          if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i))) {
2782             if (tryToVectorizePair(BI->getOperand(0), BI->getOperand(1), R)) {
2783               Changed = true;
2784               // We would like to start over since some instructions are deleted
2785               // and the iterator may become invalid value.
2786               it = BB->begin();
2787               e = BB->end();
2788             }
2789          }
2790       }
2791       continue;
2792     }
2793 
2794     // Try to vectorize trees that start at insertelement instructions.
2795     if (InsertElementInst *FirstInsertElem = dyn_cast<InsertElementInst>(it)) {
2796       SmallVector<Value *, 16> BuildVector;
2797       SmallVector<Value *, 16> BuildVectorOpds;
2798       if (!findBuildVector(FirstInsertElem, BuildVector, BuildVectorOpds))
2799         continue;
2800 
2801       // Vectorize starting with the build vector operands ignoring the
2802       // BuildVector instructions for the purpose of scheduling and user
2803       // extraction.
2804       if (tryToVectorizeList(BuildVectorOpds, R, BuildVector)) {
2805         Changed = true;
2806         it = BB->begin();
2807         e = BB->end();
2808       }
2809 
2810       continue;
2811     }
2812   }
2813 
2814   return Changed;
2815 }
2816 
2817 bool SLPVectorizer::vectorizeStoreChains(BoUpSLP &R) {
2818   bool Changed = false;
2819   // Attempt to sort and vectorize each of the store-groups.
2820   for (StoreListMap::iterator it = StoreRefs.begin(), e = StoreRefs.end();
2821        it != e; ++it) {
2822     if (it->second.size() < 2)
2823       continue;
2824 
2825     DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
2826           << it->second.size() << ".\n");
2827 
2828     // Process the stores in chunks of 16.
2829     for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI+=16) {
2830       unsigned Len = std::min<unsigned>(CE - CI, 16);
2831       ArrayRef<StoreInst *> Chunk(&it->second[CI], Len);
2832       Changed |= vectorizeStores(Chunk, -SLPCostThreshold, R);
2833     }
2834   }
2835   return Changed;
2836 }
2837 
2838 } // end anonymous namespace
2839 
2840 char SLPVectorizer::ID = 0;
2841 static const char lv_name[] = "SLP Vectorizer";
2842 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
2843 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
2844 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
2845 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
2846 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
2847 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
2848 
2849 namespace llvm {
2850 Pass *createSLPVectorizerPass() { return new SLPVectorizer(); }
2851 }
2852