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