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