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 <memory>
53 
54 using namespace llvm;
55 
56 #define SV_NAME "slp-vectorizer"
57 #define DEBUG_TYPE "SLP"
58 
59 STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
60 
61 static cl::opt<int>
62     SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
63                      cl::desc("Only vectorize if you gain more than this "
64                               "number "));
65 
66 static cl::opt<bool>
67 ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden,
68                    cl::desc("Attempt to vectorize horizontal reductions"));
69 
70 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
71     "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
72     cl::desc(
73         "Attempt to vectorize horizontal reductions feeding into a store"));
74 
75 static cl::opt<int>
76 MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden,
77     cl::desc("Attempt to vectorize for this register size in bits"));
78 
79 /// Limits the size of scheduling regions in a block.
80 /// It avoid long compile times for _very_ large blocks where vector
81 /// instructions are spread over a wide range.
82 /// This limit is way higher than needed by real-world functions.
83 static cl::opt<int>
84 ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden,
85     cl::desc("Limit the size of the SLP scheduling region per block"));
86 
87 static cl::opt<int> MinVectorRegSizeOption(
88     "slp-min-reg-size", cl::init(128), cl::Hidden,
89     cl::desc("Attempt to vectorize for this register size in bits"));
90 
91 namespace {
92 
93 // FIXME: Set this via cl::opt to allow overriding.
94 static const unsigned RecursionMaxDepth = 12;
95 
96 // Limit the number of alias checks. The limit is chosen so that
97 // it has no negative effect on the llvm benchmarks.
98 static const unsigned AliasedCheckLimit = 10;
99 
100 // Another limit for the alias checks: The maximum distance between load/store
101 // instructions where alias checks are done.
102 // This limit is useful for very large basic blocks.
103 static const unsigned MaxMemDepDistance = 160;
104 
105 /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
106 /// regions to be handled.
107 static const int MinScheduleRegionSize = 16;
108 
109 /// \brief Predicate for the element types that the SLP vectorizer supports.
110 ///
111 /// The most important thing to filter here are types which are invalid in LLVM
112 /// vectors. We also filter target specific types which have absolutely no
113 /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
114 /// avoids spending time checking the cost model and realizing that they will
115 /// be inevitably scalarized.
116 static bool isValidElementType(Type *Ty) {
117   return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() &&
118          !Ty->isPPC_FP128Ty();
119 }
120 
121 /// \returns the parent basic block if all of the instructions in \p VL
122 /// are in the same block or null otherwise.
123 static BasicBlock *getSameBlock(ArrayRef<Value *> VL) {
124   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
125   if (!I0)
126     return nullptr;
127   BasicBlock *BB = I0->getParent();
128   for (int i = 1, e = VL.size(); i < e; i++) {
129     Instruction *I = dyn_cast<Instruction>(VL[i]);
130     if (!I)
131       return nullptr;
132 
133     if (BB != I->getParent())
134       return nullptr;
135   }
136   return BB;
137 }
138 
139 /// \returns True if all of the values in \p VL are constants.
140 static bool allConstant(ArrayRef<Value *> VL) {
141   for (unsigned i = 0, e = VL.size(); i < e; ++i)
142     if (!isa<Constant>(VL[i]))
143       return false;
144   return true;
145 }
146 
147 /// \returns True if all of the values in \p VL are identical.
148 static bool isSplat(ArrayRef<Value *> VL) {
149   for (unsigned i = 1, e = VL.size(); i < e; ++i)
150     if (VL[i] != VL[0])
151       return false;
152   return true;
153 }
154 
155 ///\returns Opcode that can be clubbed with \p Op to create an alternate
156 /// sequence which can later be merged as a ShuffleVector instruction.
157 static unsigned getAltOpcode(unsigned Op) {
158   switch (Op) {
159   case Instruction::FAdd:
160     return Instruction::FSub;
161   case Instruction::FSub:
162     return Instruction::FAdd;
163   case Instruction::Add:
164     return Instruction::Sub;
165   case Instruction::Sub:
166     return Instruction::Add;
167   default:
168     return 0;
169   }
170 }
171 
172 ///\returns bool representing if Opcode \p Op can be part
173 /// of an alternate sequence which can later be merged as
174 /// a ShuffleVector instruction.
175 static bool canCombineAsAltInst(unsigned Op) {
176   return Op == Instruction::FAdd || Op == Instruction::FSub ||
177          Op == Instruction::Sub || Op == Instruction::Add;
178 }
179 
180 /// \returns ShuffleVector instruction if instructions in \p VL have
181 ///  alternate fadd,fsub / fsub,fadd/add,sub/sub,add sequence.
182 /// (i.e. e.g. opcodes of fadd,fsub,fadd,fsub...)
183 static unsigned isAltInst(ArrayRef<Value *> VL) {
184   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
185   unsigned Opcode = I0->getOpcode();
186   unsigned AltOpcode = getAltOpcode(Opcode);
187   for (int i = 1, e = VL.size(); i < e; i++) {
188     Instruction *I = dyn_cast<Instruction>(VL[i]);
189     if (!I || I->getOpcode() != ((i & 1) ? AltOpcode : Opcode))
190       return 0;
191   }
192   return Instruction::ShuffleVector;
193 }
194 
195 /// \returns The opcode if all of the Instructions in \p VL have the same
196 /// opcode, or zero.
197 static unsigned getSameOpcode(ArrayRef<Value *> VL) {
198   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
199   if (!I0)
200     return 0;
201   unsigned Opcode = I0->getOpcode();
202   for (int i = 1, e = VL.size(); i < e; i++) {
203     Instruction *I = dyn_cast<Instruction>(VL[i]);
204     if (!I || Opcode != I->getOpcode()) {
205       if (canCombineAsAltInst(Opcode) && i == 1)
206         return isAltInst(VL);
207       return 0;
208     }
209   }
210   return Opcode;
211 }
212 
213 /// Get the intersection (logical and) of all of the potential IR flags
214 /// of each scalar operation (VL) that will be converted into a vector (I).
215 /// Flag set: NSW, NUW, exact, and all of fast-math.
216 static void propagateIRFlags(Value *I, ArrayRef<Value *> VL) {
217   if (auto *VecOp = dyn_cast<BinaryOperator>(I)) {
218     if (auto *Intersection = dyn_cast<BinaryOperator>(VL[0])) {
219       // Intersection is initialized to the 0th scalar,
220       // so start counting from index '1'.
221       for (int i = 1, e = VL.size(); i < e; ++i) {
222         if (auto *Scalar = dyn_cast<BinaryOperator>(VL[i]))
223           Intersection->andIRFlags(Scalar);
224       }
225       VecOp->copyIRFlags(Intersection);
226     }
227   }
228 }
229 
230 /// \returns \p I after propagating metadata from \p VL.
231 static Instruction *propagateMetadata(Instruction *I, ArrayRef<Value *> VL) {
232   Instruction *I0 = cast<Instruction>(VL[0]);
233   SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
234   I0->getAllMetadataOtherThanDebugLoc(Metadata);
235 
236   for (unsigned i = 0, n = Metadata.size(); i != n; ++i) {
237     unsigned Kind = Metadata[i].first;
238     MDNode *MD = Metadata[i].second;
239 
240     for (int i = 1, e = VL.size(); MD && i != e; i++) {
241       Instruction *I = cast<Instruction>(VL[i]);
242       MDNode *IMD = I->getMetadata(Kind);
243 
244       switch (Kind) {
245       default:
246         MD = nullptr; // Remove unknown metadata
247         break;
248       case LLVMContext::MD_tbaa:
249         MD = MDNode::getMostGenericTBAA(MD, IMD);
250         break;
251       case LLVMContext::MD_alias_scope:
252         MD = MDNode::getMostGenericAliasScope(MD, IMD);
253         break;
254       case LLVMContext::MD_noalias:
255         MD = MDNode::intersect(MD, IMD);
256         break;
257       case LLVMContext::MD_fpmath:
258         MD = MDNode::getMostGenericFPMath(MD, IMD);
259         break;
260       case LLVMContext::MD_nontemporal:
261         MD = MDNode::intersect(MD, IMD);
262         break;
263       }
264     }
265     I->setMetadata(Kind, MD);
266   }
267   return I;
268 }
269 
270 /// \returns The type that all of the values in \p VL have or null if there
271 /// are different types.
272 static Type* getSameType(ArrayRef<Value *> VL) {
273   Type *Ty = VL[0]->getType();
274   for (int i = 1, e = VL.size(); i < e; i++)
275     if (VL[i]->getType() != Ty)
276       return nullptr;
277 
278   return Ty;
279 }
280 
281 /// \returns True if the ExtractElement instructions in VL can be vectorized
282 /// to use the original vector.
283 static bool CanReuseExtract(ArrayRef<Value *> VL) {
284   assert(Instruction::ExtractElement == getSameOpcode(VL) && "Invalid opcode");
285   // Check if all of the extracts come from the same vector and from the
286   // correct offset.
287   Value *VL0 = VL[0];
288   ExtractElementInst *E0 = cast<ExtractElementInst>(VL0);
289   Value *Vec = E0->getOperand(0);
290 
291   // We have to extract from the same vector type.
292   unsigned NElts = Vec->getType()->getVectorNumElements();
293 
294   if (NElts != VL.size())
295     return false;
296 
297   // Check that all of the indices extract from the correct offset.
298   ConstantInt *CI = dyn_cast<ConstantInt>(E0->getOperand(1));
299   if (!CI || CI->getZExtValue())
300     return false;
301 
302   for (unsigned i = 1, e = VL.size(); i < e; ++i) {
303     ExtractElementInst *E = cast<ExtractElementInst>(VL[i]);
304     ConstantInt *CI = dyn_cast<ConstantInt>(E->getOperand(1));
305 
306     if (!CI || CI->getZExtValue() != i || E->getOperand(0) != Vec)
307       return false;
308   }
309 
310   return true;
311 }
312 
313 /// \returns True if in-tree use also needs extract. This refers to
314 /// possible scalar operand in vectorized instruction.
315 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
316                                     TargetLibraryInfo *TLI) {
317 
318   unsigned Opcode = UserInst->getOpcode();
319   switch (Opcode) {
320   case Instruction::Load: {
321     LoadInst *LI = cast<LoadInst>(UserInst);
322     return (LI->getPointerOperand() == Scalar);
323   }
324   case Instruction::Store: {
325     StoreInst *SI = cast<StoreInst>(UserInst);
326     return (SI->getPointerOperand() == Scalar);
327   }
328   case Instruction::Call: {
329     CallInst *CI = cast<CallInst>(UserInst);
330     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
331     if (hasVectorInstrinsicScalarOpd(ID, 1)) {
332       return (CI->getArgOperand(1) == Scalar);
333     }
334   }
335   default:
336     return false;
337   }
338 }
339 
340 /// \returns the AA location that is being access by the instruction.
341 static MemoryLocation getLocation(Instruction *I, AliasAnalysis *AA) {
342   if (StoreInst *SI = dyn_cast<StoreInst>(I))
343     return MemoryLocation::get(SI);
344   if (LoadInst *LI = dyn_cast<LoadInst>(I))
345     return MemoryLocation::get(LI);
346   return MemoryLocation();
347 }
348 
349 /// \returns True if the instruction is not a volatile or atomic load/store.
350 static bool isSimple(Instruction *I) {
351   if (LoadInst *LI = dyn_cast<LoadInst>(I))
352     return LI->isSimple();
353   if (StoreInst *SI = dyn_cast<StoreInst>(I))
354     return SI->isSimple();
355   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
356     return !MI->isVolatile();
357   return true;
358 }
359 
360 /// Bottom Up SLP Vectorizer.
361 class BoUpSLP {
362 public:
363   typedef SmallVector<Value *, 8> ValueList;
364   typedef SmallVector<Instruction *, 16> InstrList;
365   typedef SmallPtrSet<Value *, 16> ValueSet;
366   typedef SmallVector<StoreInst *, 8> StoreList;
367 
368   BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
369           TargetLibraryInfo *TLi, AliasAnalysis *Aa, LoopInfo *Li,
370           DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB,
371           const DataLayout *DL)
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         DL(DL), 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   const DataLayout *DL;
929   /// Instruction builder to construct the vectorized tree.
930   IRBuilder<> Builder;
931 
932   /// A map of scalar integer values to the smallest bit width with which they
933   /// can legally be represented.
934   MapVector<Value *, uint64_t> MinBWs;
935 };
936 
937 #ifndef NDEBUG
938 raw_ostream &operator<<(raw_ostream &os, const BoUpSLP::ScheduleData &SD) {
939   SD.dump(os);
940   return os;
941 }
942 #endif
943 
944 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
945                         ArrayRef<Value *> UserIgnoreLst) {
946   deleteTree();
947   UserIgnoreList = UserIgnoreLst;
948   if (!getSameType(Roots))
949     return;
950   buildTree_rec(Roots, 0);
951 
952   // Collect the values that we need to extract from the tree.
953   for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
954     TreeEntry *Entry = &VectorizableTree[EIdx];
955 
956     // For each lane:
957     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
958       Value *Scalar = Entry->Scalars[Lane];
959 
960       // No need to handle users of gathered values.
961       if (Entry->NeedToGather)
962         continue;
963 
964       for (User *U : Scalar->users()) {
965         DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
966 
967         Instruction *UserInst = dyn_cast<Instruction>(U);
968         if (!UserInst)
969           continue;
970 
971         // Skip in-tree scalars that become vectors
972         if (ScalarToTreeEntry.count(U)) {
973           int Idx = ScalarToTreeEntry[U];
974           TreeEntry *UseEntry = &VectorizableTree[Idx];
975           Value *UseScalar = UseEntry->Scalars[0];
976           // Some in-tree scalars will remain as scalar in vectorized
977           // instructions. If that is the case, the one in Lane 0 will
978           // be used.
979           if (UseScalar != U ||
980               !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
981             DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
982                          << ".\n");
983             assert(!VectorizableTree[Idx].NeedToGather && "Bad state");
984             continue;
985           }
986         }
987 
988         // Ignore users in the user ignore list.
989         if (std::find(UserIgnoreList.begin(), UserIgnoreList.end(), UserInst) !=
990             UserIgnoreList.end())
991           continue;
992 
993         DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane " <<
994               Lane << " from " << *Scalar << ".\n");
995         ExternalUses.push_back(ExternalUser(Scalar, U, Lane));
996       }
997     }
998   }
999 }
1000 
1001 
1002 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth) {
1003   bool SameTy = getSameType(VL); (void)SameTy;
1004   bool isAltShuffle = false;
1005   assert(SameTy && "Invalid types!");
1006 
1007   if (Depth == RecursionMaxDepth) {
1008     DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
1009     newTreeEntry(VL, false);
1010     return;
1011   }
1012 
1013   // Don't handle vectors.
1014   if (VL[0]->getType()->isVectorTy()) {
1015     DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
1016     newTreeEntry(VL, false);
1017     return;
1018   }
1019 
1020   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1021     if (SI->getValueOperand()->getType()->isVectorTy()) {
1022       DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
1023       newTreeEntry(VL, false);
1024       return;
1025     }
1026   unsigned Opcode = getSameOpcode(VL);
1027 
1028   // Check that this shuffle vector refers to the alternate
1029   // sequence of opcodes.
1030   if (Opcode == Instruction::ShuffleVector) {
1031     Instruction *I0 = dyn_cast<Instruction>(VL[0]);
1032     unsigned Op = I0->getOpcode();
1033     if (Op != Instruction::ShuffleVector)
1034       isAltShuffle = true;
1035   }
1036 
1037   // If all of the operands are identical or constant we have a simple solution.
1038   if (allConstant(VL) || isSplat(VL) || !getSameBlock(VL) || !Opcode) {
1039     DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
1040     newTreeEntry(VL, false);
1041     return;
1042   }
1043 
1044   // We now know that this is a vector of instructions of the same type from
1045   // the same block.
1046 
1047   // Don't vectorize ephemeral values.
1048   for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1049     if (EphValues.count(VL[i])) {
1050       DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
1051             ") is ephemeral.\n");
1052       newTreeEntry(VL, false);
1053       return;
1054     }
1055   }
1056 
1057   // Check if this is a duplicate of another entry.
1058   if (ScalarToTreeEntry.count(VL[0])) {
1059     int Idx = ScalarToTreeEntry[VL[0]];
1060     TreeEntry *E = &VectorizableTree[Idx];
1061     for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1062       DEBUG(dbgs() << "SLP: \tChecking bundle: " << *VL[i] << ".\n");
1063       if (E->Scalars[i] != VL[i]) {
1064         DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
1065         newTreeEntry(VL, false);
1066         return;
1067       }
1068     }
1069     DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *VL[0] << ".\n");
1070     return;
1071   }
1072 
1073   // Check that none of the instructions in the bundle are already in the tree.
1074   for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1075     if (ScalarToTreeEntry.count(VL[i])) {
1076       DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
1077             ") is already in tree.\n");
1078       newTreeEntry(VL, false);
1079       return;
1080     }
1081   }
1082 
1083   // If any of the scalars is marked as a value that needs to stay scalar then
1084   // we need to gather the scalars.
1085   for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1086     if (MustGather.count(VL[i])) {
1087       DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
1088       newTreeEntry(VL, false);
1089       return;
1090     }
1091   }
1092 
1093   // Check that all of the users of the scalars that we want to vectorize are
1094   // schedulable.
1095   Instruction *VL0 = cast<Instruction>(VL[0]);
1096   BasicBlock *BB = cast<Instruction>(VL0)->getParent();
1097 
1098   if (!DT->isReachableFromEntry(BB)) {
1099     // Don't go into unreachable blocks. They may contain instructions with
1100     // dependency cycles which confuse the final scheduling.
1101     DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
1102     newTreeEntry(VL, false);
1103     return;
1104   }
1105 
1106   // Check that every instructions appears once in this bundle.
1107   for (unsigned i = 0, e = VL.size(); i < e; ++i)
1108     for (unsigned j = i+1; j < e; ++j)
1109       if (VL[i] == VL[j]) {
1110         DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
1111         newTreeEntry(VL, false);
1112         return;
1113       }
1114 
1115   auto &BSRef = BlocksSchedules[BB];
1116   if (!BSRef) {
1117     BSRef = llvm::make_unique<BlockScheduling>(BB);
1118   }
1119   BlockScheduling &BS = *BSRef.get();
1120 
1121   if (!BS.tryScheduleBundle(VL, this)) {
1122     DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
1123     assert((!BS.getScheduleData(VL[0]) ||
1124             !BS.getScheduleData(VL[0])->isPartOfBundle()) &&
1125            "tryScheduleBundle should cancelScheduling on failure");
1126     newTreeEntry(VL, false);
1127     return;
1128   }
1129   DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
1130 
1131   switch (Opcode) {
1132     case Instruction::PHI: {
1133       PHINode *PH = dyn_cast<PHINode>(VL0);
1134 
1135       // Check for terminator values (e.g. invoke).
1136       for (unsigned j = 0; j < VL.size(); ++j)
1137         for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1138           TerminatorInst *Term = dyn_cast<TerminatorInst>(
1139               cast<PHINode>(VL[j])->getIncomingValueForBlock(PH->getIncomingBlock(i)));
1140           if (Term) {
1141             DEBUG(dbgs() << "SLP: Need to swizzle PHINodes (TerminatorInst use).\n");
1142             BS.cancelScheduling(VL);
1143             newTreeEntry(VL, false);
1144             return;
1145           }
1146         }
1147 
1148       newTreeEntry(VL, true);
1149       DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
1150 
1151       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1152         ValueList Operands;
1153         // Prepare the operand vector.
1154         for (unsigned j = 0; j < VL.size(); ++j)
1155           Operands.push_back(cast<PHINode>(VL[j])->getIncomingValueForBlock(
1156               PH->getIncomingBlock(i)));
1157 
1158         buildTree_rec(Operands, Depth + 1);
1159       }
1160       return;
1161     }
1162     case Instruction::ExtractElement: {
1163       bool Reuse = CanReuseExtract(VL);
1164       if (Reuse) {
1165         DEBUG(dbgs() << "SLP: Reusing extract sequence.\n");
1166       } else {
1167         BS.cancelScheduling(VL);
1168       }
1169       newTreeEntry(VL, Reuse);
1170       return;
1171     }
1172     case Instruction::Load: {
1173       // Check that a vectorized load would load the same memory as a scalar
1174       // load.
1175       // For example we don't want vectorize loads that are smaller than 8 bit.
1176       // Even though we have a packed struct {<i2, i2, i2, i2>} LLVM treats
1177       // loading/storing it as an i8 struct. If we vectorize loads/stores from
1178       // such a struct we read/write packed bits disagreeing with the
1179       // unvectorized version.
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       // Check if the stores are consecutive or of we need to swizzle them.
1370       for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
1371         if (!isConsecutiveAccess(VL[i], VL[i + 1], *DL, *SE)) {
1372           BS.cancelScheduling(VL);
1373           newTreeEntry(VL, false);
1374           DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
1375           return;
1376         }
1377 
1378       newTreeEntry(VL, true);
1379       DEBUG(dbgs() << "SLP: added a vector of stores.\n");
1380 
1381       ValueList Operands;
1382       for (unsigned j = 0; j < VL.size(); ++j)
1383         Operands.push_back(cast<Instruction>(VL[j])->getOperand(0));
1384 
1385       buildTree_rec(Operands, Depth + 1);
1386       return;
1387     }
1388     case Instruction::Call: {
1389       // Check if the calls are all to the same vectorizable intrinsic.
1390       CallInst *CI = cast<CallInst>(VL[0]);
1391       // Check if this is an Intrinsic call or something that can be
1392       // represented by an intrinsic call
1393       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
1394       if (!isTriviallyVectorizable(ID)) {
1395         BS.cancelScheduling(VL);
1396         newTreeEntry(VL, false);
1397         DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
1398         return;
1399       }
1400       Function *Int = CI->getCalledFunction();
1401       Value *A1I = nullptr;
1402       if (hasVectorInstrinsicScalarOpd(ID, 1))
1403         A1I = CI->getArgOperand(1);
1404       for (unsigned i = 1, e = VL.size(); i != e; ++i) {
1405         CallInst *CI2 = dyn_cast<CallInst>(VL[i]);
1406         if (!CI2 || CI2->getCalledFunction() != Int ||
1407             getVectorIntrinsicIDForCall(CI2, TLI) != ID) {
1408           BS.cancelScheduling(VL);
1409           newTreeEntry(VL, false);
1410           DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *VL[i]
1411                        << "\n");
1412           return;
1413         }
1414         // ctlz,cttz and powi are special intrinsics whose second argument
1415         // should be same in order for them to be vectorized.
1416         if (hasVectorInstrinsicScalarOpd(ID, 1)) {
1417           Value *A1J = CI2->getArgOperand(1);
1418           if (A1I != A1J) {
1419             BS.cancelScheduling(VL);
1420             newTreeEntry(VL, false);
1421             DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
1422                          << " argument "<< A1I<<"!=" << A1J
1423                          << "\n");
1424             return;
1425           }
1426         }
1427       }
1428 
1429       newTreeEntry(VL, true);
1430       for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i) {
1431         ValueList Operands;
1432         // Prepare the operand vector.
1433         for (unsigned j = 0; j < VL.size(); ++j) {
1434           CallInst *CI2 = dyn_cast<CallInst>(VL[j]);
1435           Operands.push_back(CI2->getArgOperand(i));
1436         }
1437         buildTree_rec(Operands, Depth + 1);
1438       }
1439       return;
1440     }
1441     case Instruction::ShuffleVector: {
1442       // If this is not an alternate sequence of opcode like add-sub
1443       // then do not vectorize this instruction.
1444       if (!isAltShuffle) {
1445         BS.cancelScheduling(VL);
1446         newTreeEntry(VL, false);
1447         DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
1448         return;
1449       }
1450       newTreeEntry(VL, true);
1451       DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
1452 
1453       // Reorder operands if reordering would enable vectorization.
1454       if (isa<BinaryOperator>(VL0)) {
1455         ValueList Left, Right;
1456         reorderAltShuffleOperands(VL, Left, Right);
1457         buildTree_rec(Left, Depth + 1);
1458         buildTree_rec(Right, Depth + 1);
1459         return;
1460       }
1461 
1462       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1463         ValueList Operands;
1464         // Prepare the operand vector.
1465         for (unsigned j = 0; j < VL.size(); ++j)
1466           Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1467 
1468         buildTree_rec(Operands, Depth + 1);
1469       }
1470       return;
1471     }
1472     default:
1473       BS.cancelScheduling(VL);
1474       newTreeEntry(VL, false);
1475       DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
1476       return;
1477   }
1478 }
1479 
1480 int BoUpSLP::getEntryCost(TreeEntry *E) {
1481   ArrayRef<Value*> VL = E->Scalars;
1482 
1483   Type *ScalarTy = VL[0]->getType();
1484   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1485     ScalarTy = SI->getValueOperand()->getType();
1486   VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1487 
1488   // If we have computed a smaller type for the expression, update VecTy so
1489   // that the costs will be accurate.
1490   if (MinBWs.count(VL[0]))
1491     VecTy = VectorType::get(IntegerType::get(F->getContext(), MinBWs[VL[0]]),
1492                             VL.size());
1493 
1494   if (E->NeedToGather) {
1495     if (allConstant(VL))
1496       return 0;
1497     if (isSplat(VL)) {
1498       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
1499     }
1500     return getGatherCost(E->Scalars);
1501   }
1502   unsigned Opcode = getSameOpcode(VL);
1503   assert(Opcode && getSameType(VL) && getSameBlock(VL) && "Invalid VL");
1504   Instruction *VL0 = cast<Instruction>(VL[0]);
1505   switch (Opcode) {
1506     case Instruction::PHI: {
1507       return 0;
1508     }
1509     case Instruction::ExtractElement: {
1510       if (CanReuseExtract(VL)) {
1511         int DeadCost = 0;
1512         for (unsigned i = 0, e = VL.size(); i < e; ++i) {
1513           ExtractElementInst *E = cast<ExtractElementInst>(VL[i]);
1514           if (E->hasOneUse())
1515             // Take credit for instruction that will become dead.
1516             DeadCost +=
1517                 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, i);
1518         }
1519         return -DeadCost;
1520       }
1521       return getGatherCost(VecTy);
1522     }
1523     case Instruction::ZExt:
1524     case Instruction::SExt:
1525     case Instruction::FPToUI:
1526     case Instruction::FPToSI:
1527     case Instruction::FPExt:
1528     case Instruction::PtrToInt:
1529     case Instruction::IntToPtr:
1530     case Instruction::SIToFP:
1531     case Instruction::UIToFP:
1532     case Instruction::Trunc:
1533     case Instruction::FPTrunc:
1534     case Instruction::BitCast: {
1535       Type *SrcTy = VL0->getOperand(0)->getType();
1536 
1537       // Calculate the cost of this instruction.
1538       int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(),
1539                                                          VL0->getType(), SrcTy);
1540 
1541       VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
1542       int VecCost = TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy);
1543       return VecCost - ScalarCost;
1544     }
1545     case Instruction::FCmp:
1546     case Instruction::ICmp:
1547     case Instruction::Select:
1548     case Instruction::Add:
1549     case Instruction::FAdd:
1550     case Instruction::Sub:
1551     case Instruction::FSub:
1552     case Instruction::Mul:
1553     case Instruction::FMul:
1554     case Instruction::UDiv:
1555     case Instruction::SDiv:
1556     case Instruction::FDiv:
1557     case Instruction::URem:
1558     case Instruction::SRem:
1559     case Instruction::FRem:
1560     case Instruction::Shl:
1561     case Instruction::LShr:
1562     case Instruction::AShr:
1563     case Instruction::And:
1564     case Instruction::Or:
1565     case Instruction::Xor: {
1566       // Calculate the cost of this instruction.
1567       int ScalarCost = 0;
1568       int VecCost = 0;
1569       if (Opcode == Instruction::FCmp || Opcode == Instruction::ICmp ||
1570           Opcode == Instruction::Select) {
1571         VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
1572         ScalarCost = VecTy->getNumElements() *
1573         TTI->getCmpSelInstrCost(Opcode, ScalarTy, Builder.getInt1Ty());
1574         VecCost = TTI->getCmpSelInstrCost(Opcode, VecTy, MaskTy);
1575       } else {
1576         // Certain instructions can be cheaper to vectorize if they have a
1577         // constant second vector operand.
1578         TargetTransformInfo::OperandValueKind Op1VK =
1579             TargetTransformInfo::OK_AnyValue;
1580         TargetTransformInfo::OperandValueKind Op2VK =
1581             TargetTransformInfo::OK_UniformConstantValue;
1582         TargetTransformInfo::OperandValueProperties Op1VP =
1583             TargetTransformInfo::OP_None;
1584         TargetTransformInfo::OperandValueProperties Op2VP =
1585             TargetTransformInfo::OP_None;
1586 
1587         // If all operands are exactly the same ConstantInt then set the
1588         // operand kind to OK_UniformConstantValue.
1589         // If instead not all operands are constants, then set the operand kind
1590         // to OK_AnyValue. If all operands are constants but not the same,
1591         // then set the operand kind to OK_NonUniformConstantValue.
1592         ConstantInt *CInt = nullptr;
1593         for (unsigned i = 0; i < VL.size(); ++i) {
1594           const Instruction *I = cast<Instruction>(VL[i]);
1595           if (!isa<ConstantInt>(I->getOperand(1))) {
1596             Op2VK = TargetTransformInfo::OK_AnyValue;
1597             break;
1598           }
1599           if (i == 0) {
1600             CInt = cast<ConstantInt>(I->getOperand(1));
1601             continue;
1602           }
1603           if (Op2VK == TargetTransformInfo::OK_UniformConstantValue &&
1604               CInt != cast<ConstantInt>(I->getOperand(1)))
1605             Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
1606         }
1607         // FIXME: Currently cost of model modification for division by power of
1608         // 2 is handled for X86 and AArch64. Add support for other targets.
1609         if (Op2VK == TargetTransformInfo::OK_UniformConstantValue && CInt &&
1610             CInt->getValue().isPowerOf2())
1611           Op2VP = TargetTransformInfo::OP_PowerOf2;
1612 
1613         ScalarCost = VecTy->getNumElements() *
1614                      TTI->getArithmeticInstrCost(Opcode, ScalarTy, Op1VK, Op2VK,
1615                                                  Op1VP, Op2VP);
1616         VecCost = TTI->getArithmeticInstrCost(Opcode, VecTy, Op1VK, Op2VK,
1617                                               Op1VP, Op2VP);
1618       }
1619       return VecCost - ScalarCost;
1620     }
1621     case Instruction::GetElementPtr: {
1622       TargetTransformInfo::OperandValueKind Op1VK =
1623           TargetTransformInfo::OK_AnyValue;
1624       TargetTransformInfo::OperandValueKind Op2VK =
1625           TargetTransformInfo::OK_UniformConstantValue;
1626 
1627       int ScalarCost =
1628           VecTy->getNumElements() *
1629           TTI->getArithmeticInstrCost(Instruction::Add, ScalarTy, Op1VK, Op2VK);
1630       int VecCost =
1631           TTI->getArithmeticInstrCost(Instruction::Add, VecTy, Op1VK, Op2VK);
1632 
1633       return VecCost - ScalarCost;
1634     }
1635     case Instruction::Load: {
1636       // Cost of wide load - cost of scalar loads.
1637       int ScalarLdCost = VecTy->getNumElements() *
1638       TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
1639       int VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, 1, 0);
1640       return VecLdCost - ScalarLdCost;
1641     }
1642     case Instruction::Store: {
1643       // We know that we can merge the stores. Calculate the cost.
1644       int ScalarStCost = VecTy->getNumElements() *
1645       TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
1646       int VecStCost = TTI->getMemoryOpCost(Instruction::Store, VecTy, 1, 0);
1647       return VecStCost - ScalarStCost;
1648     }
1649     case Instruction::Call: {
1650       CallInst *CI = cast<CallInst>(VL0);
1651       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
1652 
1653       // Calculate the cost of the scalar and vector calls.
1654       SmallVector<Type*, 4> ScalarTys, VecTys;
1655       for (unsigned op = 0, opc = CI->getNumArgOperands(); op!= opc; ++op) {
1656         ScalarTys.push_back(CI->getArgOperand(op)->getType());
1657         VecTys.push_back(VectorType::get(CI->getArgOperand(op)->getType(),
1658                                          VecTy->getNumElements()));
1659       }
1660 
1661       FastMathFlags FMF;
1662       if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
1663         FMF = FPMO->getFastMathFlags();
1664 
1665       int ScalarCallCost = VecTy->getNumElements() *
1666           TTI->getIntrinsicInstrCost(ID, ScalarTy, ScalarTys, FMF);
1667 
1668       int VecCallCost = TTI->getIntrinsicInstrCost(ID, VecTy, VecTys, FMF);
1669 
1670       DEBUG(dbgs() << "SLP: Call cost "<< VecCallCost - ScalarCallCost
1671             << " (" << VecCallCost  << "-" <<  ScalarCallCost << ")"
1672             << " for " << *CI << "\n");
1673 
1674       return VecCallCost - ScalarCallCost;
1675     }
1676     case Instruction::ShuffleVector: {
1677       TargetTransformInfo::OperandValueKind Op1VK =
1678           TargetTransformInfo::OK_AnyValue;
1679       TargetTransformInfo::OperandValueKind Op2VK =
1680           TargetTransformInfo::OK_AnyValue;
1681       int ScalarCost = 0;
1682       int VecCost = 0;
1683       for (unsigned i = 0; i < VL.size(); ++i) {
1684         Instruction *I = cast<Instruction>(VL[i]);
1685         if (!I)
1686           break;
1687         ScalarCost +=
1688             TTI->getArithmeticInstrCost(I->getOpcode(), ScalarTy, Op1VK, Op2VK);
1689       }
1690       // VecCost is equal to sum of the cost of creating 2 vectors
1691       // and the cost of creating shuffle.
1692       Instruction *I0 = cast<Instruction>(VL[0]);
1693       VecCost =
1694           TTI->getArithmeticInstrCost(I0->getOpcode(), VecTy, Op1VK, Op2VK);
1695       Instruction *I1 = cast<Instruction>(VL[1]);
1696       VecCost +=
1697           TTI->getArithmeticInstrCost(I1->getOpcode(), VecTy, Op1VK, Op2VK);
1698       VecCost +=
1699           TTI->getShuffleCost(TargetTransformInfo::SK_Alternate, VecTy, 0);
1700       return VecCost - ScalarCost;
1701     }
1702     default:
1703       llvm_unreachable("Unknown instruction");
1704   }
1705 }
1706 
1707 bool BoUpSLP::isFullyVectorizableTinyTree() {
1708   DEBUG(dbgs() << "SLP: Check whether the tree with height " <<
1709         VectorizableTree.size() << " is fully vectorizable .\n");
1710 
1711   // We only handle trees of height 2.
1712   if (VectorizableTree.size() != 2)
1713     return false;
1714 
1715   // Handle splat and all-constants stores.
1716   if (!VectorizableTree[0].NeedToGather &&
1717       (allConstant(VectorizableTree[1].Scalars) ||
1718        isSplat(VectorizableTree[1].Scalars)))
1719     return true;
1720 
1721   // Gathering cost would be too much for tiny trees.
1722   if (VectorizableTree[0].NeedToGather || VectorizableTree[1].NeedToGather)
1723     return false;
1724 
1725   return true;
1726 }
1727 
1728 int BoUpSLP::getSpillCost() {
1729   // Walk from the bottom of the tree to the top, tracking which values are
1730   // live. When we see a call instruction that is not part of our tree,
1731   // query TTI to see if there is a cost to keeping values live over it
1732   // (for example, if spills and fills are required).
1733   unsigned BundleWidth = VectorizableTree.front().Scalars.size();
1734   int Cost = 0;
1735 
1736   SmallPtrSet<Instruction*, 4> LiveValues;
1737   Instruction *PrevInst = nullptr;
1738 
1739   for (unsigned N = 0; N < VectorizableTree.size(); ++N) {
1740     Instruction *Inst = dyn_cast<Instruction>(VectorizableTree[N].Scalars[0]);
1741     if (!Inst)
1742       continue;
1743 
1744     if (!PrevInst) {
1745       PrevInst = Inst;
1746       continue;
1747     }
1748 
1749     // Update LiveValues.
1750     LiveValues.erase(PrevInst);
1751     for (auto &J : PrevInst->operands()) {
1752       if (isa<Instruction>(&*J) && ScalarToTreeEntry.count(&*J))
1753         LiveValues.insert(cast<Instruction>(&*J));
1754     }
1755 
1756     DEBUG(
1757       dbgs() << "SLP: #LV: " << LiveValues.size();
1758       for (auto *X : LiveValues)
1759         dbgs() << " " << X->getName();
1760       dbgs() << ", Looking at ";
1761       Inst->dump();
1762       );
1763 
1764     // Now find the sequence of instructions between PrevInst and Inst.
1765     BasicBlock::reverse_iterator InstIt(Inst->getIterator()),
1766         PrevInstIt(PrevInst->getIterator());
1767     --PrevInstIt;
1768     while (InstIt != PrevInstIt) {
1769       if (PrevInstIt == PrevInst->getParent()->rend()) {
1770         PrevInstIt = Inst->getParent()->rbegin();
1771         continue;
1772       }
1773 
1774       if (isa<CallInst>(&*PrevInstIt) && &*PrevInstIt != PrevInst) {
1775         SmallVector<Type*, 4> V;
1776         for (auto *II : LiveValues)
1777           V.push_back(VectorType::get(II->getType(), BundleWidth));
1778         Cost += TTI->getCostOfKeepingLiveOverCall(V);
1779       }
1780 
1781       ++PrevInstIt;
1782     }
1783 
1784     PrevInst = Inst;
1785   }
1786 
1787   return Cost;
1788 }
1789 
1790 int BoUpSLP::getTreeCost() {
1791   int Cost = 0;
1792   DEBUG(dbgs() << "SLP: Calculating cost for tree of size " <<
1793         VectorizableTree.size() << ".\n");
1794 
1795   // We only vectorize tiny trees if it is fully vectorizable.
1796   if (VectorizableTree.size() < 3 && !isFullyVectorizableTinyTree()) {
1797     if (VectorizableTree.empty()) {
1798       assert(!ExternalUses.size() && "We should not have any external users");
1799     }
1800     return INT_MAX;
1801   }
1802 
1803   unsigned BundleWidth = VectorizableTree[0].Scalars.size();
1804 
1805   for (TreeEntry &TE : VectorizableTree) {
1806     int C = getEntryCost(&TE);
1807     DEBUG(dbgs() << "SLP: Adding cost " << C << " for bundle that starts with "
1808                  << *TE.Scalars[0] << ".\n");
1809     Cost += C;
1810   }
1811 
1812   SmallSet<Value *, 16> ExtractCostCalculated;
1813   int ExtractCost = 0;
1814   for (ExternalUser &EU : ExternalUses) {
1815     // We only add extract cost once for the same scalar.
1816     if (!ExtractCostCalculated.insert(EU.Scalar).second)
1817       continue;
1818 
1819     // Uses by ephemeral values are free (because the ephemeral value will be
1820     // removed prior to code generation, and so the extraction will be
1821     // removed as well).
1822     if (EphValues.count(EU.User))
1823       continue;
1824 
1825     // If we plan to rewrite the tree in a smaller type, we will need to sign
1826     // extend the extracted value back to the original type. Here, we account
1827     // for the extract and the added cost of the sign extend if needed.
1828     auto *VecTy = VectorType::get(EU.Scalar->getType(), BundleWidth);
1829     auto *ScalarRoot = VectorizableTree[0].Scalars[0];
1830     if (MinBWs.count(ScalarRoot)) {
1831       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot]);
1832       VecTy = VectorType::get(MinTy, BundleWidth);
1833       ExtractCost +=
1834           TTI->getCastInstrCost(Instruction::SExt, EU.Scalar->getType(), MinTy);
1835     }
1836     ExtractCost +=
1837         TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
1838   }
1839 
1840   int SpillCost = getSpillCost();
1841   Cost += SpillCost + ExtractCost;
1842 
1843   DEBUG(dbgs() << "SLP: Spill Cost = " << SpillCost << ".\n"
1844                << "SLP: Extract Cost = " << ExtractCost << ".\n"
1845                << "SLP: Total Cost = " << Cost << ".\n");
1846   return Cost;
1847 }
1848 
1849 int BoUpSLP::getGatherCost(Type *Ty) {
1850   int Cost = 0;
1851   for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
1852     Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
1853   return Cost;
1854 }
1855 
1856 int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) {
1857   // Find the type of the operands in VL.
1858   Type *ScalarTy = VL[0]->getType();
1859   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1860     ScalarTy = SI->getValueOperand()->getType();
1861   VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1862   // Find the cost of inserting/extracting values from the vector.
1863   return getGatherCost(VecTy);
1864 }
1865 
1866 // Reorder commutative operations in alternate shuffle if the resulting vectors
1867 // are consecutive loads. This would allow us to vectorize the tree.
1868 // If we have something like-
1869 // load a[0] - load b[0]
1870 // load b[1] + load a[1]
1871 // load a[2] - load b[2]
1872 // load a[3] + load b[3]
1873 // Reordering the second load b[1]  load a[1] would allow us to vectorize this
1874 // code.
1875 void BoUpSLP::reorderAltShuffleOperands(ArrayRef<Value *> VL,
1876                                         SmallVectorImpl<Value *> &Left,
1877                                         SmallVectorImpl<Value *> &Right) {
1878   // Push left and right operands of binary operation into Left and Right
1879   for (unsigned i = 0, e = VL.size(); i < e; ++i) {
1880     Left.push_back(cast<Instruction>(VL[i])->getOperand(0));
1881     Right.push_back(cast<Instruction>(VL[i])->getOperand(1));
1882   }
1883 
1884   // Reorder if we have a commutative operation and consecutive access
1885   // are on either side of the alternate instructions.
1886   for (unsigned j = 0; j < VL.size() - 1; ++j) {
1887     if (LoadInst *L = dyn_cast<LoadInst>(Left[j])) {
1888       if (LoadInst *L1 = dyn_cast<LoadInst>(Right[j + 1])) {
1889         Instruction *VL1 = cast<Instruction>(VL[j]);
1890         Instruction *VL2 = cast<Instruction>(VL[j + 1]);
1891         if (VL1->isCommutative() && isConsecutiveAccess(L, L1, *DL, *SE)) {
1892           std::swap(Left[j], Right[j]);
1893           continue;
1894         } else if (VL2->isCommutative() &&
1895                    isConsecutiveAccess(L, L1, *DL, *SE)) {
1896           std::swap(Left[j + 1], Right[j + 1]);
1897           continue;
1898         }
1899         // else unchanged
1900       }
1901     }
1902     if (LoadInst *L = dyn_cast<LoadInst>(Right[j])) {
1903       if (LoadInst *L1 = dyn_cast<LoadInst>(Left[j + 1])) {
1904         Instruction *VL1 = cast<Instruction>(VL[j]);
1905         Instruction *VL2 = cast<Instruction>(VL[j + 1]);
1906         if (VL1->isCommutative() && isConsecutiveAccess(L, L1, *DL, *SE)) {
1907           std::swap(Left[j], Right[j]);
1908           continue;
1909         } else if (VL2->isCommutative() &&
1910                    isConsecutiveAccess(L, L1, *DL, *SE)) {
1911           std::swap(Left[j + 1], Right[j + 1]);
1912           continue;
1913         }
1914         // else unchanged
1915       }
1916     }
1917   }
1918 }
1919 
1920 // Return true if I should be commuted before adding it's left and right
1921 // operands to the arrays Left and Right.
1922 //
1923 // The vectorizer is trying to either have all elements one side being
1924 // instruction with the same opcode to enable further vectorization, or having
1925 // a splat to lower the vectorizing cost.
1926 static bool shouldReorderOperands(int i, Instruction &I,
1927                                   SmallVectorImpl<Value *> &Left,
1928                                   SmallVectorImpl<Value *> &Right,
1929                                   bool AllSameOpcodeLeft,
1930                                   bool AllSameOpcodeRight, bool SplatLeft,
1931                                   bool SplatRight) {
1932   Value *VLeft = I.getOperand(0);
1933   Value *VRight = I.getOperand(1);
1934   // If we have "SplatRight", try to see if commuting is needed to preserve it.
1935   if (SplatRight) {
1936     if (VRight == Right[i - 1])
1937       // Preserve SplatRight
1938       return false;
1939     if (VLeft == Right[i - 1]) {
1940       // Commuting would preserve SplatRight, but we don't want to break
1941       // SplatLeft either, i.e. preserve the original order if possible.
1942       // (FIXME: why do we care?)
1943       if (SplatLeft && VLeft == Left[i - 1])
1944         return false;
1945       return true;
1946     }
1947   }
1948   // Symmetrically handle Right side.
1949   if (SplatLeft) {
1950     if (VLeft == Left[i - 1])
1951       // Preserve SplatLeft
1952       return false;
1953     if (VRight == Left[i - 1])
1954       return true;
1955   }
1956 
1957   Instruction *ILeft = dyn_cast<Instruction>(VLeft);
1958   Instruction *IRight = dyn_cast<Instruction>(VRight);
1959 
1960   // If we have "AllSameOpcodeRight", try to see if the left operands preserves
1961   // it and not the right, in this case we want to commute.
1962   if (AllSameOpcodeRight) {
1963     unsigned RightPrevOpcode = cast<Instruction>(Right[i - 1])->getOpcode();
1964     if (IRight && RightPrevOpcode == IRight->getOpcode())
1965       // Do not commute, a match on the right preserves AllSameOpcodeRight
1966       return false;
1967     if (ILeft && RightPrevOpcode == ILeft->getOpcode()) {
1968       // We have a match and may want to commute, but first check if there is
1969       // not also a match on the existing operands on the Left to preserve
1970       // AllSameOpcodeLeft, i.e. preserve the original order if possible.
1971       // (FIXME: why do we care?)
1972       if (AllSameOpcodeLeft && ILeft &&
1973           cast<Instruction>(Left[i - 1])->getOpcode() == ILeft->getOpcode())
1974         return false;
1975       return true;
1976     }
1977   }
1978   // Symmetrically handle Left side.
1979   if (AllSameOpcodeLeft) {
1980     unsigned LeftPrevOpcode = cast<Instruction>(Left[i - 1])->getOpcode();
1981     if (ILeft && LeftPrevOpcode == ILeft->getOpcode())
1982       return false;
1983     if (IRight && LeftPrevOpcode == IRight->getOpcode())
1984       return true;
1985   }
1986   return false;
1987 }
1988 
1989 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
1990                                              SmallVectorImpl<Value *> &Left,
1991                                              SmallVectorImpl<Value *> &Right) {
1992 
1993   if (VL.size()) {
1994     // Peel the first iteration out of the loop since there's nothing
1995     // interesting to do anyway and it simplifies the checks in the loop.
1996     auto VLeft = cast<Instruction>(VL[0])->getOperand(0);
1997     auto VRight = cast<Instruction>(VL[0])->getOperand(1);
1998     if (!isa<Instruction>(VRight) && isa<Instruction>(VLeft))
1999       // Favor having instruction to the right. FIXME: why?
2000       std::swap(VLeft, VRight);
2001     Left.push_back(VLeft);
2002     Right.push_back(VRight);
2003   }
2004 
2005   // Keep track if we have instructions with all the same opcode on one side.
2006   bool AllSameOpcodeLeft = isa<Instruction>(Left[0]);
2007   bool AllSameOpcodeRight = isa<Instruction>(Right[0]);
2008   // Keep track if we have one side with all the same value (broadcast).
2009   bool SplatLeft = true;
2010   bool SplatRight = true;
2011 
2012   for (unsigned i = 1, e = VL.size(); i != e; ++i) {
2013     Instruction *I = cast<Instruction>(VL[i]);
2014     assert(I->isCommutative() && "Can only process commutative instruction");
2015     // Commute to favor either a splat or maximizing having the same opcodes on
2016     // one side.
2017     if (shouldReorderOperands(i, *I, Left, Right, AllSameOpcodeLeft,
2018                               AllSameOpcodeRight, SplatLeft, SplatRight)) {
2019       Left.push_back(I->getOperand(1));
2020       Right.push_back(I->getOperand(0));
2021     } else {
2022       Left.push_back(I->getOperand(0));
2023       Right.push_back(I->getOperand(1));
2024     }
2025     // Update Splat* and AllSameOpcode* after the insertion.
2026     SplatRight = SplatRight && (Right[i - 1] == Right[i]);
2027     SplatLeft = SplatLeft && (Left[i - 1] == Left[i]);
2028     AllSameOpcodeLeft = AllSameOpcodeLeft && isa<Instruction>(Left[i]) &&
2029                         (cast<Instruction>(Left[i - 1])->getOpcode() ==
2030                          cast<Instruction>(Left[i])->getOpcode());
2031     AllSameOpcodeRight = AllSameOpcodeRight && isa<Instruction>(Right[i]) &&
2032                          (cast<Instruction>(Right[i - 1])->getOpcode() ==
2033                           cast<Instruction>(Right[i])->getOpcode());
2034   }
2035 
2036   // If one operand end up being broadcast, return this operand order.
2037   if (SplatRight || SplatLeft)
2038     return;
2039 
2040   // Finally check if we can get longer vectorizable chain by reordering
2041   // without breaking the good operand order detected above.
2042   // E.g. If we have something like-
2043   // load a[0]  load b[0]
2044   // load b[1]  load a[1]
2045   // load a[2]  load b[2]
2046   // load a[3]  load b[3]
2047   // Reordering the second load b[1]  load a[1] would allow us to vectorize
2048   // this code and we still retain AllSameOpcode property.
2049   // FIXME: This load reordering might break AllSameOpcode in some rare cases
2050   // such as-
2051   // add a[0],c[0]  load b[0]
2052   // add a[1],c[2]  load b[1]
2053   // b[2]           load b[2]
2054   // add a[3],c[3]  load b[3]
2055   for (unsigned j = 0; j < VL.size() - 1; ++j) {
2056     if (LoadInst *L = dyn_cast<LoadInst>(Left[j])) {
2057       if (LoadInst *L1 = dyn_cast<LoadInst>(Right[j + 1])) {
2058         if (isConsecutiveAccess(L, L1, *DL, *SE)) {
2059           std::swap(Left[j + 1], Right[j + 1]);
2060           continue;
2061         }
2062       }
2063     }
2064     if (LoadInst *L = dyn_cast<LoadInst>(Right[j])) {
2065       if (LoadInst *L1 = dyn_cast<LoadInst>(Left[j + 1])) {
2066         if (isConsecutiveAccess(L, L1, *DL, *SE)) {
2067           std::swap(Left[j + 1], Right[j + 1]);
2068           continue;
2069         }
2070       }
2071     }
2072     // else unchanged
2073   }
2074 }
2075 
2076 void BoUpSLP::setInsertPointAfterBundle(ArrayRef<Value *> VL) {
2077   Instruction *VL0 = cast<Instruction>(VL[0]);
2078   BasicBlock::iterator NextInst(VL0);
2079   ++NextInst;
2080   Builder.SetInsertPoint(VL0->getParent(), NextInst);
2081   Builder.SetCurrentDebugLocation(VL0->getDebugLoc());
2082 }
2083 
2084 Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
2085   Value *Vec = UndefValue::get(Ty);
2086   // Generate the 'InsertElement' instruction.
2087   for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
2088     Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
2089     if (Instruction *Insrt = dyn_cast<Instruction>(Vec)) {
2090       GatherSeq.insert(Insrt);
2091       CSEBlocks.insert(Insrt->getParent());
2092 
2093       // Add to our 'need-to-extract' list.
2094       if (ScalarToTreeEntry.count(VL[i])) {
2095         int Idx = ScalarToTreeEntry[VL[i]];
2096         TreeEntry *E = &VectorizableTree[Idx];
2097         // Find which lane we need to extract.
2098         int FoundLane = -1;
2099         for (unsigned Lane = 0, LE = VL.size(); Lane != LE; ++Lane) {
2100           // Is this the lane of the scalar that we are looking for ?
2101           if (E->Scalars[Lane] == VL[i]) {
2102             FoundLane = Lane;
2103             break;
2104           }
2105         }
2106         assert(FoundLane >= 0 && "Could not find the correct lane");
2107         ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
2108       }
2109     }
2110   }
2111 
2112   return Vec;
2113 }
2114 
2115 Value *BoUpSLP::alreadyVectorized(ArrayRef<Value *> VL) const {
2116   SmallDenseMap<Value*, int>::const_iterator Entry
2117     = ScalarToTreeEntry.find(VL[0]);
2118   if (Entry != ScalarToTreeEntry.end()) {
2119     int Idx = Entry->second;
2120     const TreeEntry *En = &VectorizableTree[Idx];
2121     if (En->isSame(VL) && En->VectorizedValue)
2122       return En->VectorizedValue;
2123   }
2124   return nullptr;
2125 }
2126 
2127 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
2128   if (ScalarToTreeEntry.count(VL[0])) {
2129     int Idx = ScalarToTreeEntry[VL[0]];
2130     TreeEntry *E = &VectorizableTree[Idx];
2131     if (E->isSame(VL))
2132       return vectorizeTree(E);
2133   }
2134 
2135   Type *ScalarTy = VL[0]->getType();
2136   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
2137     ScalarTy = SI->getValueOperand()->getType();
2138   VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
2139 
2140   return Gather(VL, VecTy);
2141 }
2142 
2143 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
2144   IRBuilder<>::InsertPointGuard Guard(Builder);
2145 
2146   if (E->VectorizedValue) {
2147     DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
2148     return E->VectorizedValue;
2149   }
2150 
2151   Instruction *VL0 = cast<Instruction>(E->Scalars[0]);
2152   Type *ScalarTy = VL0->getType();
2153   if (StoreInst *SI = dyn_cast<StoreInst>(VL0))
2154     ScalarTy = SI->getValueOperand()->getType();
2155   VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size());
2156 
2157   if (E->NeedToGather) {
2158     setInsertPointAfterBundle(E->Scalars);
2159     return Gather(E->Scalars, VecTy);
2160   }
2161 
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 = getVectorIntrinsicIDForCall(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 (auto *VecI = dyn_cast<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             TerminatorInst *IncomingTerminator =
2581                 PH->getIncomingBlock(i)->getTerminator();
2582             if (isa<CatchSwitchInst>(IncomingTerminator)) {
2583               Builder.SetInsertPoint(VecI->getParent(),
2584                                      std::next(VecI->getIterator()));
2585             } else {
2586               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
2587             }
2588             Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2589             if (MinBWs.count(ScalarRoot))
2590               Ex = Builder.CreateSExt(Ex, Scalar->getType());
2591             CSEBlocks.insert(PH->getIncomingBlock(i));
2592             PH->setOperand(i, Ex);
2593           }
2594         }
2595       } else {
2596         Builder.SetInsertPoint(cast<Instruction>(User));
2597         Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2598         if (MinBWs.count(ScalarRoot))
2599           Ex = Builder.CreateSExt(Ex, Scalar->getType());
2600         CSEBlocks.insert(cast<Instruction>(User)->getParent());
2601         User->replaceUsesOfWith(Scalar, Ex);
2602      }
2603     } else {
2604       Builder.SetInsertPoint(&F->getEntryBlock().front());
2605       Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2606       if (MinBWs.count(ScalarRoot))
2607         Ex = Builder.CreateSExt(Ex, Scalar->getType());
2608       CSEBlocks.insert(&F->getEntryBlock());
2609       User->replaceUsesOfWith(Scalar, Ex);
2610     }
2611 
2612     DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
2613   }
2614 
2615   // For each vectorized value:
2616   for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
2617     TreeEntry *Entry = &VectorizableTree[EIdx];
2618 
2619     // For each lane:
2620     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
2621       Value *Scalar = Entry->Scalars[Lane];
2622       // No need to handle users of gathered values.
2623       if (Entry->NeedToGather)
2624         continue;
2625 
2626       assert(Entry->VectorizedValue && "Can't find vectorizable value");
2627 
2628       Type *Ty = Scalar->getType();
2629       if (!Ty->isVoidTy()) {
2630 #ifndef NDEBUG
2631         for (User *U : Scalar->users()) {
2632           DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
2633 
2634           assert((ScalarToTreeEntry.count(U) ||
2635                   // It is legal to replace users in the ignorelist by undef.
2636                   (std::find(UserIgnoreList.begin(), UserIgnoreList.end(), U) !=
2637                    UserIgnoreList.end())) &&
2638                  "Replacing out-of-tree value with undef");
2639         }
2640 #endif
2641         Value *Undef = UndefValue::get(Ty);
2642         Scalar->replaceAllUsesWith(Undef);
2643       }
2644       DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
2645       eraseInstruction(cast<Instruction>(Scalar));
2646     }
2647   }
2648 
2649   Builder.ClearInsertionPoint();
2650 
2651   return VectorizableTree[0].VectorizedValue;
2652 }
2653 
2654 void BoUpSLP::optimizeGatherSequence() {
2655   DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
2656         << " gather sequences instructions.\n");
2657   // LICM InsertElementInst sequences.
2658   for (SetVector<Instruction *>::iterator it = GatherSeq.begin(),
2659        e = GatherSeq.end(); it != e; ++it) {
2660     InsertElementInst *Insert = dyn_cast<InsertElementInst>(*it);
2661 
2662     if (!Insert)
2663       continue;
2664 
2665     // Check if this block is inside a loop.
2666     Loop *L = LI->getLoopFor(Insert->getParent());
2667     if (!L)
2668       continue;
2669 
2670     // Check if it has a preheader.
2671     BasicBlock *PreHeader = L->getLoopPreheader();
2672     if (!PreHeader)
2673       continue;
2674 
2675     // If the vector or the element that we insert into it are
2676     // instructions that are defined in this basic block then we can't
2677     // hoist this instruction.
2678     Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
2679     Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
2680     if (CurrVec && L->contains(CurrVec))
2681       continue;
2682     if (NewElem && L->contains(NewElem))
2683       continue;
2684 
2685     // We can hoist this instruction. Move it to the pre-header.
2686     Insert->moveBefore(PreHeader->getTerminator());
2687   }
2688 
2689   // Make a list of all reachable blocks in our CSE queue.
2690   SmallVector<const DomTreeNode *, 8> CSEWorkList;
2691   CSEWorkList.reserve(CSEBlocks.size());
2692   for (BasicBlock *BB : CSEBlocks)
2693     if (DomTreeNode *N = DT->getNode(BB)) {
2694       assert(DT->isReachableFromEntry(N));
2695       CSEWorkList.push_back(N);
2696     }
2697 
2698   // Sort blocks by domination. This ensures we visit a block after all blocks
2699   // dominating it are visited.
2700   std::stable_sort(CSEWorkList.begin(), CSEWorkList.end(),
2701                    [this](const DomTreeNode *A, const DomTreeNode *B) {
2702     return DT->properlyDominates(A, B);
2703   });
2704 
2705   // Perform O(N^2) search over the gather sequences and merge identical
2706   // instructions. TODO: We can further optimize this scan if we split the
2707   // instructions into different buckets based on the insert lane.
2708   SmallVector<Instruction *, 16> Visited;
2709   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
2710     assert((I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
2711            "Worklist not sorted properly!");
2712     BasicBlock *BB = (*I)->getBlock();
2713     // For all instructions in blocks containing gather sequences:
2714     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) {
2715       Instruction *In = &*it++;
2716       if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In))
2717         continue;
2718 
2719       // Check if we can replace this instruction with any of the
2720       // visited instructions.
2721       for (SmallVectorImpl<Instruction *>::iterator v = Visited.begin(),
2722                                                     ve = Visited.end();
2723            v != ve; ++v) {
2724         if (In->isIdenticalTo(*v) &&
2725             DT->dominates((*v)->getParent(), In->getParent())) {
2726           In->replaceAllUsesWith(*v);
2727           eraseInstruction(In);
2728           In = nullptr;
2729           break;
2730         }
2731       }
2732       if (In) {
2733         assert(std::find(Visited.begin(), Visited.end(), In) == Visited.end());
2734         Visited.push_back(In);
2735       }
2736     }
2737   }
2738   CSEBlocks.clear();
2739   GatherSeq.clear();
2740 }
2741 
2742 // Groups the instructions to a bundle (which is then a single scheduling entity)
2743 // and schedules instructions until the bundle gets ready.
2744 bool BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL,
2745                                                  BoUpSLP *SLP) {
2746   if (isa<PHINode>(VL[0]))
2747     return true;
2748 
2749   // Initialize the instruction bundle.
2750   Instruction *OldScheduleEnd = ScheduleEnd;
2751   ScheduleData *PrevInBundle = nullptr;
2752   ScheduleData *Bundle = nullptr;
2753   bool ReSchedule = false;
2754   DEBUG(dbgs() << "SLP:  bundle: " << *VL[0] << "\n");
2755 
2756   // Make sure that the scheduling region contains all
2757   // instructions of the bundle.
2758   for (Value *V : VL) {
2759     if (!extendSchedulingRegion(V))
2760       return false;
2761   }
2762 
2763   for (Value *V : VL) {
2764     ScheduleData *BundleMember = getScheduleData(V);
2765     assert(BundleMember &&
2766            "no ScheduleData for bundle member (maybe not in same basic block)");
2767     if (BundleMember->IsScheduled) {
2768       // A bundle member was scheduled as single instruction before and now
2769       // needs to be scheduled as part of the bundle. We just get rid of the
2770       // existing schedule.
2771       DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
2772                    << " was already scheduled\n");
2773       ReSchedule = true;
2774     }
2775     assert(BundleMember->isSchedulingEntity() &&
2776            "bundle member already part of other bundle");
2777     if (PrevInBundle) {
2778       PrevInBundle->NextInBundle = BundleMember;
2779     } else {
2780       Bundle = BundleMember;
2781     }
2782     BundleMember->UnscheduledDepsInBundle = 0;
2783     Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps;
2784 
2785     // Group the instructions to a bundle.
2786     BundleMember->FirstInBundle = Bundle;
2787     PrevInBundle = BundleMember;
2788   }
2789   if (ScheduleEnd != OldScheduleEnd) {
2790     // The scheduling region got new instructions at the lower end (or it is a
2791     // new region for the first bundle). This makes it necessary to
2792     // recalculate all dependencies.
2793     // It is seldom that this needs to be done a second time after adding the
2794     // initial bundle to the region.
2795     for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2796       ScheduleData *SD = getScheduleData(I);
2797       SD->clearDependencies();
2798     }
2799     ReSchedule = true;
2800   }
2801   if (ReSchedule) {
2802     resetSchedule();
2803     initialFillReadyList(ReadyInsts);
2804   }
2805 
2806   DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle << " in block "
2807                << BB->getName() << "\n");
2808 
2809   calculateDependencies(Bundle, true, SLP);
2810 
2811   // Now try to schedule the new bundle. As soon as the bundle is "ready" it
2812   // means that there are no cyclic dependencies and we can schedule it.
2813   // Note that's important that we don't "schedule" the bundle yet (see
2814   // cancelScheduling).
2815   while (!Bundle->isReady() && !ReadyInsts.empty()) {
2816 
2817     ScheduleData *pickedSD = ReadyInsts.back();
2818     ReadyInsts.pop_back();
2819 
2820     if (pickedSD->isSchedulingEntity() && pickedSD->isReady()) {
2821       schedule(pickedSD, ReadyInsts);
2822     }
2823   }
2824   if (!Bundle->isReady()) {
2825     cancelScheduling(VL);
2826     return false;
2827   }
2828   return true;
2829 }
2830 
2831 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL) {
2832   if (isa<PHINode>(VL[0]))
2833     return;
2834 
2835   ScheduleData *Bundle = getScheduleData(VL[0]);
2836   DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
2837   assert(!Bundle->IsScheduled &&
2838          "Can't cancel bundle which is already scheduled");
2839   assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
2840          "tried to unbundle something which is not a bundle");
2841 
2842   // Un-bundle: make single instructions out of the bundle.
2843   ScheduleData *BundleMember = Bundle;
2844   while (BundleMember) {
2845     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
2846     BundleMember->FirstInBundle = BundleMember;
2847     ScheduleData *Next = BundleMember->NextInBundle;
2848     BundleMember->NextInBundle = nullptr;
2849     BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps;
2850     if (BundleMember->UnscheduledDepsInBundle == 0) {
2851       ReadyInsts.insert(BundleMember);
2852     }
2853     BundleMember = Next;
2854   }
2855 }
2856 
2857 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V) {
2858   if (getScheduleData(V))
2859     return true;
2860   Instruction *I = dyn_cast<Instruction>(V);
2861   assert(I && "bundle member must be an instruction");
2862   assert(!isa<PHINode>(I) && "phi nodes don't need to be scheduled");
2863   if (!ScheduleStart) {
2864     // It's the first instruction in the new region.
2865     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
2866     ScheduleStart = I;
2867     ScheduleEnd = I->getNextNode();
2868     assert(ScheduleEnd && "tried to vectorize a TerminatorInst?");
2869     DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
2870     return true;
2871   }
2872   // Search up and down at the same time, because we don't know if the new
2873   // instruction is above or below the existing scheduling region.
2874   BasicBlock::reverse_iterator UpIter(ScheduleStart->getIterator());
2875   BasicBlock::reverse_iterator UpperEnd = BB->rend();
2876   BasicBlock::iterator DownIter(ScheduleEnd);
2877   BasicBlock::iterator LowerEnd = BB->end();
2878   for (;;) {
2879     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
2880       DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
2881       return false;
2882     }
2883 
2884     if (UpIter != UpperEnd) {
2885       if (&*UpIter == I) {
2886         initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
2887         ScheduleStart = I;
2888         DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I << "\n");
2889         return true;
2890       }
2891       UpIter++;
2892     }
2893     if (DownIter != LowerEnd) {
2894       if (&*DownIter == I) {
2895         initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
2896                          nullptr);
2897         ScheduleEnd = I->getNextNode();
2898         assert(ScheduleEnd && "tried to vectorize a TerminatorInst?");
2899         DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
2900         return true;
2901       }
2902       DownIter++;
2903     }
2904     assert((UpIter != UpperEnd || DownIter != LowerEnd) &&
2905            "instruction not found in block");
2906   }
2907   return true;
2908 }
2909 
2910 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
2911                                                 Instruction *ToI,
2912                                                 ScheduleData *PrevLoadStore,
2913                                                 ScheduleData *NextLoadStore) {
2914   ScheduleData *CurrentLoadStore = PrevLoadStore;
2915   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
2916     ScheduleData *SD = ScheduleDataMap[I];
2917     if (!SD) {
2918       // Allocate a new ScheduleData for the instruction.
2919       if (ChunkPos >= ChunkSize) {
2920         ScheduleDataChunks.push_back(
2921             llvm::make_unique<ScheduleData[]>(ChunkSize));
2922         ChunkPos = 0;
2923       }
2924       SD = &(ScheduleDataChunks.back()[ChunkPos++]);
2925       ScheduleDataMap[I] = SD;
2926       SD->Inst = I;
2927     }
2928     assert(!isInSchedulingRegion(SD) &&
2929            "new ScheduleData already in scheduling region");
2930     SD->init(SchedulingRegionID);
2931 
2932     if (I->mayReadOrWriteMemory()) {
2933       // Update the linked list of memory accessing instructions.
2934       if (CurrentLoadStore) {
2935         CurrentLoadStore->NextLoadStore = SD;
2936       } else {
2937         FirstLoadStoreInRegion = SD;
2938       }
2939       CurrentLoadStore = SD;
2940     }
2941   }
2942   if (NextLoadStore) {
2943     if (CurrentLoadStore)
2944       CurrentLoadStore->NextLoadStore = NextLoadStore;
2945   } else {
2946     LastLoadStoreInRegion = CurrentLoadStore;
2947   }
2948 }
2949 
2950 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
2951                                                      bool InsertInReadyList,
2952                                                      BoUpSLP *SLP) {
2953   assert(SD->isSchedulingEntity());
2954 
2955   SmallVector<ScheduleData *, 10> WorkList;
2956   WorkList.push_back(SD);
2957 
2958   while (!WorkList.empty()) {
2959     ScheduleData *SD = WorkList.back();
2960     WorkList.pop_back();
2961 
2962     ScheduleData *BundleMember = SD;
2963     while (BundleMember) {
2964       assert(isInSchedulingRegion(BundleMember));
2965       if (!BundleMember->hasValidDependencies()) {
2966 
2967         DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember << "\n");
2968         BundleMember->Dependencies = 0;
2969         BundleMember->resetUnscheduledDeps();
2970 
2971         // Handle def-use chain dependencies.
2972         for (User *U : BundleMember->Inst->users()) {
2973           if (isa<Instruction>(U)) {
2974             ScheduleData *UseSD = getScheduleData(U);
2975             if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
2976               BundleMember->Dependencies++;
2977               ScheduleData *DestBundle = UseSD->FirstInBundle;
2978               if (!DestBundle->IsScheduled) {
2979                 BundleMember->incrementUnscheduledDeps(1);
2980               }
2981               if (!DestBundle->hasValidDependencies()) {
2982                 WorkList.push_back(DestBundle);
2983               }
2984             }
2985           } else {
2986             // I'm not sure if this can ever happen. But we need to be safe.
2987             // This lets the instruction/bundle never be scheduled and
2988             // eventually disable vectorization.
2989             BundleMember->Dependencies++;
2990             BundleMember->incrementUnscheduledDeps(1);
2991           }
2992         }
2993 
2994         // Handle the memory dependencies.
2995         ScheduleData *DepDest = BundleMember->NextLoadStore;
2996         if (DepDest) {
2997           Instruction *SrcInst = BundleMember->Inst;
2998           MemoryLocation SrcLoc = getLocation(SrcInst, SLP->AA);
2999           bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
3000           unsigned numAliased = 0;
3001           unsigned DistToSrc = 1;
3002 
3003           while (DepDest) {
3004             assert(isInSchedulingRegion(DepDest));
3005 
3006             // We have two limits to reduce the complexity:
3007             // 1) AliasedCheckLimit: It's a small limit to reduce calls to
3008             //    SLP->isAliased (which is the expensive part in this loop).
3009             // 2) MaxMemDepDistance: It's for very large blocks and it aborts
3010             //    the whole loop (even if the loop is fast, it's quadratic).
3011             //    It's important for the loop break condition (see below) to
3012             //    check this limit even between two read-only instructions.
3013             if (DistToSrc >= MaxMemDepDistance ||
3014                     ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
3015                      (numAliased >= AliasedCheckLimit ||
3016                       SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
3017 
3018               // We increment the counter only if the locations are aliased
3019               // (instead of counting all alias checks). This gives a better
3020               // balance between reduced runtime and accurate dependencies.
3021               numAliased++;
3022 
3023               DepDest->MemoryDependencies.push_back(BundleMember);
3024               BundleMember->Dependencies++;
3025               ScheduleData *DestBundle = DepDest->FirstInBundle;
3026               if (!DestBundle->IsScheduled) {
3027                 BundleMember->incrementUnscheduledDeps(1);
3028               }
3029               if (!DestBundle->hasValidDependencies()) {
3030                 WorkList.push_back(DestBundle);
3031               }
3032             }
3033             DepDest = DepDest->NextLoadStore;
3034 
3035             // Example, explaining the loop break condition: Let's assume our
3036             // starting instruction is i0 and MaxMemDepDistance = 3.
3037             //
3038             //                      +--------v--v--v
3039             //             i0,i1,i2,i3,i4,i5,i6,i7,i8
3040             //             +--------^--^--^
3041             //
3042             // MaxMemDepDistance let us stop alias-checking at i3 and we add
3043             // dependencies from i0 to i3,i4,.. (even if they are not aliased).
3044             // Previously we already added dependencies from i3 to i6,i7,i8
3045             // (because of MaxMemDepDistance). As we added a dependency from
3046             // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
3047             // and we can abort this loop at i6.
3048             if (DistToSrc >= 2 * MaxMemDepDistance)
3049                 break;
3050             DistToSrc++;
3051           }
3052         }
3053       }
3054       BundleMember = BundleMember->NextInBundle;
3055     }
3056     if (InsertInReadyList && SD->isReady()) {
3057       ReadyInsts.push_back(SD);
3058       DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst << "\n");
3059     }
3060   }
3061 }
3062 
3063 void BoUpSLP::BlockScheduling::resetSchedule() {
3064   assert(ScheduleStart &&
3065          "tried to reset schedule on block which has not been scheduled");
3066   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
3067     ScheduleData *SD = getScheduleData(I);
3068     assert(isInSchedulingRegion(SD));
3069     SD->IsScheduled = false;
3070     SD->resetUnscheduledDeps();
3071   }
3072   ReadyInsts.clear();
3073 }
3074 
3075 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
3076 
3077   if (!BS->ScheduleStart)
3078     return;
3079 
3080   DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
3081 
3082   BS->resetSchedule();
3083 
3084   // For the real scheduling we use a more sophisticated ready-list: it is
3085   // sorted by the original instruction location. This lets the final schedule
3086   // be as  close as possible to the original instruction order.
3087   struct ScheduleDataCompare {
3088     bool operator()(ScheduleData *SD1, ScheduleData *SD2) {
3089       return SD2->SchedulingPriority < SD1->SchedulingPriority;
3090     }
3091   };
3092   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
3093 
3094   // Ensure that all dependency data is updated and fill the ready-list with
3095   // initial instructions.
3096   int Idx = 0;
3097   int NumToSchedule = 0;
3098   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
3099        I = I->getNextNode()) {
3100     ScheduleData *SD = BS->getScheduleData(I);
3101     assert(
3102         SD->isPartOfBundle() == (ScalarToTreeEntry.count(SD->Inst) != 0) &&
3103         "scheduler and vectorizer have different opinion on what is a bundle");
3104     SD->FirstInBundle->SchedulingPriority = Idx++;
3105     if (SD->isSchedulingEntity()) {
3106       BS->calculateDependencies(SD, false, this);
3107       NumToSchedule++;
3108     }
3109   }
3110   BS->initialFillReadyList(ReadyInsts);
3111 
3112   Instruction *LastScheduledInst = BS->ScheduleEnd;
3113 
3114   // Do the "real" scheduling.
3115   while (!ReadyInsts.empty()) {
3116     ScheduleData *picked = *ReadyInsts.begin();
3117     ReadyInsts.erase(ReadyInsts.begin());
3118 
3119     // Move the scheduled instruction(s) to their dedicated places, if not
3120     // there yet.
3121     ScheduleData *BundleMember = picked;
3122     while (BundleMember) {
3123       Instruction *pickedInst = BundleMember->Inst;
3124       if (LastScheduledInst->getNextNode() != pickedInst) {
3125         BS->BB->getInstList().remove(pickedInst);
3126         BS->BB->getInstList().insert(LastScheduledInst->getIterator(),
3127                                      pickedInst);
3128       }
3129       LastScheduledInst = pickedInst;
3130       BundleMember = BundleMember->NextInBundle;
3131     }
3132 
3133     BS->schedule(picked, ReadyInsts);
3134     NumToSchedule--;
3135   }
3136   assert(NumToSchedule == 0 && "could not schedule all instructions");
3137 
3138   // Avoid duplicate scheduling of the block.
3139   BS->ScheduleStart = nullptr;
3140 }
3141 
3142 unsigned BoUpSLP::getVectorElementSize(Value *V) {
3143   // If V is a store, just return the width of the stored value without
3144   // traversing the expression tree. This is the common case.
3145   if (auto *Store = dyn_cast<StoreInst>(V))
3146     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
3147 
3148   // If V is not a store, we can traverse the expression tree to find loads
3149   // that feed it. The type of the loaded value may indicate a more suitable
3150   // width than V's type. We want to base the vector element size on the width
3151   // of memory operations where possible.
3152   SmallVector<Instruction *, 16> Worklist;
3153   SmallPtrSet<Instruction *, 16> Visited;
3154   if (auto *I = dyn_cast<Instruction>(V))
3155     Worklist.push_back(I);
3156 
3157   // Traverse the expression tree in bottom-up order looking for loads. If we
3158   // encounter an instruciton we don't yet handle, we give up.
3159   auto MaxWidth = 0u;
3160   auto FoundUnknownInst = false;
3161   while (!Worklist.empty() && !FoundUnknownInst) {
3162     auto *I = Worklist.pop_back_val();
3163     Visited.insert(I);
3164 
3165     // We should only be looking at scalar instructions here. If the current
3166     // instruction has a vector type, give up.
3167     auto *Ty = I->getType();
3168     if (isa<VectorType>(Ty))
3169       FoundUnknownInst = true;
3170 
3171     // If the current instruction is a load, update MaxWidth to reflect the
3172     // width of the loaded value.
3173     else if (isa<LoadInst>(I))
3174       MaxWidth = std::max<unsigned>(MaxWidth, DL->getTypeSizeInBits(Ty));
3175 
3176     // Otherwise, we need to visit the operands of the instruction. We only
3177     // handle the interesting cases from buildTree here. If an operand is an
3178     // instruction we haven't yet visited, we add it to the worklist.
3179     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
3180              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I)) {
3181       for (Use &U : I->operands())
3182         if (auto *J = dyn_cast<Instruction>(U.get()))
3183           if (!Visited.count(J))
3184             Worklist.push_back(J);
3185     }
3186 
3187     // If we don't yet handle the instruction, give up.
3188     else
3189       FoundUnknownInst = true;
3190   }
3191 
3192   // If we didn't encounter a memory access in the expression tree, or if we
3193   // gave up for some reason, just return the width of V.
3194   if (!MaxWidth || FoundUnknownInst)
3195     return DL->getTypeSizeInBits(V->getType());
3196 
3197   // Otherwise, return the maximum width we found.
3198   return MaxWidth;
3199 }
3200 
3201 // Determine if a value V in a vectorizable expression Expr can be demoted to a
3202 // smaller type with a truncation. We collect the values that will be demoted
3203 // in ToDemote and additional roots that require investigating in Roots.
3204 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
3205                                   SmallVectorImpl<Value *> &ToDemote,
3206                                   SmallVectorImpl<Value *> &Roots) {
3207 
3208   // We can always demote constants.
3209   if (isa<Constant>(V)) {
3210     ToDemote.push_back(V);
3211     return true;
3212   }
3213 
3214   // If the value is not an instruction in the expression with only one use, it
3215   // cannot be demoted.
3216   auto *I = dyn_cast<Instruction>(V);
3217   if (!I || !I->hasOneUse() || !Expr.count(I))
3218     return false;
3219 
3220   switch (I->getOpcode()) {
3221 
3222   // We can always demote truncations and extensions. Since truncations can
3223   // seed additional demotion, we save the truncated value.
3224   case Instruction::Trunc:
3225     Roots.push_back(I->getOperand(0));
3226   case Instruction::ZExt:
3227   case Instruction::SExt:
3228     break;
3229 
3230   // We can demote certain binary operations if we can demote both of their
3231   // operands.
3232   case Instruction::Add:
3233   case Instruction::Sub:
3234   case Instruction::Mul:
3235   case Instruction::And:
3236   case Instruction::Or:
3237   case Instruction::Xor:
3238     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
3239         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
3240       return false;
3241     break;
3242 
3243   // We can demote selects if we can demote their true and false values.
3244   case Instruction::Select: {
3245     SelectInst *SI = cast<SelectInst>(I);
3246     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
3247         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
3248       return false;
3249     break;
3250   }
3251 
3252   // We can demote phis if we can demote all their incoming operands. Note that
3253   // we don't need to worry about cycles since we ensure single use above.
3254   case Instruction::PHI: {
3255     PHINode *PN = cast<PHINode>(I);
3256     for (Value *IncValue : PN->incoming_values())
3257       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
3258         return false;
3259     break;
3260   }
3261 
3262   // Otherwise, conservatively give up.
3263   default:
3264     return false;
3265   }
3266 
3267   // Record the value that we can demote.
3268   ToDemote.push_back(V);
3269   return true;
3270 }
3271 
3272 void BoUpSLP::computeMinimumValueSizes() {
3273   // If there are no external uses, the expression tree must be rooted by a
3274   // store. We can't demote in-memory values, so there is nothing to do here.
3275   if (ExternalUses.empty())
3276     return;
3277 
3278   // We only attempt to truncate integer expressions.
3279   auto &TreeRoot = VectorizableTree[0].Scalars;
3280   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
3281   if (!TreeRootIT)
3282     return;
3283 
3284   // If the expression is not rooted by a store, these roots should have
3285   // external uses. We will rely on InstCombine to rewrite the expression in
3286   // the narrower type. However, InstCombine only rewrites single-use values.
3287   // This means that if a tree entry other than a root is used externally, it
3288   // must have multiple uses and InstCombine will not rewrite it. The code
3289   // below ensures that only the roots are used externally.
3290   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
3291   for (auto &EU : ExternalUses)
3292     if (!Expr.erase(EU.Scalar))
3293       return;
3294   if (!Expr.empty())
3295     return;
3296 
3297   // Collect the scalar values of the vectorizable expression. We will use this
3298   // context to determine which values can be demoted. If we see a truncation,
3299   // we mark it as seeding another demotion.
3300   for (auto &Entry : VectorizableTree)
3301     Expr.insert(Entry.Scalars.begin(), Entry.Scalars.end());
3302 
3303   // Ensure the roots of the vectorizable tree don't form a cycle. They must
3304   // have a single external user that is not in the vectorizable tree.
3305   for (auto *Root : TreeRoot)
3306     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
3307       return;
3308 
3309   // Conservatively determine if we can actually truncate the roots of the
3310   // expression. Collect the values that can be demoted in ToDemote and
3311   // additional roots that require investigating in Roots.
3312   SmallVector<Value *, 32> ToDemote;
3313   SmallVector<Value *, 4> Roots;
3314   for (auto *Root : TreeRoot)
3315     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
3316       return;
3317 
3318   // The maximum bit width required to represent all the values that can be
3319   // demoted without loss of precision. It would be safe to truncate the roots
3320   // of the expression to this width.
3321   auto MaxBitWidth = 8u;
3322 
3323   // We first check if all the bits of the roots are demanded. If they're not,
3324   // we can truncate the roots to this narrower type.
3325   for (auto *Root : TreeRoot) {
3326     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
3327     MaxBitWidth = std::max<unsigned>(
3328         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
3329   }
3330 
3331   // If all the bits of the roots are demanded, we can try a little harder to
3332   // compute a narrower type. This can happen, for example, if the roots are
3333   // getelementptr indices. InstCombine promotes these indices to the pointer
3334   // width. Thus, all their bits are technically demanded even though the
3335   // address computation might be vectorized in a smaller type.
3336   //
3337   // We start by looking at each entry that can be demoted. We compute the
3338   // maximum bit width required to store the scalar by using ValueTracking to
3339   // compute the number of high-order bits we can truncate.
3340   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType())) {
3341     MaxBitWidth = 8u;
3342     for (auto *Scalar : ToDemote) {
3343       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, 0, DT);
3344       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
3345       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
3346     }
3347   }
3348 
3349   // Round MaxBitWidth up to the next power-of-two.
3350   if (!isPowerOf2_64(MaxBitWidth))
3351     MaxBitWidth = NextPowerOf2(MaxBitWidth);
3352 
3353   // If the maximum bit width we compute is less than the with of the roots'
3354   // type, we can proceed with the narrowing. Otherwise, do nothing.
3355   if (MaxBitWidth >= TreeRootIT->getBitWidth())
3356     return;
3357 
3358   // If we can truncate the root, we must collect additional values that might
3359   // be demoted as a result. That is, those seeded by truncations we will
3360   // modify.
3361   while (!Roots.empty())
3362     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
3363 
3364   // Finally, map the values we can demote to the maximum bit with we computed.
3365   for (auto *Scalar : ToDemote)
3366     MinBWs[Scalar] = MaxBitWidth;
3367 }
3368 
3369 /// The SLPVectorizer Pass.
3370 struct SLPVectorizer : public FunctionPass {
3371   typedef SmallVector<StoreInst *, 8> StoreList;
3372   typedef MapVector<Value *, StoreList> StoreListMap;
3373   typedef SmallVector<WeakVH, 8> WeakVHList;
3374   typedef MapVector<Value *, WeakVHList> WeakVHListMap;
3375 
3376   /// Pass identification, replacement for typeid
3377   static char ID;
3378 
3379   explicit SLPVectorizer() : FunctionPass(ID) {
3380     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
3381   }
3382 
3383   ScalarEvolution *SE;
3384   TargetTransformInfo *TTI;
3385   TargetLibraryInfo *TLI;
3386   AliasAnalysis *AA;
3387   LoopInfo *LI;
3388   DominatorTree *DT;
3389   AssumptionCache *AC;
3390   DemandedBits *DB;
3391   const DataLayout *DL;
3392 
3393   bool doInitialization(Module &M) override {
3394     DL = &M.getDataLayout();
3395     return false;
3396   }
3397 
3398   bool runOnFunction(Function &F) override {
3399     if (skipFunction(F))
3400       return false;
3401 
3402     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
3403     TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
3404     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
3405     TLI = TLIP ? &TLIP->getTLI() : nullptr;
3406     AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3407     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
3408     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3409     AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
3410     DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
3411 
3412     Stores.clear();
3413     GEPs.clear();
3414     bool Changed = false;
3415 
3416     // If the target claims to have no vector registers don't attempt
3417     // vectorization.
3418     if (!TTI->getNumberOfRegisters(true))
3419       return false;
3420 
3421     // Use the vector register size specified by the target unless overridden
3422     // by a command-line option.
3423     // TODO: It would be better to limit the vectorization factor based on
3424     //       data type rather than just register size. For example, x86 AVX has
3425     //       256-bit registers, but it does not support integer operations
3426     //       at that width (that requires AVX2).
3427     if (MaxVectorRegSizeOption.getNumOccurrences())
3428       MaxVecRegSize = MaxVectorRegSizeOption;
3429     else
3430       MaxVecRegSize = TTI->getRegisterBitWidth(true);
3431 
3432     MinVecRegSize = MinVectorRegSizeOption;
3433 
3434     // Don't vectorize when the attribute NoImplicitFloat is used.
3435     if (F.hasFnAttribute(Attribute::NoImplicitFloat))
3436       return false;
3437 
3438     DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
3439 
3440     // Use the bottom up slp vectorizer to construct chains that start with
3441     // store instructions.
3442     BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL);
3443 
3444     // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
3445     // delete instructions.
3446 
3447     // Scan the blocks in the function in post order.
3448     for (auto BB : post_order(&F.getEntryBlock())) {
3449       collectSeedInstructions(BB);
3450 
3451       // Vectorize trees that end at stores.
3452       if (!Stores.empty()) {
3453         DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
3454                      << " underlying objects.\n");
3455         Changed |= vectorizeStoreChains(R);
3456       }
3457 
3458       // Vectorize trees that end at reductions.
3459       Changed |= vectorizeChainsInBlock(BB, R);
3460 
3461       // Vectorize the index computations of getelementptr instructions. This
3462       // is primarily intended to catch gather-like idioms ending at
3463       // non-consecutive loads.
3464       if (!GEPs.empty()) {
3465         DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
3466                      << " underlying objects.\n");
3467         Changed |= vectorizeGEPIndices(BB, R);
3468       }
3469     }
3470 
3471     if (Changed) {
3472       R.optimizeGatherSequence();
3473       DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
3474       DEBUG(verifyFunction(F));
3475     }
3476     return Changed;
3477   }
3478 
3479   void getAnalysisUsage(AnalysisUsage &AU) const override {
3480     FunctionPass::getAnalysisUsage(AU);
3481     AU.addRequired<AssumptionCacheTracker>();
3482     AU.addRequired<ScalarEvolutionWrapperPass>();
3483     AU.addRequired<AAResultsWrapperPass>();
3484     AU.addRequired<TargetTransformInfoWrapperPass>();
3485     AU.addRequired<LoopInfoWrapperPass>();
3486     AU.addRequired<DominatorTreeWrapperPass>();
3487     AU.addRequired<DemandedBitsWrapperPass>();
3488     AU.addPreserved<LoopInfoWrapperPass>();
3489     AU.addPreserved<DominatorTreeWrapperPass>();
3490     AU.addPreserved<AAResultsWrapperPass>();
3491     AU.addPreserved<GlobalsAAWrapperPass>();
3492     AU.setPreservesCFG();
3493   }
3494 
3495 private:
3496   /// \brief Collect store and getelementptr instructions and organize them
3497   /// according to the underlying object of their pointer operands. We sort the
3498   /// instructions by their underlying objects to reduce the cost of
3499   /// consecutive access queries.
3500   ///
3501   /// TODO: We can further reduce this cost if we flush the chain creation
3502   ///       every time we run into a memory barrier.
3503   void collectSeedInstructions(BasicBlock *BB);
3504 
3505   /// \brief Try to vectorize a chain that starts at two arithmetic instrs.
3506   bool tryToVectorizePair(Value *A, Value *B, BoUpSLP &R);
3507 
3508   /// \brief Try to vectorize a list of operands.
3509   /// \@param BuildVector A list of users to ignore for the purpose of
3510   ///                     scheduling and that don't need extracting.
3511   /// \returns true if a value was vectorized.
3512   bool tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
3513                           ArrayRef<Value *> BuildVector = None,
3514                           bool allowReorder = false);
3515 
3516   /// \brief Try to vectorize a chain that may start at the operands of \V;
3517   bool tryToVectorize(BinaryOperator *V, BoUpSLP &R);
3518 
3519   /// \brief Vectorize the store instructions collected in Stores.
3520   bool vectorizeStoreChains(BoUpSLP &R);
3521 
3522   /// \brief Vectorize the index computations of the getelementptr instructions
3523   /// collected in GEPs.
3524   bool vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R);
3525 
3526   /// \brief Scan the basic block and look for patterns that are likely to start
3527   /// a vectorization chain.
3528   bool vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R);
3529 
3530   bool vectorizeStoreChain(ArrayRef<Value *> Chain, int CostThreshold,
3531                            BoUpSLP &R, unsigned VecRegSize);
3532 
3533   bool vectorizeStores(ArrayRef<StoreInst *> Stores, int costThreshold,
3534                        BoUpSLP &R);
3535 
3536   /// The store instructions in a basic block organized by base pointer.
3537   StoreListMap Stores;
3538 
3539   /// The getelementptr instructions in a basic block organized by base pointer.
3540   WeakVHListMap GEPs;
3541 
3542   unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
3543   unsigned MinVecRegSize; // Set by cl::opt (default: 128).
3544 };
3545 
3546 /// \brief Check that the Values in the slice in VL array are still existent in
3547 /// the WeakVH array.
3548 /// Vectorization of part of the VL array may cause later values in the VL array
3549 /// to become invalid. We track when this has happened in the WeakVH array.
3550 static bool hasValueBeenRAUWed(ArrayRef<Value *> VL, ArrayRef<WeakVH> VH,
3551                                unsigned SliceBegin, unsigned SliceSize) {
3552   VL = VL.slice(SliceBegin, SliceSize);
3553   VH = VH.slice(SliceBegin, SliceSize);
3554   return !std::equal(VL.begin(), VL.end(), VH.begin());
3555 }
3556 
3557 bool SLPVectorizer::vectorizeStoreChain(ArrayRef<Value *> Chain,
3558                                         int CostThreshold, BoUpSLP &R,
3559                                         unsigned VecRegSize) {
3560   unsigned ChainLen = Chain.size();
3561   DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
3562         << "\n");
3563   unsigned Sz = R.getVectorElementSize(Chain[0]);
3564   unsigned VF = VecRegSize / Sz;
3565 
3566   if (!isPowerOf2_32(Sz) || VF < 2)
3567     return false;
3568 
3569   // Keep track of values that were deleted by vectorizing in the loop below.
3570   SmallVector<WeakVH, 8> TrackValues(Chain.begin(), Chain.end());
3571 
3572   bool Changed = false;
3573   // Look for profitable vectorizable trees at all offsets, starting at zero.
3574   for (unsigned i = 0, e = ChainLen; i < e; ++i) {
3575     if (i + VF > e)
3576       break;
3577 
3578     // Check that a previous iteration of this loop did not delete the Value.
3579     if (hasValueBeenRAUWed(Chain, TrackValues, i, VF))
3580       continue;
3581 
3582     DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
3583           << "\n");
3584     ArrayRef<Value *> Operands = Chain.slice(i, VF);
3585 
3586     R.buildTree(Operands);
3587     R.computeMinimumValueSizes();
3588 
3589     int Cost = R.getTreeCost();
3590 
3591     DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
3592     if (Cost < CostThreshold) {
3593       DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
3594       R.vectorizeTree();
3595 
3596       // Move to the next bundle.
3597       i += VF - 1;
3598       Changed = true;
3599     }
3600   }
3601 
3602   return Changed;
3603 }
3604 
3605 bool SLPVectorizer::vectorizeStores(ArrayRef<StoreInst *> Stores,
3606                                     int costThreshold, BoUpSLP &R) {
3607   SetVector<StoreInst *> Heads, Tails;
3608   SmallDenseMap<StoreInst *, StoreInst *> ConsecutiveChain;
3609 
3610   // We may run into multiple chains that merge into a single chain. We mark the
3611   // stores that we vectorized so that we don't visit the same store twice.
3612   BoUpSLP::ValueSet VectorizedStores;
3613   bool Changed = false;
3614 
3615   // Do a quadratic search on all of the given stores and find
3616   // all of the pairs of stores that follow each other.
3617   SmallVector<unsigned, 16> IndexQueue;
3618   for (unsigned i = 0, e = Stores.size(); i < e; ++i) {
3619     IndexQueue.clear();
3620     // If a store has multiple consecutive store candidates, search Stores
3621     // array according to the sequence: from i+1 to e, then from i-1 to 0.
3622     // This is because usually pairing with immediate succeeding or preceding
3623     // candidate create the best chance to find slp vectorization opportunity.
3624     unsigned j = 0;
3625     for (j = i + 1; j < e; ++j)
3626       IndexQueue.push_back(j);
3627     for (j = i; j > 0; --j)
3628       IndexQueue.push_back(j - 1);
3629 
3630     for (auto &k : IndexQueue) {
3631       if (isConsecutiveAccess(Stores[i], Stores[k], *DL, *SE)) {
3632         Tails.insert(Stores[k]);
3633         Heads.insert(Stores[i]);
3634         ConsecutiveChain[Stores[i]] = Stores[k];
3635         break;
3636       }
3637     }
3638   }
3639 
3640   // For stores that start but don't end a link in the chain:
3641   for (SetVector<StoreInst *>::iterator it = Heads.begin(), e = Heads.end();
3642        it != e; ++it) {
3643     if (Tails.count(*it))
3644       continue;
3645 
3646     // We found a store instr that starts a chain. Now follow the chain and try
3647     // to vectorize it.
3648     BoUpSLP::ValueList Operands;
3649     StoreInst *I = *it;
3650     // Collect the chain into a list.
3651     while (Tails.count(I) || Heads.count(I)) {
3652       if (VectorizedStores.count(I))
3653         break;
3654       Operands.push_back(I);
3655       // Move to the next value in the chain.
3656       I = ConsecutiveChain[I];
3657     }
3658 
3659     // FIXME: Is division-by-2 the correct step? Should we assert that the
3660     // register size is a power-of-2?
3661     for (unsigned Size = MaxVecRegSize; Size >= MinVecRegSize; Size /= 2) {
3662       if (vectorizeStoreChain(Operands, costThreshold, R, Size)) {
3663         // Mark the vectorized stores so that we don't vectorize them again.
3664         VectorizedStores.insert(Operands.begin(), Operands.end());
3665         Changed = true;
3666         break;
3667       }
3668     }
3669   }
3670 
3671   return Changed;
3672 }
3673 
3674 void SLPVectorizer::collectSeedInstructions(BasicBlock *BB) {
3675 
3676   // Initialize the collections. We will make a single pass over the block.
3677   Stores.clear();
3678   GEPs.clear();
3679 
3680   // Visit the store and getelementptr instructions in BB and organize them in
3681   // Stores and GEPs according to the underlying objects of their pointer
3682   // operands.
3683   for (Instruction &I : *BB) {
3684 
3685     // Ignore store instructions that are volatile or have a pointer operand
3686     // that doesn't point to a scalar type.
3687     if (auto *SI = dyn_cast<StoreInst>(&I)) {
3688       if (!SI->isSimple())
3689         continue;
3690       if (!isValidElementType(SI->getValueOperand()->getType()))
3691         continue;
3692       Stores[GetUnderlyingObject(SI->getPointerOperand(), *DL)].push_back(SI);
3693     }
3694 
3695     // Ignore getelementptr instructions that have more than one index, a
3696     // constant index, or a pointer operand that doesn't point to a scalar
3697     // type.
3698     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
3699       auto Idx = GEP->idx_begin()->get();
3700       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
3701         continue;
3702       if (!isValidElementType(Idx->getType()))
3703         continue;
3704       GEPs[GetUnderlyingObject(GEP->getPointerOperand(), *DL)].push_back(GEP);
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_DEPENDENCY(DemandedBitsWrapperPass)
4579 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
4580 
4581 namespace llvm {
4582 Pass *createSLPVectorizerPass() { return new SLPVectorizer(); }
4583 }
4584