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