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