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/SLPVectorizer.h"
19 #include "llvm/ADT/Optional.h"
20 #include "llvm/ADT/PostOrderIterator.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/CodeMetrics.h"
24 #include "llvm/Analysis/GlobalsModRef.h"
25 #include "llvm/Analysis/LoopAccessAnalysis.h"
26 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
27 #include "llvm/Analysis/ValueTracking.h"
28 #include "llvm/Analysis/VectorUtils.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/Dominators.h"
31 #include "llvm/IR/IRBuilder.h"
32 #include "llvm/IR/Instructions.h"
33 #include "llvm/IR/IntrinsicInst.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/IR/NoFolder.h"
36 #include "llvm/IR/Type.h"
37 #include "llvm/IR/Value.h"
38 #include "llvm/IR/Verifier.h"
39 #include "llvm/Pass.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/GraphWriter.h"
43 #include "llvm/Support/KnownBits.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include "llvm/Transforms/Utils/LoopUtils.h"
46 #include "llvm/Transforms/Vectorize.h"
47 #include <algorithm>
48 #include <memory>
49 
50 using namespace llvm;
51 using namespace slpvectorizer;
52 
53 #define SV_NAME "slp-vectorizer"
54 #define DEBUG_TYPE "SLP"
55 
56 STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
57 
58 static cl::opt<int>
59     SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
60                      cl::desc("Only vectorize if you gain more than this "
61                               "number "));
62 
63 static cl::opt<bool>
64 ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden,
65                    cl::desc("Attempt to vectorize horizontal reductions"));
66 
67 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
68     "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
69     cl::desc(
70         "Attempt to vectorize horizontal reductions feeding into a store"));
71 
72 static cl::opt<int>
73 MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden,
74     cl::desc("Attempt to vectorize for this register size in bits"));
75 
76 /// Limits the size of scheduling regions in a block.
77 /// It avoid long compile times for _very_ large blocks where vector
78 /// instructions are spread over a wide range.
79 /// This limit is way higher than needed by real-world functions.
80 static cl::opt<int>
81 ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden,
82     cl::desc("Limit the size of the SLP scheduling region per block"));
83 
84 static cl::opt<int> MinVectorRegSizeOption(
85     "slp-min-reg-size", cl::init(128), cl::Hidden,
86     cl::desc("Attempt to vectorize for this register size in bits"));
87 
88 static cl::opt<unsigned> RecursionMaxDepth(
89     "slp-recursion-max-depth", cl::init(12), cl::Hidden,
90     cl::desc("Limit the recursion depth when building a vectorizable tree"));
91 
92 static cl::opt<unsigned> MinTreeSize(
93     "slp-min-tree-size", cl::init(3), cl::Hidden,
94     cl::desc("Only vectorize small trees if they are fully vectorizable"));
95 
96 static cl::opt<bool>
97     ViewSLPTree("view-slp-tree", cl::Hidden,
98                 cl::desc("Display the SLP trees with Graphviz"));
99 
100 // Limit the number of alias checks. The limit is chosen so that
101 // it has no negative effect on the llvm benchmarks.
102 static const unsigned AliasedCheckLimit = 10;
103 
104 // Another limit for the alias checks: The maximum distance between load/store
105 // instructions where alias checks are done.
106 // This limit is useful for very large basic blocks.
107 static const unsigned MaxMemDepDistance = 160;
108 
109 /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
110 /// regions to be handled.
111 static const int MinScheduleRegionSize = 16;
112 
113 /// \brief Predicate for the element types that the SLP vectorizer supports.
114 ///
115 /// The most important thing to filter here are types which are invalid in LLVM
116 /// vectors. We also filter target specific types which have absolutely no
117 /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
118 /// avoids spending time checking the cost model and realizing that they will
119 /// be inevitably scalarized.
120 static bool isValidElementType(Type *Ty) {
121   return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() &&
122          !Ty->isPPC_FP128Ty();
123 }
124 
125 /// \returns true if all of the instructions in \p VL are in the same block or
126 /// false otherwise.
127 static bool allSameBlock(ArrayRef<Value *> VL) {
128   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
129   if (!I0)
130     return false;
131   BasicBlock *BB = I0->getParent();
132   for (int i = 1, e = VL.size(); i < e; i++) {
133     Instruction *I = dyn_cast<Instruction>(VL[i]);
134     if (!I)
135       return false;
136 
137     if (BB != I->getParent())
138       return false;
139   }
140   return true;
141 }
142 
143 /// \returns True if all of the values in \p VL are constants.
144 static bool allConstant(ArrayRef<Value *> VL) {
145   for (Value *i : VL)
146     if (!isa<Constant>(i))
147       return false;
148   return true;
149 }
150 
151 /// \returns True if all of the values in \p VL are identical.
152 static bool isSplat(ArrayRef<Value *> VL) {
153   for (unsigned i = 1, e = VL.size(); i < e; ++i)
154     if (VL[i] != VL[0])
155       return false;
156   return true;
157 }
158 
159 ///\returns Opcode that can be clubbed with \p Op to create an alternate
160 /// sequence which can later be merged as a ShuffleVector instruction.
161 static unsigned getAltOpcode(unsigned Op) {
162   switch (Op) {
163   case Instruction::FAdd:
164     return Instruction::FSub;
165   case Instruction::FSub:
166     return Instruction::FAdd;
167   case Instruction::Add:
168     return Instruction::Sub;
169   case Instruction::Sub:
170     return Instruction::Add;
171   default:
172     return 0;
173   }
174 }
175 
176 /// true if the \p Value is odd, false otherwise.
177 static bool isOdd(unsigned Value) {
178   return Value & 1;
179 }
180 
181 ///\returns bool representing if Opcode \p Op can be part
182 /// of an alternate sequence which can later be merged as
183 /// a ShuffleVector instruction.
184 static bool canCombineAsAltInst(unsigned Op) {
185   return Op == Instruction::FAdd || Op == Instruction::FSub ||
186          Op == Instruction::Sub || Op == Instruction::Add;
187 }
188 
189 /// \returns ShuffleVector instruction if instructions in \p VL have
190 ///  alternate fadd,fsub / fsub,fadd/add,sub/sub,add sequence.
191 /// (i.e. e.g. opcodes of fadd,fsub,fadd,fsub...)
192 static unsigned isAltInst(ArrayRef<Value *> VL) {
193   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
194   unsigned Opcode = I0->getOpcode();
195   unsigned AltOpcode = getAltOpcode(Opcode);
196   for (int i = 1, e = VL.size(); i < e; i++) {
197     Instruction *I = dyn_cast<Instruction>(VL[i]);
198     if (!I || I->getOpcode() != (isOdd(i) ? AltOpcode : Opcode))
199       return 0;
200   }
201   return Instruction::ShuffleVector;
202 }
203 
204 /// \returns The opcode if all of the Instructions in \p VL have the same
205 /// opcode, or zero.
206 static unsigned getSameOpcode(ArrayRef<Value *> VL) {
207   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
208   if (!I0)
209     return 0;
210   unsigned Opcode = I0->getOpcode();
211   for (int i = 1, e = VL.size(); i < e; i++) {
212     Instruction *I = dyn_cast<Instruction>(VL[i]);
213     if (!I || Opcode != I->getOpcode()) {
214       if (canCombineAsAltInst(Opcode) && i == 1)
215         return isAltInst(VL);
216       return 0;
217     }
218   }
219   return Opcode;
220 }
221 
222 /// \returns true if all of the values in \p VL have the same type or false
223 /// otherwise.
224 static bool allSameType(ArrayRef<Value *> VL) {
225   Type *Ty = VL[0]->getType();
226   for (int i = 1, e = VL.size(); i < e; i++)
227     if (VL[i]->getType() != Ty)
228       return false;
229 
230   return true;
231 }
232 
233 /// \returns True if Extract{Value,Element} instruction extracts element Idx.
234 static bool matchExtractIndex(Instruction *E, unsigned Idx, unsigned Opcode) {
235   assert(Opcode == Instruction::ExtractElement ||
236          Opcode == Instruction::ExtractValue);
237   if (Opcode == Instruction::ExtractElement) {
238     ConstantInt *CI = dyn_cast<ConstantInt>(E->getOperand(1));
239     return CI && CI->getZExtValue() == Idx;
240   } else {
241     ExtractValueInst *EI = cast<ExtractValueInst>(E);
242     return EI->getNumIndices() == 1 && *EI->idx_begin() == Idx;
243   }
244 }
245 
246 /// \returns True if in-tree use also needs extract. This refers to
247 /// possible scalar operand in vectorized instruction.
248 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
249                                     TargetLibraryInfo *TLI) {
250 
251   unsigned Opcode = UserInst->getOpcode();
252   switch (Opcode) {
253   case Instruction::Load: {
254     LoadInst *LI = cast<LoadInst>(UserInst);
255     return (LI->getPointerOperand() == Scalar);
256   }
257   case Instruction::Store: {
258     StoreInst *SI = cast<StoreInst>(UserInst);
259     return (SI->getPointerOperand() == Scalar);
260   }
261   case Instruction::Call: {
262     CallInst *CI = cast<CallInst>(UserInst);
263     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
264     if (hasVectorInstrinsicScalarOpd(ID, 1)) {
265       return (CI->getArgOperand(1) == Scalar);
266     }
267     LLVM_FALLTHROUGH;
268   }
269   default:
270     return false;
271   }
272 }
273 
274 /// \returns the AA location that is being access by the instruction.
275 static MemoryLocation getLocation(Instruction *I, AliasAnalysis *AA) {
276   if (StoreInst *SI = dyn_cast<StoreInst>(I))
277     return MemoryLocation::get(SI);
278   if (LoadInst *LI = dyn_cast<LoadInst>(I))
279     return MemoryLocation::get(LI);
280   return MemoryLocation();
281 }
282 
283 /// \returns True if the instruction is not a volatile or atomic load/store.
284 static bool isSimple(Instruction *I) {
285   if (LoadInst *LI = dyn_cast<LoadInst>(I))
286     return LI->isSimple();
287   if (StoreInst *SI = dyn_cast<StoreInst>(I))
288     return SI->isSimple();
289   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
290     return !MI->isVolatile();
291   return true;
292 }
293 
294 namespace llvm {
295 namespace slpvectorizer {
296 /// Bottom Up SLP Vectorizer.
297 class BoUpSLP {
298 public:
299   typedef SmallVector<Value *, 8> ValueList;
300   typedef SmallVector<Instruction *, 16> InstrList;
301   typedef SmallPtrSet<Value *, 16> ValueSet;
302   typedef SmallVector<StoreInst *, 8> StoreList;
303   typedef MapVector<Value *, SmallVector<Instruction *, 2>>
304       ExtraValueToDebugLocsMap;
305 
306   BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
307           TargetLibraryInfo *TLi, AliasAnalysis *Aa, LoopInfo *Li,
308           DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB,
309           const DataLayout *DL, OptimizationRemarkEmitter *ORE)
310       : NumLoadsWantToKeepOrder(0), NumLoadsWantToChangeOrder(0), F(Func),
311         SE(Se), TTI(Tti), TLI(TLi), AA(Aa), LI(Li), DT(Dt), AC(AC), DB(DB),
312         DL(DL), ORE(ORE), Builder(Se->getContext()) {
313     CodeMetrics::collectEphemeralValues(F, AC, EphValues);
314     // Use the vector register size specified by the target unless overridden
315     // by a command-line option.
316     // TODO: It would be better to limit the vectorization factor based on
317     //       data type rather than just register size. For example, x86 AVX has
318     //       256-bit registers, but it does not support integer operations
319     //       at that width (that requires AVX2).
320     if (MaxVectorRegSizeOption.getNumOccurrences())
321       MaxVecRegSize = MaxVectorRegSizeOption;
322     else
323       MaxVecRegSize = TTI->getRegisterBitWidth(true);
324 
325     if (MinVectorRegSizeOption.getNumOccurrences())
326       MinVecRegSize = MinVectorRegSizeOption;
327     else
328       MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
329   }
330 
331   /// \brief Vectorize the tree that starts with the elements in \p VL.
332   /// Returns the vectorized root.
333   Value *vectorizeTree();
334   /// Vectorize the tree but with the list of externally used values \p
335   /// ExternallyUsedValues. Values in this MapVector can be replaced but the
336   /// generated extractvalue instructions.
337   Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues);
338 
339   /// \returns the cost incurred by unwanted spills and fills, caused by
340   /// holding live values over call sites.
341   int getSpillCost();
342 
343   /// \returns the vectorization cost of the subtree that starts at \p VL.
344   /// A negative number means that this is profitable.
345   int getTreeCost();
346 
347   /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
348   /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
349   void buildTree(ArrayRef<Value *> Roots,
350                  ArrayRef<Value *> UserIgnoreLst = None);
351   /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
352   /// the purpose of scheduling and extraction in the \p UserIgnoreLst taking
353   /// into account (anf updating it, if required) list of externally used
354   /// values stored in \p ExternallyUsedValues.
355   void buildTree(ArrayRef<Value *> Roots,
356                  ExtraValueToDebugLocsMap &ExternallyUsedValues,
357                  ArrayRef<Value *> UserIgnoreLst = None);
358 
359   /// Clear the internal data structures that are created by 'buildTree'.
360   void deleteTree() {
361     VectorizableTree.clear();
362     ScalarToTreeEntry.clear();
363     MustGather.clear();
364     ExternalUses.clear();
365     NumLoadsWantToKeepOrder = 0;
366     NumLoadsWantToChangeOrder = 0;
367     for (auto &Iter : BlocksSchedules) {
368       BlockScheduling *BS = Iter.second.get();
369       BS->clear();
370     }
371     MinBWs.clear();
372   }
373 
374   unsigned getTreeSize() const { return VectorizableTree.size(); }
375 
376   /// \brief Perform LICM and CSE on the newly generated gather sequences.
377   void optimizeGatherSequence();
378 
379   /// \returns true if it is beneficial to reverse the vector order.
380   bool shouldReorder() const {
381     return NumLoadsWantToChangeOrder > NumLoadsWantToKeepOrder;
382   }
383 
384   /// \return The vector element size in bits to use when vectorizing the
385   /// expression tree ending at \p V. If V is a store, the size is the width of
386   /// the stored value. Otherwise, the size is the width of the largest loaded
387   /// value reaching V. This method is used by the vectorizer to calculate
388   /// vectorization factors.
389   unsigned getVectorElementSize(Value *V);
390 
391   /// Compute the minimum type sizes required to represent the entries in a
392   /// vectorizable tree.
393   void computeMinimumValueSizes();
394 
395   // \returns maximum vector register size as set by TTI or overridden by cl::opt.
396   unsigned getMaxVecRegSize() const {
397     return MaxVecRegSize;
398   }
399 
400   // \returns minimum vector register size as set by cl::opt.
401   unsigned getMinVecRegSize() const {
402     return MinVecRegSize;
403   }
404 
405   /// \brief Check if ArrayType or StructType is isomorphic to some VectorType.
406   ///
407   /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
408   unsigned canMapToVector(Type *T, const DataLayout &DL) const;
409 
410   /// \returns True if the VectorizableTree is both tiny and not fully
411   /// vectorizable. We do not vectorize such trees.
412   bool isTreeTinyAndNotFullyVectorizable();
413 
414   OptimizationRemarkEmitter *getORE() { return ORE; }
415 
416 private:
417   struct TreeEntry;
418 
419   /// Checks if all users of \p I are the part of the vectorization tree.
420   bool areAllUsersVectorized(Instruction *I) const;
421 
422   /// \returns the cost of the vectorizable entry.
423   int getEntryCost(TreeEntry *E);
424 
425   /// This is the recursive part of buildTree.
426   void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth, int);
427 
428   /// \returns True if the ExtractElement/ExtractValue instructions in VL can
429   /// be vectorized to use the original vector (or aggregate "bitcast" to a vector).
430   bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue) const;
431 
432   /// Vectorize a single entry in the tree.
433   Value *vectorizeTree(TreeEntry *E);
434 
435   /// Vectorize a single entry in the tree, starting in \p VL.
436   Value *vectorizeTree(ArrayRef<Value *> VL);
437 
438   /// \returns the pointer to the vectorized value if \p VL is already
439   /// vectorized, or NULL. They may happen in cycles.
440   Value *alreadyVectorized(ArrayRef<Value *> VL, Value *OpValue) const;
441 
442   /// \returns the scalarization cost for this type. Scalarization in this
443   /// context means the creation of vectors from a group of scalars.
444   int getGatherCost(Type *Ty);
445 
446   /// \returns the scalarization cost for this list of values. Assuming that
447   /// this subtree gets vectorized, we may need to extract the values from the
448   /// roots. This method calculates the cost of extracting the values.
449   int getGatherCost(ArrayRef<Value *> VL);
450 
451   /// \brief Set the Builder insert point to one after the last instruction in
452   /// the bundle
453   void setInsertPointAfterBundle(ArrayRef<Value *> VL);
454 
455   /// \returns a vector from a collection of scalars in \p VL.
456   Value *Gather(ArrayRef<Value *> VL, VectorType *Ty);
457 
458   /// \returns whether the VectorizableTree is fully vectorizable and will
459   /// be beneficial even the tree height is tiny.
460   bool isFullyVectorizableTinyTree();
461 
462   /// \reorder commutative operands in alt shuffle if they result in
463   ///  vectorized code.
464   void reorderAltShuffleOperands(ArrayRef<Value *> VL,
465                                  SmallVectorImpl<Value *> &Left,
466                                  SmallVectorImpl<Value *> &Right);
467   /// \reorder commutative operands to get better probability of
468   /// generating vectorized code.
469   void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
470                                       SmallVectorImpl<Value *> &Left,
471                                       SmallVectorImpl<Value *> &Right);
472   struct TreeEntry {
473     TreeEntry(std::vector<TreeEntry> &Container)
474         : Scalars(), VectorizedValue(nullptr), NeedToGather(0),
475           Container(Container) {}
476 
477     /// \returns true if the scalars in VL are equal to this entry.
478     bool isSame(ArrayRef<Value *> VL) const {
479       assert(VL.size() == Scalars.size() && "Invalid size");
480       return std::equal(VL.begin(), VL.end(), Scalars.begin());
481     }
482 
483     /// A vector of scalars.
484     ValueList Scalars;
485 
486     /// The Scalars are vectorized into this value. It is initialized to Null.
487     Value *VectorizedValue;
488 
489     /// Do we need to gather this sequence ?
490     bool NeedToGather;
491 
492     /// Points back to the VectorizableTree.
493     ///
494     /// Only used for Graphviz right now.  Unfortunately GraphTrait::NodeRef has
495     /// to be a pointer and needs to be able to initialize the child iterator.
496     /// Thus we need a reference back to the container to translate the indices
497     /// to entries.
498     std::vector<TreeEntry> &Container;
499 
500     /// The TreeEntry index containing the user of this entry.  We can actually
501     /// have multiple users so the data structure is not truly a tree.
502     SmallVector<int, 1> UserTreeIndices;
503   };
504 
505   /// Create a new VectorizableTree entry.
506   TreeEntry *newTreeEntry(ArrayRef<Value *> VL, bool Vectorized,
507                           int &UserTreeIdx) {
508     VectorizableTree.emplace_back(VectorizableTree);
509     int idx = VectorizableTree.size() - 1;
510     TreeEntry *Last = &VectorizableTree[idx];
511     Last->Scalars.insert(Last->Scalars.begin(), VL.begin(), VL.end());
512     Last->NeedToGather = !Vectorized;
513     if (Vectorized) {
514       for (int i = 0, e = VL.size(); i != e; ++i) {
515         assert(!getTreeEntry(VL[i]) && "Scalar already in tree!");
516         ScalarToTreeEntry[VL[i]] = idx;
517       }
518     } else {
519       MustGather.insert(VL.begin(), VL.end());
520     }
521 
522     if (UserTreeIdx >= 0)
523       Last->UserTreeIndices.push_back(UserTreeIdx);
524     UserTreeIdx = idx;
525     return Last;
526   }
527 
528   /// -- Vectorization State --
529   /// Holds all of the tree entries.
530   std::vector<TreeEntry> VectorizableTree;
531 
532   TreeEntry *getTreeEntry(Value *V) {
533     auto I = ScalarToTreeEntry.find(V);
534     if (I != ScalarToTreeEntry.end())
535       return &VectorizableTree[I->second];
536     return nullptr;
537   }
538 
539   const TreeEntry *getTreeEntry(Value *V) const {
540     auto I = ScalarToTreeEntry.find(V);
541     if (I != ScalarToTreeEntry.end())
542       return &VectorizableTree[I->second];
543     return nullptr;
544   }
545 
546   /// Maps a specific scalar to its tree entry.
547   SmallDenseMap<Value*, int> ScalarToTreeEntry;
548 
549   /// A list of scalars that we found that we need to keep as scalars.
550   ValueSet MustGather;
551 
552   /// This POD struct describes one external user in the vectorized tree.
553   struct ExternalUser {
554     ExternalUser (Value *S, llvm::User *U, int L) :
555       Scalar(S), User(U), Lane(L){}
556     // Which scalar in our function.
557     Value *Scalar;
558     // Which user that uses the scalar.
559     llvm::User *User;
560     // Which lane does the scalar belong to.
561     int Lane;
562   };
563   typedef SmallVector<ExternalUser, 16> UserList;
564 
565   /// Checks if two instructions may access the same memory.
566   ///
567   /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
568   /// is invariant in the calling loop.
569   bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
570                  Instruction *Inst2) {
571 
572     // First check if the result is already in the cache.
573     AliasCacheKey key = std::make_pair(Inst1, Inst2);
574     Optional<bool> &result = AliasCache[key];
575     if (result.hasValue()) {
576       return result.getValue();
577     }
578     MemoryLocation Loc2 = getLocation(Inst2, AA);
579     bool aliased = true;
580     if (Loc1.Ptr && Loc2.Ptr && isSimple(Inst1) && isSimple(Inst2)) {
581       // Do the alias check.
582       aliased = AA->alias(Loc1, Loc2);
583     }
584     // Store the result in the cache.
585     result = aliased;
586     return aliased;
587   }
588 
589   typedef std::pair<Instruction *, Instruction *> AliasCacheKey;
590 
591   /// Cache for alias results.
592   /// TODO: consider moving this to the AliasAnalysis itself.
593   DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
594 
595   /// Removes an instruction from its block and eventually deletes it.
596   /// It's like Instruction::eraseFromParent() except that the actual deletion
597   /// is delayed until BoUpSLP is destructed.
598   /// This is required to ensure that there are no incorrect collisions in the
599   /// AliasCache, which can happen if a new instruction is allocated at the
600   /// same address as a previously deleted instruction.
601   void eraseInstruction(Instruction *I) {
602     I->removeFromParent();
603     I->dropAllReferences();
604     DeletedInstructions.emplace_back(I);
605   }
606 
607   /// Temporary store for deleted instructions. Instructions will be deleted
608   /// eventually when the BoUpSLP is destructed.
609   SmallVector<unique_value, 8> DeletedInstructions;
610 
611   /// A list of values that need to extracted out of the tree.
612   /// This list holds pairs of (Internal Scalar : External User). External User
613   /// can be nullptr, it means that this Internal Scalar will be used later,
614   /// after vectorization.
615   UserList ExternalUses;
616 
617   /// Values used only by @llvm.assume calls.
618   SmallPtrSet<const Value *, 32> EphValues;
619 
620   /// Holds all of the instructions that we gathered.
621   SetVector<Instruction *> GatherSeq;
622   /// A list of blocks that we are going to CSE.
623   SetVector<BasicBlock *> CSEBlocks;
624 
625   /// Contains all scheduling relevant data for an instruction.
626   /// A ScheduleData either represents a single instruction or a member of an
627   /// instruction bundle (= a group of instructions which is combined into a
628   /// vector instruction).
629   struct ScheduleData {
630 
631     // The initial value for the dependency counters. It means that the
632     // dependencies are not calculated yet.
633     enum { InvalidDeps = -1 };
634 
635     ScheduleData()
636         : Inst(nullptr), FirstInBundle(nullptr), NextInBundle(nullptr),
637           NextLoadStore(nullptr), SchedulingRegionID(0), SchedulingPriority(0),
638           Dependencies(InvalidDeps), UnscheduledDeps(InvalidDeps),
639           UnscheduledDepsInBundle(InvalidDeps), IsScheduled(false) {}
640 
641     void init(int BlockSchedulingRegionID) {
642       FirstInBundle = this;
643       NextInBundle = nullptr;
644       NextLoadStore = nullptr;
645       IsScheduled = false;
646       SchedulingRegionID = BlockSchedulingRegionID;
647       UnscheduledDepsInBundle = UnscheduledDeps;
648       clearDependencies();
649     }
650 
651     /// Returns true if the dependency information has been calculated.
652     bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
653 
654     /// Returns true for single instructions and for bundle representatives
655     /// (= the head of a bundle).
656     bool isSchedulingEntity() const { return FirstInBundle == this; }
657 
658     /// Returns true if it represents an instruction bundle and not only a
659     /// single instruction.
660     bool isPartOfBundle() const {
661       return NextInBundle != nullptr || FirstInBundle != this;
662     }
663 
664     /// Returns true if it is ready for scheduling, i.e. it has no more
665     /// unscheduled depending instructions/bundles.
666     bool isReady() const {
667       assert(isSchedulingEntity() &&
668              "can't consider non-scheduling entity for ready list");
669       return UnscheduledDepsInBundle == 0 && !IsScheduled;
670     }
671 
672     /// Modifies the number of unscheduled dependencies, also updating it for
673     /// the whole bundle.
674     int incrementUnscheduledDeps(int Incr) {
675       UnscheduledDeps += Incr;
676       return FirstInBundle->UnscheduledDepsInBundle += Incr;
677     }
678 
679     /// Sets the number of unscheduled dependencies to the number of
680     /// dependencies.
681     void resetUnscheduledDeps() {
682       incrementUnscheduledDeps(Dependencies - UnscheduledDeps);
683     }
684 
685     /// Clears all dependency information.
686     void clearDependencies() {
687       Dependencies = InvalidDeps;
688       resetUnscheduledDeps();
689       MemoryDependencies.clear();
690     }
691 
692     void dump(raw_ostream &os) const {
693       if (!isSchedulingEntity()) {
694         os << "/ " << *Inst;
695       } else if (NextInBundle) {
696         os << '[' << *Inst;
697         ScheduleData *SD = NextInBundle;
698         while (SD) {
699           os << ';' << *SD->Inst;
700           SD = SD->NextInBundle;
701         }
702         os << ']';
703       } else {
704         os << *Inst;
705       }
706     }
707 
708     Instruction *Inst;
709 
710     /// Points to the head in an instruction bundle (and always to this for
711     /// single instructions).
712     ScheduleData *FirstInBundle;
713 
714     /// Single linked list of all instructions in a bundle. Null if it is a
715     /// single instruction.
716     ScheduleData *NextInBundle;
717 
718     /// Single linked list of all memory instructions (e.g. load, store, call)
719     /// in the block - until the end of the scheduling region.
720     ScheduleData *NextLoadStore;
721 
722     /// The dependent memory instructions.
723     /// This list is derived on demand in calculateDependencies().
724     SmallVector<ScheduleData *, 4> MemoryDependencies;
725 
726     /// This ScheduleData is in the current scheduling region if this matches
727     /// the current SchedulingRegionID of BlockScheduling.
728     int SchedulingRegionID;
729 
730     /// Used for getting a "good" final ordering of instructions.
731     int SchedulingPriority;
732 
733     /// The number of dependencies. Constitutes of the number of users of the
734     /// instruction plus the number of dependent memory instructions (if any).
735     /// This value is calculated on demand.
736     /// If InvalidDeps, the number of dependencies is not calculated yet.
737     ///
738     int Dependencies;
739 
740     /// The number of dependencies minus the number of dependencies of scheduled
741     /// instructions. As soon as this is zero, the instruction/bundle gets ready
742     /// for scheduling.
743     /// Note that this is negative as long as Dependencies is not calculated.
744     int UnscheduledDeps;
745 
746     /// The sum of UnscheduledDeps in a bundle. Equals to UnscheduledDeps for
747     /// single instructions.
748     int UnscheduledDepsInBundle;
749 
750     /// True if this instruction is scheduled (or considered as scheduled in the
751     /// dry-run).
752     bool IsScheduled;
753   };
754 
755 #ifndef NDEBUG
756   friend inline raw_ostream &operator<<(raw_ostream &os,
757                                         const BoUpSLP::ScheduleData &SD) {
758     SD.dump(os);
759     return os;
760   }
761 #endif
762   friend struct GraphTraits<BoUpSLP *>;
763   friend struct DOTGraphTraits<BoUpSLP *>;
764 
765   /// Contains all scheduling data for a basic block.
766   ///
767   struct BlockScheduling {
768 
769     BlockScheduling(BasicBlock *BB)
770         : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize),
771           ScheduleStart(nullptr), ScheduleEnd(nullptr),
772           FirstLoadStoreInRegion(nullptr), LastLoadStoreInRegion(nullptr),
773           ScheduleRegionSize(0),
774           ScheduleRegionSizeLimit(ScheduleRegionSizeBudget),
775           // Make sure that the initial SchedulingRegionID is greater than the
776           // initial SchedulingRegionID in ScheduleData (which is 0).
777           SchedulingRegionID(1) {}
778 
779     void clear() {
780       ReadyInsts.clear();
781       ScheduleStart = nullptr;
782       ScheduleEnd = nullptr;
783       FirstLoadStoreInRegion = nullptr;
784       LastLoadStoreInRegion = nullptr;
785 
786       // Reduce the maximum schedule region size by the size of the
787       // previous scheduling run.
788       ScheduleRegionSizeLimit -= ScheduleRegionSize;
789       if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
790         ScheduleRegionSizeLimit = MinScheduleRegionSize;
791       ScheduleRegionSize = 0;
792 
793       // Make a new scheduling region, i.e. all existing ScheduleData is not
794       // in the new region yet.
795       ++SchedulingRegionID;
796     }
797 
798     ScheduleData *getScheduleData(Value *V) {
799       ScheduleData *SD = ScheduleDataMap[V];
800       if (SD && SD->SchedulingRegionID == SchedulingRegionID)
801         return SD;
802       return nullptr;
803     }
804 
805     bool isInSchedulingRegion(ScheduleData *SD) {
806       return SD->SchedulingRegionID == SchedulingRegionID;
807     }
808 
809     /// Marks an instruction as scheduled and puts all dependent ready
810     /// instructions into the ready-list.
811     template <typename ReadyListType>
812     void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
813       SD->IsScheduled = true;
814       DEBUG(dbgs() << "SLP:   schedule " << *SD << "\n");
815 
816       ScheduleData *BundleMember = SD;
817       while (BundleMember) {
818         // Handle the def-use chain dependencies.
819         for (Use &U : BundleMember->Inst->operands()) {
820           ScheduleData *OpDef = getScheduleData(U.get());
821           if (OpDef && OpDef->hasValidDependencies() &&
822               OpDef->incrementUnscheduledDeps(-1) == 0) {
823             // There are no more unscheduled dependencies after decrementing,
824             // so we can put the dependent instruction into the ready list.
825             ScheduleData *DepBundle = OpDef->FirstInBundle;
826             assert(!DepBundle->IsScheduled &&
827                    "already scheduled bundle gets ready");
828             ReadyList.insert(DepBundle);
829             DEBUG(dbgs() << "SLP:    gets ready (def): " << *DepBundle << "\n");
830           }
831         }
832         // Handle the memory dependencies.
833         for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
834           if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
835             // There are no more unscheduled dependencies after decrementing,
836             // so we can put the dependent instruction into the ready list.
837             ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
838             assert(!DepBundle->IsScheduled &&
839                    "already scheduled bundle gets ready");
840             ReadyList.insert(DepBundle);
841             DEBUG(dbgs() << "SLP:    gets ready (mem): " << *DepBundle << "\n");
842           }
843         }
844         BundleMember = BundleMember->NextInBundle;
845       }
846     }
847 
848     /// Put all instructions into the ReadyList which are ready for scheduling.
849     template <typename ReadyListType>
850     void initialFillReadyList(ReadyListType &ReadyList) {
851       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
852         ScheduleData *SD = getScheduleData(I);
853         if (SD->isSchedulingEntity() && SD->isReady()) {
854           ReadyList.insert(SD);
855           DEBUG(dbgs() << "SLP:    initially in ready list: " << *I << "\n");
856         }
857       }
858     }
859 
860     /// Checks if a bundle of instructions can be scheduled, i.e. has no
861     /// cyclic dependencies. This is only a dry-run, no instructions are
862     /// actually moved at this stage.
863     bool tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP, Value *OpValue);
864 
865     /// Un-bundles a group of instructions.
866     void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
867 
868     /// Extends the scheduling region so that V is inside the region.
869     /// \returns true if the region size is within the limit.
870     bool extendSchedulingRegion(Value *V);
871 
872     /// Initialize the ScheduleData structures for new instructions in the
873     /// scheduling region.
874     void initScheduleData(Instruction *FromI, Instruction *ToI,
875                           ScheduleData *PrevLoadStore,
876                           ScheduleData *NextLoadStore);
877 
878     /// Updates the dependency information of a bundle and of all instructions/
879     /// bundles which depend on the original bundle.
880     void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
881                                BoUpSLP *SLP);
882 
883     /// Sets all instruction in the scheduling region to un-scheduled.
884     void resetSchedule();
885 
886     BasicBlock *BB;
887 
888     /// Simple memory allocation for ScheduleData.
889     std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
890 
891     /// The size of a ScheduleData array in ScheduleDataChunks.
892     int ChunkSize;
893 
894     /// The allocator position in the current chunk, which is the last entry
895     /// of ScheduleDataChunks.
896     int ChunkPos;
897 
898     /// Attaches ScheduleData to Instruction.
899     /// Note that the mapping survives during all vectorization iterations, i.e.
900     /// ScheduleData structures are recycled.
901     DenseMap<Value *, ScheduleData *> ScheduleDataMap;
902 
903     struct ReadyList : SmallVector<ScheduleData *, 8> {
904       void insert(ScheduleData *SD) { push_back(SD); }
905     };
906 
907     /// The ready-list for scheduling (only used for the dry-run).
908     ReadyList ReadyInsts;
909 
910     /// The first instruction of the scheduling region.
911     Instruction *ScheduleStart;
912 
913     /// The first instruction _after_ the scheduling region.
914     Instruction *ScheduleEnd;
915 
916     /// The first memory accessing instruction in the scheduling region
917     /// (can be null).
918     ScheduleData *FirstLoadStoreInRegion;
919 
920     /// The last memory accessing instruction in the scheduling region
921     /// (can be null).
922     ScheduleData *LastLoadStoreInRegion;
923 
924     /// The current size of the scheduling region.
925     int ScheduleRegionSize;
926 
927     /// The maximum size allowed for the scheduling region.
928     int ScheduleRegionSizeLimit;
929 
930     /// The ID of the scheduling region. For a new vectorization iteration this
931     /// is incremented which "removes" all ScheduleData from the region.
932     int SchedulingRegionID;
933   };
934 
935   /// Attaches the BlockScheduling structures to basic blocks.
936   MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
937 
938   /// Performs the "real" scheduling. Done before vectorization is actually
939   /// performed in a basic block.
940   void scheduleBlock(BlockScheduling *BS);
941 
942   /// List of users to ignore during scheduling and that don't need extracting.
943   ArrayRef<Value *> UserIgnoreList;
944 
945   // Number of load bundles that contain consecutive loads.
946   int NumLoadsWantToKeepOrder;
947 
948   // Number of load bundles that contain consecutive loads in reversed order.
949   int NumLoadsWantToChangeOrder;
950 
951   // Analysis and block reference.
952   Function *F;
953   ScalarEvolution *SE;
954   TargetTransformInfo *TTI;
955   TargetLibraryInfo *TLI;
956   AliasAnalysis *AA;
957   LoopInfo *LI;
958   DominatorTree *DT;
959   AssumptionCache *AC;
960   DemandedBits *DB;
961   const DataLayout *DL;
962   OptimizationRemarkEmitter *ORE;
963 
964   unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
965   unsigned MinVecRegSize; // Set by cl::opt (default: 128).
966   /// Instruction builder to construct the vectorized tree.
967   IRBuilder<> Builder;
968 
969   /// A map of scalar integer values to the smallest bit width with which they
970   /// can legally be represented. The values map to (width, signed) pairs,
971   /// where "width" indicates the minimum bit width and "signed" is True if the
972   /// value must be signed-extended, rather than zero-extended, back to its
973   /// original width.
974   MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
975 };
976 } // end namespace slpvectorizer
977 
978 template <> struct GraphTraits<BoUpSLP *> {
979   typedef BoUpSLP::TreeEntry TreeEntry;
980 
981   /// NodeRef has to be a pointer per the GraphWriter.
982   typedef TreeEntry *NodeRef;
983 
984   /// \brief Add the VectorizableTree to the index iterator to be able to return
985   /// TreeEntry pointers.
986   struct ChildIteratorType
987       : public iterator_adaptor_base<ChildIteratorType,
988                                      SmallVector<int, 1>::iterator> {
989 
990     std::vector<TreeEntry> &VectorizableTree;
991 
992     ChildIteratorType(SmallVector<int, 1>::iterator W,
993                       std::vector<TreeEntry> &VT)
994         : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
995 
996     NodeRef operator*() { return &VectorizableTree[*I]; }
997   };
998 
999   static NodeRef getEntryNode(BoUpSLP &R) { return &R.VectorizableTree[0]; }
1000 
1001   static ChildIteratorType child_begin(NodeRef N) {
1002     return {N->UserTreeIndices.begin(), N->Container};
1003   }
1004   static ChildIteratorType child_end(NodeRef N) {
1005     return {N->UserTreeIndices.end(), N->Container};
1006   }
1007 
1008   /// For the node iterator we just need to turn the TreeEntry iterator into a
1009   /// TreeEntry* iterator so that it dereferences to NodeRef.
1010   typedef pointer_iterator<std::vector<TreeEntry>::iterator> nodes_iterator;
1011 
1012   static nodes_iterator nodes_begin(BoUpSLP *R) {
1013     return nodes_iterator(R->VectorizableTree.begin());
1014   }
1015   static nodes_iterator nodes_end(BoUpSLP *R) {
1016     return nodes_iterator(R->VectorizableTree.end());
1017   }
1018 
1019   static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
1020 };
1021 
1022 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
1023   typedef BoUpSLP::TreeEntry TreeEntry;
1024 
1025   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
1026 
1027   std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
1028     std::string Str;
1029     raw_string_ostream OS(Str);
1030     if (isSplat(Entry->Scalars)) {
1031       OS << "<splat> " << *Entry->Scalars[0];
1032       return Str;
1033     }
1034     for (auto V : Entry->Scalars) {
1035       OS << *V;
1036       if (std::any_of(
1037               R->ExternalUses.begin(), R->ExternalUses.end(),
1038               [&](const BoUpSLP::ExternalUser &EU) { return EU.Scalar == V; }))
1039         OS << " <extract>";
1040       OS << "\n";
1041     }
1042     return Str;
1043   }
1044 
1045   static std::string getNodeAttributes(const TreeEntry *Entry,
1046                                        const BoUpSLP *) {
1047     if (Entry->NeedToGather)
1048       return "color=red";
1049     return "";
1050   }
1051 };
1052 
1053 } // end namespace llvm
1054 
1055 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
1056                         ArrayRef<Value *> UserIgnoreLst) {
1057   ExtraValueToDebugLocsMap ExternallyUsedValues;
1058   buildTree(Roots, ExternallyUsedValues, UserIgnoreLst);
1059 }
1060 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
1061                         ExtraValueToDebugLocsMap &ExternallyUsedValues,
1062                         ArrayRef<Value *> UserIgnoreLst) {
1063   deleteTree();
1064   UserIgnoreList = UserIgnoreLst;
1065   if (!allSameType(Roots))
1066     return;
1067   buildTree_rec(Roots, 0, -1);
1068 
1069   // Collect the values that we need to extract from the tree.
1070   for (TreeEntry &EIdx : VectorizableTree) {
1071     TreeEntry *Entry = &EIdx;
1072 
1073     // No need to handle users of gathered values.
1074     if (Entry->NeedToGather)
1075       continue;
1076 
1077     // For each lane:
1078     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
1079       Value *Scalar = Entry->Scalars[Lane];
1080 
1081       // Check if the scalar is externally used as an extra arg.
1082       auto ExtI = ExternallyUsedValues.find(Scalar);
1083       if (ExtI != ExternallyUsedValues.end()) {
1084         DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane " <<
1085               Lane << " from " << *Scalar << ".\n");
1086         ExternalUses.emplace_back(Scalar, nullptr, Lane);
1087         continue;
1088       }
1089       for (User *U : Scalar->users()) {
1090         DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
1091 
1092         Instruction *UserInst = dyn_cast<Instruction>(U);
1093         if (!UserInst)
1094           continue;
1095 
1096         // Skip in-tree scalars that become vectors
1097         if (TreeEntry *UseEntry = getTreeEntry(U)) {
1098           Value *UseScalar = UseEntry->Scalars[0];
1099           // Some in-tree scalars will remain as scalar in vectorized
1100           // instructions. If that is the case, the one in Lane 0 will
1101           // be used.
1102           if (UseScalar != U ||
1103               !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
1104             DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
1105                          << ".\n");
1106             assert(!UseEntry->NeedToGather && "Bad state");
1107             continue;
1108           }
1109         }
1110 
1111         // Ignore users in the user ignore list.
1112         if (is_contained(UserIgnoreList, UserInst))
1113           continue;
1114 
1115         DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane " <<
1116               Lane << " from " << *Scalar << ".\n");
1117         ExternalUses.push_back(ExternalUser(Scalar, U, Lane));
1118       }
1119     }
1120   }
1121 }
1122 
1123 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
1124                             int UserTreeIdx) {
1125   bool isAltShuffle = false;
1126   assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
1127 
1128   if (Depth == RecursionMaxDepth) {
1129     DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
1130     newTreeEntry(VL, false, UserTreeIdx);
1131     return;
1132   }
1133 
1134   // Don't handle vectors.
1135   if (VL[0]->getType()->isVectorTy()) {
1136     DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
1137     newTreeEntry(VL, false, UserTreeIdx);
1138     return;
1139   }
1140 
1141   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1142     if (SI->getValueOperand()->getType()->isVectorTy()) {
1143       DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
1144       newTreeEntry(VL, false, UserTreeIdx);
1145       return;
1146     }
1147   unsigned Opcode = getSameOpcode(VL);
1148 
1149   // Check that this shuffle vector refers to the alternate
1150   // sequence of opcodes.
1151   if (Opcode == Instruction::ShuffleVector) {
1152     Instruction *I0 = dyn_cast<Instruction>(VL[0]);
1153     unsigned Op = I0->getOpcode();
1154     if (Op != Instruction::ShuffleVector)
1155       isAltShuffle = true;
1156   }
1157 
1158   // If all of the operands are identical or constant we have a simple solution.
1159   if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !Opcode) {
1160     DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
1161     newTreeEntry(VL, false, UserTreeIdx);
1162     return;
1163   }
1164 
1165   // We now know that this is a vector of instructions of the same type from
1166   // the same block.
1167 
1168   // Don't vectorize ephemeral values.
1169   for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1170     if (EphValues.count(VL[i])) {
1171       DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
1172             ") is ephemeral.\n");
1173       newTreeEntry(VL, false, UserTreeIdx);
1174       return;
1175     }
1176   }
1177 
1178   // Check if this is a duplicate of another entry.
1179   if (TreeEntry *E = getTreeEntry(VL[0])) {
1180     for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1181       DEBUG(dbgs() << "SLP: \tChecking bundle: " << *VL[i] << ".\n");
1182       if (E->Scalars[i] != VL[i]) {
1183         DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
1184         newTreeEntry(VL, false, UserTreeIdx);
1185         return;
1186       }
1187     }
1188     // Record the reuse of the tree node.  FIXME, currently this is only used to
1189     // properly draw the graph rather than for the actual vectorization.
1190     E->UserTreeIndices.push_back(UserTreeIdx);
1191     DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *VL[0] << ".\n");
1192     return;
1193   }
1194 
1195   // Check that none of the instructions in the bundle are already in the tree.
1196   for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1197     if (ScalarToTreeEntry.count(VL[i])) {
1198       DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
1199             ") is already in tree.\n");
1200       newTreeEntry(VL, false, UserTreeIdx);
1201       return;
1202     }
1203   }
1204 
1205   // If any of the scalars is marked as a value that needs to stay scalar then
1206   // we need to gather the scalars.
1207   for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1208     if (MustGather.count(VL[i])) {
1209       DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
1210       newTreeEntry(VL, false, UserTreeIdx);
1211       return;
1212     }
1213   }
1214 
1215   // Check that all of the users of the scalars that we want to vectorize are
1216   // schedulable.
1217   Instruction *VL0 = cast<Instruction>(VL[0]);
1218   BasicBlock *BB = VL0->getParent();
1219 
1220   if (!DT->isReachableFromEntry(BB)) {
1221     // Don't go into unreachable blocks. They may contain instructions with
1222     // dependency cycles which confuse the final scheduling.
1223     DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
1224     newTreeEntry(VL, false, UserTreeIdx);
1225     return;
1226   }
1227 
1228   // Check that every instructions appears once in this bundle.
1229   for (unsigned i = 0, e = VL.size(); i < e; ++i)
1230     for (unsigned j = i+1; j < e; ++j)
1231       if (VL[i] == VL[j]) {
1232         DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
1233         newTreeEntry(VL, false, UserTreeIdx);
1234         return;
1235       }
1236 
1237   auto &BSRef = BlocksSchedules[BB];
1238   if (!BSRef) {
1239     BSRef = llvm::make_unique<BlockScheduling>(BB);
1240   }
1241   BlockScheduling &BS = *BSRef.get();
1242 
1243   if (!BS.tryScheduleBundle(VL, this, VL0)) {
1244     DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
1245     assert((!BS.getScheduleData(VL[0]) ||
1246             !BS.getScheduleData(VL[0])->isPartOfBundle()) &&
1247            "tryScheduleBundle should cancelScheduling on failure");
1248     newTreeEntry(VL, false, UserTreeIdx);
1249     return;
1250   }
1251   DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
1252 
1253   switch (Opcode) {
1254     case Instruction::PHI: {
1255       PHINode *PH = dyn_cast<PHINode>(VL0);
1256 
1257       // Check for terminator values (e.g. invoke).
1258       for (unsigned j = 0; j < VL.size(); ++j)
1259         for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1260           TerminatorInst *Term = dyn_cast<TerminatorInst>(
1261               cast<PHINode>(VL[j])->getIncomingValueForBlock(PH->getIncomingBlock(i)));
1262           if (Term) {
1263             DEBUG(dbgs() << "SLP: Need to swizzle PHINodes (TerminatorInst use).\n");
1264             BS.cancelScheduling(VL, VL0);
1265             newTreeEntry(VL, false, UserTreeIdx);
1266             return;
1267           }
1268         }
1269 
1270       newTreeEntry(VL, true, UserTreeIdx);
1271       DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
1272 
1273       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1274         ValueList Operands;
1275         // Prepare the operand vector.
1276         for (Value *j : VL)
1277           Operands.push_back(cast<PHINode>(j)->getIncomingValueForBlock(
1278               PH->getIncomingBlock(i)));
1279 
1280         buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1281       }
1282       return;
1283     }
1284     case Instruction::ExtractValue:
1285     case Instruction::ExtractElement: {
1286       bool Reuse = canReuseExtract(VL, VL0);
1287       if (Reuse) {
1288         DEBUG(dbgs() << "SLP: Reusing extract sequence.\n");
1289       } else {
1290         BS.cancelScheduling(VL, VL0);
1291       }
1292       newTreeEntry(VL, Reuse, UserTreeIdx);
1293       return;
1294     }
1295     case Instruction::Load: {
1296       // Check that a vectorized load would load the same memory as a scalar
1297       // load.
1298       // For example we don't want vectorize loads that are smaller than 8 bit.
1299       // Even though we have a packed struct {<i2, i2, i2, i2>} LLVM treats
1300       // loading/storing it as an i8 struct. If we vectorize loads/stores from
1301       // such a struct we read/write packed bits disagreeing with the
1302       // unvectorized version.
1303       Type *ScalarTy = VL0->getType();
1304 
1305       if (DL->getTypeSizeInBits(ScalarTy) !=
1306           DL->getTypeAllocSizeInBits(ScalarTy)) {
1307         BS.cancelScheduling(VL, VL0);
1308         newTreeEntry(VL, false, UserTreeIdx);
1309         DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
1310         return;
1311       }
1312 
1313       // Make sure all loads in the bundle are simple - we can't vectorize
1314       // atomic or volatile loads.
1315       for (unsigned i = 0, e = VL.size() - 1; i < e; ++i) {
1316         LoadInst *L = cast<LoadInst>(VL[i]);
1317         if (!L->isSimple()) {
1318           BS.cancelScheduling(VL, VL0);
1319           newTreeEntry(VL, false, UserTreeIdx);
1320           DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
1321           return;
1322         }
1323       }
1324 
1325       // Check if the loads are consecutive, reversed, or neither.
1326       // TODO: What we really want is to sort the loads, but for now, check
1327       // the two likely directions.
1328       bool Consecutive = true;
1329       bool ReverseConsecutive = true;
1330       for (unsigned i = 0, e = VL.size() - 1; i < e; ++i) {
1331         if (!isConsecutiveAccess(VL[i], VL[i + 1], *DL, *SE)) {
1332           Consecutive = false;
1333           break;
1334         } else {
1335           ReverseConsecutive = false;
1336         }
1337       }
1338 
1339       if (Consecutive) {
1340         ++NumLoadsWantToKeepOrder;
1341         newTreeEntry(VL, true, UserTreeIdx);
1342         DEBUG(dbgs() << "SLP: added a vector of loads.\n");
1343         return;
1344       }
1345 
1346       // If none of the load pairs were consecutive when checked in order,
1347       // check the reverse order.
1348       if (ReverseConsecutive)
1349         for (unsigned i = VL.size() - 1; i > 0; --i)
1350           if (!isConsecutiveAccess(VL[i], VL[i - 1], *DL, *SE)) {
1351             ReverseConsecutive = false;
1352             break;
1353           }
1354 
1355       BS.cancelScheduling(VL, VL0);
1356       newTreeEntry(VL, false, UserTreeIdx);
1357 
1358       if (ReverseConsecutive) {
1359         ++NumLoadsWantToChangeOrder;
1360         DEBUG(dbgs() << "SLP: Gathering reversed loads.\n");
1361       } else {
1362         DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
1363       }
1364       return;
1365     }
1366     case Instruction::ZExt:
1367     case Instruction::SExt:
1368     case Instruction::FPToUI:
1369     case Instruction::FPToSI:
1370     case Instruction::FPExt:
1371     case Instruction::PtrToInt:
1372     case Instruction::IntToPtr:
1373     case Instruction::SIToFP:
1374     case Instruction::UIToFP:
1375     case Instruction::Trunc:
1376     case Instruction::FPTrunc:
1377     case Instruction::BitCast: {
1378       Type *SrcTy = VL0->getOperand(0)->getType();
1379       for (unsigned i = 0; i < VL.size(); ++i) {
1380         Type *Ty = cast<Instruction>(VL[i])->getOperand(0)->getType();
1381         if (Ty != SrcTy || !isValidElementType(Ty)) {
1382           BS.cancelScheduling(VL, VL0);
1383           newTreeEntry(VL, false, UserTreeIdx);
1384           DEBUG(dbgs() << "SLP: Gathering casts with different src types.\n");
1385           return;
1386         }
1387       }
1388       newTreeEntry(VL, true, UserTreeIdx);
1389       DEBUG(dbgs() << "SLP: added a vector of casts.\n");
1390 
1391       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1392         ValueList Operands;
1393         // Prepare the operand vector.
1394         for (Value *j : VL)
1395           Operands.push_back(cast<Instruction>(j)->getOperand(i));
1396 
1397         buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1398       }
1399       return;
1400     }
1401     case Instruction::ICmp:
1402     case Instruction::FCmp: {
1403       // Check that all of the compares have the same predicate.
1404       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
1405       Type *ComparedTy = VL0->getOperand(0)->getType();
1406       for (unsigned i = 1, e = VL.size(); i < e; ++i) {
1407         CmpInst *Cmp = cast<CmpInst>(VL[i]);
1408         if (Cmp->getPredicate() != P0 ||
1409             Cmp->getOperand(0)->getType() != ComparedTy) {
1410           BS.cancelScheduling(VL, VL0);
1411           newTreeEntry(VL, false, UserTreeIdx);
1412           DEBUG(dbgs() << "SLP: Gathering cmp with different predicate.\n");
1413           return;
1414         }
1415       }
1416 
1417       newTreeEntry(VL, true, UserTreeIdx);
1418       DEBUG(dbgs() << "SLP: added a vector of compares.\n");
1419 
1420       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1421         ValueList Operands;
1422         // Prepare the operand vector.
1423         for (Value *j : VL)
1424           Operands.push_back(cast<Instruction>(j)->getOperand(i));
1425 
1426         buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1427       }
1428       return;
1429     }
1430     case Instruction::Select:
1431     case Instruction::Add:
1432     case Instruction::FAdd:
1433     case Instruction::Sub:
1434     case Instruction::FSub:
1435     case Instruction::Mul:
1436     case Instruction::FMul:
1437     case Instruction::UDiv:
1438     case Instruction::SDiv:
1439     case Instruction::FDiv:
1440     case Instruction::URem:
1441     case Instruction::SRem:
1442     case Instruction::FRem:
1443     case Instruction::Shl:
1444     case Instruction::LShr:
1445     case Instruction::AShr:
1446     case Instruction::And:
1447     case Instruction::Or:
1448     case Instruction::Xor: {
1449       newTreeEntry(VL, true, UserTreeIdx);
1450       DEBUG(dbgs() << "SLP: added a vector of bin op.\n");
1451 
1452       // Sort operands of the instructions so that each side is more likely to
1453       // have the same opcode.
1454       if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
1455         ValueList Left, Right;
1456         reorderInputsAccordingToOpcode(VL, Left, Right);
1457         buildTree_rec(Left, Depth + 1, UserTreeIdx);
1458         buildTree_rec(Right, Depth + 1, UserTreeIdx);
1459         return;
1460       }
1461 
1462       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1463         ValueList Operands;
1464         // Prepare the operand vector.
1465         for (Value *j : VL)
1466           Operands.push_back(cast<Instruction>(j)->getOperand(i));
1467 
1468         buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1469       }
1470       return;
1471     }
1472     case Instruction::GetElementPtr: {
1473       // We don't combine GEPs with complicated (nested) indexing.
1474       for (unsigned j = 0; j < VL.size(); ++j) {
1475         if (cast<Instruction>(VL[j])->getNumOperands() != 2) {
1476           DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
1477           BS.cancelScheduling(VL, VL0);
1478           newTreeEntry(VL, false, UserTreeIdx);
1479           return;
1480         }
1481       }
1482 
1483       // We can't combine several GEPs into one vector if they operate on
1484       // different types.
1485       Type *Ty0 = VL0->getOperand(0)->getType();
1486       for (unsigned j = 0; j < VL.size(); ++j) {
1487         Type *CurTy = cast<Instruction>(VL[j])->getOperand(0)->getType();
1488         if (Ty0 != CurTy) {
1489           DEBUG(dbgs() << "SLP: not-vectorizable GEP (different types).\n");
1490           BS.cancelScheduling(VL, VL0);
1491           newTreeEntry(VL, false, UserTreeIdx);
1492           return;
1493         }
1494       }
1495 
1496       // We don't combine GEPs with non-constant indexes.
1497       for (unsigned j = 0; j < VL.size(); ++j) {
1498         auto Op = cast<Instruction>(VL[j])->getOperand(1);
1499         if (!isa<ConstantInt>(Op)) {
1500           DEBUG(
1501               dbgs() << "SLP: not-vectorizable GEP (non-constant indexes).\n");
1502           BS.cancelScheduling(VL, VL0);
1503           newTreeEntry(VL, false, UserTreeIdx);
1504           return;
1505         }
1506       }
1507 
1508       newTreeEntry(VL, true, UserTreeIdx);
1509       DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
1510       for (unsigned i = 0, e = 2; i < e; ++i) {
1511         ValueList Operands;
1512         // Prepare the operand vector.
1513         for (Value *j : VL)
1514           Operands.push_back(cast<Instruction>(j)->getOperand(i));
1515 
1516         buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1517       }
1518       return;
1519     }
1520     case Instruction::Store: {
1521       // Check if the stores are consecutive or of we need to swizzle them.
1522       for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
1523         if (!isConsecutiveAccess(VL[i], VL[i + 1], *DL, *SE)) {
1524           BS.cancelScheduling(VL, VL0);
1525           newTreeEntry(VL, false, UserTreeIdx);
1526           DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
1527           return;
1528         }
1529 
1530       newTreeEntry(VL, true, UserTreeIdx);
1531       DEBUG(dbgs() << "SLP: added a vector of stores.\n");
1532 
1533       ValueList Operands;
1534       for (Value *j : VL)
1535         Operands.push_back(cast<Instruction>(j)->getOperand(0));
1536 
1537       buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1538       return;
1539     }
1540     case Instruction::Call: {
1541       // Check if the calls are all to the same vectorizable intrinsic.
1542       CallInst *CI = cast<CallInst>(VL0);
1543       // Check if this is an Intrinsic call or something that can be
1544       // represented by an intrinsic call
1545       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
1546       if (!isTriviallyVectorizable(ID)) {
1547         BS.cancelScheduling(VL, VL0);
1548         newTreeEntry(VL, false, UserTreeIdx);
1549         DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
1550         return;
1551       }
1552       Function *Int = CI->getCalledFunction();
1553       Value *A1I = nullptr;
1554       if (hasVectorInstrinsicScalarOpd(ID, 1))
1555         A1I = CI->getArgOperand(1);
1556       for (unsigned i = 1, e = VL.size(); i != e; ++i) {
1557         CallInst *CI2 = dyn_cast<CallInst>(VL[i]);
1558         if (!CI2 || CI2->getCalledFunction() != Int ||
1559             getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
1560             !CI->hasIdenticalOperandBundleSchema(*CI2)) {
1561           BS.cancelScheduling(VL, VL0);
1562           newTreeEntry(VL, false, UserTreeIdx);
1563           DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *VL[i]
1564                        << "\n");
1565           return;
1566         }
1567         // ctlz,cttz and powi are special intrinsics whose second argument
1568         // should be same in order for them to be vectorized.
1569         if (hasVectorInstrinsicScalarOpd(ID, 1)) {
1570           Value *A1J = CI2->getArgOperand(1);
1571           if (A1I != A1J) {
1572             BS.cancelScheduling(VL, VL0);
1573             newTreeEntry(VL, false, UserTreeIdx);
1574             DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
1575                          << " argument "<< A1I<<"!=" << A1J
1576                          << "\n");
1577             return;
1578           }
1579         }
1580         // Verify that the bundle operands are identical between the two calls.
1581         if (CI->hasOperandBundles() &&
1582             !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
1583                         CI->op_begin() + CI->getBundleOperandsEndIndex(),
1584                         CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
1585           BS.cancelScheduling(VL, VL0);
1586           newTreeEntry(VL, false, UserTreeIdx);
1587           DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:" << *CI << "!="
1588                        << *VL[i] << '\n');
1589           return;
1590         }
1591       }
1592 
1593       newTreeEntry(VL, true, UserTreeIdx);
1594       for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i) {
1595         ValueList Operands;
1596         // Prepare the operand vector.
1597         for (Value *j : VL) {
1598           CallInst *CI2 = dyn_cast<CallInst>(j);
1599           Operands.push_back(CI2->getArgOperand(i));
1600         }
1601         buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1602       }
1603       return;
1604     }
1605     case Instruction::ShuffleVector: {
1606       // If this is not an alternate sequence of opcode like add-sub
1607       // then do not vectorize this instruction.
1608       if (!isAltShuffle) {
1609         BS.cancelScheduling(VL, VL0);
1610         newTreeEntry(VL, false, UserTreeIdx);
1611         DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
1612         return;
1613       }
1614       newTreeEntry(VL, true, UserTreeIdx);
1615       DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
1616 
1617       // Reorder operands if reordering would enable vectorization.
1618       if (isa<BinaryOperator>(VL0)) {
1619         ValueList Left, Right;
1620         reorderAltShuffleOperands(VL, Left, Right);
1621         buildTree_rec(Left, Depth + 1, UserTreeIdx);
1622         buildTree_rec(Right, Depth + 1, UserTreeIdx);
1623         return;
1624       }
1625 
1626       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1627         ValueList Operands;
1628         // Prepare the operand vector.
1629         for (Value *j : VL)
1630           Operands.push_back(cast<Instruction>(j)->getOperand(i));
1631 
1632         buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1633       }
1634       return;
1635     }
1636     default:
1637       BS.cancelScheduling(VL, VL0);
1638       newTreeEntry(VL, false, UserTreeIdx);
1639       DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
1640       return;
1641   }
1642 }
1643 
1644 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
1645   unsigned N;
1646   Type *EltTy;
1647   auto *ST = dyn_cast<StructType>(T);
1648   if (ST) {
1649     N = ST->getNumElements();
1650     EltTy = *ST->element_begin();
1651   } else {
1652     N = cast<ArrayType>(T)->getNumElements();
1653     EltTy = cast<ArrayType>(T)->getElementType();
1654   }
1655   if (!isValidElementType(EltTy))
1656     return 0;
1657   uint64_t VTSize = DL.getTypeStoreSizeInBits(VectorType::get(EltTy, N));
1658   if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
1659     return 0;
1660   if (ST) {
1661     // Check that struct is homogeneous.
1662     for (const auto *Ty : ST->elements())
1663       if (Ty != EltTy)
1664         return 0;
1665   }
1666   return N;
1667 }
1668 
1669 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue) const {
1670   Instruction *E0 = cast<Instruction>(OpValue);
1671   assert(E0->getOpcode() == Instruction::ExtractElement ||
1672          E0->getOpcode() == Instruction::ExtractValue);
1673   assert(E0->getOpcode() == getSameOpcode(VL) && "Invalid opcode");
1674   // Check if all of the extracts come from the same vector and from the
1675   // correct offset.
1676   Value *Vec = E0->getOperand(0);
1677 
1678   // We have to extract from a vector/aggregate with the same number of elements.
1679   unsigned NElts;
1680   if (E0->getOpcode() == Instruction::ExtractValue) {
1681     const DataLayout &DL = E0->getModule()->getDataLayout();
1682     NElts = canMapToVector(Vec->getType(), DL);
1683     if (!NElts)
1684       return false;
1685     // Check if load can be rewritten as load of vector.
1686     LoadInst *LI = dyn_cast<LoadInst>(Vec);
1687     if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
1688       return false;
1689   } else {
1690     NElts = Vec->getType()->getVectorNumElements();
1691   }
1692 
1693   if (NElts != VL.size())
1694     return false;
1695 
1696   // Check that all of the indices extract from the correct offset.
1697   for (unsigned I = 0, E = VL.size(); I < E; ++I) {
1698     Instruction *Inst = cast<Instruction>(VL[I]);
1699     if (!matchExtractIndex(Inst, I, Inst->getOpcode()))
1700       return false;
1701     if (Inst->getOperand(0) != Vec)
1702       return false;
1703   }
1704 
1705   return true;
1706 }
1707 
1708 bool BoUpSLP::areAllUsersVectorized(Instruction *I) const {
1709   return I->hasOneUse() ||
1710          std::all_of(I->user_begin(), I->user_end(), [this](User *U) {
1711            return ScalarToTreeEntry.count(U) > 0;
1712          });
1713 }
1714 
1715 int BoUpSLP::getEntryCost(TreeEntry *E) {
1716   ArrayRef<Value*> VL = E->Scalars;
1717 
1718   Type *ScalarTy = VL[0]->getType();
1719   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1720     ScalarTy = SI->getValueOperand()->getType();
1721   else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
1722     ScalarTy = CI->getOperand(0)->getType();
1723   VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1724 
1725   // If we have computed a smaller type for the expression, update VecTy so
1726   // that the costs will be accurate.
1727   if (MinBWs.count(VL[0]))
1728     VecTy = VectorType::get(
1729         IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
1730 
1731   if (E->NeedToGather) {
1732     if (allConstant(VL))
1733       return 0;
1734     if (isSplat(VL)) {
1735       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
1736     }
1737     return getGatherCost(E->Scalars);
1738   }
1739   unsigned Opcode = getSameOpcode(VL);
1740   assert(Opcode && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
1741   Instruction *VL0 = cast<Instruction>(VL[0]);
1742   switch (Opcode) {
1743     case Instruction::PHI: {
1744       return 0;
1745     }
1746     case Instruction::ExtractValue:
1747     case Instruction::ExtractElement: {
1748       if (canReuseExtract(VL, VL0)) {
1749         int DeadCost = 0;
1750         for (unsigned i = 0, e = VL.size(); i < e; ++i) {
1751           Instruction *E = cast<Instruction>(VL[i]);
1752           // If all users are going to be vectorized, instruction can be
1753           // considered as dead.
1754           // The same, if have only one user, it will be vectorized for sure.
1755           if (areAllUsersVectorized(E))
1756             // Take credit for instruction that will become dead.
1757             DeadCost +=
1758                 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, i);
1759         }
1760         return -DeadCost;
1761       }
1762       return getGatherCost(VecTy);
1763     }
1764     case Instruction::ZExt:
1765     case Instruction::SExt:
1766     case Instruction::FPToUI:
1767     case Instruction::FPToSI:
1768     case Instruction::FPExt:
1769     case Instruction::PtrToInt:
1770     case Instruction::IntToPtr:
1771     case Instruction::SIToFP:
1772     case Instruction::UIToFP:
1773     case Instruction::Trunc:
1774     case Instruction::FPTrunc:
1775     case Instruction::BitCast: {
1776       Type *SrcTy = VL0->getOperand(0)->getType();
1777 
1778       // Calculate the cost of this instruction.
1779       int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(),
1780                                                          VL0->getType(), SrcTy, VL0);
1781 
1782       VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
1783       int VecCost = TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy, VL0);
1784       return VecCost - ScalarCost;
1785     }
1786     case Instruction::FCmp:
1787     case Instruction::ICmp:
1788     case Instruction::Select: {
1789       // Calculate the cost of this instruction.
1790       VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
1791       int ScalarCost = VecTy->getNumElements() *
1792           TTI->getCmpSelInstrCost(Opcode, ScalarTy, Builder.getInt1Ty(), VL0);
1793       int VecCost = TTI->getCmpSelInstrCost(Opcode, VecTy, MaskTy, VL0);
1794       return VecCost - ScalarCost;
1795     }
1796     case Instruction::Add:
1797     case Instruction::FAdd:
1798     case Instruction::Sub:
1799     case Instruction::FSub:
1800     case Instruction::Mul:
1801     case Instruction::FMul:
1802     case Instruction::UDiv:
1803     case Instruction::SDiv:
1804     case Instruction::FDiv:
1805     case Instruction::URem:
1806     case Instruction::SRem:
1807     case Instruction::FRem:
1808     case Instruction::Shl:
1809     case Instruction::LShr:
1810     case Instruction::AShr:
1811     case Instruction::And:
1812     case Instruction::Or:
1813     case Instruction::Xor: {
1814       // Certain instructions can be cheaper to vectorize if they have a
1815       // constant second vector operand.
1816       TargetTransformInfo::OperandValueKind Op1VK =
1817           TargetTransformInfo::OK_AnyValue;
1818       TargetTransformInfo::OperandValueKind Op2VK =
1819           TargetTransformInfo::OK_UniformConstantValue;
1820       TargetTransformInfo::OperandValueProperties Op1VP =
1821           TargetTransformInfo::OP_None;
1822       TargetTransformInfo::OperandValueProperties Op2VP =
1823           TargetTransformInfo::OP_None;
1824 
1825       // If all operands are exactly the same ConstantInt then set the
1826       // operand kind to OK_UniformConstantValue.
1827       // If instead not all operands are constants, then set the operand kind
1828       // to OK_AnyValue. If all operands are constants but not the same,
1829       // then set the operand kind to OK_NonUniformConstantValue.
1830       ConstantInt *CInt = nullptr;
1831       for (unsigned i = 0; i < VL.size(); ++i) {
1832         const Instruction *I = cast<Instruction>(VL[i]);
1833         if (!isa<ConstantInt>(I->getOperand(1))) {
1834           Op2VK = TargetTransformInfo::OK_AnyValue;
1835           break;
1836         }
1837         if (i == 0) {
1838           CInt = cast<ConstantInt>(I->getOperand(1));
1839           continue;
1840         }
1841         if (Op2VK == TargetTransformInfo::OK_UniformConstantValue &&
1842             CInt != cast<ConstantInt>(I->getOperand(1)))
1843           Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
1844       }
1845       // FIXME: Currently cost of model modification for division by power of
1846       // 2 is handled for X86 and AArch64. Add support for other targets.
1847       if (Op2VK == TargetTransformInfo::OK_UniformConstantValue && CInt &&
1848           CInt->getValue().isPowerOf2())
1849         Op2VP = TargetTransformInfo::OP_PowerOf2;
1850 
1851       SmallVector<const Value *, 4> Operands(VL0->operand_values());
1852       int ScalarCost =
1853           VecTy->getNumElements() *
1854           TTI->getArithmeticInstrCost(Opcode, ScalarTy, Op1VK, Op2VK, Op1VP,
1855                                       Op2VP, Operands);
1856       int VecCost = TTI->getArithmeticInstrCost(Opcode, VecTy, Op1VK, Op2VK,
1857                                                 Op1VP, Op2VP, Operands);
1858       return VecCost - ScalarCost;
1859     }
1860     case Instruction::GetElementPtr: {
1861       TargetTransformInfo::OperandValueKind Op1VK =
1862           TargetTransformInfo::OK_AnyValue;
1863       TargetTransformInfo::OperandValueKind Op2VK =
1864           TargetTransformInfo::OK_UniformConstantValue;
1865 
1866       int ScalarCost =
1867           VecTy->getNumElements() *
1868           TTI->getArithmeticInstrCost(Instruction::Add, ScalarTy, Op1VK, Op2VK);
1869       int VecCost =
1870           TTI->getArithmeticInstrCost(Instruction::Add, VecTy, Op1VK, Op2VK);
1871 
1872       return VecCost - ScalarCost;
1873     }
1874     case Instruction::Load: {
1875       // Cost of wide load - cost of scalar loads.
1876       unsigned alignment = dyn_cast<LoadInst>(VL0)->getAlignment();
1877       int ScalarLdCost = VecTy->getNumElements() *
1878           TTI->getMemoryOpCost(Instruction::Load, ScalarTy, alignment, 0, VL0);
1879       int VecLdCost = TTI->getMemoryOpCost(Instruction::Load,
1880                                            VecTy, alignment, 0, VL0);
1881       return VecLdCost - ScalarLdCost;
1882     }
1883     case Instruction::Store: {
1884       // We know that we can merge the stores. Calculate the cost.
1885       unsigned alignment = dyn_cast<StoreInst>(VL0)->getAlignment();
1886       int ScalarStCost = VecTy->getNumElements() *
1887           TTI->getMemoryOpCost(Instruction::Store, ScalarTy, alignment, 0, VL0);
1888       int VecStCost = TTI->getMemoryOpCost(Instruction::Store,
1889                                            VecTy, alignment, 0, VL0);
1890       return VecStCost - ScalarStCost;
1891     }
1892     case Instruction::Call: {
1893       CallInst *CI = cast<CallInst>(VL0);
1894       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
1895 
1896       // Calculate the cost of the scalar and vector calls.
1897       SmallVector<Type*, 4> ScalarTys;
1898       for (unsigned op = 0, opc = CI->getNumArgOperands(); op!= opc; ++op)
1899         ScalarTys.push_back(CI->getArgOperand(op)->getType());
1900 
1901       FastMathFlags FMF;
1902       if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
1903         FMF = FPMO->getFastMathFlags();
1904 
1905       int ScalarCallCost = VecTy->getNumElements() *
1906           TTI->getIntrinsicInstrCost(ID, ScalarTy, ScalarTys, FMF);
1907 
1908       SmallVector<Value *, 4> Args(CI->arg_operands());
1909       int VecCallCost = TTI->getIntrinsicInstrCost(ID, CI->getType(), Args, FMF,
1910                                                    VecTy->getNumElements());
1911 
1912       DEBUG(dbgs() << "SLP: Call cost "<< VecCallCost - ScalarCallCost
1913             << " (" << VecCallCost  << "-" <<  ScalarCallCost << ")"
1914             << " for " << *CI << "\n");
1915 
1916       return VecCallCost - ScalarCallCost;
1917     }
1918     case Instruction::ShuffleVector: {
1919       TargetTransformInfo::OperandValueKind Op1VK =
1920           TargetTransformInfo::OK_AnyValue;
1921       TargetTransformInfo::OperandValueKind Op2VK =
1922           TargetTransformInfo::OK_AnyValue;
1923       int ScalarCost = 0;
1924       int VecCost = 0;
1925       for (Value *i : VL) {
1926         Instruction *I = cast<Instruction>(i);
1927         if (!I)
1928           break;
1929         ScalarCost +=
1930             TTI->getArithmeticInstrCost(I->getOpcode(), ScalarTy, Op1VK, Op2VK);
1931       }
1932       // VecCost is equal to sum of the cost of creating 2 vectors
1933       // and the cost of creating shuffle.
1934       Instruction *I0 = cast<Instruction>(VL[0]);
1935       VecCost =
1936           TTI->getArithmeticInstrCost(I0->getOpcode(), VecTy, Op1VK, Op2VK);
1937       Instruction *I1 = cast<Instruction>(VL[1]);
1938       VecCost +=
1939           TTI->getArithmeticInstrCost(I1->getOpcode(), VecTy, Op1VK, Op2VK);
1940       VecCost +=
1941           TTI->getShuffleCost(TargetTransformInfo::SK_Alternate, VecTy, 0);
1942       return VecCost - ScalarCost;
1943     }
1944     default:
1945       llvm_unreachable("Unknown instruction");
1946   }
1947 }
1948 
1949 bool BoUpSLP::isFullyVectorizableTinyTree() {
1950   DEBUG(dbgs() << "SLP: Check whether the tree with height " <<
1951         VectorizableTree.size() << " is fully vectorizable .\n");
1952 
1953   // We only handle trees of heights 1 and 2.
1954   if (VectorizableTree.size() == 1 && !VectorizableTree[0].NeedToGather)
1955     return true;
1956 
1957   if (VectorizableTree.size() != 2)
1958     return false;
1959 
1960   // Handle splat and all-constants stores.
1961   if (!VectorizableTree[0].NeedToGather &&
1962       (allConstant(VectorizableTree[1].Scalars) ||
1963        isSplat(VectorizableTree[1].Scalars)))
1964     return true;
1965 
1966   // Gathering cost would be too much for tiny trees.
1967   if (VectorizableTree[0].NeedToGather || VectorizableTree[1].NeedToGather)
1968     return false;
1969 
1970   return true;
1971 }
1972 
1973 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable() {
1974 
1975   // We can vectorize the tree if its size is greater than or equal to the
1976   // minimum size specified by the MinTreeSize command line option.
1977   if (VectorizableTree.size() >= MinTreeSize)
1978     return false;
1979 
1980   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
1981   // can vectorize it if we can prove it fully vectorizable.
1982   if (isFullyVectorizableTinyTree())
1983     return false;
1984 
1985   assert(VectorizableTree.empty()
1986              ? ExternalUses.empty()
1987              : true && "We shouldn't have any external users");
1988 
1989   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
1990   // vectorizable.
1991   return true;
1992 }
1993 
1994 int BoUpSLP::getSpillCost() {
1995   // Walk from the bottom of the tree to the top, tracking which values are
1996   // live. When we see a call instruction that is not part of our tree,
1997   // query TTI to see if there is a cost to keeping values live over it
1998   // (for example, if spills and fills are required).
1999   unsigned BundleWidth = VectorizableTree.front().Scalars.size();
2000   int Cost = 0;
2001 
2002   SmallPtrSet<Instruction*, 4> LiveValues;
2003   Instruction *PrevInst = nullptr;
2004 
2005   for (const auto &N : VectorizableTree) {
2006     Instruction *Inst = dyn_cast<Instruction>(N.Scalars[0]);
2007     if (!Inst)
2008       continue;
2009 
2010     if (!PrevInst) {
2011       PrevInst = Inst;
2012       continue;
2013     }
2014 
2015     // Update LiveValues.
2016     LiveValues.erase(PrevInst);
2017     for (auto &J : PrevInst->operands()) {
2018       if (isa<Instruction>(&*J) && getTreeEntry(&*J))
2019         LiveValues.insert(cast<Instruction>(&*J));
2020     }
2021 
2022     DEBUG(
2023       dbgs() << "SLP: #LV: " << LiveValues.size();
2024       for (auto *X : LiveValues)
2025         dbgs() << " " << X->getName();
2026       dbgs() << ", Looking at ";
2027       Inst->dump();
2028       );
2029 
2030     // Now find the sequence of instructions between PrevInst and Inst.
2031     BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
2032                                  PrevInstIt =
2033                                      PrevInst->getIterator().getReverse();
2034     while (InstIt != PrevInstIt) {
2035       if (PrevInstIt == PrevInst->getParent()->rend()) {
2036         PrevInstIt = Inst->getParent()->rbegin();
2037         continue;
2038       }
2039 
2040       if (isa<CallInst>(&*PrevInstIt) && &*PrevInstIt != PrevInst) {
2041         SmallVector<Type*, 4> V;
2042         for (auto *II : LiveValues)
2043           V.push_back(VectorType::get(II->getType(), BundleWidth));
2044         Cost += TTI->getCostOfKeepingLiveOverCall(V);
2045       }
2046 
2047       ++PrevInstIt;
2048     }
2049 
2050     PrevInst = Inst;
2051   }
2052 
2053   return Cost;
2054 }
2055 
2056 int BoUpSLP::getTreeCost() {
2057   int Cost = 0;
2058   DEBUG(dbgs() << "SLP: Calculating cost for tree of size " <<
2059         VectorizableTree.size() << ".\n");
2060 
2061   unsigned BundleWidth = VectorizableTree[0].Scalars.size();
2062 
2063   for (TreeEntry &TE : VectorizableTree) {
2064     int C = getEntryCost(&TE);
2065     DEBUG(dbgs() << "SLP: Adding cost " << C << " for bundle that starts with "
2066                  << *TE.Scalars[0] << ".\n");
2067     Cost += C;
2068   }
2069 
2070   SmallSet<Value *, 16> ExtractCostCalculated;
2071   int ExtractCost = 0;
2072   for (ExternalUser &EU : ExternalUses) {
2073     // We only add extract cost once for the same scalar.
2074     if (!ExtractCostCalculated.insert(EU.Scalar).second)
2075       continue;
2076 
2077     // Uses by ephemeral values are free (because the ephemeral value will be
2078     // removed prior to code generation, and so the extraction will be
2079     // removed as well).
2080     if (EphValues.count(EU.User))
2081       continue;
2082 
2083     // If we plan to rewrite the tree in a smaller type, we will need to sign
2084     // extend the extracted value back to the original type. Here, we account
2085     // for the extract and the added cost of the sign extend if needed.
2086     auto *VecTy = VectorType::get(EU.Scalar->getType(), BundleWidth);
2087     auto *ScalarRoot = VectorizableTree[0].Scalars[0];
2088     if (MinBWs.count(ScalarRoot)) {
2089       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
2090       auto Extend =
2091           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
2092       VecTy = VectorType::get(MinTy, BundleWidth);
2093       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
2094                                                    VecTy, EU.Lane);
2095     } else {
2096       ExtractCost +=
2097           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
2098     }
2099   }
2100 
2101   int SpillCost = getSpillCost();
2102   Cost += SpillCost + ExtractCost;
2103 
2104   std::string Str;
2105   {
2106     raw_string_ostream OS(Str);
2107     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
2108        << "SLP: Extract Cost = " << ExtractCost << ".\n"
2109        << "SLP: Total Cost = " << Cost << ".\n";
2110   }
2111   DEBUG(dbgs() << Str);
2112 
2113   if (ViewSLPTree)
2114     ViewGraph(this, "SLP" + F->getName(), false, Str);
2115 
2116   return Cost;
2117 }
2118 
2119 int BoUpSLP::getGatherCost(Type *Ty) {
2120   int Cost = 0;
2121   for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
2122     Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
2123   return Cost;
2124 }
2125 
2126 int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) {
2127   // Find the type of the operands in VL.
2128   Type *ScalarTy = VL[0]->getType();
2129   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
2130     ScalarTy = SI->getValueOperand()->getType();
2131   VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
2132   // Find the cost of inserting/extracting values from the vector.
2133   return getGatherCost(VecTy);
2134 }
2135 
2136 // Reorder commutative operations in alternate shuffle if the resulting vectors
2137 // are consecutive loads. This would allow us to vectorize the tree.
2138 // If we have something like-
2139 // load a[0] - load b[0]
2140 // load b[1] + load a[1]
2141 // load a[2] - load b[2]
2142 // load a[3] + load b[3]
2143 // Reordering the second load b[1]  load a[1] would allow us to vectorize this
2144 // code.
2145 void BoUpSLP::reorderAltShuffleOperands(ArrayRef<Value *> VL,
2146                                         SmallVectorImpl<Value *> &Left,
2147                                         SmallVectorImpl<Value *> &Right) {
2148   // Push left and right operands of binary operation into Left and Right
2149   for (Value *i : VL) {
2150     Left.push_back(cast<Instruction>(i)->getOperand(0));
2151     Right.push_back(cast<Instruction>(i)->getOperand(1));
2152   }
2153 
2154   // Reorder if we have a commutative operation and consecutive access
2155   // are on either side of the alternate instructions.
2156   for (unsigned j = 0; j < VL.size() - 1; ++j) {
2157     if (LoadInst *L = dyn_cast<LoadInst>(Left[j])) {
2158       if (LoadInst *L1 = dyn_cast<LoadInst>(Right[j + 1])) {
2159         Instruction *VL1 = cast<Instruction>(VL[j]);
2160         Instruction *VL2 = cast<Instruction>(VL[j + 1]);
2161         if (VL1->isCommutative() && isConsecutiveAccess(L, L1, *DL, *SE)) {
2162           std::swap(Left[j], Right[j]);
2163           continue;
2164         } else if (VL2->isCommutative() &&
2165                    isConsecutiveAccess(L, L1, *DL, *SE)) {
2166           std::swap(Left[j + 1], Right[j + 1]);
2167           continue;
2168         }
2169         // else unchanged
2170       }
2171     }
2172     if (LoadInst *L = dyn_cast<LoadInst>(Right[j])) {
2173       if (LoadInst *L1 = dyn_cast<LoadInst>(Left[j + 1])) {
2174         Instruction *VL1 = cast<Instruction>(VL[j]);
2175         Instruction *VL2 = cast<Instruction>(VL[j + 1]);
2176         if (VL1->isCommutative() && isConsecutiveAccess(L, L1, *DL, *SE)) {
2177           std::swap(Left[j], Right[j]);
2178           continue;
2179         } else if (VL2->isCommutative() &&
2180                    isConsecutiveAccess(L, L1, *DL, *SE)) {
2181           std::swap(Left[j + 1], Right[j + 1]);
2182           continue;
2183         }
2184         // else unchanged
2185       }
2186     }
2187   }
2188 }
2189 
2190 // Return true if I should be commuted before adding it's left and right
2191 // operands to the arrays Left and Right.
2192 //
2193 // The vectorizer is trying to either have all elements one side being
2194 // instruction with the same opcode to enable further vectorization, or having
2195 // a splat to lower the vectorizing cost.
2196 static bool shouldReorderOperands(int i, Instruction &I,
2197                                   SmallVectorImpl<Value *> &Left,
2198                                   SmallVectorImpl<Value *> &Right,
2199                                   bool AllSameOpcodeLeft,
2200                                   bool AllSameOpcodeRight, bool SplatLeft,
2201                                   bool SplatRight) {
2202   Value *VLeft = I.getOperand(0);
2203   Value *VRight = I.getOperand(1);
2204   // If we have "SplatRight", try to see if commuting is needed to preserve it.
2205   if (SplatRight) {
2206     if (VRight == Right[i - 1])
2207       // Preserve SplatRight
2208       return false;
2209     if (VLeft == Right[i - 1]) {
2210       // Commuting would preserve SplatRight, but we don't want to break
2211       // SplatLeft either, i.e. preserve the original order if possible.
2212       // (FIXME: why do we care?)
2213       if (SplatLeft && VLeft == Left[i - 1])
2214         return false;
2215       return true;
2216     }
2217   }
2218   // Symmetrically handle Right side.
2219   if (SplatLeft) {
2220     if (VLeft == Left[i - 1])
2221       // Preserve SplatLeft
2222       return false;
2223     if (VRight == Left[i - 1])
2224       return true;
2225   }
2226 
2227   Instruction *ILeft = dyn_cast<Instruction>(VLeft);
2228   Instruction *IRight = dyn_cast<Instruction>(VRight);
2229 
2230   // If we have "AllSameOpcodeRight", try to see if the left operands preserves
2231   // it and not the right, in this case we want to commute.
2232   if (AllSameOpcodeRight) {
2233     unsigned RightPrevOpcode = cast<Instruction>(Right[i - 1])->getOpcode();
2234     if (IRight && RightPrevOpcode == IRight->getOpcode())
2235       // Do not commute, a match on the right preserves AllSameOpcodeRight
2236       return false;
2237     if (ILeft && RightPrevOpcode == ILeft->getOpcode()) {
2238       // We have a match and may want to commute, but first check if there is
2239       // not also a match on the existing operands on the Left to preserve
2240       // AllSameOpcodeLeft, i.e. preserve the original order if possible.
2241       // (FIXME: why do we care?)
2242       if (AllSameOpcodeLeft && ILeft &&
2243           cast<Instruction>(Left[i - 1])->getOpcode() == ILeft->getOpcode())
2244         return false;
2245       return true;
2246     }
2247   }
2248   // Symmetrically handle Left side.
2249   if (AllSameOpcodeLeft) {
2250     unsigned LeftPrevOpcode = cast<Instruction>(Left[i - 1])->getOpcode();
2251     if (ILeft && LeftPrevOpcode == ILeft->getOpcode())
2252       return false;
2253     if (IRight && LeftPrevOpcode == IRight->getOpcode())
2254       return true;
2255   }
2256   return false;
2257 }
2258 
2259 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
2260                                              SmallVectorImpl<Value *> &Left,
2261                                              SmallVectorImpl<Value *> &Right) {
2262 
2263   if (VL.size()) {
2264     // Peel the first iteration out of the loop since there's nothing
2265     // interesting to do anyway and it simplifies the checks in the loop.
2266     auto VLeft = cast<Instruction>(VL[0])->getOperand(0);
2267     auto VRight = cast<Instruction>(VL[0])->getOperand(1);
2268     if (!isa<Instruction>(VRight) && isa<Instruction>(VLeft))
2269       // Favor having instruction to the right. FIXME: why?
2270       std::swap(VLeft, VRight);
2271     Left.push_back(VLeft);
2272     Right.push_back(VRight);
2273   }
2274 
2275   // Keep track if we have instructions with all the same opcode on one side.
2276   bool AllSameOpcodeLeft = isa<Instruction>(Left[0]);
2277   bool AllSameOpcodeRight = isa<Instruction>(Right[0]);
2278   // Keep track if we have one side with all the same value (broadcast).
2279   bool SplatLeft = true;
2280   bool SplatRight = true;
2281 
2282   for (unsigned i = 1, e = VL.size(); i != e; ++i) {
2283     Instruction *I = cast<Instruction>(VL[i]);
2284     assert(I->isCommutative() && "Can only process commutative instruction");
2285     // Commute to favor either a splat or maximizing having the same opcodes on
2286     // one side.
2287     if (shouldReorderOperands(i, *I, Left, Right, AllSameOpcodeLeft,
2288                               AllSameOpcodeRight, SplatLeft, SplatRight)) {
2289       Left.push_back(I->getOperand(1));
2290       Right.push_back(I->getOperand(0));
2291     } else {
2292       Left.push_back(I->getOperand(0));
2293       Right.push_back(I->getOperand(1));
2294     }
2295     // Update Splat* and AllSameOpcode* after the insertion.
2296     SplatRight = SplatRight && (Right[i - 1] == Right[i]);
2297     SplatLeft = SplatLeft && (Left[i - 1] == Left[i]);
2298     AllSameOpcodeLeft = AllSameOpcodeLeft && isa<Instruction>(Left[i]) &&
2299                         (cast<Instruction>(Left[i - 1])->getOpcode() ==
2300                          cast<Instruction>(Left[i])->getOpcode());
2301     AllSameOpcodeRight = AllSameOpcodeRight && isa<Instruction>(Right[i]) &&
2302                          (cast<Instruction>(Right[i - 1])->getOpcode() ==
2303                           cast<Instruction>(Right[i])->getOpcode());
2304   }
2305 
2306   // If one operand end up being broadcast, return this operand order.
2307   if (SplatRight || SplatLeft)
2308     return;
2309 
2310   // Finally check if we can get longer vectorizable chain by reordering
2311   // without breaking the good operand order detected above.
2312   // E.g. If we have something like-
2313   // load a[0]  load b[0]
2314   // load b[1]  load a[1]
2315   // load a[2]  load b[2]
2316   // load a[3]  load b[3]
2317   // Reordering the second load b[1]  load a[1] would allow us to vectorize
2318   // this code and we still retain AllSameOpcode property.
2319   // FIXME: This load reordering might break AllSameOpcode in some rare cases
2320   // such as-
2321   // add a[0],c[0]  load b[0]
2322   // add a[1],c[2]  load b[1]
2323   // b[2]           load b[2]
2324   // add a[3],c[3]  load b[3]
2325   for (unsigned j = 0; j < VL.size() - 1; ++j) {
2326     if (LoadInst *L = dyn_cast<LoadInst>(Left[j])) {
2327       if (LoadInst *L1 = dyn_cast<LoadInst>(Right[j + 1])) {
2328         if (isConsecutiveAccess(L, L1, *DL, *SE)) {
2329           std::swap(Left[j + 1], Right[j + 1]);
2330           continue;
2331         }
2332       }
2333     }
2334     if (LoadInst *L = dyn_cast<LoadInst>(Right[j])) {
2335       if (LoadInst *L1 = dyn_cast<LoadInst>(Left[j + 1])) {
2336         if (isConsecutiveAccess(L, L1, *DL, *SE)) {
2337           std::swap(Left[j + 1], Right[j + 1]);
2338           continue;
2339         }
2340       }
2341     }
2342     // else unchanged
2343   }
2344 }
2345 
2346 void BoUpSLP::setInsertPointAfterBundle(ArrayRef<Value *> VL) {
2347 
2348   // Get the basic block this bundle is in. All instructions in the bundle
2349   // should be in this block.
2350   auto *Front = cast<Instruction>(VL.front());
2351   auto *BB = Front->getParent();
2352   assert(all_of(make_range(VL.begin(), VL.end()), [&](Value *V) -> bool {
2353     return cast<Instruction>(V)->getParent() == BB;
2354   }));
2355 
2356   // The last instruction in the bundle in program order.
2357   Instruction *LastInst = nullptr;
2358 
2359   // Find the last instruction. The common case should be that BB has been
2360   // scheduled, and the last instruction is VL.back(). So we start with
2361   // VL.back() and iterate over schedule data until we reach the end of the
2362   // bundle. The end of the bundle is marked by null ScheduleData.
2363   if (BlocksSchedules.count(BB)) {
2364     auto *Bundle = BlocksSchedules[BB]->getScheduleData(VL.back());
2365     if (Bundle && Bundle->isPartOfBundle())
2366       for (; Bundle; Bundle = Bundle->NextInBundle)
2367         LastInst = Bundle->Inst;
2368   }
2369 
2370   // LastInst can still be null at this point if there's either not an entry
2371   // for BB in BlocksSchedules or there's no ScheduleData available for
2372   // VL.back(). This can be the case if buildTree_rec aborts for various
2373   // reasons (e.g., the maximum recursion depth is reached, the maximum region
2374   // size is reached, etc.). ScheduleData is initialized in the scheduling
2375   // "dry-run".
2376   //
2377   // If this happens, we can still find the last instruction by brute force. We
2378   // iterate forwards from Front (inclusive) until we either see all
2379   // instructions in the bundle or reach the end of the block. If Front is the
2380   // last instruction in program order, LastInst will be set to Front, and we
2381   // will visit all the remaining instructions in the block.
2382   //
2383   // One of the reasons we exit early from buildTree_rec is to place an upper
2384   // bound on compile-time. Thus, taking an additional compile-time hit here is
2385   // not ideal. However, this should be exceedingly rare since it requires that
2386   // we both exit early from buildTree_rec and that the bundle be out-of-order
2387   // (causing us to iterate all the way to the end of the block).
2388   if (!LastInst) {
2389     SmallPtrSet<Value *, 16> Bundle(VL.begin(), VL.end());
2390     for (auto &I : make_range(BasicBlock::iterator(Front), BB->end())) {
2391       if (Bundle.erase(&I))
2392         LastInst = &I;
2393       if (Bundle.empty())
2394         break;
2395     }
2396   }
2397 
2398   // Set the insertion point after the last instruction in the bundle. Set the
2399   // debug location to Front.
2400   Builder.SetInsertPoint(BB, ++LastInst->getIterator());
2401   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
2402 }
2403 
2404 Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
2405   Value *Vec = UndefValue::get(Ty);
2406   // Generate the 'InsertElement' instruction.
2407   for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
2408     Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
2409     if (Instruction *Insrt = dyn_cast<Instruction>(Vec)) {
2410       GatherSeq.insert(Insrt);
2411       CSEBlocks.insert(Insrt->getParent());
2412 
2413       // Add to our 'need-to-extract' list.
2414       if (TreeEntry *E = getTreeEntry(VL[i])) {
2415         // Find which lane we need to extract.
2416         int FoundLane = -1;
2417         for (unsigned Lane = 0, LE = VL.size(); Lane != LE; ++Lane) {
2418           // Is this the lane of the scalar that we are looking for ?
2419           if (E->Scalars[Lane] == VL[i]) {
2420             FoundLane = Lane;
2421             break;
2422           }
2423         }
2424         assert(FoundLane >= 0 && "Could not find the correct lane");
2425         ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
2426       }
2427     }
2428   }
2429 
2430   return Vec;
2431 }
2432 
2433 Value *BoUpSLP::alreadyVectorized(ArrayRef<Value *> VL, Value *OpValue) const {
2434   if (const TreeEntry *En = getTreeEntry(OpValue)) {
2435     if (En->isSame(VL) && En->VectorizedValue)
2436       return En->VectorizedValue;
2437   }
2438   return nullptr;
2439 }
2440 
2441 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
2442   if (TreeEntry *E = getTreeEntry(VL[0]))
2443     if (E->isSame(VL))
2444       return vectorizeTree(E);
2445 
2446   Type *ScalarTy = VL[0]->getType();
2447   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
2448     ScalarTy = SI->getValueOperand()->getType();
2449   VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
2450 
2451   return Gather(VL, VecTy);
2452 }
2453 
2454 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
2455   IRBuilder<>::InsertPointGuard Guard(Builder);
2456 
2457   if (E->VectorizedValue) {
2458     DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
2459     return E->VectorizedValue;
2460   }
2461 
2462   Instruction *VL0 = cast<Instruction>(E->Scalars[0]);
2463   Type *ScalarTy = VL0->getType();
2464   if (StoreInst *SI = dyn_cast<StoreInst>(VL0))
2465     ScalarTy = SI->getValueOperand()->getType();
2466   VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size());
2467 
2468   if (E->NeedToGather) {
2469     setInsertPointAfterBundle(E->Scalars);
2470     auto *V = Gather(E->Scalars, VecTy);
2471     E->VectorizedValue = V;
2472     return V;
2473   }
2474 
2475   unsigned Opcode = getSameOpcode(E->Scalars);
2476 
2477   switch (Opcode) {
2478     case Instruction::PHI: {
2479       PHINode *PH = dyn_cast<PHINode>(VL0);
2480       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
2481       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
2482       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
2483       E->VectorizedValue = NewPhi;
2484 
2485       // PHINodes may have multiple entries from the same block. We want to
2486       // visit every block once.
2487       SmallSet<BasicBlock*, 4> VisitedBBs;
2488 
2489       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
2490         ValueList Operands;
2491         BasicBlock *IBB = PH->getIncomingBlock(i);
2492 
2493         if (!VisitedBBs.insert(IBB).second) {
2494           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
2495           continue;
2496         }
2497 
2498         // Prepare the operand vector.
2499         for (Value *V : E->Scalars)
2500           Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(IBB));
2501 
2502         Builder.SetInsertPoint(IBB->getTerminator());
2503         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
2504         Value *Vec = vectorizeTree(Operands);
2505         NewPhi->addIncoming(Vec, IBB);
2506       }
2507 
2508       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
2509              "Invalid number of incoming values");
2510       return NewPhi;
2511     }
2512 
2513     case Instruction::ExtractElement: {
2514       if (canReuseExtract(E->Scalars, VL0)) {
2515         Value *V = VL0->getOperand(0);
2516         E->VectorizedValue = V;
2517         return V;
2518       }
2519       setInsertPointAfterBundle(E->Scalars);
2520       auto *V = Gather(E->Scalars, VecTy);
2521       E->VectorizedValue = V;
2522       return V;
2523     }
2524     case Instruction::ExtractValue: {
2525       if (canReuseExtract(E->Scalars, VL0)) {
2526         LoadInst *LI = cast<LoadInst>(VL0->getOperand(0));
2527         Builder.SetInsertPoint(LI);
2528         PointerType *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
2529         Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
2530         LoadInst *V = Builder.CreateAlignedLoad(Ptr, LI->getAlignment());
2531         E->VectorizedValue = V;
2532         return propagateMetadata(V, E->Scalars);
2533       }
2534       setInsertPointAfterBundle(E->Scalars);
2535       auto *V = Gather(E->Scalars, VecTy);
2536       E->VectorizedValue = V;
2537       return V;
2538     }
2539     case Instruction::ZExt:
2540     case Instruction::SExt:
2541     case Instruction::FPToUI:
2542     case Instruction::FPToSI:
2543     case Instruction::FPExt:
2544     case Instruction::PtrToInt:
2545     case Instruction::IntToPtr:
2546     case Instruction::SIToFP:
2547     case Instruction::UIToFP:
2548     case Instruction::Trunc:
2549     case Instruction::FPTrunc:
2550     case Instruction::BitCast: {
2551       ValueList INVL;
2552       for (Value *V : E->Scalars)
2553         INVL.push_back(cast<Instruction>(V)->getOperand(0));
2554 
2555       setInsertPointAfterBundle(E->Scalars);
2556 
2557       Value *InVec = vectorizeTree(INVL);
2558 
2559       if (Value *V = alreadyVectorized(E->Scalars, VL0))
2560         return V;
2561 
2562       CastInst *CI = dyn_cast<CastInst>(VL0);
2563       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
2564       E->VectorizedValue = V;
2565       ++NumVectorInstructions;
2566       return V;
2567     }
2568     case Instruction::FCmp:
2569     case Instruction::ICmp: {
2570       ValueList LHSV, RHSV;
2571       for (Value *V : E->Scalars) {
2572         LHSV.push_back(cast<Instruction>(V)->getOperand(0));
2573         RHSV.push_back(cast<Instruction>(V)->getOperand(1));
2574       }
2575 
2576       setInsertPointAfterBundle(E->Scalars);
2577 
2578       Value *L = vectorizeTree(LHSV);
2579       Value *R = vectorizeTree(RHSV);
2580 
2581       if (Value *V = alreadyVectorized(E->Scalars, VL0))
2582         return V;
2583 
2584       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
2585       Value *V;
2586       if (Opcode == Instruction::FCmp)
2587         V = Builder.CreateFCmp(P0, L, R);
2588       else
2589         V = Builder.CreateICmp(P0, L, R);
2590 
2591       E->VectorizedValue = V;
2592       propagateIRFlags(E->VectorizedValue, E->Scalars);
2593       ++NumVectorInstructions;
2594       return V;
2595     }
2596     case Instruction::Select: {
2597       ValueList TrueVec, FalseVec, CondVec;
2598       for (Value *V : E->Scalars) {
2599         CondVec.push_back(cast<Instruction>(V)->getOperand(0));
2600         TrueVec.push_back(cast<Instruction>(V)->getOperand(1));
2601         FalseVec.push_back(cast<Instruction>(V)->getOperand(2));
2602       }
2603 
2604       setInsertPointAfterBundle(E->Scalars);
2605 
2606       Value *Cond = vectorizeTree(CondVec);
2607       Value *True = vectorizeTree(TrueVec);
2608       Value *False = vectorizeTree(FalseVec);
2609 
2610       if (Value *V = alreadyVectorized(E->Scalars, VL0))
2611         return V;
2612 
2613       Value *V = Builder.CreateSelect(Cond, True, False);
2614       E->VectorizedValue = V;
2615       ++NumVectorInstructions;
2616       return V;
2617     }
2618     case Instruction::Add:
2619     case Instruction::FAdd:
2620     case Instruction::Sub:
2621     case Instruction::FSub:
2622     case Instruction::Mul:
2623     case Instruction::FMul:
2624     case Instruction::UDiv:
2625     case Instruction::SDiv:
2626     case Instruction::FDiv:
2627     case Instruction::URem:
2628     case Instruction::SRem:
2629     case Instruction::FRem:
2630     case Instruction::Shl:
2631     case Instruction::LShr:
2632     case Instruction::AShr:
2633     case Instruction::And:
2634     case Instruction::Or:
2635     case Instruction::Xor: {
2636       ValueList LHSVL, RHSVL;
2637       if (isa<BinaryOperator>(VL0) && VL0->isCommutative())
2638         reorderInputsAccordingToOpcode(E->Scalars, LHSVL, RHSVL);
2639       else
2640         for (Value *V : E->Scalars) {
2641           LHSVL.push_back(cast<Instruction>(V)->getOperand(0));
2642           RHSVL.push_back(cast<Instruction>(V)->getOperand(1));
2643         }
2644 
2645       setInsertPointAfterBundle(E->Scalars);
2646 
2647       Value *LHS = vectorizeTree(LHSVL);
2648       Value *RHS = vectorizeTree(RHSVL);
2649 
2650       if (Value *V = alreadyVectorized(E->Scalars, VL0))
2651         return V;
2652 
2653       BinaryOperator *BinOp = cast<BinaryOperator>(VL0);
2654       Value *V = Builder.CreateBinOp(BinOp->getOpcode(), LHS, RHS);
2655       E->VectorizedValue = V;
2656       propagateIRFlags(E->VectorizedValue, E->Scalars);
2657       ++NumVectorInstructions;
2658 
2659       if (Instruction *I = dyn_cast<Instruction>(V))
2660         return propagateMetadata(I, E->Scalars);
2661 
2662       return V;
2663     }
2664     case Instruction::Load: {
2665       // Loads are inserted at the head of the tree because we don't want to
2666       // sink them all the way down past store instructions.
2667       setInsertPointAfterBundle(E->Scalars);
2668 
2669       LoadInst *LI = cast<LoadInst>(VL0);
2670       Type *ScalarLoadTy = LI->getType();
2671       unsigned AS = LI->getPointerAddressSpace();
2672 
2673       Value *VecPtr = Builder.CreateBitCast(LI->getPointerOperand(),
2674                                             VecTy->getPointerTo(AS));
2675 
2676       // The pointer operand uses an in-tree scalar so we add the new BitCast to
2677       // ExternalUses list to make sure that an extract will be generated in the
2678       // future.
2679       Value *PO = LI->getPointerOperand();
2680       if (getTreeEntry(PO))
2681         ExternalUses.push_back(ExternalUser(PO, cast<User>(VecPtr), 0));
2682 
2683       unsigned Alignment = LI->getAlignment();
2684       LI = Builder.CreateLoad(VecPtr);
2685       if (!Alignment) {
2686         Alignment = DL->getABITypeAlignment(ScalarLoadTy);
2687       }
2688       LI->setAlignment(Alignment);
2689       E->VectorizedValue = LI;
2690       ++NumVectorInstructions;
2691       return propagateMetadata(LI, E->Scalars);
2692     }
2693     case Instruction::Store: {
2694       StoreInst *SI = cast<StoreInst>(VL0);
2695       unsigned Alignment = SI->getAlignment();
2696       unsigned AS = SI->getPointerAddressSpace();
2697 
2698       ValueList ValueOp;
2699       for (Value *V : E->Scalars)
2700         ValueOp.push_back(cast<StoreInst>(V)->getValueOperand());
2701 
2702       setInsertPointAfterBundle(E->Scalars);
2703 
2704       Value *VecValue = vectorizeTree(ValueOp);
2705       Value *VecPtr = Builder.CreateBitCast(SI->getPointerOperand(),
2706                                             VecTy->getPointerTo(AS));
2707       StoreInst *S = Builder.CreateStore(VecValue, VecPtr);
2708 
2709       // The pointer operand uses an in-tree scalar so we add the new BitCast to
2710       // ExternalUses list to make sure that an extract will be generated in the
2711       // future.
2712       Value *PO = SI->getPointerOperand();
2713       if (getTreeEntry(PO))
2714         ExternalUses.push_back(ExternalUser(PO, cast<User>(VecPtr), 0));
2715 
2716       if (!Alignment) {
2717         Alignment = DL->getABITypeAlignment(SI->getValueOperand()->getType());
2718       }
2719       S->setAlignment(Alignment);
2720       E->VectorizedValue = S;
2721       ++NumVectorInstructions;
2722       return propagateMetadata(S, E->Scalars);
2723     }
2724     case Instruction::GetElementPtr: {
2725       setInsertPointAfterBundle(E->Scalars);
2726 
2727       ValueList Op0VL;
2728       for (Value *V : E->Scalars)
2729         Op0VL.push_back(cast<GetElementPtrInst>(V)->getOperand(0));
2730 
2731       Value *Op0 = vectorizeTree(Op0VL);
2732 
2733       std::vector<Value *> OpVecs;
2734       for (int j = 1, e = cast<GetElementPtrInst>(VL0)->getNumOperands(); j < e;
2735            ++j) {
2736         ValueList OpVL;
2737         for (Value *V : E->Scalars)
2738           OpVL.push_back(cast<GetElementPtrInst>(V)->getOperand(j));
2739 
2740         Value *OpVec = vectorizeTree(OpVL);
2741         OpVecs.push_back(OpVec);
2742       }
2743 
2744       Value *V = Builder.CreateGEP(
2745           cast<GetElementPtrInst>(VL0)->getSourceElementType(), Op0, OpVecs);
2746       E->VectorizedValue = V;
2747       ++NumVectorInstructions;
2748 
2749       if (Instruction *I = dyn_cast<Instruction>(V))
2750         return propagateMetadata(I, E->Scalars);
2751 
2752       return V;
2753     }
2754     case Instruction::Call: {
2755       CallInst *CI = cast<CallInst>(VL0);
2756       setInsertPointAfterBundle(VL0);
2757       Function *FI;
2758       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
2759       Value *ScalarArg = nullptr;
2760       if (CI && (FI = CI->getCalledFunction())) {
2761         IID = FI->getIntrinsicID();
2762       }
2763       std::vector<Value *> OpVecs;
2764       for (int j = 0, e = CI->getNumArgOperands(); j < e; ++j) {
2765         ValueList OpVL;
2766         // ctlz,cttz and powi are special intrinsics whose second argument is
2767         // a scalar. This argument should not be vectorized.
2768         if (hasVectorInstrinsicScalarOpd(IID, 1) && j == 1) {
2769           CallInst *CEI = cast<CallInst>(E->Scalars[0]);
2770           ScalarArg = CEI->getArgOperand(j);
2771           OpVecs.push_back(CEI->getArgOperand(j));
2772           continue;
2773         }
2774         for (Value *V : E->Scalars) {
2775           CallInst *CEI = cast<CallInst>(V);
2776           OpVL.push_back(CEI->getArgOperand(j));
2777         }
2778 
2779         Value *OpVec = vectorizeTree(OpVL);
2780         DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
2781         OpVecs.push_back(OpVec);
2782       }
2783 
2784       Module *M = F->getParent();
2785       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
2786       Type *Tys[] = { VectorType::get(CI->getType(), E->Scalars.size()) };
2787       Function *CF = Intrinsic::getDeclaration(M, ID, Tys);
2788       SmallVector<OperandBundleDef, 1> OpBundles;
2789       CI->getOperandBundlesAsDefs(OpBundles);
2790       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
2791 
2792       // The scalar argument uses an in-tree scalar so we add the new vectorized
2793       // call to ExternalUses list to make sure that an extract will be
2794       // generated in the future.
2795       if (ScalarArg && getTreeEntry(ScalarArg))
2796         ExternalUses.push_back(ExternalUser(ScalarArg, cast<User>(V), 0));
2797 
2798       E->VectorizedValue = V;
2799       propagateIRFlags(E->VectorizedValue, E->Scalars);
2800       ++NumVectorInstructions;
2801       return V;
2802     }
2803     case Instruction::ShuffleVector: {
2804       ValueList LHSVL, RHSVL;
2805       assert(isa<BinaryOperator>(VL0) && "Invalid Shuffle Vector Operand");
2806       reorderAltShuffleOperands(E->Scalars, LHSVL, RHSVL);
2807       setInsertPointAfterBundle(E->Scalars);
2808 
2809       Value *LHS = vectorizeTree(LHSVL);
2810       Value *RHS = vectorizeTree(RHSVL);
2811 
2812       if (Value *V = alreadyVectorized(E->Scalars, VL0))
2813         return V;
2814 
2815       // Create a vector of LHS op1 RHS
2816       BinaryOperator *BinOp0 = cast<BinaryOperator>(VL0);
2817       Value *V0 = Builder.CreateBinOp(BinOp0->getOpcode(), LHS, RHS);
2818 
2819       // Create a vector of LHS op2 RHS
2820       Instruction *VL1 = cast<Instruction>(E->Scalars[1]);
2821       BinaryOperator *BinOp1 = cast<BinaryOperator>(VL1);
2822       Value *V1 = Builder.CreateBinOp(BinOp1->getOpcode(), LHS, RHS);
2823 
2824       // Create shuffle to take alternate operations from the vector.
2825       // Also, gather up odd and even scalar ops to propagate IR flags to
2826       // each vector operation.
2827       ValueList OddScalars, EvenScalars;
2828       unsigned e = E->Scalars.size();
2829       SmallVector<Constant *, 8> Mask(e);
2830       for (unsigned i = 0; i < e; ++i) {
2831         if (isOdd(i)) {
2832           Mask[i] = Builder.getInt32(e + i);
2833           OddScalars.push_back(E->Scalars[i]);
2834         } else {
2835           Mask[i] = Builder.getInt32(i);
2836           EvenScalars.push_back(E->Scalars[i]);
2837         }
2838       }
2839 
2840       Value *ShuffleMask = ConstantVector::get(Mask);
2841       propagateIRFlags(V0, EvenScalars);
2842       propagateIRFlags(V1, OddScalars);
2843 
2844       Value *V = Builder.CreateShuffleVector(V0, V1, ShuffleMask);
2845       E->VectorizedValue = V;
2846       ++NumVectorInstructions;
2847       if (Instruction *I = dyn_cast<Instruction>(V))
2848         return propagateMetadata(I, E->Scalars);
2849 
2850       return V;
2851     }
2852     default:
2853     llvm_unreachable("unknown inst");
2854   }
2855   return nullptr;
2856 }
2857 
2858 Value *BoUpSLP::vectorizeTree() {
2859   ExtraValueToDebugLocsMap ExternallyUsedValues;
2860   return vectorizeTree(ExternallyUsedValues);
2861 }
2862 
2863 Value *
2864 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
2865 
2866   // All blocks must be scheduled before any instructions are inserted.
2867   for (auto &BSIter : BlocksSchedules) {
2868     scheduleBlock(BSIter.second.get());
2869   }
2870 
2871   Builder.SetInsertPoint(&F->getEntryBlock().front());
2872   auto *VectorRoot = vectorizeTree(&VectorizableTree[0]);
2873 
2874   // If the vectorized tree can be rewritten in a smaller type, we truncate the
2875   // vectorized root. InstCombine will then rewrite the entire expression. We
2876   // sign extend the extracted values below.
2877   auto *ScalarRoot = VectorizableTree[0].Scalars[0];
2878   if (MinBWs.count(ScalarRoot)) {
2879     if (auto *I = dyn_cast<Instruction>(VectorRoot))
2880       Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
2881     auto BundleWidth = VectorizableTree[0].Scalars.size();
2882     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
2883     auto *VecTy = VectorType::get(MinTy, BundleWidth);
2884     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
2885     VectorizableTree[0].VectorizedValue = Trunc;
2886   }
2887 
2888   DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() << " values .\n");
2889 
2890   // If necessary, sign-extend or zero-extend ScalarRoot to the larger type
2891   // specified by ScalarType.
2892   auto extend = [&](Value *ScalarRoot, Value *Ex, Type *ScalarType) {
2893     if (!MinBWs.count(ScalarRoot))
2894       return Ex;
2895     if (MinBWs[ScalarRoot].second)
2896       return Builder.CreateSExt(Ex, ScalarType);
2897     return Builder.CreateZExt(Ex, ScalarType);
2898   };
2899 
2900   // Extract all of the elements with the external uses.
2901   for (const auto &ExternalUse : ExternalUses) {
2902     Value *Scalar = ExternalUse.Scalar;
2903     llvm::User *User = ExternalUse.User;
2904 
2905     // Skip users that we already RAUW. This happens when one instruction
2906     // has multiple uses of the same value.
2907     if (User && !is_contained(Scalar->users(), User))
2908       continue;
2909     TreeEntry *E = getTreeEntry(Scalar);
2910     assert(E && "Invalid scalar");
2911     assert(!E->NeedToGather && "Extracting from a gather list");
2912 
2913     Value *Vec = E->VectorizedValue;
2914     assert(Vec && "Can't find vectorizable value");
2915 
2916     Value *Lane = Builder.getInt32(ExternalUse.Lane);
2917     // If User == nullptr, the Scalar is used as extra arg. Generate
2918     // ExtractElement instruction and update the record for this scalar in
2919     // ExternallyUsedValues.
2920     if (!User) {
2921       assert(ExternallyUsedValues.count(Scalar) &&
2922              "Scalar with nullptr as an external user must be registered in "
2923              "ExternallyUsedValues map");
2924       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
2925         Builder.SetInsertPoint(VecI->getParent(),
2926                                std::next(VecI->getIterator()));
2927       } else {
2928         Builder.SetInsertPoint(&F->getEntryBlock().front());
2929       }
2930       Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2931       Ex = extend(ScalarRoot, Ex, Scalar->getType());
2932       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
2933       auto &Locs = ExternallyUsedValues[Scalar];
2934       ExternallyUsedValues.insert({Ex, Locs});
2935       ExternallyUsedValues.erase(Scalar);
2936       continue;
2937     }
2938 
2939     // Generate extracts for out-of-tree users.
2940     // Find the insertion point for the extractelement lane.
2941     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
2942       if (PHINode *PH = dyn_cast<PHINode>(User)) {
2943         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
2944           if (PH->getIncomingValue(i) == Scalar) {
2945             TerminatorInst *IncomingTerminator =
2946                 PH->getIncomingBlock(i)->getTerminator();
2947             if (isa<CatchSwitchInst>(IncomingTerminator)) {
2948               Builder.SetInsertPoint(VecI->getParent(),
2949                                      std::next(VecI->getIterator()));
2950             } else {
2951               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
2952             }
2953             Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2954             Ex = extend(ScalarRoot, Ex, Scalar->getType());
2955             CSEBlocks.insert(PH->getIncomingBlock(i));
2956             PH->setOperand(i, Ex);
2957           }
2958         }
2959       } else {
2960         Builder.SetInsertPoint(cast<Instruction>(User));
2961         Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2962         Ex = extend(ScalarRoot, Ex, Scalar->getType());
2963         CSEBlocks.insert(cast<Instruction>(User)->getParent());
2964         User->replaceUsesOfWith(Scalar, Ex);
2965      }
2966     } else {
2967       Builder.SetInsertPoint(&F->getEntryBlock().front());
2968       Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2969       Ex = extend(ScalarRoot, Ex, Scalar->getType());
2970       CSEBlocks.insert(&F->getEntryBlock());
2971       User->replaceUsesOfWith(Scalar, Ex);
2972     }
2973 
2974     DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
2975   }
2976 
2977   // For each vectorized value:
2978   for (TreeEntry &EIdx : VectorizableTree) {
2979     TreeEntry *Entry = &EIdx;
2980 
2981     // For each lane:
2982     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
2983       Value *Scalar = Entry->Scalars[Lane];
2984       // No need to handle users of gathered values.
2985       if (Entry->NeedToGather)
2986         continue;
2987 
2988       assert(Entry->VectorizedValue && "Can't find vectorizable value");
2989 
2990       Type *Ty = Scalar->getType();
2991       if (!Ty->isVoidTy()) {
2992 #ifndef NDEBUG
2993         for (User *U : Scalar->users()) {
2994           DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
2995 
2996           // It is legal to replace users in the ignorelist by undef.
2997           assert((getTreeEntry(U) || is_contained(UserIgnoreList, U)) &&
2998                  "Replacing out-of-tree value with undef");
2999         }
3000 #endif
3001         Value *Undef = UndefValue::get(Ty);
3002         Scalar->replaceAllUsesWith(Undef);
3003       }
3004       DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
3005       eraseInstruction(cast<Instruction>(Scalar));
3006     }
3007   }
3008 
3009   Builder.ClearInsertionPoint();
3010 
3011   return VectorizableTree[0].VectorizedValue;
3012 }
3013 
3014 void BoUpSLP::optimizeGatherSequence() {
3015   DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
3016         << " gather sequences instructions.\n");
3017   // LICM InsertElementInst sequences.
3018   for (Instruction *it : GatherSeq) {
3019     InsertElementInst *Insert = dyn_cast<InsertElementInst>(it);
3020 
3021     if (!Insert)
3022       continue;
3023 
3024     // Check if this block is inside a loop.
3025     Loop *L = LI->getLoopFor(Insert->getParent());
3026     if (!L)
3027       continue;
3028 
3029     // Check if it has a preheader.
3030     BasicBlock *PreHeader = L->getLoopPreheader();
3031     if (!PreHeader)
3032       continue;
3033 
3034     // If the vector or the element that we insert into it are
3035     // instructions that are defined in this basic block then we can't
3036     // hoist this instruction.
3037     Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
3038     Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
3039     if (CurrVec && L->contains(CurrVec))
3040       continue;
3041     if (NewElem && L->contains(NewElem))
3042       continue;
3043 
3044     // We can hoist this instruction. Move it to the pre-header.
3045     Insert->moveBefore(PreHeader->getTerminator());
3046   }
3047 
3048   // Make a list of all reachable blocks in our CSE queue.
3049   SmallVector<const DomTreeNode *, 8> CSEWorkList;
3050   CSEWorkList.reserve(CSEBlocks.size());
3051   for (BasicBlock *BB : CSEBlocks)
3052     if (DomTreeNode *N = DT->getNode(BB)) {
3053       assert(DT->isReachableFromEntry(N));
3054       CSEWorkList.push_back(N);
3055     }
3056 
3057   // Sort blocks by domination. This ensures we visit a block after all blocks
3058   // dominating it are visited.
3059   std::stable_sort(CSEWorkList.begin(), CSEWorkList.end(),
3060                    [this](const DomTreeNode *A, const DomTreeNode *B) {
3061     return DT->properlyDominates(A, B);
3062   });
3063 
3064   // Perform O(N^2) search over the gather sequences and merge identical
3065   // instructions. TODO: We can further optimize this scan if we split the
3066   // instructions into different buckets based on the insert lane.
3067   SmallVector<Instruction *, 16> Visited;
3068   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
3069     assert((I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
3070            "Worklist not sorted properly!");
3071     BasicBlock *BB = (*I)->getBlock();
3072     // For all instructions in blocks containing gather sequences:
3073     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) {
3074       Instruction *In = &*it++;
3075       if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In))
3076         continue;
3077 
3078       // Check if we can replace this instruction with any of the
3079       // visited instructions.
3080       for (Instruction *v : Visited) {
3081         if (In->isIdenticalTo(v) &&
3082             DT->dominates(v->getParent(), In->getParent())) {
3083           In->replaceAllUsesWith(v);
3084           eraseInstruction(In);
3085           In = nullptr;
3086           break;
3087         }
3088       }
3089       if (In) {
3090         assert(!is_contained(Visited, In));
3091         Visited.push_back(In);
3092       }
3093     }
3094   }
3095   CSEBlocks.clear();
3096   GatherSeq.clear();
3097 }
3098 
3099 // Groups the instructions to a bundle (which is then a single scheduling entity)
3100 // and schedules instructions until the bundle gets ready.
3101 bool BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL,
3102                                                  BoUpSLP *SLP, Value *OpValue) {
3103   if (isa<PHINode>(OpValue))
3104     return true;
3105 
3106   // Initialize the instruction bundle.
3107   Instruction *OldScheduleEnd = ScheduleEnd;
3108   ScheduleData *PrevInBundle = nullptr;
3109   ScheduleData *Bundle = nullptr;
3110   bool ReSchedule = false;
3111   DEBUG(dbgs() << "SLP:  bundle: " << *OpValue << "\n");
3112 
3113   // Make sure that the scheduling region contains all
3114   // instructions of the bundle.
3115   for (Value *V : VL) {
3116     if (!extendSchedulingRegion(V))
3117       return false;
3118   }
3119 
3120   for (Value *V : VL) {
3121     ScheduleData *BundleMember = getScheduleData(V);
3122     assert(BundleMember &&
3123            "no ScheduleData for bundle member (maybe not in same basic block)");
3124     if (BundleMember->IsScheduled) {
3125       // A bundle member was scheduled as single instruction before and now
3126       // needs to be scheduled as part of the bundle. We just get rid of the
3127       // existing schedule.
3128       DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
3129                    << " was already scheduled\n");
3130       ReSchedule = true;
3131     }
3132     assert(BundleMember->isSchedulingEntity() &&
3133            "bundle member already part of other bundle");
3134     if (PrevInBundle) {
3135       PrevInBundle->NextInBundle = BundleMember;
3136     } else {
3137       Bundle = BundleMember;
3138     }
3139     BundleMember->UnscheduledDepsInBundle = 0;
3140     Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps;
3141 
3142     // Group the instructions to a bundle.
3143     BundleMember->FirstInBundle = Bundle;
3144     PrevInBundle = BundleMember;
3145   }
3146   if (ScheduleEnd != OldScheduleEnd) {
3147     // The scheduling region got new instructions at the lower end (or it is a
3148     // new region for the first bundle). This makes it necessary to
3149     // recalculate all dependencies.
3150     // It is seldom that this needs to be done a second time after adding the
3151     // initial bundle to the region.
3152     for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
3153       ScheduleData *SD = getScheduleData(I);
3154       SD->clearDependencies();
3155     }
3156     ReSchedule = true;
3157   }
3158   if (ReSchedule) {
3159     resetSchedule();
3160     initialFillReadyList(ReadyInsts);
3161   }
3162 
3163   DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle << " in block "
3164                << BB->getName() << "\n");
3165 
3166   calculateDependencies(Bundle, true, SLP);
3167 
3168   // Now try to schedule the new bundle. As soon as the bundle is "ready" it
3169   // means that there are no cyclic dependencies and we can schedule it.
3170   // Note that's important that we don't "schedule" the bundle yet (see
3171   // cancelScheduling).
3172   while (!Bundle->isReady() && !ReadyInsts.empty()) {
3173 
3174     ScheduleData *pickedSD = ReadyInsts.back();
3175     ReadyInsts.pop_back();
3176 
3177     if (pickedSD->isSchedulingEntity() && pickedSD->isReady()) {
3178       schedule(pickedSD, ReadyInsts);
3179     }
3180   }
3181   if (!Bundle->isReady()) {
3182     cancelScheduling(VL, OpValue);
3183     return false;
3184   }
3185   return true;
3186 }
3187 
3188 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
3189                                                 Value *OpValue) {
3190   if (isa<PHINode>(OpValue))
3191     return;
3192 
3193   ScheduleData *Bundle = getScheduleData(OpValue);
3194   DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
3195   assert(!Bundle->IsScheduled &&
3196          "Can't cancel bundle which is already scheduled");
3197   assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
3198          "tried to unbundle something which is not a bundle");
3199 
3200   // Un-bundle: make single instructions out of the bundle.
3201   ScheduleData *BundleMember = Bundle;
3202   while (BundleMember) {
3203     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
3204     BundleMember->FirstInBundle = BundleMember;
3205     ScheduleData *Next = BundleMember->NextInBundle;
3206     BundleMember->NextInBundle = nullptr;
3207     BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps;
3208     if (BundleMember->UnscheduledDepsInBundle == 0) {
3209       ReadyInsts.insert(BundleMember);
3210     }
3211     BundleMember = Next;
3212   }
3213 }
3214 
3215 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V) {
3216   if (getScheduleData(V))
3217     return true;
3218   Instruction *I = dyn_cast<Instruction>(V);
3219   assert(I && "bundle member must be an instruction");
3220   assert(!isa<PHINode>(I) && "phi nodes don't need to be scheduled");
3221   if (!ScheduleStart) {
3222     // It's the first instruction in the new region.
3223     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
3224     ScheduleStart = I;
3225     ScheduleEnd = I->getNextNode();
3226     assert(ScheduleEnd && "tried to vectorize a TerminatorInst?");
3227     DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
3228     return true;
3229   }
3230   // Search up and down at the same time, because we don't know if the new
3231   // instruction is above or below the existing scheduling region.
3232   BasicBlock::reverse_iterator UpIter =
3233       ++ScheduleStart->getIterator().getReverse();
3234   BasicBlock::reverse_iterator UpperEnd = BB->rend();
3235   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
3236   BasicBlock::iterator LowerEnd = BB->end();
3237   for (;;) {
3238     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
3239       DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
3240       return false;
3241     }
3242 
3243     if (UpIter != UpperEnd) {
3244       if (&*UpIter == I) {
3245         initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
3246         ScheduleStart = I;
3247         DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I << "\n");
3248         return true;
3249       }
3250       UpIter++;
3251     }
3252     if (DownIter != LowerEnd) {
3253       if (&*DownIter == I) {
3254         initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
3255                          nullptr);
3256         ScheduleEnd = I->getNextNode();
3257         assert(ScheduleEnd && "tried to vectorize a TerminatorInst?");
3258         DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
3259         return true;
3260       }
3261       DownIter++;
3262     }
3263     assert((UpIter != UpperEnd || DownIter != LowerEnd) &&
3264            "instruction not found in block");
3265   }
3266   return true;
3267 }
3268 
3269 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
3270                                                 Instruction *ToI,
3271                                                 ScheduleData *PrevLoadStore,
3272                                                 ScheduleData *NextLoadStore) {
3273   ScheduleData *CurrentLoadStore = PrevLoadStore;
3274   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
3275     ScheduleData *SD = ScheduleDataMap[I];
3276     if (!SD) {
3277       // Allocate a new ScheduleData for the instruction.
3278       if (ChunkPos >= ChunkSize) {
3279         ScheduleDataChunks.push_back(
3280             llvm::make_unique<ScheduleData[]>(ChunkSize));
3281         ChunkPos = 0;
3282       }
3283       SD = &(ScheduleDataChunks.back()[ChunkPos++]);
3284       ScheduleDataMap[I] = SD;
3285       SD->Inst = I;
3286     }
3287     assert(!isInSchedulingRegion(SD) &&
3288            "new ScheduleData already in scheduling region");
3289     SD->init(SchedulingRegionID);
3290 
3291     if (I->mayReadOrWriteMemory()) {
3292       // Update the linked list of memory accessing instructions.
3293       if (CurrentLoadStore) {
3294         CurrentLoadStore->NextLoadStore = SD;
3295       } else {
3296         FirstLoadStoreInRegion = SD;
3297       }
3298       CurrentLoadStore = SD;
3299     }
3300   }
3301   if (NextLoadStore) {
3302     if (CurrentLoadStore)
3303       CurrentLoadStore->NextLoadStore = NextLoadStore;
3304   } else {
3305     LastLoadStoreInRegion = CurrentLoadStore;
3306   }
3307 }
3308 
3309 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
3310                                                      bool InsertInReadyList,
3311                                                      BoUpSLP *SLP) {
3312   assert(SD->isSchedulingEntity());
3313 
3314   SmallVector<ScheduleData *, 10> WorkList;
3315   WorkList.push_back(SD);
3316 
3317   while (!WorkList.empty()) {
3318     ScheduleData *SD = WorkList.back();
3319     WorkList.pop_back();
3320 
3321     ScheduleData *BundleMember = SD;
3322     while (BundleMember) {
3323       assert(isInSchedulingRegion(BundleMember));
3324       if (!BundleMember->hasValidDependencies()) {
3325 
3326         DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember << "\n");
3327         BundleMember->Dependencies = 0;
3328         BundleMember->resetUnscheduledDeps();
3329 
3330         // Handle def-use chain dependencies.
3331         for (User *U : BundleMember->Inst->users()) {
3332           if (isa<Instruction>(U)) {
3333             ScheduleData *UseSD = getScheduleData(U);
3334             if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
3335               BundleMember->Dependencies++;
3336               ScheduleData *DestBundle = UseSD->FirstInBundle;
3337               if (!DestBundle->IsScheduled)
3338                 BundleMember->incrementUnscheduledDeps(1);
3339               if (!DestBundle->hasValidDependencies())
3340                 WorkList.push_back(DestBundle);
3341             }
3342           } else {
3343             // I'm not sure if this can ever happen. But we need to be safe.
3344             // This lets the instruction/bundle never be scheduled and
3345             // eventually disable vectorization.
3346             BundleMember->Dependencies++;
3347             BundleMember->incrementUnscheduledDeps(1);
3348           }
3349         }
3350 
3351         // Handle the memory dependencies.
3352         ScheduleData *DepDest = BundleMember->NextLoadStore;
3353         if (DepDest) {
3354           Instruction *SrcInst = BundleMember->Inst;
3355           MemoryLocation SrcLoc = getLocation(SrcInst, SLP->AA);
3356           bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
3357           unsigned numAliased = 0;
3358           unsigned DistToSrc = 1;
3359 
3360           while (DepDest) {
3361             assert(isInSchedulingRegion(DepDest));
3362 
3363             // We have two limits to reduce the complexity:
3364             // 1) AliasedCheckLimit: It's a small limit to reduce calls to
3365             //    SLP->isAliased (which is the expensive part in this loop).
3366             // 2) MaxMemDepDistance: It's for very large blocks and it aborts
3367             //    the whole loop (even if the loop is fast, it's quadratic).
3368             //    It's important for the loop break condition (see below) to
3369             //    check this limit even between two read-only instructions.
3370             if (DistToSrc >= MaxMemDepDistance ||
3371                     ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
3372                      (numAliased >= AliasedCheckLimit ||
3373                       SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
3374 
3375               // We increment the counter only if the locations are aliased
3376               // (instead of counting all alias checks). This gives a better
3377               // balance between reduced runtime and accurate dependencies.
3378               numAliased++;
3379 
3380               DepDest->MemoryDependencies.push_back(BundleMember);
3381               BundleMember->Dependencies++;
3382               ScheduleData *DestBundle = DepDest->FirstInBundle;
3383               if (!DestBundle->IsScheduled) {
3384                 BundleMember->incrementUnscheduledDeps(1);
3385               }
3386               if (!DestBundle->hasValidDependencies()) {
3387                 WorkList.push_back(DestBundle);
3388               }
3389             }
3390             DepDest = DepDest->NextLoadStore;
3391 
3392             // Example, explaining the loop break condition: Let's assume our
3393             // starting instruction is i0 and MaxMemDepDistance = 3.
3394             //
3395             //                      +--------v--v--v
3396             //             i0,i1,i2,i3,i4,i5,i6,i7,i8
3397             //             +--------^--^--^
3398             //
3399             // MaxMemDepDistance let us stop alias-checking at i3 and we add
3400             // dependencies from i0 to i3,i4,.. (even if they are not aliased).
3401             // Previously we already added dependencies from i3 to i6,i7,i8
3402             // (because of MaxMemDepDistance). As we added a dependency from
3403             // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
3404             // and we can abort this loop at i6.
3405             if (DistToSrc >= 2 * MaxMemDepDistance)
3406                 break;
3407             DistToSrc++;
3408           }
3409         }
3410       }
3411       BundleMember = BundleMember->NextInBundle;
3412     }
3413     if (InsertInReadyList && SD->isReady()) {
3414       ReadyInsts.push_back(SD);
3415       DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst << "\n");
3416     }
3417   }
3418 }
3419 
3420 void BoUpSLP::BlockScheduling::resetSchedule() {
3421   assert(ScheduleStart &&
3422          "tried to reset schedule on block which has not been scheduled");
3423   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
3424     ScheduleData *SD = getScheduleData(I);
3425     assert(isInSchedulingRegion(SD));
3426     SD->IsScheduled = false;
3427     SD->resetUnscheduledDeps();
3428   }
3429   ReadyInsts.clear();
3430 }
3431 
3432 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
3433 
3434   if (!BS->ScheduleStart)
3435     return;
3436 
3437   DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
3438 
3439   BS->resetSchedule();
3440 
3441   // For the real scheduling we use a more sophisticated ready-list: it is
3442   // sorted by the original instruction location. This lets the final schedule
3443   // be as  close as possible to the original instruction order.
3444   struct ScheduleDataCompare {
3445     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
3446       return SD2->SchedulingPriority < SD1->SchedulingPriority;
3447     }
3448   };
3449   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
3450 
3451   // Ensure that all dependency data is updated and fill the ready-list with
3452   // initial instructions.
3453   int Idx = 0;
3454   int NumToSchedule = 0;
3455   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
3456        I = I->getNextNode()) {
3457     ScheduleData *SD = BS->getScheduleData(I);
3458     assert(
3459         SD->isPartOfBundle() == (getTreeEntry(SD->Inst) != nullptr) &&
3460         "scheduler and vectorizer have different opinion on what is a bundle");
3461     SD->FirstInBundle->SchedulingPriority = Idx++;
3462     if (SD->isSchedulingEntity()) {
3463       BS->calculateDependencies(SD, false, this);
3464       NumToSchedule++;
3465     }
3466   }
3467   BS->initialFillReadyList(ReadyInsts);
3468 
3469   Instruction *LastScheduledInst = BS->ScheduleEnd;
3470 
3471   // Do the "real" scheduling.
3472   while (!ReadyInsts.empty()) {
3473     ScheduleData *picked = *ReadyInsts.begin();
3474     ReadyInsts.erase(ReadyInsts.begin());
3475 
3476     // Move the scheduled instruction(s) to their dedicated places, if not
3477     // there yet.
3478     ScheduleData *BundleMember = picked;
3479     while (BundleMember) {
3480       Instruction *pickedInst = BundleMember->Inst;
3481       if (LastScheduledInst->getNextNode() != pickedInst) {
3482         BS->BB->getInstList().remove(pickedInst);
3483         BS->BB->getInstList().insert(LastScheduledInst->getIterator(),
3484                                      pickedInst);
3485       }
3486       LastScheduledInst = pickedInst;
3487       BundleMember = BundleMember->NextInBundle;
3488     }
3489 
3490     BS->schedule(picked, ReadyInsts);
3491     NumToSchedule--;
3492   }
3493   assert(NumToSchedule == 0 && "could not schedule all instructions");
3494 
3495   // Avoid duplicate scheduling of the block.
3496   BS->ScheduleStart = nullptr;
3497 }
3498 
3499 unsigned BoUpSLP::getVectorElementSize(Value *V) {
3500   // If V is a store, just return the width of the stored value without
3501   // traversing the expression tree. This is the common case.
3502   if (auto *Store = dyn_cast<StoreInst>(V))
3503     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
3504 
3505   // If V is not a store, we can traverse the expression tree to find loads
3506   // that feed it. The type of the loaded value may indicate a more suitable
3507   // width than V's type. We want to base the vector element size on the width
3508   // of memory operations where possible.
3509   SmallVector<Instruction *, 16> Worklist;
3510   SmallPtrSet<Instruction *, 16> Visited;
3511   if (auto *I = dyn_cast<Instruction>(V))
3512     Worklist.push_back(I);
3513 
3514   // Traverse the expression tree in bottom-up order looking for loads. If we
3515   // encounter an instruciton we don't yet handle, we give up.
3516   auto MaxWidth = 0u;
3517   auto FoundUnknownInst = false;
3518   while (!Worklist.empty() && !FoundUnknownInst) {
3519     auto *I = Worklist.pop_back_val();
3520     Visited.insert(I);
3521 
3522     // We should only be looking at scalar instructions here. If the current
3523     // instruction has a vector type, give up.
3524     auto *Ty = I->getType();
3525     if (isa<VectorType>(Ty))
3526       FoundUnknownInst = true;
3527 
3528     // If the current instruction is a load, update MaxWidth to reflect the
3529     // width of the loaded value.
3530     else if (isa<LoadInst>(I))
3531       MaxWidth = std::max<unsigned>(MaxWidth, DL->getTypeSizeInBits(Ty));
3532 
3533     // Otherwise, we need to visit the operands of the instruction. We only
3534     // handle the interesting cases from buildTree here. If an operand is an
3535     // instruction we haven't yet visited, we add it to the worklist.
3536     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
3537              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I)) {
3538       for (Use &U : I->operands())
3539         if (auto *J = dyn_cast<Instruction>(U.get()))
3540           if (!Visited.count(J))
3541             Worklist.push_back(J);
3542     }
3543 
3544     // If we don't yet handle the instruction, give up.
3545     else
3546       FoundUnknownInst = true;
3547   }
3548 
3549   // If we didn't encounter a memory access in the expression tree, or if we
3550   // gave up for some reason, just return the width of V.
3551   if (!MaxWidth || FoundUnknownInst)
3552     return DL->getTypeSizeInBits(V->getType());
3553 
3554   // Otherwise, return the maximum width we found.
3555   return MaxWidth;
3556 }
3557 
3558 // Determine if a value V in a vectorizable expression Expr can be demoted to a
3559 // smaller type with a truncation. We collect the values that will be demoted
3560 // in ToDemote and additional roots that require investigating in Roots.
3561 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
3562                                   SmallVectorImpl<Value *> &ToDemote,
3563                                   SmallVectorImpl<Value *> &Roots) {
3564 
3565   // We can always demote constants.
3566   if (isa<Constant>(V)) {
3567     ToDemote.push_back(V);
3568     return true;
3569   }
3570 
3571   // If the value is not an instruction in the expression with only one use, it
3572   // cannot be demoted.
3573   auto *I = dyn_cast<Instruction>(V);
3574   if (!I || !I->hasOneUse() || !Expr.count(I))
3575     return false;
3576 
3577   switch (I->getOpcode()) {
3578 
3579   // We can always demote truncations and extensions. Since truncations can
3580   // seed additional demotion, we save the truncated value.
3581   case Instruction::Trunc:
3582     Roots.push_back(I->getOperand(0));
3583   case Instruction::ZExt:
3584   case Instruction::SExt:
3585     break;
3586 
3587   // We can demote certain binary operations if we can demote both of their
3588   // operands.
3589   case Instruction::Add:
3590   case Instruction::Sub:
3591   case Instruction::Mul:
3592   case Instruction::And:
3593   case Instruction::Or:
3594   case Instruction::Xor:
3595     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
3596         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
3597       return false;
3598     break;
3599 
3600   // We can demote selects if we can demote their true and false values.
3601   case Instruction::Select: {
3602     SelectInst *SI = cast<SelectInst>(I);
3603     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
3604         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
3605       return false;
3606     break;
3607   }
3608 
3609   // We can demote phis if we can demote all their incoming operands. Note that
3610   // we don't need to worry about cycles since we ensure single use above.
3611   case Instruction::PHI: {
3612     PHINode *PN = cast<PHINode>(I);
3613     for (Value *IncValue : PN->incoming_values())
3614       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
3615         return false;
3616     break;
3617   }
3618 
3619   // Otherwise, conservatively give up.
3620   default:
3621     return false;
3622   }
3623 
3624   // Record the value that we can demote.
3625   ToDemote.push_back(V);
3626   return true;
3627 }
3628 
3629 void BoUpSLP::computeMinimumValueSizes() {
3630   // If there are no external uses, the expression tree must be rooted by a
3631   // store. We can't demote in-memory values, so there is nothing to do here.
3632   if (ExternalUses.empty())
3633     return;
3634 
3635   // We only attempt to truncate integer expressions.
3636   auto &TreeRoot = VectorizableTree[0].Scalars;
3637   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
3638   if (!TreeRootIT)
3639     return;
3640 
3641   // If the expression is not rooted by a store, these roots should have
3642   // external uses. We will rely on InstCombine to rewrite the expression in
3643   // the narrower type. However, InstCombine only rewrites single-use values.
3644   // This means that if a tree entry other than a root is used externally, it
3645   // must have multiple uses and InstCombine will not rewrite it. The code
3646   // below ensures that only the roots are used externally.
3647   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
3648   for (auto &EU : ExternalUses)
3649     if (!Expr.erase(EU.Scalar))
3650       return;
3651   if (!Expr.empty())
3652     return;
3653 
3654   // Collect the scalar values of the vectorizable expression. We will use this
3655   // context to determine which values can be demoted. If we see a truncation,
3656   // we mark it as seeding another demotion.
3657   for (auto &Entry : VectorizableTree)
3658     Expr.insert(Entry.Scalars.begin(), Entry.Scalars.end());
3659 
3660   // Ensure the roots of the vectorizable tree don't form a cycle. They must
3661   // have a single external user that is not in the vectorizable tree.
3662   for (auto *Root : TreeRoot)
3663     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
3664       return;
3665 
3666   // Conservatively determine if we can actually truncate the roots of the
3667   // expression. Collect the values that can be demoted in ToDemote and
3668   // additional roots that require investigating in Roots.
3669   SmallVector<Value *, 32> ToDemote;
3670   SmallVector<Value *, 4> Roots;
3671   for (auto *Root : TreeRoot)
3672     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
3673       return;
3674 
3675   // The maximum bit width required to represent all the values that can be
3676   // demoted without loss of precision. It would be safe to truncate the roots
3677   // of the expression to this width.
3678   auto MaxBitWidth = 8u;
3679 
3680   // We first check if all the bits of the roots are demanded. If they're not,
3681   // we can truncate the roots to this narrower type.
3682   for (auto *Root : TreeRoot) {
3683     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
3684     MaxBitWidth = std::max<unsigned>(
3685         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
3686   }
3687 
3688   // True if the roots can be zero-extended back to their original type, rather
3689   // than sign-extended. We know that if the leading bits are not demanded, we
3690   // can safely zero-extend. So we initialize IsKnownPositive to True.
3691   bool IsKnownPositive = true;
3692 
3693   // If all the bits of the roots are demanded, we can try a little harder to
3694   // compute a narrower type. This can happen, for example, if the roots are
3695   // getelementptr indices. InstCombine promotes these indices to the pointer
3696   // width. Thus, all their bits are technically demanded even though the
3697   // address computation might be vectorized in a smaller type.
3698   //
3699   // We start by looking at each entry that can be demoted. We compute the
3700   // maximum bit width required to store the scalar by using ValueTracking to
3701   // compute the number of high-order bits we can truncate.
3702   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType())) {
3703     MaxBitWidth = 8u;
3704 
3705     // Determine if the sign bit of all the roots is known to be zero. If not,
3706     // IsKnownPositive is set to False.
3707     IsKnownPositive = all_of(TreeRoot, [&](Value *R) {
3708       KnownBits Known = computeKnownBits(R, *DL);
3709       return Known.isNonNegative();
3710     });
3711 
3712     // Determine the maximum number of bits required to store the scalar
3713     // values.
3714     for (auto *Scalar : ToDemote) {
3715       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, 0, DT);
3716       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
3717       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
3718     }
3719 
3720     // If we can't prove that the sign bit is zero, we must add one to the
3721     // maximum bit width to account for the unknown sign bit. This preserves
3722     // the existing sign bit so we can safely sign-extend the root back to the
3723     // original type. Otherwise, if we know the sign bit is zero, we will
3724     // zero-extend the root instead.
3725     //
3726     // FIXME: This is somewhat suboptimal, as there will be cases where adding
3727     //        one to the maximum bit width will yield a larger-than-necessary
3728     //        type. In general, we need to add an extra bit only if we can't
3729     //        prove that the upper bit of the original type is equal to the
3730     //        upper bit of the proposed smaller type. If these two bits are the
3731     //        same (either zero or one) we know that sign-extending from the
3732     //        smaller type will result in the same value. Here, since we can't
3733     //        yet prove this, we are just making the proposed smaller type
3734     //        larger to ensure correctness.
3735     if (!IsKnownPositive)
3736       ++MaxBitWidth;
3737   }
3738 
3739   // Round MaxBitWidth up to the next power-of-two.
3740   if (!isPowerOf2_64(MaxBitWidth))
3741     MaxBitWidth = NextPowerOf2(MaxBitWidth);
3742 
3743   // If the maximum bit width we compute is less than the with of the roots'
3744   // type, we can proceed with the narrowing. Otherwise, do nothing.
3745   if (MaxBitWidth >= TreeRootIT->getBitWidth())
3746     return;
3747 
3748   // If we can truncate the root, we must collect additional values that might
3749   // be demoted as a result. That is, those seeded by truncations we will
3750   // modify.
3751   while (!Roots.empty())
3752     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
3753 
3754   // Finally, map the values we can demote to the maximum bit with we computed.
3755   for (auto *Scalar : ToDemote)
3756     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
3757 }
3758 
3759 namespace {
3760 /// The SLPVectorizer Pass.
3761 struct SLPVectorizer : public FunctionPass {
3762   SLPVectorizerPass Impl;
3763 
3764   /// Pass identification, replacement for typeid
3765   static char ID;
3766 
3767   explicit SLPVectorizer() : FunctionPass(ID) {
3768     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
3769   }
3770 
3771 
3772   bool doInitialization(Module &M) override {
3773     return false;
3774   }
3775 
3776   bool runOnFunction(Function &F) override {
3777     if (skipFunction(F))
3778       return false;
3779 
3780     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
3781     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
3782     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
3783     auto *TLI = TLIP ? &TLIP->getTLI() : nullptr;
3784     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3785     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
3786     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3787     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
3788     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
3789     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
3790 
3791     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
3792   }
3793 
3794   void getAnalysisUsage(AnalysisUsage &AU) const override {
3795     FunctionPass::getAnalysisUsage(AU);
3796     AU.addRequired<AssumptionCacheTracker>();
3797     AU.addRequired<ScalarEvolutionWrapperPass>();
3798     AU.addRequired<AAResultsWrapperPass>();
3799     AU.addRequired<TargetTransformInfoWrapperPass>();
3800     AU.addRequired<LoopInfoWrapperPass>();
3801     AU.addRequired<DominatorTreeWrapperPass>();
3802     AU.addRequired<DemandedBitsWrapperPass>();
3803     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
3804     AU.addPreserved<LoopInfoWrapperPass>();
3805     AU.addPreserved<DominatorTreeWrapperPass>();
3806     AU.addPreserved<AAResultsWrapperPass>();
3807     AU.addPreserved<GlobalsAAWrapperPass>();
3808     AU.setPreservesCFG();
3809   }
3810 };
3811 } // end anonymous namespace
3812 
3813 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
3814   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
3815   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
3816   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
3817   auto *AA = &AM.getResult<AAManager>(F);
3818   auto *LI = &AM.getResult<LoopAnalysis>(F);
3819   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
3820   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
3821   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
3822   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
3823 
3824   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
3825   if (!Changed)
3826     return PreservedAnalyses::all();
3827 
3828   PreservedAnalyses PA;
3829   PA.preserveSet<CFGAnalyses>();
3830   PA.preserve<AAManager>();
3831   PA.preserve<GlobalsAA>();
3832   return PA;
3833 }
3834 
3835 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
3836                                 TargetTransformInfo *TTI_,
3837                                 TargetLibraryInfo *TLI_, AliasAnalysis *AA_,
3838                                 LoopInfo *LI_, DominatorTree *DT_,
3839                                 AssumptionCache *AC_, DemandedBits *DB_,
3840                                 OptimizationRemarkEmitter *ORE_) {
3841   SE = SE_;
3842   TTI = TTI_;
3843   TLI = TLI_;
3844   AA = AA_;
3845   LI = LI_;
3846   DT = DT_;
3847   AC = AC_;
3848   DB = DB_;
3849   DL = &F.getParent()->getDataLayout();
3850 
3851   Stores.clear();
3852   GEPs.clear();
3853   bool Changed = false;
3854 
3855   // If the target claims to have no vector registers don't attempt
3856   // vectorization.
3857   if (!TTI->getNumberOfRegisters(true))
3858     return false;
3859 
3860   // Don't vectorize when the attribute NoImplicitFloat is used.
3861   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
3862     return false;
3863 
3864   DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
3865 
3866   // Use the bottom up slp vectorizer to construct chains that start with
3867   // store instructions.
3868   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
3869 
3870   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
3871   // delete instructions.
3872 
3873   // Scan the blocks in the function in post order.
3874   for (auto BB : post_order(&F.getEntryBlock())) {
3875     collectSeedInstructions(BB);
3876 
3877     // Vectorize trees that end at stores.
3878     if (!Stores.empty()) {
3879       DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
3880                    << " underlying objects.\n");
3881       Changed |= vectorizeStoreChains(R);
3882     }
3883 
3884     // Vectorize trees that end at reductions.
3885     Changed |= vectorizeChainsInBlock(BB, R);
3886 
3887     // Vectorize the index computations of getelementptr instructions. This
3888     // is primarily intended to catch gather-like idioms ending at
3889     // non-consecutive loads.
3890     if (!GEPs.empty()) {
3891       DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
3892                    << " underlying objects.\n");
3893       Changed |= vectorizeGEPIndices(BB, R);
3894     }
3895   }
3896 
3897   if (Changed) {
3898     R.optimizeGatherSequence();
3899     DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
3900     DEBUG(verifyFunction(F));
3901   }
3902   return Changed;
3903 }
3904 
3905 /// \brief Check that the Values in the slice in VL array are still existent in
3906 /// the WeakTrackingVH array.
3907 /// Vectorization of part of the VL array may cause later values in the VL array
3908 /// to become invalid. We track when this has happened in the WeakTrackingVH
3909 /// array.
3910 static bool hasValueBeenRAUWed(ArrayRef<Value *> VL,
3911                                ArrayRef<WeakTrackingVH> VH, unsigned SliceBegin,
3912                                unsigned SliceSize) {
3913   VL = VL.slice(SliceBegin, SliceSize);
3914   VH = VH.slice(SliceBegin, SliceSize);
3915   return !std::equal(VL.begin(), VL.end(), VH.begin());
3916 }
3917 
3918 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
3919                                             unsigned VecRegSize) {
3920   unsigned ChainLen = Chain.size();
3921   DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
3922         << "\n");
3923   unsigned Sz = R.getVectorElementSize(Chain[0]);
3924   unsigned VF = VecRegSize / Sz;
3925 
3926   if (!isPowerOf2_32(Sz) || VF < 2)
3927     return false;
3928 
3929   // Keep track of values that were deleted by vectorizing in the loop below.
3930   SmallVector<WeakTrackingVH, 8> TrackValues(Chain.begin(), Chain.end());
3931 
3932   bool Changed = false;
3933   // Look for profitable vectorizable trees at all offsets, starting at zero.
3934   for (unsigned i = 0, e = ChainLen; i < e; ++i) {
3935     if (i + VF > e)
3936       break;
3937 
3938     // Check that a previous iteration of this loop did not delete the Value.
3939     if (hasValueBeenRAUWed(Chain, TrackValues, i, VF))
3940       continue;
3941 
3942     DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
3943           << "\n");
3944     ArrayRef<Value *> Operands = Chain.slice(i, VF);
3945 
3946     R.buildTree(Operands);
3947     if (R.isTreeTinyAndNotFullyVectorizable())
3948       continue;
3949 
3950     R.computeMinimumValueSizes();
3951 
3952     int Cost = R.getTreeCost();
3953 
3954     DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
3955     if (Cost < -SLPCostThreshold) {
3956       DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
3957       using namespace ore;
3958       R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
3959                                           cast<StoreInst>(Chain[i]))
3960                        << "Stores SLP vectorized with cost " << NV("Cost", Cost)
3961                        << " and with tree size "
3962                        << NV("TreeSize", R.getTreeSize()));
3963 
3964       R.vectorizeTree();
3965 
3966       // Move to the next bundle.
3967       i += VF - 1;
3968       Changed = true;
3969     }
3970   }
3971 
3972   return Changed;
3973 }
3974 
3975 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
3976                                         BoUpSLP &R) {
3977   SetVector<StoreInst *> Heads, Tails;
3978   SmallDenseMap<StoreInst *, StoreInst *> ConsecutiveChain;
3979 
3980   // We may run into multiple chains that merge into a single chain. We mark the
3981   // stores that we vectorized so that we don't visit the same store twice.
3982   BoUpSLP::ValueSet VectorizedStores;
3983   bool Changed = false;
3984 
3985   // Do a quadratic search on all of the given stores and find
3986   // all of the pairs of stores that follow each other.
3987   SmallVector<unsigned, 16> IndexQueue;
3988   for (unsigned i = 0, e = Stores.size(); i < e; ++i) {
3989     IndexQueue.clear();
3990     // If a store has multiple consecutive store candidates, search Stores
3991     // array according to the sequence: from i+1 to e, then from i-1 to 0.
3992     // This is because usually pairing with immediate succeeding or preceding
3993     // candidate create the best chance to find slp vectorization opportunity.
3994     unsigned j = 0;
3995     for (j = i + 1; j < e; ++j)
3996       IndexQueue.push_back(j);
3997     for (j = i; j > 0; --j)
3998       IndexQueue.push_back(j - 1);
3999 
4000     for (auto &k : IndexQueue) {
4001       if (isConsecutiveAccess(Stores[i], Stores[k], *DL, *SE)) {
4002         Tails.insert(Stores[k]);
4003         Heads.insert(Stores[i]);
4004         ConsecutiveChain[Stores[i]] = Stores[k];
4005         break;
4006       }
4007     }
4008   }
4009 
4010   // For stores that start but don't end a link in the chain:
4011   for (SetVector<StoreInst *>::iterator it = Heads.begin(), e = Heads.end();
4012        it != e; ++it) {
4013     if (Tails.count(*it))
4014       continue;
4015 
4016     // We found a store instr that starts a chain. Now follow the chain and try
4017     // to vectorize it.
4018     BoUpSLP::ValueList Operands;
4019     StoreInst *I = *it;
4020     // Collect the chain into a list.
4021     while (Tails.count(I) || Heads.count(I)) {
4022       if (VectorizedStores.count(I))
4023         break;
4024       Operands.push_back(I);
4025       // Move to the next value in the chain.
4026       I = ConsecutiveChain[I];
4027     }
4028 
4029     // FIXME: Is division-by-2 the correct step? Should we assert that the
4030     // register size is a power-of-2?
4031     for (unsigned Size = R.getMaxVecRegSize(); Size >= R.getMinVecRegSize();
4032          Size /= 2) {
4033       if (vectorizeStoreChain(Operands, R, Size)) {
4034         // Mark the vectorized stores so that we don't vectorize them again.
4035         VectorizedStores.insert(Operands.begin(), Operands.end());
4036         Changed = true;
4037         break;
4038       }
4039     }
4040   }
4041 
4042   return Changed;
4043 }
4044 
4045 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
4046 
4047   // Initialize the collections. We will make a single pass over the block.
4048   Stores.clear();
4049   GEPs.clear();
4050 
4051   // Visit the store and getelementptr instructions in BB and organize them in
4052   // Stores and GEPs according to the underlying objects of their pointer
4053   // operands.
4054   for (Instruction &I : *BB) {
4055 
4056     // Ignore store instructions that are volatile or have a pointer operand
4057     // that doesn't point to a scalar type.
4058     if (auto *SI = dyn_cast<StoreInst>(&I)) {
4059       if (!SI->isSimple())
4060         continue;
4061       if (!isValidElementType(SI->getValueOperand()->getType()))
4062         continue;
4063       Stores[GetUnderlyingObject(SI->getPointerOperand(), *DL)].push_back(SI);
4064     }
4065 
4066     // Ignore getelementptr instructions that have more than one index, a
4067     // constant index, or a pointer operand that doesn't point to a scalar
4068     // type.
4069     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
4070       auto Idx = GEP->idx_begin()->get();
4071       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
4072         continue;
4073       if (!isValidElementType(Idx->getType()))
4074         continue;
4075       if (GEP->getType()->isVectorTy())
4076         continue;
4077       GEPs[GetUnderlyingObject(GEP->getPointerOperand(), *DL)].push_back(GEP);
4078     }
4079   }
4080 }
4081 
4082 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
4083   if (!A || !B)
4084     return false;
4085   Value *VL[] = { A, B };
4086   return tryToVectorizeList(VL, R, None, true);
4087 }
4088 
4089 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
4090                                            ArrayRef<Value *> BuildVector,
4091                                            bool AllowReorder) {
4092   if (VL.size() < 2)
4093     return false;
4094 
4095   DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = " << VL.size()
4096                << ".\n");
4097 
4098   // Check that all of the parts are scalar instructions of the same type.
4099   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
4100   if (!I0)
4101     return false;
4102 
4103   unsigned Opcode0 = I0->getOpcode();
4104 
4105   unsigned Sz = R.getVectorElementSize(I0);
4106   unsigned MinVF = std::max(2U, R.getMinVecRegSize() / Sz);
4107   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
4108   if (MaxVF < 2)
4109     return false;
4110 
4111   for (Value *V : VL) {
4112     Type *Ty = V->getType();
4113     if (!isValidElementType(Ty))
4114       return false;
4115     Instruction *Inst = dyn_cast<Instruction>(V);
4116     if (!Inst || Inst->getOpcode() != Opcode0)
4117       return false;
4118   }
4119 
4120   bool Changed = false;
4121 
4122   // Keep track of values that were deleted by vectorizing in the loop below.
4123   SmallVector<WeakTrackingVH, 8> TrackValues(VL.begin(), VL.end());
4124 
4125   unsigned NextInst = 0, MaxInst = VL.size();
4126   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF;
4127        VF /= 2) {
4128     // No actual vectorization should happen, if number of parts is the same as
4129     // provided vectorization factor (i.e. the scalar type is used for vector
4130     // code during codegen).
4131     auto *VecTy = VectorType::get(VL[0]->getType(), VF);
4132     if (TTI->getNumberOfParts(VecTy) == VF)
4133       continue;
4134     for (unsigned I = NextInst; I < MaxInst; ++I) {
4135       unsigned OpsWidth = 0;
4136 
4137       if (I + VF > MaxInst)
4138         OpsWidth = MaxInst - I;
4139       else
4140         OpsWidth = VF;
4141 
4142       if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
4143         break;
4144 
4145       // Check that a previous iteration of this loop did not delete the Value.
4146       if (hasValueBeenRAUWed(VL, TrackValues, I, OpsWidth))
4147         continue;
4148 
4149       DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
4150                    << "\n");
4151       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
4152 
4153       ArrayRef<Value *> BuildVectorSlice;
4154       if (!BuildVector.empty())
4155         BuildVectorSlice = BuildVector.slice(I, OpsWidth);
4156 
4157       R.buildTree(Ops, BuildVectorSlice);
4158       // TODO: check if we can allow reordering for more cases.
4159       if (AllowReorder && R.shouldReorder()) {
4160         // Conceptually, there is nothing actually preventing us from trying to
4161         // reorder a larger list. In fact, we do exactly this when vectorizing
4162         // reductions. However, at this point, we only expect to get here when
4163         // there are exactly two operations.
4164         assert(Ops.size() == 2);
4165         assert(BuildVectorSlice.empty());
4166         Value *ReorderedOps[] = {Ops[1], Ops[0]};
4167         R.buildTree(ReorderedOps, None);
4168       }
4169       if (R.isTreeTinyAndNotFullyVectorizable())
4170         continue;
4171 
4172       R.computeMinimumValueSizes();
4173       int Cost = R.getTreeCost();
4174 
4175       if (Cost < -SLPCostThreshold) {
4176         DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
4177         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
4178                                             cast<Instruction>(Ops[0]))
4179                          << "SLP vectorized with cost " << ore::NV("Cost", Cost)
4180                          << " and with tree size "
4181                          << ore::NV("TreeSize", R.getTreeSize()));
4182 
4183         Value *VectorizedRoot = R.vectorizeTree();
4184 
4185         // Reconstruct the build vector by extracting the vectorized root. This
4186         // way we handle the case where some elements of the vector are
4187         // undefined.
4188         //  (return (inserelt <4 xi32> (insertelt undef (opd0) 0) (opd1) 2))
4189         if (!BuildVectorSlice.empty()) {
4190           // The insert point is the last build vector instruction. The
4191           // vectorized root will precede it. This guarantees that we get an
4192           // instruction. The vectorized tree could have been constant folded.
4193           Instruction *InsertAfter = cast<Instruction>(BuildVectorSlice.back());
4194           unsigned VecIdx = 0;
4195           for (auto &V : BuildVectorSlice) {
4196             IRBuilder<NoFolder> Builder(InsertAfter->getParent(),
4197                                         ++BasicBlock::iterator(InsertAfter));
4198             Instruction *I = cast<Instruction>(V);
4199             assert(isa<InsertElementInst>(I) || isa<InsertValueInst>(I));
4200             Instruction *Extract =
4201                 cast<Instruction>(Builder.CreateExtractElement(
4202                     VectorizedRoot, Builder.getInt32(VecIdx++)));
4203             I->setOperand(1, Extract);
4204             I->removeFromParent();
4205             I->insertAfter(Extract);
4206             InsertAfter = I;
4207           }
4208         }
4209         // Move to the next bundle.
4210         I += VF - 1;
4211         NextInst = I + 1;
4212         Changed = true;
4213       }
4214     }
4215   }
4216 
4217   return Changed;
4218 }
4219 
4220 bool SLPVectorizerPass::tryToVectorize(BinaryOperator *V, BoUpSLP &R) {
4221   if (!V)
4222     return false;
4223 
4224   Value *P = V->getParent();
4225 
4226   // Vectorize in current basic block only.
4227   auto *Op0 = dyn_cast<Instruction>(V->getOperand(0));
4228   auto *Op1 = dyn_cast<Instruction>(V->getOperand(1));
4229   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
4230     return false;
4231 
4232   // Try to vectorize V.
4233   if (tryToVectorizePair(Op0, Op1, R))
4234     return true;
4235 
4236   auto *A = dyn_cast<BinaryOperator>(Op0);
4237   auto *B = dyn_cast<BinaryOperator>(Op1);
4238   // Try to skip B.
4239   if (B && B->hasOneUse()) {
4240     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
4241     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
4242     if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
4243       return true;
4244     if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
4245       return true;
4246   }
4247 
4248   // Try to skip A.
4249   if (A && A->hasOneUse()) {
4250     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
4251     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
4252     if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
4253       return true;
4254     if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
4255       return true;
4256   }
4257   return false;
4258 }
4259 
4260 /// \brief Generate a shuffle mask to be used in a reduction tree.
4261 ///
4262 /// \param VecLen The length of the vector to be reduced.
4263 /// \param NumEltsToRdx The number of elements that should be reduced in the
4264 ///        vector.
4265 /// \param IsPairwise Whether the reduction is a pairwise or splitting
4266 ///        reduction. A pairwise reduction will generate a mask of
4267 ///        <0,2,...> or <1,3,..> while a splitting reduction will generate
4268 ///        <2,3, undef,undef> for a vector of 4 and NumElts = 2.
4269 /// \param IsLeft True will generate a mask of even elements, odd otherwise.
4270 static Value *createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx,
4271                                    bool IsPairwise, bool IsLeft,
4272                                    IRBuilder<> &Builder) {
4273   assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask");
4274 
4275   SmallVector<Constant *, 32> ShuffleMask(
4276       VecLen, UndefValue::get(Builder.getInt32Ty()));
4277 
4278   if (IsPairwise)
4279     // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
4280     for (unsigned i = 0; i != NumEltsToRdx; ++i)
4281       ShuffleMask[i] = Builder.getInt32(2 * i + !IsLeft);
4282   else
4283     // Move the upper half of the vector to the lower half.
4284     for (unsigned i = 0; i != NumEltsToRdx; ++i)
4285       ShuffleMask[i] = Builder.getInt32(NumEltsToRdx + i);
4286 
4287   return ConstantVector::get(ShuffleMask);
4288 }
4289 
4290 namespace {
4291 /// Model horizontal reductions.
4292 ///
4293 /// A horizontal reduction is a tree of reduction operations (currently add and
4294 /// fadd) that has operations that can be put into a vector as its leaf.
4295 /// For example, this tree:
4296 ///
4297 /// mul mul mul mul
4298 ///  \  /    \  /
4299 ///   +       +
4300 ///    \     /
4301 ///       +
4302 /// This tree has "mul" as its reduced values and "+" as its reduction
4303 /// operations. A reduction might be feeding into a store or a binary operation
4304 /// feeding a phi.
4305 ///    ...
4306 ///    \  /
4307 ///     +
4308 ///     |
4309 ///  phi +=
4310 ///
4311 ///  Or:
4312 ///    ...
4313 ///    \  /
4314 ///     +
4315 ///     |
4316 ///   *p =
4317 ///
4318 class HorizontalReduction {
4319   SmallVector<Value *, 16> ReductionOps;
4320   SmallVector<Value *, 32> ReducedVals;
4321   // Use map vector to make stable output.
4322   MapVector<Instruction *, Value *> ExtraArgs;
4323 
4324   BinaryOperator *ReductionRoot = nullptr;
4325 
4326   /// The opcode of the reduction.
4327   Instruction::BinaryOps ReductionOpcode = Instruction::BinaryOpsEnd;
4328   /// The opcode of the values we perform a reduction on.
4329   unsigned ReducedValueOpcode = 0;
4330   /// Should we model this reduction as a pairwise reduction tree or a tree that
4331   /// splits the vector in halves and adds those halves.
4332   bool IsPairwiseReduction = false;
4333 
4334   /// Checks if the ParentStackElem.first should be marked as a reduction
4335   /// operation with an extra argument or as extra argument itself.
4336   void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem,
4337                     Value *ExtraArg) {
4338     if (ExtraArgs.count(ParentStackElem.first)) {
4339       ExtraArgs[ParentStackElem.first] = nullptr;
4340       // We ran into something like:
4341       // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg.
4342       // The whole ParentStackElem.first should be considered as an extra value
4343       // in this case.
4344       // Do not perform analysis of remaining operands of ParentStackElem.first
4345       // instruction, this whole instruction is an extra argument.
4346       ParentStackElem.second = ParentStackElem.first->getNumOperands();
4347     } else {
4348       // We ran into something like:
4349       // ParentStackElem.first += ... + ExtraArg + ...
4350       ExtraArgs[ParentStackElem.first] = ExtraArg;
4351     }
4352   }
4353 
4354 public:
4355   HorizontalReduction() = default;
4356 
4357   /// \brief Try to find a reduction tree.
4358   bool matchAssociativeReduction(PHINode *Phi, BinaryOperator *B) {
4359     assert((!Phi || is_contained(Phi->operands(), B)) &&
4360            "Thi phi needs to use the binary operator");
4361 
4362     // We could have a initial reductions that is not an add.
4363     //  r *= v1 + v2 + v3 + v4
4364     // In such a case start looking for a tree rooted in the first '+'.
4365     if (Phi) {
4366       if (B->getOperand(0) == Phi) {
4367         Phi = nullptr;
4368         B = dyn_cast<BinaryOperator>(B->getOperand(1));
4369       } else if (B->getOperand(1) == Phi) {
4370         Phi = nullptr;
4371         B = dyn_cast<BinaryOperator>(B->getOperand(0));
4372       }
4373     }
4374 
4375     if (!B)
4376       return false;
4377 
4378     Type *Ty = B->getType();
4379     if (!isValidElementType(Ty))
4380       return false;
4381 
4382     ReductionOpcode = B->getOpcode();
4383     ReducedValueOpcode = 0;
4384     ReductionRoot = B;
4385 
4386     // We currently only support adds.
4387     if ((ReductionOpcode != Instruction::Add &&
4388          ReductionOpcode != Instruction::FAdd) ||
4389         !B->isAssociative())
4390       return false;
4391 
4392     // Post order traverse the reduction tree starting at B. We only handle true
4393     // trees containing only binary operators or selects.
4394     SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
4395     Stack.push_back(std::make_pair(B, 0));
4396     while (!Stack.empty()) {
4397       Instruction *TreeN = Stack.back().first;
4398       unsigned EdgeToVist = Stack.back().second++;
4399       bool IsReducedValue = TreeN->getOpcode() != ReductionOpcode;
4400 
4401       // Postorder vist.
4402       if (EdgeToVist == 2 || IsReducedValue) {
4403         if (IsReducedValue)
4404           ReducedVals.push_back(TreeN);
4405         else {
4406           auto I = ExtraArgs.find(TreeN);
4407           if (I != ExtraArgs.end() && !I->second) {
4408             // Check if TreeN is an extra argument of its parent operation.
4409             if (Stack.size() <= 1) {
4410               // TreeN can't be an extra argument as it is a root reduction
4411               // operation.
4412               return false;
4413             }
4414             // Yes, TreeN is an extra argument, do not add it to a list of
4415             // reduction operations.
4416             // Stack[Stack.size() - 2] always points to the parent operation.
4417             markExtraArg(Stack[Stack.size() - 2], TreeN);
4418             ExtraArgs.erase(TreeN);
4419           } else
4420             ReductionOps.push_back(TreeN);
4421         }
4422         // Retract.
4423         Stack.pop_back();
4424         continue;
4425       }
4426 
4427       // Visit left or right.
4428       Value *NextV = TreeN->getOperand(EdgeToVist);
4429       if (NextV != Phi) {
4430         auto *I = dyn_cast<Instruction>(NextV);
4431         // Continue analysis if the next operand is a reduction operation or
4432         // (possibly) a reduced value. If the reduced value opcode is not set,
4433         // the first met operation != reduction operation is considered as the
4434         // reduced value class.
4435         if (I && (!ReducedValueOpcode || I->getOpcode() == ReducedValueOpcode ||
4436                   I->getOpcode() == ReductionOpcode)) {
4437           // Only handle trees in the current basic block.
4438           if (I->getParent() != B->getParent()) {
4439             // I is an extra argument for TreeN (its parent operation).
4440             markExtraArg(Stack.back(), I);
4441             continue;
4442           }
4443 
4444           // Each tree node needs to have one user except for the ultimate
4445           // reduction.
4446           if (!I->hasOneUse() && I != B) {
4447             // I is an extra argument for TreeN (its parent operation).
4448             markExtraArg(Stack.back(), I);
4449             continue;
4450           }
4451 
4452           if (I->getOpcode() == ReductionOpcode) {
4453             // We need to be able to reassociate the reduction operations.
4454             if (!I->isAssociative()) {
4455               // I is an extra argument for TreeN (its parent operation).
4456               markExtraArg(Stack.back(), I);
4457               continue;
4458             }
4459           } else if (ReducedValueOpcode &&
4460                      ReducedValueOpcode != I->getOpcode()) {
4461             // Make sure that the opcodes of the operations that we are going to
4462             // reduce match.
4463             // I is an extra argument for TreeN (its parent operation).
4464             markExtraArg(Stack.back(), I);
4465             continue;
4466           } else if (!ReducedValueOpcode)
4467             ReducedValueOpcode = I->getOpcode();
4468 
4469           Stack.push_back(std::make_pair(I, 0));
4470           continue;
4471         }
4472       }
4473       // NextV is an extra argument for TreeN (its parent operation).
4474       markExtraArg(Stack.back(), NextV);
4475     }
4476     return true;
4477   }
4478 
4479   /// \brief Attempt to vectorize the tree found by
4480   /// matchAssociativeReduction.
4481   bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
4482     if (ReducedVals.empty())
4483       return false;
4484 
4485     // If there is a sufficient number of reduction values, reduce
4486     // to a nearby power-of-2. Can safely generate oversized
4487     // vectors and rely on the backend to split them to legal sizes.
4488     unsigned NumReducedVals = ReducedVals.size();
4489     if (NumReducedVals < 4)
4490       return false;
4491 
4492     unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
4493 
4494     Value *VectorizedTree = nullptr;
4495     IRBuilder<> Builder(ReductionRoot);
4496     FastMathFlags Unsafe;
4497     Unsafe.setUnsafeAlgebra();
4498     Builder.setFastMathFlags(Unsafe);
4499     unsigned i = 0;
4500 
4501     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
4502     // The same extra argument may be used several time, so log each attempt
4503     // to use it.
4504     for (auto &Pair : ExtraArgs)
4505       ExternallyUsedValues[Pair.second].push_back(Pair.first);
4506     while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) {
4507       auto VL = makeArrayRef(&ReducedVals[i], ReduxWidth);
4508       V.buildTree(VL, ExternallyUsedValues, ReductionOps);
4509       if (V.shouldReorder()) {
4510         SmallVector<Value *, 8> Reversed(VL.rbegin(), VL.rend());
4511         V.buildTree(Reversed, ExternallyUsedValues, ReductionOps);
4512       }
4513       if (V.isTreeTinyAndNotFullyVectorizable())
4514         break;
4515 
4516       V.computeMinimumValueSizes();
4517 
4518       // Estimate cost.
4519       int Cost =
4520           V.getTreeCost() + getReductionCost(TTI, ReducedVals[i], ReduxWidth);
4521       if (Cost >= -SLPCostThreshold)
4522         break;
4523 
4524       DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" << Cost
4525                    << ". (HorRdx)\n");
4526       auto *I0 = cast<Instruction>(VL[0]);
4527       V.getORE()->emit(
4528           OptimizationRemark(SV_NAME, "VectorizedHorizontalReduction", I0)
4529           << "Vectorized horizontal reduction with cost "
4530           << ore::NV("Cost", Cost) << " and with tree size "
4531           << ore::NV("TreeSize", V.getTreeSize()));
4532 
4533       // Vectorize a tree.
4534       DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
4535       Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues);
4536 
4537       // Emit a reduction.
4538       Value *ReducedSubTree =
4539           emitReduction(VectorizedRoot, Builder, ReduxWidth, ReductionOps, TTI);
4540       if (VectorizedTree) {
4541         Builder.SetCurrentDebugLocation(Loc);
4542         VectorizedTree = Builder.CreateBinOp(ReductionOpcode, VectorizedTree,
4543                                              ReducedSubTree, "bin.rdx");
4544         propagateIRFlags(VectorizedTree, ReductionOps);
4545       } else
4546         VectorizedTree = ReducedSubTree;
4547       i += ReduxWidth;
4548       ReduxWidth = PowerOf2Floor(NumReducedVals - i);
4549     }
4550 
4551     if (VectorizedTree) {
4552       // Finish the reduction.
4553       for (; i < NumReducedVals; ++i) {
4554         auto *I = cast<Instruction>(ReducedVals[i]);
4555         Builder.SetCurrentDebugLocation(I->getDebugLoc());
4556         VectorizedTree =
4557             Builder.CreateBinOp(ReductionOpcode, VectorizedTree, I);
4558         propagateIRFlags(VectorizedTree, ReductionOps);
4559       }
4560       for (auto &Pair : ExternallyUsedValues) {
4561         assert(!Pair.second.empty() &&
4562                "At least one DebugLoc must be inserted");
4563         // Add each externally used value to the final reduction.
4564         for (auto *I : Pair.second) {
4565           Builder.SetCurrentDebugLocation(I->getDebugLoc());
4566           VectorizedTree = Builder.CreateBinOp(ReductionOpcode, VectorizedTree,
4567                                                Pair.first, "bin.extra");
4568           propagateIRFlags(VectorizedTree, I);
4569         }
4570       }
4571       // Update users.
4572       ReductionRoot->replaceAllUsesWith(VectorizedTree);
4573     }
4574     return VectorizedTree != nullptr;
4575   }
4576 
4577   unsigned numReductionValues() const {
4578     return ReducedVals.size();
4579   }
4580 
4581 private:
4582   /// \brief Calculate the cost of a reduction.
4583   int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal,
4584                        unsigned ReduxWidth) {
4585     Type *ScalarTy = FirstReducedVal->getType();
4586     Type *VecTy = VectorType::get(ScalarTy, ReduxWidth);
4587 
4588     int PairwiseRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, true);
4589     int SplittingRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, false);
4590 
4591     IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
4592     int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
4593 
4594     int ScalarReduxCost =
4595         (ReduxWidth - 1) *
4596         TTI->getArithmeticInstrCost(ReductionOpcode, ScalarTy);
4597 
4598     DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost
4599                  << " for reduction that starts with " << *FirstReducedVal
4600                  << " (It is a "
4601                  << (IsPairwiseReduction ? "pairwise" : "splitting")
4602                  << " reduction)\n");
4603 
4604     return VecReduxCost - ScalarReduxCost;
4605   }
4606 
4607   /// \brief Emit a horizontal reduction of the vectorized value.
4608   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
4609                        unsigned ReduxWidth, ArrayRef<Value *> RedOps,
4610                        const TargetTransformInfo *TTI) {
4611     assert(VectorizedValue && "Need to have a vectorized tree node");
4612     assert(isPowerOf2_32(ReduxWidth) &&
4613            "We only handle power-of-two reductions for now");
4614 
4615     if (!IsPairwiseReduction)
4616       return createSimpleTargetReduction(
4617           Builder, TTI, ReductionOpcode, VectorizedValue,
4618           TargetTransformInfo::ReductionFlags(), RedOps);
4619 
4620     Value *TmpVec = VectorizedValue;
4621     for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
4622       Value *LeftMask =
4623           createRdxShuffleMask(ReduxWidth, i, true, true, Builder);
4624       Value *RightMask =
4625           createRdxShuffleMask(ReduxWidth, i, true, false, Builder);
4626 
4627       Value *LeftShuf = Builder.CreateShuffleVector(
4628           TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l");
4629       Value *RightShuf = Builder.CreateShuffleVector(
4630           TmpVec, UndefValue::get(TmpVec->getType()), (RightMask),
4631           "rdx.shuf.r");
4632       TmpVec =
4633           Builder.CreateBinOp(ReductionOpcode, LeftShuf, RightShuf, "bin.rdx");
4634       propagateIRFlags(TmpVec, RedOps);
4635     }
4636 
4637     // The result is in the first element of the vector.
4638     return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
4639   }
4640 };
4641 } // end anonymous namespace
4642 
4643 /// \brief Recognize construction of vectors like
4644 ///  %ra = insertelement <4 x float> undef, float %s0, i32 0
4645 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
4646 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
4647 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
4648 ///
4649 /// Returns true if it matches
4650 ///
4651 static bool findBuildVector(InsertElementInst *FirstInsertElem,
4652                             SmallVectorImpl<Value *> &BuildVector,
4653                             SmallVectorImpl<Value *> &BuildVectorOpds) {
4654   if (!isa<UndefValue>(FirstInsertElem->getOperand(0)))
4655     return false;
4656 
4657   InsertElementInst *IE = FirstInsertElem;
4658   while (true) {
4659     BuildVector.push_back(IE);
4660     BuildVectorOpds.push_back(IE->getOperand(1));
4661 
4662     if (IE->use_empty())
4663       return false;
4664 
4665     InsertElementInst *NextUse = dyn_cast<InsertElementInst>(IE->user_back());
4666     if (!NextUse)
4667       return true;
4668 
4669     // If this isn't the final use, make sure the next insertelement is the only
4670     // use. It's OK if the final constructed vector is used multiple times
4671     if (!IE->hasOneUse())
4672       return false;
4673 
4674     IE = NextUse;
4675   }
4676 
4677   return false;
4678 }
4679 
4680 /// \brief Like findBuildVector, but looks backwards for construction of aggregate.
4681 ///
4682 /// \return true if it matches.
4683 static bool findBuildAggregate(InsertValueInst *IV,
4684                                SmallVectorImpl<Value *> &BuildVector,
4685                                SmallVectorImpl<Value *> &BuildVectorOpds) {
4686   Value *V;
4687   do {
4688     BuildVector.push_back(IV);
4689     BuildVectorOpds.push_back(IV->getInsertedValueOperand());
4690     V = IV->getAggregateOperand();
4691     if (isa<UndefValue>(V))
4692       break;
4693     IV = dyn_cast<InsertValueInst>(V);
4694     if (!IV || !IV->hasOneUse())
4695       return false;
4696   } while (true);
4697   std::reverse(BuildVector.begin(), BuildVector.end());
4698   std::reverse(BuildVectorOpds.begin(), BuildVectorOpds.end());
4699   return true;
4700 }
4701 
4702 static bool PhiTypeSorterFunc(Value *V, Value *V2) {
4703   return V->getType() < V2->getType();
4704 }
4705 
4706 /// \brief Try and get a reduction value from a phi node.
4707 ///
4708 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
4709 /// if they come from either \p ParentBB or a containing loop latch.
4710 ///
4711 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
4712 /// if not possible.
4713 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
4714                                 BasicBlock *ParentBB, LoopInfo *LI) {
4715   // There are situations where the reduction value is not dominated by the
4716   // reduction phi. Vectorizing such cases has been reported to cause
4717   // miscompiles. See PR25787.
4718   auto DominatedReduxValue = [&](Value *R) {
4719     return (
4720         dyn_cast<Instruction>(R) &&
4721         DT->dominates(P->getParent(), dyn_cast<Instruction>(R)->getParent()));
4722   };
4723 
4724   Value *Rdx = nullptr;
4725 
4726   // Return the incoming value if it comes from the same BB as the phi node.
4727   if (P->getIncomingBlock(0) == ParentBB) {
4728     Rdx = P->getIncomingValue(0);
4729   } else if (P->getIncomingBlock(1) == ParentBB) {
4730     Rdx = P->getIncomingValue(1);
4731   }
4732 
4733   if (Rdx && DominatedReduxValue(Rdx))
4734     return Rdx;
4735 
4736   // Otherwise, check whether we have a loop latch to look at.
4737   Loop *BBL = LI->getLoopFor(ParentBB);
4738   if (!BBL)
4739     return nullptr;
4740   BasicBlock *BBLatch = BBL->getLoopLatch();
4741   if (!BBLatch)
4742     return nullptr;
4743 
4744   // There is a loop latch, return the incoming value if it comes from
4745   // that. This reduction pattern occasionally turns up.
4746   if (P->getIncomingBlock(0) == BBLatch) {
4747     Rdx = P->getIncomingValue(0);
4748   } else if (P->getIncomingBlock(1) == BBLatch) {
4749     Rdx = P->getIncomingValue(1);
4750   }
4751 
4752   if (Rdx && DominatedReduxValue(Rdx))
4753     return Rdx;
4754 
4755   return nullptr;
4756 }
4757 
4758 /// Attempt to reduce a horizontal reduction.
4759 /// If it is legal to match a horizontal reduction feeding the phi node \a P
4760 /// with reduction operators \a Root (or one of its operands) in a basic block
4761 /// \a BB, then check if it can be done. If horizontal reduction is not found
4762 /// and root instruction is a binary operation, vectorization of the operands is
4763 /// attempted.
4764 /// \returns true if a horizontal reduction was matched and reduced or operands
4765 /// of one of the binary instruction were vectorized.
4766 /// \returns false if a horizontal reduction was not matched (or not possible)
4767 /// or no vectorization of any binary operation feeding \a Root instruction was
4768 /// performed.
4769 static bool tryToVectorizeHorReductionOrInstOperands(
4770     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
4771     TargetTransformInfo *TTI,
4772     const function_ref<bool(BinaryOperator *, BoUpSLP &)> Vectorize) {
4773   if (!ShouldVectorizeHor)
4774     return false;
4775 
4776   if (!Root)
4777     return false;
4778 
4779   if (Root->getParent() != BB || isa<PHINode>(Root))
4780     return false;
4781   // Start analysis starting from Root instruction. If horizontal reduction is
4782   // found, try to vectorize it. If it is not a horizontal reduction or
4783   // vectorization is not possible or not effective, and currently analyzed
4784   // instruction is a binary operation, try to vectorize the operands, using
4785   // pre-order DFS traversal order. If the operands were not vectorized, repeat
4786   // the same procedure considering each operand as a possible root of the
4787   // horizontal reduction.
4788   // Interrupt the process if the Root instruction itself was vectorized or all
4789   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
4790   SmallVector<std::pair<WeakTrackingVH, unsigned>, 8> Stack(1, {Root, 0});
4791   SmallSet<Value *, 8> VisitedInstrs;
4792   bool Res = false;
4793   while (!Stack.empty()) {
4794     Value *V;
4795     unsigned Level;
4796     std::tie(V, Level) = Stack.pop_back_val();
4797     if (!V)
4798       continue;
4799     auto *Inst = dyn_cast<Instruction>(V);
4800     if (!Inst)
4801       continue;
4802     if (auto *BI = dyn_cast<BinaryOperator>(Inst)) {
4803       HorizontalReduction HorRdx;
4804       if (HorRdx.matchAssociativeReduction(P, BI)) {
4805         if (HorRdx.tryToReduce(R, TTI)) {
4806           Res = true;
4807           // Set P to nullptr to avoid re-analysis of phi node in
4808           // matchAssociativeReduction function unless this is the root node.
4809           P = nullptr;
4810           continue;
4811         }
4812       }
4813       if (P) {
4814         Inst = dyn_cast<Instruction>(BI->getOperand(0));
4815         if (Inst == P)
4816           Inst = dyn_cast<Instruction>(BI->getOperand(1));
4817         if (!Inst) {
4818           // Set P to nullptr to avoid re-analysis of phi node in
4819           // matchAssociativeReduction function unless this is the root node.
4820           P = nullptr;
4821           continue;
4822         }
4823       }
4824     }
4825     // Set P to nullptr to avoid re-analysis of phi node in
4826     // matchAssociativeReduction function unless this is the root node.
4827     P = nullptr;
4828     if (Vectorize(dyn_cast<BinaryOperator>(Inst), R)) {
4829       Res = true;
4830       continue;
4831     }
4832 
4833     // Try to vectorize operands.
4834     // Continue analysis for the instruction from the same basic block only to
4835     // save compile time.
4836     if (++Level < RecursionMaxDepth)
4837       for (auto *Op : Inst->operand_values())
4838         if (VisitedInstrs.insert(Op).second)
4839           if (auto *I = dyn_cast<Instruction>(Op))
4840             if (!isa<PHINode>(Inst) && I->getParent() == BB)
4841               Stack.emplace_back(Op, Level);
4842   }
4843   return Res;
4844 }
4845 
4846 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
4847                                                  BasicBlock *BB, BoUpSLP &R,
4848                                                  TargetTransformInfo *TTI) {
4849   if (!V)
4850     return false;
4851   auto *I = dyn_cast<Instruction>(V);
4852   if (!I)
4853     return false;
4854 
4855   if (!isa<BinaryOperator>(I))
4856     P = nullptr;
4857   // Try to match and vectorize a horizontal reduction.
4858   return tryToVectorizeHorReductionOrInstOperands(
4859       P, I, BB, R, TTI, [this](BinaryOperator *BI, BoUpSLP &R) -> bool {
4860         return tryToVectorize(BI, R);
4861       });
4862 }
4863 
4864 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
4865   bool Changed = false;
4866   SmallVector<Value *, 4> Incoming;
4867   SmallSet<Value *, 16> VisitedInstrs;
4868 
4869   bool HaveVectorizedPhiNodes = true;
4870   while (HaveVectorizedPhiNodes) {
4871     HaveVectorizedPhiNodes = false;
4872 
4873     // Collect the incoming values from the PHIs.
4874     Incoming.clear();
4875     for (Instruction &I : *BB) {
4876       PHINode *P = dyn_cast<PHINode>(&I);
4877       if (!P)
4878         break;
4879 
4880       if (!VisitedInstrs.count(P))
4881         Incoming.push_back(P);
4882     }
4883 
4884     // Sort by type.
4885     std::stable_sort(Incoming.begin(), Incoming.end(), PhiTypeSorterFunc);
4886 
4887     // Try to vectorize elements base on their type.
4888     for (SmallVector<Value *, 4>::iterator IncIt = Incoming.begin(),
4889                                            E = Incoming.end();
4890          IncIt != E;) {
4891 
4892       // Look for the next elements with the same type.
4893       SmallVector<Value *, 4>::iterator SameTypeIt = IncIt;
4894       while (SameTypeIt != E &&
4895              (*SameTypeIt)->getType() == (*IncIt)->getType()) {
4896         VisitedInstrs.insert(*SameTypeIt);
4897         ++SameTypeIt;
4898       }
4899 
4900       // Try to vectorize them.
4901       unsigned NumElts = (SameTypeIt - IncIt);
4902       DEBUG(errs() << "SLP: Trying to vectorize starting at PHIs (" << NumElts << ")\n");
4903       // The order in which the phi nodes appear in the program does not matter.
4904       // So allow tryToVectorizeList to reorder them if it is beneficial. This
4905       // is done when there are exactly two elements since tryToVectorizeList
4906       // asserts that there are only two values when AllowReorder is true.
4907       bool AllowReorder = NumElts == 2;
4908       if (NumElts > 1 && tryToVectorizeList(makeArrayRef(IncIt, NumElts), R,
4909                                             None, AllowReorder)) {
4910         // Success start over because instructions might have been changed.
4911         HaveVectorizedPhiNodes = true;
4912         Changed = true;
4913         break;
4914       }
4915 
4916       // Start over at the next instruction of a different type (or the end).
4917       IncIt = SameTypeIt;
4918     }
4919   }
4920 
4921   VisitedInstrs.clear();
4922 
4923   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) {
4924     // We may go through BB multiple times so skip the one we have checked.
4925     if (!VisitedInstrs.insert(&*it).second)
4926       continue;
4927 
4928     if (isa<DbgInfoIntrinsic>(it))
4929       continue;
4930 
4931     // Try to vectorize reductions that use PHINodes.
4932     if (PHINode *P = dyn_cast<PHINode>(it)) {
4933       // Check that the PHI is a reduction PHI.
4934       if (P->getNumIncomingValues() != 2)
4935         return Changed;
4936 
4937       // Try to match and vectorize a horizontal reduction.
4938       if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
4939                                    TTI)) {
4940         Changed = true;
4941         it = BB->begin();
4942         e = BB->end();
4943         continue;
4944       }
4945       continue;
4946     }
4947 
4948     if (ShouldStartVectorizeHorAtStore) {
4949       if (StoreInst *SI = dyn_cast<StoreInst>(it)) {
4950         // Try to match and vectorize a horizontal reduction.
4951         if (vectorizeRootInstruction(nullptr, SI->getValueOperand(), BB, R,
4952                                      TTI)) {
4953           Changed = true;
4954           it = BB->begin();
4955           e = BB->end();
4956           continue;
4957         }
4958       }
4959     }
4960 
4961     // Try to vectorize horizontal reductions feeding into a return.
4962     if (ReturnInst *RI = dyn_cast<ReturnInst>(it)) {
4963       if (RI->getNumOperands() != 0) {
4964         // Try to match and vectorize a horizontal reduction.
4965         if (vectorizeRootInstruction(nullptr, RI->getOperand(0), BB, R, TTI)) {
4966           Changed = true;
4967           it = BB->begin();
4968           e = BB->end();
4969           continue;
4970         }
4971       }
4972     }
4973 
4974     // Try to vectorize trees that start at compare instructions.
4975     if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
4976       if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) {
4977         Changed = true;
4978         // We would like to start over since some instructions are deleted
4979         // and the iterator may become invalid value.
4980         it = BB->begin();
4981         e = BB->end();
4982         continue;
4983       }
4984 
4985       for (int I = 0; I < 2; ++I) {
4986         if (vectorizeRootInstruction(nullptr, CI->getOperand(I), BB, R, TTI)) {
4987           Changed = true;
4988           // We would like to start over since some instructions are deleted
4989           // and the iterator may become invalid value.
4990           it = BB->begin();
4991           e = BB->end();
4992           break;
4993         }
4994       }
4995       continue;
4996     }
4997 
4998     // Try to vectorize trees that start at insertelement instructions.
4999     if (InsertElementInst *FirstInsertElem = dyn_cast<InsertElementInst>(it)) {
5000       SmallVector<Value *, 16> BuildVector;
5001       SmallVector<Value *, 16> BuildVectorOpds;
5002       if (!findBuildVector(FirstInsertElem, BuildVector, BuildVectorOpds))
5003         continue;
5004 
5005       // Vectorize starting with the build vector operands ignoring the
5006       // BuildVector instructions for the purpose of scheduling and user
5007       // extraction.
5008       if (tryToVectorizeList(BuildVectorOpds, R, BuildVector)) {
5009         Changed = true;
5010         it = BB->begin();
5011         e = BB->end();
5012       }
5013 
5014       continue;
5015     }
5016 
5017     // Try to vectorize trees that start at insertvalue instructions feeding into
5018     // a store.
5019     if (StoreInst *SI = dyn_cast<StoreInst>(it)) {
5020       if (InsertValueInst *LastInsertValue = dyn_cast<InsertValueInst>(SI->getValueOperand())) {
5021         const DataLayout &DL = BB->getModule()->getDataLayout();
5022         if (R.canMapToVector(SI->getValueOperand()->getType(), DL)) {
5023           SmallVector<Value *, 16> BuildVector;
5024           SmallVector<Value *, 16> BuildVectorOpds;
5025           if (!findBuildAggregate(LastInsertValue, BuildVector, BuildVectorOpds))
5026             continue;
5027 
5028           DEBUG(dbgs() << "SLP: store of array mappable to vector: " << *SI << "\n");
5029           if (tryToVectorizeList(BuildVectorOpds, R, BuildVector, false)) {
5030             Changed = true;
5031             it = BB->begin();
5032             e = BB->end();
5033           }
5034           continue;
5035         }
5036       }
5037     }
5038   }
5039 
5040   return Changed;
5041 }
5042 
5043 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
5044   auto Changed = false;
5045   for (auto &Entry : GEPs) {
5046 
5047     // If the getelementptr list has fewer than two elements, there's nothing
5048     // to do.
5049     if (Entry.second.size() < 2)
5050       continue;
5051 
5052     DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
5053                  << Entry.second.size() << ".\n");
5054 
5055     // We process the getelementptr list in chunks of 16 (like we do for
5056     // stores) to minimize compile-time.
5057     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += 16) {
5058       auto Len = std::min<unsigned>(BE - BI, 16);
5059       auto GEPList = makeArrayRef(&Entry.second[BI], Len);
5060 
5061       // Initialize a set a candidate getelementptrs. Note that we use a
5062       // SetVector here to preserve program order. If the index computations
5063       // are vectorizable and begin with loads, we want to minimize the chance
5064       // of having to reorder them later.
5065       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
5066 
5067       // Some of the candidates may have already been vectorized after we
5068       // initially collected them. If so, the WeakTrackingVHs will have
5069       // nullified the
5070       // values, so remove them from the set of candidates.
5071       Candidates.remove(nullptr);
5072 
5073       // Remove from the set of candidates all pairs of getelementptrs with
5074       // constant differences. Such getelementptrs are likely not good
5075       // candidates for vectorization in a bottom-up phase since one can be
5076       // computed from the other. We also ensure all candidate getelementptr
5077       // indices are unique.
5078       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
5079         auto *GEPI = cast<GetElementPtrInst>(GEPList[I]);
5080         if (!Candidates.count(GEPI))
5081           continue;
5082         auto *SCEVI = SE->getSCEV(GEPList[I]);
5083         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
5084           auto *GEPJ = cast<GetElementPtrInst>(GEPList[J]);
5085           auto *SCEVJ = SE->getSCEV(GEPList[J]);
5086           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
5087             Candidates.remove(GEPList[I]);
5088             Candidates.remove(GEPList[J]);
5089           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
5090             Candidates.remove(GEPList[J]);
5091           }
5092         }
5093       }
5094 
5095       // We break out of the above computation as soon as we know there are
5096       // fewer than two candidates remaining.
5097       if (Candidates.size() < 2)
5098         continue;
5099 
5100       // Add the single, non-constant index of each candidate to the bundle. We
5101       // ensured the indices met these constraints when we originally collected
5102       // the getelementptrs.
5103       SmallVector<Value *, 16> Bundle(Candidates.size());
5104       auto BundleIndex = 0u;
5105       for (auto *V : Candidates) {
5106         auto *GEP = cast<GetElementPtrInst>(V);
5107         auto *GEPIdx = GEP->idx_begin()->get();
5108         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
5109         Bundle[BundleIndex++] = GEPIdx;
5110       }
5111 
5112       // Try and vectorize the indices. We are currently only interested in
5113       // gather-like cases of the form:
5114       //
5115       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
5116       //
5117       // where the loads of "a", the loads of "b", and the subtractions can be
5118       // performed in parallel. It's likely that detecting this pattern in a
5119       // bottom-up phase will be simpler and less costly than building a
5120       // full-blown top-down phase beginning at the consecutive loads.
5121       Changed |= tryToVectorizeList(Bundle, R);
5122     }
5123   }
5124   return Changed;
5125 }
5126 
5127 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
5128   bool Changed = false;
5129   // Attempt to sort and vectorize each of the store-groups.
5130   for (StoreListMap::iterator it = Stores.begin(), e = Stores.end(); it != e;
5131        ++it) {
5132     if (it->second.size() < 2)
5133       continue;
5134 
5135     DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
5136           << it->second.size() << ".\n");
5137 
5138     // Process the stores in chunks of 16.
5139     // TODO: The limit of 16 inhibits greater vectorization factors.
5140     //       For example, AVX2 supports v32i8. Increasing this limit, however,
5141     //       may cause a significant compile-time increase.
5142     for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI+=16) {
5143       unsigned Len = std::min<unsigned>(CE - CI, 16);
5144       Changed |= vectorizeStores(makeArrayRef(&it->second[CI], Len), R);
5145     }
5146   }
5147   return Changed;
5148 }
5149 
5150 char SLPVectorizer::ID = 0;
5151 static const char lv_name[] = "SLP Vectorizer";
5152 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
5153 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
5154 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
5155 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
5156 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
5157 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
5158 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
5159 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
5160 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
5161 
5162 namespace llvm {
5163 Pass *createSLPVectorizerPass() { return new SLPVectorizer(); }
5164 }
5165