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