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