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 the parent basic block if all of the instructions in \p VL
119 /// are in the same block or null otherwise.
120 static BasicBlock *getSameBlock(ArrayRef<Value *> VL) {
121   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
122   if (!I0)
123     return nullptr;
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 nullptr;
129 
130     if (BB != I->getParent())
131       return nullptr;
132   }
133   return BB;
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 The type that all of the values in \p VL have or null if there
228 /// are different types.
229 static Type* getSameType(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 nullptr;
234 
235   return Ty;
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 (!getSameType(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 SameTy = allConstant(VL) || getSameType(VL); (void)SameTy;
979   bool isAltShuffle = false;
980   assert(SameTy && "Invalid types!");
981 
982   if (Depth == RecursionMaxDepth) {
983     DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
984     newTreeEntry(VL, false);
985     return;
986   }
987 
988   // Don't handle vectors.
989   if (VL[0]->getType()->isVectorTy()) {
990     DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
991     newTreeEntry(VL, false);
992     return;
993   }
994 
995   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
996     if (SI->getValueOperand()->getType()->isVectorTy()) {
997       DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
998       newTreeEntry(VL, false);
999       return;
1000     }
1001   unsigned Opcode = getSameOpcode(VL);
1002 
1003   // Check that this shuffle vector refers to the alternate
1004   // sequence of opcodes.
1005   if (Opcode == Instruction::ShuffleVector) {
1006     Instruction *I0 = dyn_cast<Instruction>(VL[0]);
1007     unsigned Op = I0->getOpcode();
1008     if (Op != Instruction::ShuffleVector)
1009       isAltShuffle = true;
1010   }
1011 
1012   // If all of the operands are identical or constant we have a simple solution.
1013   if (allConstant(VL) || isSplat(VL) || !getSameBlock(VL) || !Opcode) {
1014     DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
1015     newTreeEntry(VL, false);
1016     return;
1017   }
1018 
1019   // We now know that this is a vector of instructions of the same type from
1020   // the same block.
1021 
1022   // Don't vectorize ephemeral values.
1023   for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1024     if (EphValues.count(VL[i])) {
1025       DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
1026             ") is ephemeral.\n");
1027       newTreeEntry(VL, false);
1028       return;
1029     }
1030   }
1031 
1032   // Check if this is a duplicate of another entry.
1033   if (ScalarToTreeEntry.count(VL[0])) {
1034     int Idx = ScalarToTreeEntry[VL[0]];
1035     TreeEntry *E = &VectorizableTree[Idx];
1036     for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1037       DEBUG(dbgs() << "SLP: \tChecking bundle: " << *VL[i] << ".\n");
1038       if (E->Scalars[i] != VL[i]) {
1039         DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
1040         newTreeEntry(VL, false);
1041         return;
1042       }
1043     }
1044     DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *VL[0] << ".\n");
1045     return;
1046   }
1047 
1048   // Check that none of the instructions in the bundle are already in the tree.
1049   for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1050     if (ScalarToTreeEntry.count(VL[i])) {
1051       DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
1052             ") is already in tree.\n");
1053       newTreeEntry(VL, false);
1054       return;
1055     }
1056   }
1057 
1058   // If any of the scalars is marked as a value that needs to stay scalar then
1059   // we need to gather the scalars.
1060   for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1061     if (MustGather.count(VL[i])) {
1062       DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
1063       newTreeEntry(VL, false);
1064       return;
1065     }
1066   }
1067 
1068   // Check that all of the users of the scalars that we want to vectorize are
1069   // schedulable.
1070   Instruction *VL0 = cast<Instruction>(VL[0]);
1071   BasicBlock *BB = cast<Instruction>(VL0)->getParent();
1072 
1073   if (!DT->isReachableFromEntry(BB)) {
1074     // Don't go into unreachable blocks. They may contain instructions with
1075     // dependency cycles which confuse the final scheduling.
1076     DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
1077     newTreeEntry(VL, false);
1078     return;
1079   }
1080 
1081   // Check that every instructions appears once in this bundle.
1082   for (unsigned i = 0, e = VL.size(); i < e; ++i)
1083     for (unsigned j = i+1; j < e; ++j)
1084       if (VL[i] == VL[j]) {
1085         DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
1086         newTreeEntry(VL, false);
1087         return;
1088       }
1089 
1090   auto &BSRef = BlocksSchedules[BB];
1091   if (!BSRef) {
1092     BSRef = llvm::make_unique<BlockScheduling>(BB);
1093   }
1094   BlockScheduling &BS = *BSRef.get();
1095 
1096   if (!BS.tryScheduleBundle(VL, this)) {
1097     DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
1098     assert((!BS.getScheduleData(VL[0]) ||
1099             !BS.getScheduleData(VL[0])->isPartOfBundle()) &&
1100            "tryScheduleBundle should cancelScheduling on failure");
1101     newTreeEntry(VL, false);
1102     return;
1103   }
1104   DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
1105 
1106   switch (Opcode) {
1107     case Instruction::PHI: {
1108       PHINode *PH = dyn_cast<PHINode>(VL0);
1109 
1110       // Check for terminator values (e.g. invoke).
1111       for (unsigned j = 0; j < VL.size(); ++j)
1112         for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1113           TerminatorInst *Term = dyn_cast<TerminatorInst>(
1114               cast<PHINode>(VL[j])->getIncomingValueForBlock(PH->getIncomingBlock(i)));
1115           if (Term) {
1116             DEBUG(dbgs() << "SLP: Need to swizzle PHINodes (TerminatorInst use).\n");
1117             BS.cancelScheduling(VL);
1118             newTreeEntry(VL, false);
1119             return;
1120           }
1121         }
1122 
1123       newTreeEntry(VL, true);
1124       DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
1125 
1126       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1127         ValueList Operands;
1128         // Prepare the operand vector.
1129         for (Value *j : VL)
1130           Operands.push_back(cast<PHINode>(j)->getIncomingValueForBlock(
1131               PH->getIncomingBlock(i)));
1132 
1133         buildTree_rec(Operands, Depth + 1);
1134       }
1135       return;
1136     }
1137     case Instruction::ExtractValue:
1138     case Instruction::ExtractElement: {
1139       bool Reuse = canReuseExtract(VL, Opcode);
1140       if (Reuse) {
1141         DEBUG(dbgs() << "SLP: Reusing extract sequence.\n");
1142       } else {
1143         BS.cancelScheduling(VL);
1144       }
1145       newTreeEntry(VL, Reuse);
1146       return;
1147     }
1148     case Instruction::Load: {
1149       // Check that a vectorized load would load the same memory as a scalar
1150       // load.
1151       // For example we don't want vectorize loads that are smaller than 8 bit.
1152       // Even though we have a packed struct {<i2, i2, i2, i2>} LLVM treats
1153       // loading/storing it as an i8 struct. If we vectorize loads/stores from
1154       // such a struct we read/write packed bits disagreeing with the
1155       // unvectorized version.
1156       Type *ScalarTy = VL[0]->getType();
1157 
1158       if (DL->getTypeSizeInBits(ScalarTy) !=
1159           DL->getTypeAllocSizeInBits(ScalarTy)) {
1160         BS.cancelScheduling(VL);
1161         newTreeEntry(VL, false);
1162         DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
1163         return;
1164       }
1165 
1166       // Make sure all loads in the bundle are simple - we can't vectorize
1167       // atomic or volatile loads.
1168       for (unsigned i = 0, e = VL.size() - 1; i < e; ++i) {
1169         LoadInst *L = cast<LoadInst>(VL[i]);
1170         if (!L->isSimple()) {
1171           BS.cancelScheduling(VL);
1172           newTreeEntry(VL, false);
1173           DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
1174           return;
1175         }
1176       }
1177 
1178       // Check if the loads are consecutive, reversed, or neither.
1179       // TODO: What we really want is to sort the loads, but for now, check
1180       // the two likely directions.
1181       bool Consecutive = true;
1182       bool ReverseConsecutive = true;
1183       for (unsigned i = 0, e = VL.size() - 1; i < e; ++i) {
1184         if (!isConsecutiveAccess(VL[i], VL[i + 1], *DL, *SE)) {
1185           Consecutive = false;
1186           break;
1187         } else {
1188           ReverseConsecutive = false;
1189         }
1190       }
1191 
1192       if (Consecutive) {
1193         ++NumLoadsWantToKeepOrder;
1194         newTreeEntry(VL, true);
1195         DEBUG(dbgs() << "SLP: added a vector of loads.\n");
1196         return;
1197       }
1198 
1199       // If none of the load pairs were consecutive when checked in order,
1200       // check the reverse order.
1201       if (ReverseConsecutive)
1202         for (unsigned i = VL.size() - 1; i > 0; --i)
1203           if (!isConsecutiveAccess(VL[i], VL[i - 1], *DL, *SE)) {
1204             ReverseConsecutive = false;
1205             break;
1206           }
1207 
1208       BS.cancelScheduling(VL);
1209       newTreeEntry(VL, false);
1210 
1211       if (ReverseConsecutive) {
1212         ++NumLoadsWantToChangeOrder;
1213         DEBUG(dbgs() << "SLP: Gathering reversed loads.\n");
1214       } else {
1215         DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
1216       }
1217       return;
1218     }
1219     case Instruction::ZExt:
1220     case Instruction::SExt:
1221     case Instruction::FPToUI:
1222     case Instruction::FPToSI:
1223     case Instruction::FPExt:
1224     case Instruction::PtrToInt:
1225     case Instruction::IntToPtr:
1226     case Instruction::SIToFP:
1227     case Instruction::UIToFP:
1228     case Instruction::Trunc:
1229     case Instruction::FPTrunc:
1230     case Instruction::BitCast: {
1231       Type *SrcTy = VL0->getOperand(0)->getType();
1232       for (unsigned i = 0; i < VL.size(); ++i) {
1233         Type *Ty = cast<Instruction>(VL[i])->getOperand(0)->getType();
1234         if (Ty != SrcTy || !isValidElementType(Ty)) {
1235           BS.cancelScheduling(VL);
1236           newTreeEntry(VL, false);
1237           DEBUG(dbgs() << "SLP: Gathering casts with different src types.\n");
1238           return;
1239         }
1240       }
1241       newTreeEntry(VL, true);
1242       DEBUG(dbgs() << "SLP: added a vector of casts.\n");
1243 
1244       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1245         ValueList Operands;
1246         // Prepare the operand vector.
1247         for (Value *j : VL)
1248           Operands.push_back(cast<Instruction>(j)->getOperand(i));
1249 
1250         buildTree_rec(Operands, Depth+1);
1251       }
1252       return;
1253     }
1254     case Instruction::ICmp:
1255     case Instruction::FCmp: {
1256       // Check that all of the compares have the same predicate.
1257       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
1258       Type *ComparedTy = cast<Instruction>(VL[0])->getOperand(0)->getType();
1259       for (unsigned i = 1, e = VL.size(); i < e; ++i) {
1260         CmpInst *Cmp = cast<CmpInst>(VL[i]);
1261         if (Cmp->getPredicate() != P0 ||
1262             Cmp->getOperand(0)->getType() != ComparedTy) {
1263           BS.cancelScheduling(VL);
1264           newTreeEntry(VL, false);
1265           DEBUG(dbgs() << "SLP: Gathering cmp with different predicate.\n");
1266           return;
1267         }
1268       }
1269 
1270       newTreeEntry(VL, true);
1271       DEBUG(dbgs() << "SLP: added a vector of compares.\n");
1272 
1273       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1274         ValueList Operands;
1275         // Prepare the operand vector.
1276         for (Value *j : VL)
1277           Operands.push_back(cast<Instruction>(j)->getOperand(i));
1278 
1279         buildTree_rec(Operands, Depth+1);
1280       }
1281       return;
1282     }
1283     case Instruction::Select:
1284     case Instruction::Add:
1285     case Instruction::FAdd:
1286     case Instruction::Sub:
1287     case Instruction::FSub:
1288     case Instruction::Mul:
1289     case Instruction::FMul:
1290     case Instruction::UDiv:
1291     case Instruction::SDiv:
1292     case Instruction::FDiv:
1293     case Instruction::URem:
1294     case Instruction::SRem:
1295     case Instruction::FRem:
1296     case Instruction::Shl:
1297     case Instruction::LShr:
1298     case Instruction::AShr:
1299     case Instruction::And:
1300     case Instruction::Or:
1301     case Instruction::Xor: {
1302       newTreeEntry(VL, true);
1303       DEBUG(dbgs() << "SLP: added a vector of bin op.\n");
1304 
1305       // Sort operands of the instructions so that each side is more likely to
1306       // have the same opcode.
1307       if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
1308         ValueList Left, Right;
1309         reorderInputsAccordingToOpcode(VL, Left, Right);
1310         buildTree_rec(Left, Depth + 1);
1311         buildTree_rec(Right, Depth + 1);
1312         return;
1313       }
1314 
1315       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1316         ValueList Operands;
1317         // Prepare the operand vector.
1318         for (Value *j : VL)
1319           Operands.push_back(cast<Instruction>(j)->getOperand(i));
1320 
1321         buildTree_rec(Operands, Depth+1);
1322       }
1323       return;
1324     }
1325     case Instruction::GetElementPtr: {
1326       // We don't combine GEPs with complicated (nested) indexing.
1327       for (unsigned j = 0; j < VL.size(); ++j) {
1328         if (cast<Instruction>(VL[j])->getNumOperands() != 2) {
1329           DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
1330           BS.cancelScheduling(VL);
1331           newTreeEntry(VL, false);
1332           return;
1333         }
1334       }
1335 
1336       // We can't combine several GEPs into one vector if they operate on
1337       // different types.
1338       Type *Ty0 = cast<Instruction>(VL0)->getOperand(0)->getType();
1339       for (unsigned j = 0; j < VL.size(); ++j) {
1340         Type *CurTy = cast<Instruction>(VL[j])->getOperand(0)->getType();
1341         if (Ty0 != CurTy) {
1342           DEBUG(dbgs() << "SLP: not-vectorizable GEP (different types).\n");
1343           BS.cancelScheduling(VL);
1344           newTreeEntry(VL, false);
1345           return;
1346         }
1347       }
1348 
1349       // We don't combine GEPs with non-constant indexes.
1350       for (unsigned j = 0; j < VL.size(); ++j) {
1351         auto Op = cast<Instruction>(VL[j])->getOperand(1);
1352         if (!isa<ConstantInt>(Op)) {
1353           DEBUG(
1354               dbgs() << "SLP: not-vectorizable GEP (non-constant indexes).\n");
1355           BS.cancelScheduling(VL);
1356           newTreeEntry(VL, false);
1357           return;
1358         }
1359       }
1360 
1361       newTreeEntry(VL, true);
1362       DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
1363       for (unsigned i = 0, e = 2; i < e; ++i) {
1364         ValueList Operands;
1365         // Prepare the operand vector.
1366         for (Value *j : VL)
1367           Operands.push_back(cast<Instruction>(j)->getOperand(i));
1368 
1369         buildTree_rec(Operands, Depth + 1);
1370       }
1371       return;
1372     }
1373     case Instruction::Store: {
1374       // Check if the stores are consecutive or of we need to swizzle them.
1375       for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
1376         if (!isConsecutiveAccess(VL[i], VL[i + 1], *DL, *SE)) {
1377           BS.cancelScheduling(VL);
1378           newTreeEntry(VL, false);
1379           DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
1380           return;
1381         }
1382 
1383       newTreeEntry(VL, true);
1384       DEBUG(dbgs() << "SLP: added a vector of stores.\n");
1385 
1386       ValueList Operands;
1387       for (Value *j : VL)
1388         Operands.push_back(cast<Instruction>(j)->getOperand(0));
1389 
1390       buildTree_rec(Operands, Depth + 1);
1391       return;
1392     }
1393     case Instruction::Call: {
1394       // Check if the calls are all to the same vectorizable intrinsic.
1395       CallInst *CI = cast<CallInst>(VL[0]);
1396       // Check if this is an Intrinsic call or something that can be
1397       // represented by an intrinsic call
1398       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
1399       if (!isTriviallyVectorizable(ID)) {
1400         BS.cancelScheduling(VL);
1401         newTreeEntry(VL, false);
1402         DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
1403         return;
1404       }
1405       Function *Int = CI->getCalledFunction();
1406       Value *A1I = nullptr;
1407       if (hasVectorInstrinsicScalarOpd(ID, 1))
1408         A1I = CI->getArgOperand(1);
1409       for (unsigned i = 1, e = VL.size(); i != e; ++i) {
1410         CallInst *CI2 = dyn_cast<CallInst>(VL[i]);
1411         if (!CI2 || CI2->getCalledFunction() != Int ||
1412             getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
1413             !CI->hasIdenticalOperandBundleSchema(*CI2)) {
1414           BS.cancelScheduling(VL);
1415           newTreeEntry(VL, false);
1416           DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *VL[i]
1417                        << "\n");
1418           return;
1419         }
1420         // ctlz,cttz and powi are special intrinsics whose second argument
1421         // should be same in order for them to be vectorized.
1422         if (hasVectorInstrinsicScalarOpd(ID, 1)) {
1423           Value *A1J = CI2->getArgOperand(1);
1424           if (A1I != A1J) {
1425             BS.cancelScheduling(VL);
1426             newTreeEntry(VL, false);
1427             DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
1428                          << " argument "<< A1I<<"!=" << A1J
1429                          << "\n");
1430             return;
1431           }
1432         }
1433         // Verify that the bundle operands are identical between the two calls.
1434         if (CI->hasOperandBundles() &&
1435             !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
1436                         CI->op_begin() + CI->getBundleOperandsEndIndex(),
1437                         CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
1438           BS.cancelScheduling(VL);
1439           newTreeEntry(VL, false);
1440           DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:" << *CI << "!="
1441                        << *VL[i] << '\n');
1442           return;
1443         }
1444       }
1445 
1446       newTreeEntry(VL, true);
1447       for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i) {
1448         ValueList Operands;
1449         // Prepare the operand vector.
1450         for (Value *j : VL) {
1451           CallInst *CI2 = dyn_cast<CallInst>(j);
1452           Operands.push_back(CI2->getArgOperand(i));
1453         }
1454         buildTree_rec(Operands, Depth + 1);
1455       }
1456       return;
1457     }
1458     case Instruction::ShuffleVector: {
1459       // If this is not an alternate sequence of opcode like add-sub
1460       // then do not vectorize this instruction.
1461       if (!isAltShuffle) {
1462         BS.cancelScheduling(VL);
1463         newTreeEntry(VL, false);
1464         DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
1465         return;
1466       }
1467       newTreeEntry(VL, true);
1468       DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
1469 
1470       // Reorder operands if reordering would enable vectorization.
1471       if (isa<BinaryOperator>(VL0)) {
1472         ValueList Left, Right;
1473         reorderAltShuffleOperands(VL, Left, Right);
1474         buildTree_rec(Left, Depth + 1);
1475         buildTree_rec(Right, Depth + 1);
1476         return;
1477       }
1478 
1479       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1480         ValueList Operands;
1481         // Prepare the operand vector.
1482         for (Value *j : VL)
1483           Operands.push_back(cast<Instruction>(j)->getOperand(i));
1484 
1485         buildTree_rec(Operands, Depth + 1);
1486       }
1487       return;
1488     }
1489     default:
1490       BS.cancelScheduling(VL);
1491       newTreeEntry(VL, false);
1492       DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
1493       return;
1494   }
1495 }
1496 
1497 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
1498   unsigned N;
1499   Type *EltTy;
1500   auto *ST = dyn_cast<StructType>(T);
1501   if (ST) {
1502     N = ST->getNumElements();
1503     EltTy = *ST->element_begin();
1504   } else {
1505     N = cast<ArrayType>(T)->getNumElements();
1506     EltTy = cast<ArrayType>(T)->getElementType();
1507   }
1508   if (!isValidElementType(EltTy))
1509     return 0;
1510   uint64_t VTSize = DL.getTypeStoreSizeInBits(VectorType::get(EltTy, N));
1511   if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
1512     return 0;
1513   if (ST) {
1514     // Check that struct is homogeneous.
1515     for (const auto *Ty : ST->elements())
1516       if (Ty != EltTy)
1517         return 0;
1518   }
1519   return N;
1520 }
1521 
1522 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, unsigned Opcode) const {
1523   assert(Opcode == Instruction::ExtractElement ||
1524          Opcode == Instruction::ExtractValue);
1525   assert(Opcode == getSameOpcode(VL) && "Invalid opcode");
1526   // Check if all of the extracts come from the same vector and from the
1527   // correct offset.
1528   Value *VL0 = VL[0];
1529   Instruction *E0 = cast<Instruction>(VL0);
1530   Value *Vec = E0->getOperand(0);
1531 
1532   // We have to extract from a vector/aggregate with the same number of elements.
1533   unsigned NElts;
1534   if (Opcode == Instruction::ExtractValue) {
1535     const DataLayout &DL = E0->getModule()->getDataLayout();
1536     NElts = canMapToVector(Vec->getType(), DL);
1537     if (!NElts)
1538       return false;
1539     // Check if load can be rewritten as load of vector.
1540     LoadInst *LI = dyn_cast<LoadInst>(Vec);
1541     if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
1542       return false;
1543   } else {
1544     NElts = Vec->getType()->getVectorNumElements();
1545   }
1546 
1547   if (NElts != VL.size())
1548     return false;
1549 
1550   // Check that all of the indices extract from the correct offset.
1551   if (!matchExtractIndex(E0, 0, Opcode))
1552     return false;
1553 
1554   for (unsigned i = 1, e = VL.size(); i < e; ++i) {
1555     Instruction *E = cast<Instruction>(VL[i]);
1556     if (!matchExtractIndex(E, i, Opcode))
1557       return false;
1558     if (E->getOperand(0) != Vec)
1559       return false;
1560   }
1561 
1562   return true;
1563 }
1564 
1565 int BoUpSLP::getEntryCost(TreeEntry *E) {
1566   ArrayRef<Value*> VL = E->Scalars;
1567 
1568   Type *ScalarTy = VL[0]->getType();
1569   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1570     ScalarTy = SI->getValueOperand()->getType();
1571   VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1572 
1573   // If we have computed a smaller type for the expression, update VecTy so
1574   // that the costs will be accurate.
1575   if (MinBWs.count(VL[0]))
1576     VecTy = VectorType::get(IntegerType::get(F->getContext(), MinBWs[VL[0]]),
1577                             VL.size());
1578 
1579   if (E->NeedToGather) {
1580     if (allConstant(VL))
1581       return 0;
1582     if (isSplat(VL)) {
1583       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
1584     }
1585     return getGatherCost(E->Scalars);
1586   }
1587   unsigned Opcode = getSameOpcode(VL);
1588   assert(Opcode && getSameType(VL) && getSameBlock(VL) && "Invalid VL");
1589   Instruction *VL0 = cast<Instruction>(VL[0]);
1590   switch (Opcode) {
1591     case Instruction::PHI: {
1592       return 0;
1593     }
1594     case Instruction::ExtractValue:
1595     case Instruction::ExtractElement: {
1596       if (canReuseExtract(VL, Opcode)) {
1597         int DeadCost = 0;
1598         for (unsigned i = 0, e = VL.size(); i < e; ++i) {
1599           Instruction *E = cast<Instruction>(VL[i]);
1600           if (E->hasOneUse())
1601             // Take credit for instruction that will become dead.
1602             DeadCost +=
1603                 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, i);
1604         }
1605         return -DeadCost;
1606       }
1607       return getGatherCost(VecTy);
1608     }
1609     case Instruction::ZExt:
1610     case Instruction::SExt:
1611     case Instruction::FPToUI:
1612     case Instruction::FPToSI:
1613     case Instruction::FPExt:
1614     case Instruction::PtrToInt:
1615     case Instruction::IntToPtr:
1616     case Instruction::SIToFP:
1617     case Instruction::UIToFP:
1618     case Instruction::Trunc:
1619     case Instruction::FPTrunc:
1620     case Instruction::BitCast: {
1621       Type *SrcTy = VL0->getOperand(0)->getType();
1622 
1623       // Calculate the cost of this instruction.
1624       int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(),
1625                                                          VL0->getType(), SrcTy);
1626 
1627       VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
1628       int VecCost = TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy);
1629       return VecCost - ScalarCost;
1630     }
1631     case Instruction::FCmp:
1632     case Instruction::ICmp:
1633     case Instruction::Select: {
1634       // Calculate the cost of this instruction.
1635       VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
1636       int ScalarCost = VecTy->getNumElements() *
1637           TTI->getCmpSelInstrCost(Opcode, ScalarTy, Builder.getInt1Ty());
1638       int VecCost = TTI->getCmpSelInstrCost(Opcode, VecTy, MaskTy);
1639       return VecCost - ScalarCost;
1640     }
1641     case Instruction::Add:
1642     case Instruction::FAdd:
1643     case Instruction::Sub:
1644     case Instruction::FSub:
1645     case Instruction::Mul:
1646     case Instruction::FMul:
1647     case Instruction::UDiv:
1648     case Instruction::SDiv:
1649     case Instruction::FDiv:
1650     case Instruction::URem:
1651     case Instruction::SRem:
1652     case Instruction::FRem:
1653     case Instruction::Shl:
1654     case Instruction::LShr:
1655     case Instruction::AShr:
1656     case Instruction::And:
1657     case Instruction::Or:
1658     case Instruction::Xor: {
1659       // Certain instructions can be cheaper to vectorize if they have a
1660       // constant second vector operand.
1661       TargetTransformInfo::OperandValueKind Op1VK =
1662           TargetTransformInfo::OK_AnyValue;
1663       TargetTransformInfo::OperandValueKind Op2VK =
1664           TargetTransformInfo::OK_UniformConstantValue;
1665       TargetTransformInfo::OperandValueProperties Op1VP =
1666           TargetTransformInfo::OP_None;
1667       TargetTransformInfo::OperandValueProperties Op2VP =
1668           TargetTransformInfo::OP_None;
1669 
1670       // If all operands are exactly the same ConstantInt then set the
1671       // operand kind to OK_UniformConstantValue.
1672       // If instead not all operands are constants, then set the operand kind
1673       // to OK_AnyValue. If all operands are constants but not the same,
1674       // then set the operand kind to OK_NonUniformConstantValue.
1675       ConstantInt *CInt = nullptr;
1676       for (unsigned i = 0; i < VL.size(); ++i) {
1677         const Instruction *I = cast<Instruction>(VL[i]);
1678         if (!isa<ConstantInt>(I->getOperand(1))) {
1679           Op2VK = TargetTransformInfo::OK_AnyValue;
1680           break;
1681         }
1682         if (i == 0) {
1683           CInt = cast<ConstantInt>(I->getOperand(1));
1684           continue;
1685         }
1686         if (Op2VK == TargetTransformInfo::OK_UniformConstantValue &&
1687             CInt != cast<ConstantInt>(I->getOperand(1)))
1688           Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
1689       }
1690       // FIXME: Currently cost of model modification for division by power of
1691       // 2 is handled for X86 and AArch64. Add support for other targets.
1692       if (Op2VK == TargetTransformInfo::OK_UniformConstantValue && CInt &&
1693           CInt->getValue().isPowerOf2())
1694         Op2VP = TargetTransformInfo::OP_PowerOf2;
1695 
1696       int ScalarCost = VecTy->getNumElements() *
1697                        TTI->getArithmeticInstrCost(Opcode, ScalarTy, Op1VK,
1698                                                    Op2VK, Op1VP, Op2VP);
1699       int VecCost = TTI->getArithmeticInstrCost(Opcode, VecTy, Op1VK, Op2VK,
1700                                                 Op1VP, Op2VP);
1701       return VecCost - ScalarCost;
1702     }
1703     case Instruction::GetElementPtr: {
1704       TargetTransformInfo::OperandValueKind Op1VK =
1705           TargetTransformInfo::OK_AnyValue;
1706       TargetTransformInfo::OperandValueKind Op2VK =
1707           TargetTransformInfo::OK_UniformConstantValue;
1708 
1709       int ScalarCost =
1710           VecTy->getNumElements() *
1711           TTI->getArithmeticInstrCost(Instruction::Add, ScalarTy, Op1VK, Op2VK);
1712       int VecCost =
1713           TTI->getArithmeticInstrCost(Instruction::Add, VecTy, Op1VK, Op2VK);
1714 
1715       return VecCost - ScalarCost;
1716     }
1717     case Instruction::Load: {
1718       // Cost of wide load - cost of scalar loads.
1719       unsigned alignment = dyn_cast<LoadInst>(VL0)->getAlignment();
1720       int ScalarLdCost = VecTy->getNumElements() *
1721             TTI->getMemoryOpCost(Instruction::Load, ScalarTy, alignment, 0);
1722       int VecLdCost = TTI->getMemoryOpCost(Instruction::Load,
1723                                            VecTy, alignment, 0);
1724       return VecLdCost - ScalarLdCost;
1725     }
1726     case Instruction::Store: {
1727       // We know that we can merge the stores. Calculate the cost.
1728       unsigned alignment = dyn_cast<StoreInst>(VL0)->getAlignment();
1729       int ScalarStCost = VecTy->getNumElements() *
1730             TTI->getMemoryOpCost(Instruction::Store, ScalarTy, alignment, 0);
1731       int VecStCost = TTI->getMemoryOpCost(Instruction::Store,
1732                                            VecTy, alignment, 0);
1733       return VecStCost - ScalarStCost;
1734     }
1735     case Instruction::Call: {
1736       CallInst *CI = cast<CallInst>(VL0);
1737       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
1738 
1739       // Calculate the cost of the scalar and vector calls.
1740       SmallVector<Type*, 4> ScalarTys, VecTys;
1741       for (unsigned op = 0, opc = CI->getNumArgOperands(); op!= opc; ++op) {
1742         ScalarTys.push_back(CI->getArgOperand(op)->getType());
1743         VecTys.push_back(VectorType::get(CI->getArgOperand(op)->getType(),
1744                                          VecTy->getNumElements()));
1745       }
1746 
1747       FastMathFlags FMF;
1748       if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
1749         FMF = FPMO->getFastMathFlags();
1750 
1751       int ScalarCallCost = VecTy->getNumElements() *
1752           TTI->getIntrinsicInstrCost(ID, ScalarTy, ScalarTys, FMF);
1753 
1754       int VecCallCost = TTI->getIntrinsicInstrCost(ID, VecTy, VecTys, FMF);
1755 
1756       DEBUG(dbgs() << "SLP: Call cost "<< VecCallCost - ScalarCallCost
1757             << " (" << VecCallCost  << "-" <<  ScalarCallCost << ")"
1758             << " for " << *CI << "\n");
1759 
1760       return VecCallCost - ScalarCallCost;
1761     }
1762     case Instruction::ShuffleVector: {
1763       TargetTransformInfo::OperandValueKind Op1VK =
1764           TargetTransformInfo::OK_AnyValue;
1765       TargetTransformInfo::OperandValueKind Op2VK =
1766           TargetTransformInfo::OK_AnyValue;
1767       int ScalarCost = 0;
1768       int VecCost = 0;
1769       for (Value *i : VL) {
1770         Instruction *I = cast<Instruction>(i);
1771         if (!I)
1772           break;
1773         ScalarCost +=
1774             TTI->getArithmeticInstrCost(I->getOpcode(), ScalarTy, Op1VK, Op2VK);
1775       }
1776       // VecCost is equal to sum of the cost of creating 2 vectors
1777       // and the cost of creating shuffle.
1778       Instruction *I0 = cast<Instruction>(VL[0]);
1779       VecCost =
1780           TTI->getArithmeticInstrCost(I0->getOpcode(), VecTy, Op1VK, Op2VK);
1781       Instruction *I1 = cast<Instruction>(VL[1]);
1782       VecCost +=
1783           TTI->getArithmeticInstrCost(I1->getOpcode(), VecTy, Op1VK, Op2VK);
1784       VecCost +=
1785           TTI->getShuffleCost(TargetTransformInfo::SK_Alternate, VecTy, 0);
1786       return VecCost - ScalarCost;
1787     }
1788     default:
1789       llvm_unreachable("Unknown instruction");
1790   }
1791 }
1792 
1793 bool BoUpSLP::isFullyVectorizableTinyTree() {
1794   DEBUG(dbgs() << "SLP: Check whether the tree with height " <<
1795         VectorizableTree.size() << " is fully vectorizable .\n");
1796 
1797   // We only handle trees of height 2.
1798   if (VectorizableTree.size() != 2)
1799     return false;
1800 
1801   // Handle splat and all-constants stores.
1802   if (!VectorizableTree[0].NeedToGather &&
1803       (allConstant(VectorizableTree[1].Scalars) ||
1804        isSplat(VectorizableTree[1].Scalars)))
1805     return true;
1806 
1807   // Gathering cost would be too much for tiny trees.
1808   if (VectorizableTree[0].NeedToGather || VectorizableTree[1].NeedToGather)
1809     return false;
1810 
1811   return true;
1812 }
1813 
1814 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable() {
1815 
1816   // We can vectorize the tree if its size is greater than or equal to the
1817   // minimum size specified by the MinTreeSize command line option.
1818   if (VectorizableTree.size() >= MinTreeSize)
1819     return false;
1820 
1821   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
1822   // can vectorize it if we can prove it fully vectorizable.
1823   if (isFullyVectorizableTinyTree())
1824     return false;
1825 
1826   assert(VectorizableTree.empty()
1827              ? ExternalUses.empty()
1828              : true && "We shouldn't have any external users");
1829 
1830   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
1831   // vectorizable.
1832   return true;
1833 }
1834 
1835 int BoUpSLP::getSpillCost() {
1836   // Walk from the bottom of the tree to the top, tracking which values are
1837   // live. When we see a call instruction that is not part of our tree,
1838   // query TTI to see if there is a cost to keeping values live over it
1839   // (for example, if spills and fills are required).
1840   unsigned BundleWidth = VectorizableTree.front().Scalars.size();
1841   int Cost = 0;
1842 
1843   SmallPtrSet<Instruction*, 4> LiveValues;
1844   Instruction *PrevInst = nullptr;
1845 
1846   for (const auto &N : VectorizableTree) {
1847     Instruction *Inst = dyn_cast<Instruction>(N.Scalars[0]);
1848     if (!Inst)
1849       continue;
1850 
1851     if (!PrevInst) {
1852       PrevInst = Inst;
1853       continue;
1854     }
1855 
1856     // Update LiveValues.
1857     LiveValues.erase(PrevInst);
1858     for (auto &J : PrevInst->operands()) {
1859       if (isa<Instruction>(&*J) && ScalarToTreeEntry.count(&*J))
1860         LiveValues.insert(cast<Instruction>(&*J));
1861     }
1862 
1863     DEBUG(
1864       dbgs() << "SLP: #LV: " << LiveValues.size();
1865       for (auto *X : LiveValues)
1866         dbgs() << " " << X->getName();
1867       dbgs() << ", Looking at ";
1868       Inst->dump();
1869       );
1870 
1871     // Now find the sequence of instructions between PrevInst and Inst.
1872     BasicBlock::reverse_iterator InstIt(Inst->getIterator()),
1873         PrevInstIt(PrevInst->getIterator());
1874     --PrevInstIt;
1875     while (InstIt != PrevInstIt) {
1876       if (PrevInstIt == PrevInst->getParent()->rend()) {
1877         PrevInstIt = Inst->getParent()->rbegin();
1878         continue;
1879       }
1880 
1881       if (isa<CallInst>(&*PrevInstIt) && &*PrevInstIt != PrevInst) {
1882         SmallVector<Type*, 4> V;
1883         for (auto *II : LiveValues)
1884           V.push_back(VectorType::get(II->getType(), BundleWidth));
1885         Cost += TTI->getCostOfKeepingLiveOverCall(V);
1886       }
1887 
1888       ++PrevInstIt;
1889     }
1890 
1891     PrevInst = Inst;
1892   }
1893 
1894   return Cost;
1895 }
1896 
1897 int BoUpSLP::getTreeCost() {
1898   int Cost = 0;
1899   DEBUG(dbgs() << "SLP: Calculating cost for tree of size " <<
1900         VectorizableTree.size() << ".\n");
1901 
1902   unsigned BundleWidth = VectorizableTree[0].Scalars.size();
1903 
1904   for (TreeEntry &TE : VectorizableTree) {
1905     int C = getEntryCost(&TE);
1906     DEBUG(dbgs() << "SLP: Adding cost " << C << " for bundle that starts with "
1907                  << *TE.Scalars[0] << ".\n");
1908     Cost += C;
1909   }
1910 
1911   SmallSet<Value *, 16> ExtractCostCalculated;
1912   int ExtractCost = 0;
1913   for (ExternalUser &EU : ExternalUses) {
1914     // We only add extract cost once for the same scalar.
1915     if (!ExtractCostCalculated.insert(EU.Scalar).second)
1916       continue;
1917 
1918     // Uses by ephemeral values are free (because the ephemeral value will be
1919     // removed prior to code generation, and so the extraction will be
1920     // removed as well).
1921     if (EphValues.count(EU.User))
1922       continue;
1923 
1924     // If we plan to rewrite the tree in a smaller type, we will need to sign
1925     // extend the extracted value back to the original type. Here, we account
1926     // for the extract and the added cost of the sign extend if needed.
1927     auto *VecTy = VectorType::get(EU.Scalar->getType(), BundleWidth);
1928     auto *ScalarRoot = VectorizableTree[0].Scalars[0];
1929     if (MinBWs.count(ScalarRoot)) {
1930       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot]);
1931       VecTy = VectorType::get(MinTy, BundleWidth);
1932       ExtractCost += TTI->getExtractWithExtendCost(
1933           Instruction::SExt, EU.Scalar->getType(), VecTy, EU.Lane);
1934     } else {
1935       ExtractCost +=
1936           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
1937     }
1938   }
1939 
1940   int SpillCost = getSpillCost();
1941   Cost += SpillCost + ExtractCost;
1942 
1943   DEBUG(dbgs() << "SLP: Spill Cost = " << SpillCost << ".\n"
1944                << "SLP: Extract Cost = " << ExtractCost << ".\n"
1945                << "SLP: Total Cost = " << Cost << ".\n");
1946   return Cost;
1947 }
1948 
1949 int BoUpSLP::getGatherCost(Type *Ty) {
1950   int Cost = 0;
1951   for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
1952     Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
1953   return Cost;
1954 }
1955 
1956 int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) {
1957   // Find the type of the operands in VL.
1958   Type *ScalarTy = VL[0]->getType();
1959   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1960     ScalarTy = SI->getValueOperand()->getType();
1961   VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1962   // Find the cost of inserting/extracting values from the vector.
1963   return getGatherCost(VecTy);
1964 }
1965 
1966 // Reorder commutative operations in alternate shuffle if the resulting vectors
1967 // are consecutive loads. This would allow us to vectorize the tree.
1968 // If we have something like-
1969 // load a[0] - load b[0]
1970 // load b[1] + load a[1]
1971 // load a[2] - load b[2]
1972 // load a[3] + load b[3]
1973 // Reordering the second load b[1]  load a[1] would allow us to vectorize this
1974 // code.
1975 void BoUpSLP::reorderAltShuffleOperands(ArrayRef<Value *> VL,
1976                                         SmallVectorImpl<Value *> &Left,
1977                                         SmallVectorImpl<Value *> &Right) {
1978   // Push left and right operands of binary operation into Left and Right
1979   for (Value *i : VL) {
1980     Left.push_back(cast<Instruction>(i)->getOperand(0));
1981     Right.push_back(cast<Instruction>(i)->getOperand(1));
1982   }
1983 
1984   // Reorder if we have a commutative operation and consecutive access
1985   // are on either side of the alternate instructions.
1986   for (unsigned j = 0; j < VL.size() - 1; ++j) {
1987     if (LoadInst *L = dyn_cast<LoadInst>(Left[j])) {
1988       if (LoadInst *L1 = dyn_cast<LoadInst>(Right[j + 1])) {
1989         Instruction *VL1 = cast<Instruction>(VL[j]);
1990         Instruction *VL2 = cast<Instruction>(VL[j + 1]);
1991         if (VL1->isCommutative() && isConsecutiveAccess(L, L1, *DL, *SE)) {
1992           std::swap(Left[j], Right[j]);
1993           continue;
1994         } else if (VL2->isCommutative() &&
1995                    isConsecutiveAccess(L, L1, *DL, *SE)) {
1996           std::swap(Left[j + 1], Right[j + 1]);
1997           continue;
1998         }
1999         // else unchanged
2000       }
2001     }
2002     if (LoadInst *L = dyn_cast<LoadInst>(Right[j])) {
2003       if (LoadInst *L1 = dyn_cast<LoadInst>(Left[j + 1])) {
2004         Instruction *VL1 = cast<Instruction>(VL[j]);
2005         Instruction *VL2 = cast<Instruction>(VL[j + 1]);
2006         if (VL1->isCommutative() && isConsecutiveAccess(L, L1, *DL, *SE)) {
2007           std::swap(Left[j], Right[j]);
2008           continue;
2009         } else if (VL2->isCommutative() &&
2010                    isConsecutiveAccess(L, L1, *DL, *SE)) {
2011           std::swap(Left[j + 1], Right[j + 1]);
2012           continue;
2013         }
2014         // else unchanged
2015       }
2016     }
2017   }
2018 }
2019 
2020 // Return true if I should be commuted before adding it's left and right
2021 // operands to the arrays Left and Right.
2022 //
2023 // The vectorizer is trying to either have all elements one side being
2024 // instruction with the same opcode to enable further vectorization, or having
2025 // a splat to lower the vectorizing cost.
2026 static bool shouldReorderOperands(int i, Instruction &I,
2027                                   SmallVectorImpl<Value *> &Left,
2028                                   SmallVectorImpl<Value *> &Right,
2029                                   bool AllSameOpcodeLeft,
2030                                   bool AllSameOpcodeRight, bool SplatLeft,
2031                                   bool SplatRight) {
2032   Value *VLeft = I.getOperand(0);
2033   Value *VRight = I.getOperand(1);
2034   // If we have "SplatRight", try to see if commuting is needed to preserve it.
2035   if (SplatRight) {
2036     if (VRight == Right[i - 1])
2037       // Preserve SplatRight
2038       return false;
2039     if (VLeft == Right[i - 1]) {
2040       // Commuting would preserve SplatRight, but we don't want to break
2041       // SplatLeft either, i.e. preserve the original order if possible.
2042       // (FIXME: why do we care?)
2043       if (SplatLeft && VLeft == Left[i - 1])
2044         return false;
2045       return true;
2046     }
2047   }
2048   // Symmetrically handle Right side.
2049   if (SplatLeft) {
2050     if (VLeft == Left[i - 1])
2051       // Preserve SplatLeft
2052       return false;
2053     if (VRight == Left[i - 1])
2054       return true;
2055   }
2056 
2057   Instruction *ILeft = dyn_cast<Instruction>(VLeft);
2058   Instruction *IRight = dyn_cast<Instruction>(VRight);
2059 
2060   // If we have "AllSameOpcodeRight", try to see if the left operands preserves
2061   // it and not the right, in this case we want to commute.
2062   if (AllSameOpcodeRight) {
2063     unsigned RightPrevOpcode = cast<Instruction>(Right[i - 1])->getOpcode();
2064     if (IRight && RightPrevOpcode == IRight->getOpcode())
2065       // Do not commute, a match on the right preserves AllSameOpcodeRight
2066       return false;
2067     if (ILeft && RightPrevOpcode == ILeft->getOpcode()) {
2068       // We have a match and may want to commute, but first check if there is
2069       // not also a match on the existing operands on the Left to preserve
2070       // AllSameOpcodeLeft, i.e. preserve the original order if possible.
2071       // (FIXME: why do we care?)
2072       if (AllSameOpcodeLeft && ILeft &&
2073           cast<Instruction>(Left[i - 1])->getOpcode() == ILeft->getOpcode())
2074         return false;
2075       return true;
2076     }
2077   }
2078   // Symmetrically handle Left side.
2079   if (AllSameOpcodeLeft) {
2080     unsigned LeftPrevOpcode = cast<Instruction>(Left[i - 1])->getOpcode();
2081     if (ILeft && LeftPrevOpcode == ILeft->getOpcode())
2082       return false;
2083     if (IRight && LeftPrevOpcode == IRight->getOpcode())
2084       return true;
2085   }
2086   return false;
2087 }
2088 
2089 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
2090                                              SmallVectorImpl<Value *> &Left,
2091                                              SmallVectorImpl<Value *> &Right) {
2092 
2093   if (VL.size()) {
2094     // Peel the first iteration out of the loop since there's nothing
2095     // interesting to do anyway and it simplifies the checks in the loop.
2096     auto VLeft = cast<Instruction>(VL[0])->getOperand(0);
2097     auto VRight = cast<Instruction>(VL[0])->getOperand(1);
2098     if (!isa<Instruction>(VRight) && isa<Instruction>(VLeft))
2099       // Favor having instruction to the right. FIXME: why?
2100       std::swap(VLeft, VRight);
2101     Left.push_back(VLeft);
2102     Right.push_back(VRight);
2103   }
2104 
2105   // Keep track if we have instructions with all the same opcode on one side.
2106   bool AllSameOpcodeLeft = isa<Instruction>(Left[0]);
2107   bool AllSameOpcodeRight = isa<Instruction>(Right[0]);
2108   // Keep track if we have one side with all the same value (broadcast).
2109   bool SplatLeft = true;
2110   bool SplatRight = true;
2111 
2112   for (unsigned i = 1, e = VL.size(); i != e; ++i) {
2113     Instruction *I = cast<Instruction>(VL[i]);
2114     assert(I->isCommutative() && "Can only process commutative instruction");
2115     // Commute to favor either a splat or maximizing having the same opcodes on
2116     // one side.
2117     if (shouldReorderOperands(i, *I, Left, Right, AllSameOpcodeLeft,
2118                               AllSameOpcodeRight, SplatLeft, SplatRight)) {
2119       Left.push_back(I->getOperand(1));
2120       Right.push_back(I->getOperand(0));
2121     } else {
2122       Left.push_back(I->getOperand(0));
2123       Right.push_back(I->getOperand(1));
2124     }
2125     // Update Splat* and AllSameOpcode* after the insertion.
2126     SplatRight = SplatRight && (Right[i - 1] == Right[i]);
2127     SplatLeft = SplatLeft && (Left[i - 1] == Left[i]);
2128     AllSameOpcodeLeft = AllSameOpcodeLeft && isa<Instruction>(Left[i]) &&
2129                         (cast<Instruction>(Left[i - 1])->getOpcode() ==
2130                          cast<Instruction>(Left[i])->getOpcode());
2131     AllSameOpcodeRight = AllSameOpcodeRight && isa<Instruction>(Right[i]) &&
2132                          (cast<Instruction>(Right[i - 1])->getOpcode() ==
2133                           cast<Instruction>(Right[i])->getOpcode());
2134   }
2135 
2136   // If one operand end up being broadcast, return this operand order.
2137   if (SplatRight || SplatLeft)
2138     return;
2139 
2140   // Finally check if we can get longer vectorizable chain by reordering
2141   // without breaking the good operand order detected above.
2142   // E.g. If we have something like-
2143   // load a[0]  load b[0]
2144   // load b[1]  load a[1]
2145   // load a[2]  load b[2]
2146   // load a[3]  load b[3]
2147   // Reordering the second load b[1]  load a[1] would allow us to vectorize
2148   // this code and we still retain AllSameOpcode property.
2149   // FIXME: This load reordering might break AllSameOpcode in some rare cases
2150   // such as-
2151   // add a[0],c[0]  load b[0]
2152   // add a[1],c[2]  load b[1]
2153   // b[2]           load b[2]
2154   // add a[3],c[3]  load b[3]
2155   for (unsigned j = 0; j < VL.size() - 1; ++j) {
2156     if (LoadInst *L = dyn_cast<LoadInst>(Left[j])) {
2157       if (LoadInst *L1 = dyn_cast<LoadInst>(Right[j + 1])) {
2158         if (isConsecutiveAccess(L, L1, *DL, *SE)) {
2159           std::swap(Left[j + 1], Right[j + 1]);
2160           continue;
2161         }
2162       }
2163     }
2164     if (LoadInst *L = dyn_cast<LoadInst>(Right[j])) {
2165       if (LoadInst *L1 = dyn_cast<LoadInst>(Left[j + 1])) {
2166         if (isConsecutiveAccess(L, L1, *DL, *SE)) {
2167           std::swap(Left[j + 1], Right[j + 1]);
2168           continue;
2169         }
2170       }
2171     }
2172     // else unchanged
2173   }
2174 }
2175 
2176 void BoUpSLP::setInsertPointAfterBundle(ArrayRef<Value *> VL) {
2177 
2178   // Get the basic block this bundle is in. All instructions in the bundle
2179   // should be in this block.
2180   auto *Front = cast<Instruction>(VL.front());
2181   auto *BB = Front->getParent();
2182   assert(all_of(make_range(VL.begin(), VL.end()), [&](Value *V) -> bool {
2183     return cast<Instruction>(V)->getParent() == BB;
2184   }));
2185 
2186   // The last instruction in the bundle in program order.
2187   Instruction *LastInst = nullptr;
2188 
2189   // Find the last instruction. The common case should be that BB has been
2190   // scheduled, and the last instruction is VL.back(). So we start with
2191   // VL.back() and iterate over schedule data until we reach the end of the
2192   // bundle. The end of the bundle is marked by null ScheduleData.
2193   if (BlocksSchedules.count(BB)) {
2194     auto *Bundle = BlocksSchedules[BB]->getScheduleData(VL.back());
2195     if (Bundle && Bundle->isPartOfBundle())
2196       for (; Bundle; Bundle = Bundle->NextInBundle)
2197         LastInst = Bundle->Inst;
2198   }
2199 
2200   // LastInst can still be null at this point if there's either not an entry
2201   // for BB in BlocksSchedules or there's no ScheduleData available for
2202   // VL.back(). This can be the case if buildTree_rec aborts for various
2203   // reasons (e.g., the maximum recursion depth is reached, the maximum region
2204   // size is reached, etc.). ScheduleData is initialized in the scheduling
2205   // "dry-run".
2206   //
2207   // If this happens, we can still find the last instruction by brute force. We
2208   // iterate forwards from Front (inclusive) until we either see all
2209   // instructions in the bundle or reach the end of the block. If Front is the
2210   // last instruction in program order, LastInst will be set to Front, and we
2211   // will visit all the remaining instructions in the block.
2212   //
2213   // One of the reasons we exit early from buildTree_rec is to place an upper
2214   // bound on compile-time. Thus, taking an additional compile-time hit here is
2215   // not ideal. However, this should be exceedingly rare since it requires that
2216   // we both exit early from buildTree_rec and that the bundle be out-of-order
2217   // (causing us to iterate all the way to the end of the block).
2218   if (!LastInst) {
2219     SmallPtrSet<Value *, 16> Bundle(VL.begin(), VL.end());
2220     for (auto &I : make_range(BasicBlock::iterator(Front), BB->end())) {
2221       if (Bundle.erase(&I))
2222         LastInst = &I;
2223       if (Bundle.empty())
2224         break;
2225     }
2226   }
2227 
2228   // Set the insertion point after the last instruction in the bundle. Set the
2229   // debug location to Front.
2230   Builder.SetInsertPoint(BB, next(BasicBlock::iterator(LastInst)));
2231   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
2232 }
2233 
2234 Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
2235   Value *Vec = UndefValue::get(Ty);
2236   // Generate the 'InsertElement' instruction.
2237   for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
2238     Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
2239     if (Instruction *Insrt = dyn_cast<Instruction>(Vec)) {
2240       GatherSeq.insert(Insrt);
2241       CSEBlocks.insert(Insrt->getParent());
2242 
2243       // Add to our 'need-to-extract' list.
2244       if (ScalarToTreeEntry.count(VL[i])) {
2245         int Idx = ScalarToTreeEntry[VL[i]];
2246         TreeEntry *E = &VectorizableTree[Idx];
2247         // Find which lane we need to extract.
2248         int FoundLane = -1;
2249         for (unsigned Lane = 0, LE = VL.size(); Lane != LE; ++Lane) {
2250           // Is this the lane of the scalar that we are looking for ?
2251           if (E->Scalars[Lane] == VL[i]) {
2252             FoundLane = Lane;
2253             break;
2254           }
2255         }
2256         assert(FoundLane >= 0 && "Could not find the correct lane");
2257         ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
2258       }
2259     }
2260   }
2261 
2262   return Vec;
2263 }
2264 
2265 Value *BoUpSLP::alreadyVectorized(ArrayRef<Value *> VL) const {
2266   SmallDenseMap<Value*, int>::const_iterator Entry
2267     = ScalarToTreeEntry.find(VL[0]);
2268   if (Entry != ScalarToTreeEntry.end()) {
2269     int Idx = Entry->second;
2270     const TreeEntry *En = &VectorizableTree[Idx];
2271     if (En->isSame(VL) && En->VectorizedValue)
2272       return En->VectorizedValue;
2273   }
2274   return nullptr;
2275 }
2276 
2277 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
2278   if (ScalarToTreeEntry.count(VL[0])) {
2279     int Idx = ScalarToTreeEntry[VL[0]];
2280     TreeEntry *E = &VectorizableTree[Idx];
2281     if (E->isSame(VL))
2282       return vectorizeTree(E);
2283   }
2284 
2285   Type *ScalarTy = VL[0]->getType();
2286   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
2287     ScalarTy = SI->getValueOperand()->getType();
2288   VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
2289 
2290   return Gather(VL, VecTy);
2291 }
2292 
2293 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
2294   IRBuilder<>::InsertPointGuard Guard(Builder);
2295 
2296   if (E->VectorizedValue) {
2297     DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
2298     return E->VectorizedValue;
2299   }
2300 
2301   Instruction *VL0 = cast<Instruction>(E->Scalars[0]);
2302   Type *ScalarTy = VL0->getType();
2303   if (StoreInst *SI = dyn_cast<StoreInst>(VL0))
2304     ScalarTy = SI->getValueOperand()->getType();
2305   VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size());
2306 
2307   if (E->NeedToGather) {
2308     setInsertPointAfterBundle(E->Scalars);
2309     auto *V = Gather(E->Scalars, VecTy);
2310     E->VectorizedValue = V;
2311     return V;
2312   }
2313 
2314   unsigned Opcode = getSameOpcode(E->Scalars);
2315 
2316   switch (Opcode) {
2317     case Instruction::PHI: {
2318       PHINode *PH = dyn_cast<PHINode>(VL0);
2319       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
2320       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
2321       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
2322       E->VectorizedValue = NewPhi;
2323 
2324       // PHINodes may have multiple entries from the same block. We want to
2325       // visit every block once.
2326       SmallSet<BasicBlock*, 4> VisitedBBs;
2327 
2328       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
2329         ValueList Operands;
2330         BasicBlock *IBB = PH->getIncomingBlock(i);
2331 
2332         if (!VisitedBBs.insert(IBB).second) {
2333           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
2334           continue;
2335         }
2336 
2337         // Prepare the operand vector.
2338         for (Value *V : E->Scalars)
2339           Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(IBB));
2340 
2341         Builder.SetInsertPoint(IBB->getTerminator());
2342         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
2343         Value *Vec = vectorizeTree(Operands);
2344         NewPhi->addIncoming(Vec, IBB);
2345       }
2346 
2347       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
2348              "Invalid number of incoming values");
2349       return NewPhi;
2350     }
2351 
2352     case Instruction::ExtractElement: {
2353       if (canReuseExtract(E->Scalars, Instruction::ExtractElement)) {
2354         Value *V = VL0->getOperand(0);
2355         E->VectorizedValue = V;
2356         return V;
2357       }
2358       setInsertPointAfterBundle(E->Scalars);
2359       auto *V = Gather(E->Scalars, VecTy);
2360       E->VectorizedValue = V;
2361       return V;
2362     }
2363     case Instruction::ExtractValue: {
2364       if (canReuseExtract(E->Scalars, Instruction::ExtractValue)) {
2365         LoadInst *LI = cast<LoadInst>(VL0->getOperand(0));
2366         Builder.SetInsertPoint(LI);
2367         PointerType *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
2368         Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
2369         LoadInst *V = Builder.CreateAlignedLoad(Ptr, LI->getAlignment());
2370         E->VectorizedValue = V;
2371         return propagateMetadata(V, E->Scalars);
2372       }
2373       setInsertPointAfterBundle(E->Scalars);
2374       auto *V = Gather(E->Scalars, VecTy);
2375       E->VectorizedValue = V;
2376       return V;
2377     }
2378     case Instruction::ZExt:
2379     case Instruction::SExt:
2380     case Instruction::FPToUI:
2381     case Instruction::FPToSI:
2382     case Instruction::FPExt:
2383     case Instruction::PtrToInt:
2384     case Instruction::IntToPtr:
2385     case Instruction::SIToFP:
2386     case Instruction::UIToFP:
2387     case Instruction::Trunc:
2388     case Instruction::FPTrunc:
2389     case Instruction::BitCast: {
2390       ValueList INVL;
2391       for (Value *V : E->Scalars)
2392         INVL.push_back(cast<Instruction>(V)->getOperand(0));
2393 
2394       setInsertPointAfterBundle(E->Scalars);
2395 
2396       Value *InVec = vectorizeTree(INVL);
2397 
2398       if (Value *V = alreadyVectorized(E->Scalars))
2399         return V;
2400 
2401       CastInst *CI = dyn_cast<CastInst>(VL0);
2402       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
2403       E->VectorizedValue = V;
2404       ++NumVectorInstructions;
2405       return V;
2406     }
2407     case Instruction::FCmp:
2408     case Instruction::ICmp: {
2409       ValueList LHSV, RHSV;
2410       for (Value *V : E->Scalars) {
2411         LHSV.push_back(cast<Instruction>(V)->getOperand(0));
2412         RHSV.push_back(cast<Instruction>(V)->getOperand(1));
2413       }
2414 
2415       setInsertPointAfterBundle(E->Scalars);
2416 
2417       Value *L = vectorizeTree(LHSV);
2418       Value *R = vectorizeTree(RHSV);
2419 
2420       if (Value *V = alreadyVectorized(E->Scalars))
2421         return V;
2422 
2423       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
2424       Value *V;
2425       if (Opcode == Instruction::FCmp)
2426         V = Builder.CreateFCmp(P0, L, R);
2427       else
2428         V = Builder.CreateICmp(P0, L, R);
2429 
2430       E->VectorizedValue = V;
2431       ++NumVectorInstructions;
2432       return V;
2433     }
2434     case Instruction::Select: {
2435       ValueList TrueVec, FalseVec, CondVec;
2436       for (Value *V : E->Scalars) {
2437         CondVec.push_back(cast<Instruction>(V)->getOperand(0));
2438         TrueVec.push_back(cast<Instruction>(V)->getOperand(1));
2439         FalseVec.push_back(cast<Instruction>(V)->getOperand(2));
2440       }
2441 
2442       setInsertPointAfterBundle(E->Scalars);
2443 
2444       Value *Cond = vectorizeTree(CondVec);
2445       Value *True = vectorizeTree(TrueVec);
2446       Value *False = vectorizeTree(FalseVec);
2447 
2448       if (Value *V = alreadyVectorized(E->Scalars))
2449         return V;
2450 
2451       Value *V = Builder.CreateSelect(Cond, True, False);
2452       E->VectorizedValue = V;
2453       ++NumVectorInstructions;
2454       return V;
2455     }
2456     case Instruction::Add:
2457     case Instruction::FAdd:
2458     case Instruction::Sub:
2459     case Instruction::FSub:
2460     case Instruction::Mul:
2461     case Instruction::FMul:
2462     case Instruction::UDiv:
2463     case Instruction::SDiv:
2464     case Instruction::FDiv:
2465     case Instruction::URem:
2466     case Instruction::SRem:
2467     case Instruction::FRem:
2468     case Instruction::Shl:
2469     case Instruction::LShr:
2470     case Instruction::AShr:
2471     case Instruction::And:
2472     case Instruction::Or:
2473     case Instruction::Xor: {
2474       ValueList LHSVL, RHSVL;
2475       if (isa<BinaryOperator>(VL0) && VL0->isCommutative())
2476         reorderInputsAccordingToOpcode(E->Scalars, LHSVL, RHSVL);
2477       else
2478         for (Value *V : E->Scalars) {
2479           LHSVL.push_back(cast<Instruction>(V)->getOperand(0));
2480           RHSVL.push_back(cast<Instruction>(V)->getOperand(1));
2481         }
2482 
2483       setInsertPointAfterBundle(E->Scalars);
2484 
2485       Value *LHS = vectorizeTree(LHSVL);
2486       Value *RHS = vectorizeTree(RHSVL);
2487 
2488       if (LHS == RHS && isa<Instruction>(LHS)) {
2489         assert((VL0->getOperand(0) == VL0->getOperand(1)) && "Invalid order");
2490       }
2491 
2492       if (Value *V = alreadyVectorized(E->Scalars))
2493         return V;
2494 
2495       BinaryOperator *BinOp = cast<BinaryOperator>(VL0);
2496       Value *V = Builder.CreateBinOp(BinOp->getOpcode(), LHS, RHS);
2497       E->VectorizedValue = V;
2498       propagateIRFlags(E->VectorizedValue, E->Scalars);
2499       ++NumVectorInstructions;
2500 
2501       if (Instruction *I = dyn_cast<Instruction>(V))
2502         return propagateMetadata(I, E->Scalars);
2503 
2504       return V;
2505     }
2506     case Instruction::Load: {
2507       // Loads are inserted at the head of the tree because we don't want to
2508       // sink them all the way down past store instructions.
2509       setInsertPointAfterBundle(E->Scalars);
2510 
2511       LoadInst *LI = cast<LoadInst>(VL0);
2512       Type *ScalarLoadTy = LI->getType();
2513       unsigned AS = LI->getPointerAddressSpace();
2514 
2515       Value *VecPtr = Builder.CreateBitCast(LI->getPointerOperand(),
2516                                             VecTy->getPointerTo(AS));
2517 
2518       // The pointer operand uses an in-tree scalar so we add the new BitCast to
2519       // ExternalUses list to make sure that an extract will be generated in the
2520       // future.
2521       if (ScalarToTreeEntry.count(LI->getPointerOperand()))
2522         ExternalUses.push_back(
2523             ExternalUser(LI->getPointerOperand(), cast<User>(VecPtr), 0));
2524 
2525       unsigned Alignment = LI->getAlignment();
2526       LI = Builder.CreateLoad(VecPtr);
2527       if (!Alignment) {
2528         Alignment = DL->getABITypeAlignment(ScalarLoadTy);
2529       }
2530       LI->setAlignment(Alignment);
2531       E->VectorizedValue = LI;
2532       ++NumVectorInstructions;
2533       return propagateMetadata(LI, E->Scalars);
2534     }
2535     case Instruction::Store: {
2536       StoreInst *SI = cast<StoreInst>(VL0);
2537       unsigned Alignment = SI->getAlignment();
2538       unsigned AS = SI->getPointerAddressSpace();
2539 
2540       ValueList ValueOp;
2541       for (Value *V : E->Scalars)
2542         ValueOp.push_back(cast<StoreInst>(V)->getValueOperand());
2543 
2544       setInsertPointAfterBundle(E->Scalars);
2545 
2546       Value *VecValue = vectorizeTree(ValueOp);
2547       Value *VecPtr = Builder.CreateBitCast(SI->getPointerOperand(),
2548                                             VecTy->getPointerTo(AS));
2549       StoreInst *S = Builder.CreateStore(VecValue, VecPtr);
2550 
2551       // The pointer operand uses an in-tree scalar so we add the new BitCast to
2552       // ExternalUses list to make sure that an extract will be generated in the
2553       // future.
2554       if (ScalarToTreeEntry.count(SI->getPointerOperand()))
2555         ExternalUses.push_back(
2556             ExternalUser(SI->getPointerOperand(), cast<User>(VecPtr), 0));
2557 
2558       if (!Alignment) {
2559         Alignment = DL->getABITypeAlignment(SI->getValueOperand()->getType());
2560       }
2561       S->setAlignment(Alignment);
2562       E->VectorizedValue = S;
2563       ++NumVectorInstructions;
2564       return propagateMetadata(S, E->Scalars);
2565     }
2566     case Instruction::GetElementPtr: {
2567       setInsertPointAfterBundle(E->Scalars);
2568 
2569       ValueList Op0VL;
2570       for (Value *V : E->Scalars)
2571         Op0VL.push_back(cast<GetElementPtrInst>(V)->getOperand(0));
2572 
2573       Value *Op0 = vectorizeTree(Op0VL);
2574 
2575       std::vector<Value *> OpVecs;
2576       for (int j = 1, e = cast<GetElementPtrInst>(VL0)->getNumOperands(); j < e;
2577            ++j) {
2578         ValueList OpVL;
2579         for (Value *V : E->Scalars)
2580           OpVL.push_back(cast<GetElementPtrInst>(V)->getOperand(j));
2581 
2582         Value *OpVec = vectorizeTree(OpVL);
2583         OpVecs.push_back(OpVec);
2584       }
2585 
2586       Value *V = Builder.CreateGEP(
2587           cast<GetElementPtrInst>(VL0)->getSourceElementType(), Op0, OpVecs);
2588       E->VectorizedValue = V;
2589       ++NumVectorInstructions;
2590 
2591       if (Instruction *I = dyn_cast<Instruction>(V))
2592         return propagateMetadata(I, E->Scalars);
2593 
2594       return V;
2595     }
2596     case Instruction::Call: {
2597       CallInst *CI = cast<CallInst>(VL0);
2598       setInsertPointAfterBundle(E->Scalars);
2599       Function *FI;
2600       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
2601       Value *ScalarArg = nullptr;
2602       if (CI && (FI = CI->getCalledFunction())) {
2603         IID = FI->getIntrinsicID();
2604       }
2605       std::vector<Value *> OpVecs;
2606       for (int j = 0, e = CI->getNumArgOperands(); j < e; ++j) {
2607         ValueList OpVL;
2608         // ctlz,cttz and powi are special intrinsics whose second argument is
2609         // a scalar. This argument should not be vectorized.
2610         if (hasVectorInstrinsicScalarOpd(IID, 1) && j == 1) {
2611           CallInst *CEI = cast<CallInst>(E->Scalars[0]);
2612           ScalarArg = CEI->getArgOperand(j);
2613           OpVecs.push_back(CEI->getArgOperand(j));
2614           continue;
2615         }
2616         for (Value *V : E->Scalars) {
2617           CallInst *CEI = cast<CallInst>(V);
2618           OpVL.push_back(CEI->getArgOperand(j));
2619         }
2620 
2621         Value *OpVec = vectorizeTree(OpVL);
2622         DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
2623         OpVecs.push_back(OpVec);
2624       }
2625 
2626       Module *M = F->getParent();
2627       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
2628       Type *Tys[] = { VectorType::get(CI->getType(), E->Scalars.size()) };
2629       Function *CF = Intrinsic::getDeclaration(M, ID, Tys);
2630       SmallVector<OperandBundleDef, 1> OpBundles;
2631       CI->getOperandBundlesAsDefs(OpBundles);
2632       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
2633 
2634       // The scalar argument uses an in-tree scalar so we add the new vectorized
2635       // call to ExternalUses list to make sure that an extract will be
2636       // generated in the future.
2637       if (ScalarArg && ScalarToTreeEntry.count(ScalarArg))
2638         ExternalUses.push_back(ExternalUser(ScalarArg, cast<User>(V), 0));
2639 
2640       E->VectorizedValue = V;
2641       ++NumVectorInstructions;
2642       return V;
2643     }
2644     case Instruction::ShuffleVector: {
2645       ValueList LHSVL, RHSVL;
2646       assert(isa<BinaryOperator>(VL0) && "Invalid Shuffle Vector Operand");
2647       reorderAltShuffleOperands(E->Scalars, LHSVL, RHSVL);
2648       setInsertPointAfterBundle(E->Scalars);
2649 
2650       Value *LHS = vectorizeTree(LHSVL);
2651       Value *RHS = vectorizeTree(RHSVL);
2652 
2653       if (Value *V = alreadyVectorized(E->Scalars))
2654         return V;
2655 
2656       // Create a vector of LHS op1 RHS
2657       BinaryOperator *BinOp0 = cast<BinaryOperator>(VL0);
2658       Value *V0 = Builder.CreateBinOp(BinOp0->getOpcode(), LHS, RHS);
2659 
2660       // Create a vector of LHS op2 RHS
2661       Instruction *VL1 = cast<Instruction>(E->Scalars[1]);
2662       BinaryOperator *BinOp1 = cast<BinaryOperator>(VL1);
2663       Value *V1 = Builder.CreateBinOp(BinOp1->getOpcode(), LHS, RHS);
2664 
2665       // Create shuffle to take alternate operations from the vector.
2666       // Also, gather up odd and even scalar ops to propagate IR flags to
2667       // each vector operation.
2668       ValueList OddScalars, EvenScalars;
2669       unsigned e = E->Scalars.size();
2670       SmallVector<Constant *, 8> Mask(e);
2671       for (unsigned i = 0; i < e; ++i) {
2672         if (i & 1) {
2673           Mask[i] = Builder.getInt32(e + i);
2674           OddScalars.push_back(E->Scalars[i]);
2675         } else {
2676           Mask[i] = Builder.getInt32(i);
2677           EvenScalars.push_back(E->Scalars[i]);
2678         }
2679       }
2680 
2681       Value *ShuffleMask = ConstantVector::get(Mask);
2682       propagateIRFlags(V0, EvenScalars);
2683       propagateIRFlags(V1, OddScalars);
2684 
2685       Value *V = Builder.CreateShuffleVector(V0, V1, ShuffleMask);
2686       E->VectorizedValue = V;
2687       ++NumVectorInstructions;
2688       if (Instruction *I = dyn_cast<Instruction>(V))
2689         return propagateMetadata(I, E->Scalars);
2690 
2691       return V;
2692     }
2693     default:
2694     llvm_unreachable("unknown inst");
2695   }
2696   return nullptr;
2697 }
2698 
2699 Value *BoUpSLP::vectorizeTree() {
2700 
2701   // All blocks must be scheduled before any instructions are inserted.
2702   for (auto &BSIter : BlocksSchedules) {
2703     scheduleBlock(BSIter.second.get());
2704   }
2705 
2706   Builder.SetInsertPoint(&F->getEntryBlock().front());
2707   auto *VectorRoot = vectorizeTree(&VectorizableTree[0]);
2708 
2709   // If the vectorized tree can be rewritten in a smaller type, we truncate the
2710   // vectorized root. InstCombine will then rewrite the entire expression. We
2711   // sign extend the extracted values below.
2712   auto *ScalarRoot = VectorizableTree[0].Scalars[0];
2713   if (MinBWs.count(ScalarRoot)) {
2714     if (auto *I = dyn_cast<Instruction>(VectorRoot))
2715       Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
2716     auto BundleWidth = VectorizableTree[0].Scalars.size();
2717     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot]);
2718     auto *VecTy = VectorType::get(MinTy, BundleWidth);
2719     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
2720     VectorizableTree[0].VectorizedValue = Trunc;
2721   }
2722 
2723   DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() << " values .\n");
2724 
2725   // Extract all of the elements with the external uses.
2726   for (const auto &ExternalUse : ExternalUses) {
2727     Value *Scalar = ExternalUse.Scalar;
2728     llvm::User *User = ExternalUse.User;
2729 
2730     // Skip users that we already RAUW. This happens when one instruction
2731     // has multiple uses of the same value.
2732     if (!is_contained(Scalar->users(), User))
2733       continue;
2734     assert(ScalarToTreeEntry.count(Scalar) && "Invalid scalar");
2735 
2736     int Idx = ScalarToTreeEntry[Scalar];
2737     TreeEntry *E = &VectorizableTree[Idx];
2738     assert(!E->NeedToGather && "Extracting from a gather list");
2739 
2740     Value *Vec = E->VectorizedValue;
2741     assert(Vec && "Can't find vectorizable value");
2742 
2743     Value *Lane = Builder.getInt32(ExternalUse.Lane);
2744     // Generate extracts for out-of-tree users.
2745     // Find the insertion point for the extractelement lane.
2746     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
2747       if (PHINode *PH = dyn_cast<PHINode>(User)) {
2748         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
2749           if (PH->getIncomingValue(i) == Scalar) {
2750             TerminatorInst *IncomingTerminator =
2751                 PH->getIncomingBlock(i)->getTerminator();
2752             if (isa<CatchSwitchInst>(IncomingTerminator)) {
2753               Builder.SetInsertPoint(VecI->getParent(),
2754                                      std::next(VecI->getIterator()));
2755             } else {
2756               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
2757             }
2758             Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2759             if (MinBWs.count(ScalarRoot))
2760               Ex = Builder.CreateSExt(Ex, Scalar->getType());
2761             CSEBlocks.insert(PH->getIncomingBlock(i));
2762             PH->setOperand(i, Ex);
2763           }
2764         }
2765       } else {
2766         Builder.SetInsertPoint(cast<Instruction>(User));
2767         Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2768         if (MinBWs.count(ScalarRoot))
2769           Ex = Builder.CreateSExt(Ex, Scalar->getType());
2770         CSEBlocks.insert(cast<Instruction>(User)->getParent());
2771         User->replaceUsesOfWith(Scalar, Ex);
2772      }
2773     } else {
2774       Builder.SetInsertPoint(&F->getEntryBlock().front());
2775       Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2776       if (MinBWs.count(ScalarRoot))
2777         Ex = Builder.CreateSExt(Ex, Scalar->getType());
2778       CSEBlocks.insert(&F->getEntryBlock());
2779       User->replaceUsesOfWith(Scalar, Ex);
2780     }
2781 
2782     DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
2783   }
2784 
2785   // For each vectorized value:
2786   for (TreeEntry &EIdx : VectorizableTree) {
2787     TreeEntry *Entry = &EIdx;
2788 
2789     // For each lane:
2790     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
2791       Value *Scalar = Entry->Scalars[Lane];
2792       // No need to handle users of gathered values.
2793       if (Entry->NeedToGather)
2794         continue;
2795 
2796       assert(Entry->VectorizedValue && "Can't find vectorizable value");
2797 
2798       Type *Ty = Scalar->getType();
2799       if (!Ty->isVoidTy()) {
2800 #ifndef NDEBUG
2801         for (User *U : Scalar->users()) {
2802           DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
2803 
2804           assert((ScalarToTreeEntry.count(U) ||
2805                   // It is legal to replace users in the ignorelist by undef.
2806                   is_contained(UserIgnoreList, U)) &&
2807                  "Replacing out-of-tree value with undef");
2808         }
2809 #endif
2810         Value *Undef = UndefValue::get(Ty);
2811         Scalar->replaceAllUsesWith(Undef);
2812       }
2813       DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
2814       eraseInstruction(cast<Instruction>(Scalar));
2815     }
2816   }
2817 
2818   Builder.ClearInsertionPoint();
2819 
2820   return VectorizableTree[0].VectorizedValue;
2821 }
2822 
2823 void BoUpSLP::optimizeGatherSequence() {
2824   DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
2825         << " gather sequences instructions.\n");
2826   // LICM InsertElementInst sequences.
2827   for (Instruction *it : GatherSeq) {
2828     InsertElementInst *Insert = dyn_cast<InsertElementInst>(it);
2829 
2830     if (!Insert)
2831       continue;
2832 
2833     // Check if this block is inside a loop.
2834     Loop *L = LI->getLoopFor(Insert->getParent());
2835     if (!L)
2836       continue;
2837 
2838     // Check if it has a preheader.
2839     BasicBlock *PreHeader = L->getLoopPreheader();
2840     if (!PreHeader)
2841       continue;
2842 
2843     // If the vector or the element that we insert into it are
2844     // instructions that are defined in this basic block then we can't
2845     // hoist this instruction.
2846     Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
2847     Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
2848     if (CurrVec && L->contains(CurrVec))
2849       continue;
2850     if (NewElem && L->contains(NewElem))
2851       continue;
2852 
2853     // We can hoist this instruction. Move it to the pre-header.
2854     Insert->moveBefore(PreHeader->getTerminator());
2855   }
2856 
2857   // Make a list of all reachable blocks in our CSE queue.
2858   SmallVector<const DomTreeNode *, 8> CSEWorkList;
2859   CSEWorkList.reserve(CSEBlocks.size());
2860   for (BasicBlock *BB : CSEBlocks)
2861     if (DomTreeNode *N = DT->getNode(BB)) {
2862       assert(DT->isReachableFromEntry(N));
2863       CSEWorkList.push_back(N);
2864     }
2865 
2866   // Sort blocks by domination. This ensures we visit a block after all blocks
2867   // dominating it are visited.
2868   std::stable_sort(CSEWorkList.begin(), CSEWorkList.end(),
2869                    [this](const DomTreeNode *A, const DomTreeNode *B) {
2870     return DT->properlyDominates(A, B);
2871   });
2872 
2873   // Perform O(N^2) search over the gather sequences and merge identical
2874   // instructions. TODO: We can further optimize this scan if we split the
2875   // instructions into different buckets based on the insert lane.
2876   SmallVector<Instruction *, 16> Visited;
2877   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
2878     assert((I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
2879            "Worklist not sorted properly!");
2880     BasicBlock *BB = (*I)->getBlock();
2881     // For all instructions in blocks containing gather sequences:
2882     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) {
2883       Instruction *In = &*it++;
2884       if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In))
2885         continue;
2886 
2887       // Check if we can replace this instruction with any of the
2888       // visited instructions.
2889       for (Instruction *v : Visited) {
2890         if (In->isIdenticalTo(v) &&
2891             DT->dominates(v->getParent(), In->getParent())) {
2892           In->replaceAllUsesWith(v);
2893           eraseInstruction(In);
2894           In = nullptr;
2895           break;
2896         }
2897       }
2898       if (In) {
2899         assert(!is_contained(Visited, In));
2900         Visited.push_back(In);
2901       }
2902     }
2903   }
2904   CSEBlocks.clear();
2905   GatherSeq.clear();
2906 }
2907 
2908 // Groups the instructions to a bundle (which is then a single scheduling entity)
2909 // and schedules instructions until the bundle gets ready.
2910 bool BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL,
2911                                                  BoUpSLP *SLP) {
2912   if (isa<PHINode>(VL[0]))
2913     return true;
2914 
2915   // Initialize the instruction bundle.
2916   Instruction *OldScheduleEnd = ScheduleEnd;
2917   ScheduleData *PrevInBundle = nullptr;
2918   ScheduleData *Bundle = nullptr;
2919   bool ReSchedule = false;
2920   DEBUG(dbgs() << "SLP:  bundle: " << *VL[0] << "\n");
2921 
2922   // Make sure that the scheduling region contains all
2923   // instructions of the bundle.
2924   for (Value *V : VL) {
2925     if (!extendSchedulingRegion(V))
2926       return false;
2927   }
2928 
2929   for (Value *V : VL) {
2930     ScheduleData *BundleMember = getScheduleData(V);
2931     assert(BundleMember &&
2932            "no ScheduleData for bundle member (maybe not in same basic block)");
2933     if (BundleMember->IsScheduled) {
2934       // A bundle member was scheduled as single instruction before and now
2935       // needs to be scheduled as part of the bundle. We just get rid of the
2936       // existing schedule.
2937       DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
2938                    << " was already scheduled\n");
2939       ReSchedule = true;
2940     }
2941     assert(BundleMember->isSchedulingEntity() &&
2942            "bundle member already part of other bundle");
2943     if (PrevInBundle) {
2944       PrevInBundle->NextInBundle = BundleMember;
2945     } else {
2946       Bundle = BundleMember;
2947     }
2948     BundleMember->UnscheduledDepsInBundle = 0;
2949     Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps;
2950 
2951     // Group the instructions to a bundle.
2952     BundleMember->FirstInBundle = Bundle;
2953     PrevInBundle = BundleMember;
2954   }
2955   if (ScheduleEnd != OldScheduleEnd) {
2956     // The scheduling region got new instructions at the lower end (or it is a
2957     // new region for the first bundle). This makes it necessary to
2958     // recalculate all dependencies.
2959     // It is seldom that this needs to be done a second time after adding the
2960     // initial bundle to the region.
2961     for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2962       ScheduleData *SD = getScheduleData(I);
2963       SD->clearDependencies();
2964     }
2965     ReSchedule = true;
2966   }
2967   if (ReSchedule) {
2968     resetSchedule();
2969     initialFillReadyList(ReadyInsts);
2970   }
2971 
2972   DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle << " in block "
2973                << BB->getName() << "\n");
2974 
2975   calculateDependencies(Bundle, true, SLP);
2976 
2977   // Now try to schedule the new bundle. As soon as the bundle is "ready" it
2978   // means that there are no cyclic dependencies and we can schedule it.
2979   // Note that's important that we don't "schedule" the bundle yet (see
2980   // cancelScheduling).
2981   while (!Bundle->isReady() && !ReadyInsts.empty()) {
2982 
2983     ScheduleData *pickedSD = ReadyInsts.back();
2984     ReadyInsts.pop_back();
2985 
2986     if (pickedSD->isSchedulingEntity() && pickedSD->isReady()) {
2987       schedule(pickedSD, ReadyInsts);
2988     }
2989   }
2990   if (!Bundle->isReady()) {
2991     cancelScheduling(VL);
2992     return false;
2993   }
2994   return true;
2995 }
2996 
2997 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL) {
2998   if (isa<PHINode>(VL[0]))
2999     return;
3000 
3001   ScheduleData *Bundle = getScheduleData(VL[0]);
3002   DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
3003   assert(!Bundle->IsScheduled &&
3004          "Can't cancel bundle which is already scheduled");
3005   assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
3006          "tried to unbundle something which is not a bundle");
3007 
3008   // Un-bundle: make single instructions out of the bundle.
3009   ScheduleData *BundleMember = Bundle;
3010   while (BundleMember) {
3011     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
3012     BundleMember->FirstInBundle = BundleMember;
3013     ScheduleData *Next = BundleMember->NextInBundle;
3014     BundleMember->NextInBundle = nullptr;
3015     BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps;
3016     if (BundleMember->UnscheduledDepsInBundle == 0) {
3017       ReadyInsts.insert(BundleMember);
3018     }
3019     BundleMember = Next;
3020   }
3021 }
3022 
3023 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V) {
3024   if (getScheduleData(V))
3025     return true;
3026   Instruction *I = dyn_cast<Instruction>(V);
3027   assert(I && "bundle member must be an instruction");
3028   assert(!isa<PHINode>(I) && "phi nodes don't need to be scheduled");
3029   if (!ScheduleStart) {
3030     // It's the first instruction in the new region.
3031     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
3032     ScheduleStart = I;
3033     ScheduleEnd = I->getNextNode();
3034     assert(ScheduleEnd && "tried to vectorize a TerminatorInst?");
3035     DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
3036     return true;
3037   }
3038   // Search up and down at the same time, because we don't know if the new
3039   // instruction is above or below the existing scheduling region.
3040   BasicBlock::reverse_iterator UpIter(ScheduleStart->getIterator());
3041   BasicBlock::reverse_iterator UpperEnd = BB->rend();
3042   BasicBlock::iterator DownIter(ScheduleEnd);
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,
3689                                             int CostThreshold, BoUpSLP &R,
3690                                             unsigned VecRegSize) {
3691   unsigned ChainLen = Chain.size();
3692   DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
3693         << "\n");
3694   unsigned Sz = R.getVectorElementSize(Chain[0]);
3695   unsigned VF = VecRegSize / Sz;
3696 
3697   if (!isPowerOf2_32(Sz) || VF < 2)
3698     return false;
3699 
3700   // Keep track of values that were deleted by vectorizing in the loop below.
3701   SmallVector<WeakVH, 8> TrackValues(Chain.begin(), Chain.end());
3702 
3703   bool Changed = false;
3704   // Look for profitable vectorizable trees at all offsets, starting at zero.
3705   for (unsigned i = 0, e = ChainLen; i < e; ++i) {
3706     if (i + VF > e)
3707       break;
3708 
3709     // Check that a previous iteration of this loop did not delete the Value.
3710     if (hasValueBeenRAUWed(Chain, TrackValues, i, VF))
3711       continue;
3712 
3713     DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
3714           << "\n");
3715     ArrayRef<Value *> Operands = Chain.slice(i, VF);
3716 
3717     R.buildTree(Operands);
3718     if (R.isTreeTinyAndNotFullyVectorizable())
3719       continue;
3720 
3721     R.computeMinimumValueSizes();
3722 
3723     int Cost = R.getTreeCost();
3724 
3725     DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
3726     if (Cost < CostThreshold) {
3727       DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
3728       R.vectorizeTree();
3729 
3730       // Move to the next bundle.
3731       i += VF - 1;
3732       Changed = true;
3733     }
3734   }
3735 
3736   return Changed;
3737 }
3738 
3739 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
3740                                         int costThreshold, BoUpSLP &R) {
3741   SetVector<StoreInst *> Heads, Tails;
3742   SmallDenseMap<StoreInst *, StoreInst *> ConsecutiveChain;
3743 
3744   // We may run into multiple chains that merge into a single chain. We mark the
3745   // stores that we vectorized so that we don't visit the same store twice.
3746   BoUpSLP::ValueSet VectorizedStores;
3747   bool Changed = false;
3748 
3749   // Do a quadratic search on all of the given stores and find
3750   // all of the pairs of stores that follow each other.
3751   SmallVector<unsigned, 16> IndexQueue;
3752   for (unsigned i = 0, e = Stores.size(); i < e; ++i) {
3753     IndexQueue.clear();
3754     // If a store has multiple consecutive store candidates, search Stores
3755     // array according to the sequence: from i+1 to e, then from i-1 to 0.
3756     // This is because usually pairing with immediate succeeding or preceding
3757     // candidate create the best chance to find slp vectorization opportunity.
3758     unsigned j = 0;
3759     for (j = i + 1; j < e; ++j)
3760       IndexQueue.push_back(j);
3761     for (j = i; j > 0; --j)
3762       IndexQueue.push_back(j - 1);
3763 
3764     for (auto &k : IndexQueue) {
3765       if (isConsecutiveAccess(Stores[i], Stores[k], *DL, *SE)) {
3766         Tails.insert(Stores[k]);
3767         Heads.insert(Stores[i]);
3768         ConsecutiveChain[Stores[i]] = Stores[k];
3769         break;
3770       }
3771     }
3772   }
3773 
3774   // For stores that start but don't end a link in the chain:
3775   for (SetVector<StoreInst *>::iterator it = Heads.begin(), e = Heads.end();
3776        it != e; ++it) {
3777     if (Tails.count(*it))
3778       continue;
3779 
3780     // We found a store instr that starts a chain. Now follow the chain and try
3781     // to vectorize it.
3782     BoUpSLP::ValueList Operands;
3783     StoreInst *I = *it;
3784     // Collect the chain into a list.
3785     while (Tails.count(I) || Heads.count(I)) {
3786       if (VectorizedStores.count(I))
3787         break;
3788       Operands.push_back(I);
3789       // Move to the next value in the chain.
3790       I = ConsecutiveChain[I];
3791     }
3792 
3793     // FIXME: Is division-by-2 the correct step? Should we assert that the
3794     // register size is a power-of-2?
3795     for (unsigned Size = R.getMaxVecRegSize(); Size >= R.getMinVecRegSize(); Size /= 2) {
3796       if (vectorizeStoreChain(Operands, costThreshold, 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: Vectorizing a list of length = " << VL.size() << ".\n");
3859 
3860   // Check that all of the parts are scalar instructions of the same type.
3861   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
3862   if (!I0)
3863     return false;
3864 
3865   unsigned Opcode0 = I0->getOpcode();
3866 
3867   // FIXME: Register size should be a parameter to this function, so we can
3868   // try different vectorization factors.
3869   unsigned Sz = R.getVectorElementSize(I0);
3870   unsigned VF = R.getMinVecRegSize() / Sz;
3871 
3872   for (Value *V : VL) {
3873     Type *Ty = V->getType();
3874     if (!isValidElementType(Ty))
3875       return false;
3876     Instruction *Inst = dyn_cast<Instruction>(V);
3877     if (!Inst || Inst->getOpcode() != Opcode0)
3878       return false;
3879   }
3880 
3881   bool Changed = false;
3882 
3883   // Keep track of values that were deleted by vectorizing in the loop below.
3884   SmallVector<WeakVH, 8> TrackValues(VL.begin(), VL.end());
3885 
3886   for (unsigned i = 0, e = VL.size(); i < e; ++i) {
3887     unsigned OpsWidth = 0;
3888 
3889     if (i + VF > e)
3890       OpsWidth = e - i;
3891     else
3892       OpsWidth = VF;
3893 
3894     if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
3895       break;
3896 
3897     // Check that a previous iteration of this loop did not delete the Value.
3898     if (hasValueBeenRAUWed(VL, TrackValues, i, OpsWidth))
3899       continue;
3900 
3901     DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
3902                  << "\n");
3903     ArrayRef<Value *> Ops = VL.slice(i, OpsWidth);
3904 
3905     ArrayRef<Value *> BuildVectorSlice;
3906     if (!BuildVector.empty())
3907       BuildVectorSlice = BuildVector.slice(i, OpsWidth);
3908 
3909     R.buildTree(Ops, BuildVectorSlice);
3910     // TODO: check if we can allow reordering for more cases.
3911     if (allowReorder && R.shouldReorder()) {
3912       // Conceptually, there is nothing actually preventing us from trying to
3913       // reorder a larger list. In fact, we do exactly this when vectorizing
3914       // reductions. However, at this point, we only expect to get here from
3915       // tryToVectorizePair().
3916       assert(Ops.size() == 2);
3917       assert(BuildVectorSlice.empty());
3918       Value *ReorderedOps[] = { Ops[1], Ops[0] };
3919       R.buildTree(ReorderedOps, None);
3920     }
3921     if (R.isTreeTinyAndNotFullyVectorizable())
3922       continue;
3923 
3924     R.computeMinimumValueSizes();
3925     int Cost = R.getTreeCost();
3926 
3927     if (Cost < -SLPCostThreshold) {
3928       DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
3929       Value *VectorizedRoot = R.vectorizeTree();
3930 
3931       // Reconstruct the build vector by extracting the vectorized root. This
3932       // way we handle the case where some elements of the vector are undefined.
3933       //  (return (inserelt <4 xi32> (insertelt undef (opd0) 0) (opd1) 2))
3934       if (!BuildVectorSlice.empty()) {
3935         // The insert point is the last build vector instruction. The vectorized
3936         // root will precede it. This guarantees that we get an instruction. The
3937         // vectorized tree could have been constant folded.
3938         Instruction *InsertAfter = cast<Instruction>(BuildVectorSlice.back());
3939         unsigned VecIdx = 0;
3940         for (auto &V : BuildVectorSlice) {
3941           IRBuilder<NoFolder> Builder(InsertAfter->getParent(),
3942                                       ++BasicBlock::iterator(InsertAfter));
3943           Instruction *I = cast<Instruction>(V);
3944           assert(isa<InsertElementInst>(I) || isa<InsertValueInst>(I));
3945           Instruction *Extract = cast<Instruction>(Builder.CreateExtractElement(
3946               VectorizedRoot, Builder.getInt32(VecIdx++)));
3947           I->setOperand(1, Extract);
3948           I->removeFromParent();
3949           I->insertAfter(Extract);
3950           InsertAfter = I;
3951         }
3952       }
3953       // Move to the next bundle.
3954       i += VF - 1;
3955       Changed = true;
3956     }
3957   }
3958 
3959   return Changed;
3960 }
3961 
3962 bool SLPVectorizerPass::tryToVectorize(BinaryOperator *V, BoUpSLP &R) {
3963   if (!V)
3964     return false;
3965 
3966   // Try to vectorize V.
3967   if (tryToVectorizePair(V->getOperand(0), V->getOperand(1), R))
3968     return true;
3969 
3970   BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0));
3971   BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1));
3972   // Try to skip B.
3973   if (B && B->hasOneUse()) {
3974     BinaryOperator *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
3975     BinaryOperator *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
3976     if (tryToVectorizePair(A, B0, R)) {
3977       return true;
3978     }
3979     if (tryToVectorizePair(A, B1, R)) {
3980       return true;
3981     }
3982   }
3983 
3984   // Try to skip A.
3985   if (A && A->hasOneUse()) {
3986     BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
3987     BinaryOperator *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
3988     if (tryToVectorizePair(A0, B, R)) {
3989       return true;
3990     }
3991     if (tryToVectorizePair(A1, B, R)) {
3992       return true;
3993     }
3994   }
3995   return 0;
3996 }
3997 
3998 /// \brief Generate a shuffle mask to be used in a reduction tree.
3999 ///
4000 /// \param VecLen The length of the vector to be reduced.
4001 /// \param NumEltsToRdx The number of elements that should be reduced in the
4002 ///        vector.
4003 /// \param IsPairwise Whether the reduction is a pairwise or splitting
4004 ///        reduction. A pairwise reduction will generate a mask of
4005 ///        <0,2,...> or <1,3,..> while a splitting reduction will generate
4006 ///        <2,3, undef,undef> for a vector of 4 and NumElts = 2.
4007 /// \param IsLeft True will generate a mask of even elements, odd otherwise.
4008 static Value *createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx,
4009                                    bool IsPairwise, bool IsLeft,
4010                                    IRBuilder<> &Builder) {
4011   assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask");
4012 
4013   SmallVector<Constant *, 32> ShuffleMask(
4014       VecLen, UndefValue::get(Builder.getInt32Ty()));
4015 
4016   if (IsPairwise)
4017     // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
4018     for (unsigned i = 0; i != NumEltsToRdx; ++i)
4019       ShuffleMask[i] = Builder.getInt32(2 * i + !IsLeft);
4020   else
4021     // Move the upper half of the vector to the lower half.
4022     for (unsigned i = 0; i != NumEltsToRdx; ++i)
4023       ShuffleMask[i] = Builder.getInt32(NumEltsToRdx + i);
4024 
4025   return ConstantVector::get(ShuffleMask);
4026 }
4027 
4028 namespace {
4029 /// Model horizontal reductions.
4030 ///
4031 /// A horizontal reduction is a tree of reduction operations (currently add and
4032 /// fadd) that has operations that can be put into a vector as its leaf.
4033 /// For example, this tree:
4034 ///
4035 /// mul mul mul mul
4036 ///  \  /    \  /
4037 ///   +       +
4038 ///    \     /
4039 ///       +
4040 /// This tree has "mul" as its reduced values and "+" as its reduction
4041 /// operations. A reduction might be feeding into a store or a binary operation
4042 /// feeding a phi.
4043 ///    ...
4044 ///    \  /
4045 ///     +
4046 ///     |
4047 ///  phi +=
4048 ///
4049 ///  Or:
4050 ///    ...
4051 ///    \  /
4052 ///     +
4053 ///     |
4054 ///   *p =
4055 ///
4056 class HorizontalReduction {
4057   SmallVector<Value *, 16> ReductionOps;
4058   SmallVector<Value *, 32> ReducedVals;
4059 
4060   BinaryOperator *ReductionRoot;
4061   PHINode *ReductionPHI;
4062 
4063   /// The opcode of the reduction.
4064   unsigned ReductionOpcode;
4065   /// The opcode of the values we perform a reduction on.
4066   unsigned ReducedValueOpcode;
4067   /// Should we model this reduction as a pairwise reduction tree or a tree that
4068   /// splits the vector in halves and adds those halves.
4069   bool IsPairwiseReduction;
4070 
4071 public:
4072   /// The width of one full horizontal reduction operation.
4073   unsigned ReduxWidth;
4074 
4075   /// Minimal width of available vector registers. It's used to determine
4076   /// ReduxWidth.
4077   unsigned MinVecRegSize;
4078 
4079   HorizontalReduction(unsigned MinVecRegSize)
4080       : ReductionRoot(nullptr), ReductionPHI(nullptr), ReductionOpcode(0),
4081         ReducedValueOpcode(0), IsPairwiseReduction(false), ReduxWidth(0),
4082         MinVecRegSize(MinVecRegSize) {}
4083 
4084   /// \brief Try to find a reduction tree.
4085   bool matchAssociativeReduction(PHINode *Phi, BinaryOperator *B) {
4086     assert((!Phi || is_contained(Phi->operands(), B)) &&
4087            "Thi phi needs to use the binary operator");
4088 
4089     // We could have a initial reductions that is not an add.
4090     //  r *= v1 + v2 + v3 + v4
4091     // In such a case start looking for a tree rooted in the first '+'.
4092     if (Phi) {
4093       if (B->getOperand(0) == Phi) {
4094         Phi = nullptr;
4095         B = dyn_cast<BinaryOperator>(B->getOperand(1));
4096       } else if (B->getOperand(1) == Phi) {
4097         Phi = nullptr;
4098         B = dyn_cast<BinaryOperator>(B->getOperand(0));
4099       }
4100     }
4101 
4102     if (!B)
4103       return false;
4104 
4105     Type *Ty = B->getType();
4106     if (!isValidElementType(Ty))
4107       return false;
4108 
4109     const DataLayout &DL = B->getModule()->getDataLayout();
4110     ReductionOpcode = B->getOpcode();
4111     ReducedValueOpcode = 0;
4112     // FIXME: Register size should be a parameter to this function, so we can
4113     // try different vectorization factors.
4114     ReduxWidth = MinVecRegSize / DL.getTypeSizeInBits(Ty);
4115     ReductionRoot = B;
4116     ReductionPHI = Phi;
4117 
4118     if (ReduxWidth < 4)
4119       return false;
4120 
4121     // We currently only support adds.
4122     if (ReductionOpcode != Instruction::Add &&
4123         ReductionOpcode != Instruction::FAdd)
4124       return false;
4125 
4126     // Post order traverse the reduction tree starting at B. We only handle true
4127     // trees containing only binary operators or selects.
4128     SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
4129     Stack.push_back(std::make_pair(B, 0));
4130     while (!Stack.empty()) {
4131       Instruction *TreeN = Stack.back().first;
4132       unsigned EdgeToVist = Stack.back().second++;
4133       bool IsReducedValue = TreeN->getOpcode() != ReductionOpcode;
4134 
4135       // Only handle trees in the current basic block.
4136       if (TreeN->getParent() != B->getParent())
4137         return false;
4138 
4139       // Each tree node needs to have one user except for the ultimate
4140       // reduction.
4141       if (!TreeN->hasOneUse() && TreeN != B)
4142         return false;
4143 
4144       // Postorder vist.
4145       if (EdgeToVist == 2 || IsReducedValue) {
4146         if (IsReducedValue) {
4147           // Make sure that the opcodes of the operations that we are going to
4148           // reduce match.
4149           if (!ReducedValueOpcode)
4150             ReducedValueOpcode = TreeN->getOpcode();
4151           else if (ReducedValueOpcode != TreeN->getOpcode())
4152             return false;
4153           ReducedVals.push_back(TreeN);
4154         } else {
4155           // We need to be able to reassociate the adds.
4156           if (!TreeN->isAssociative())
4157             return false;
4158           ReductionOps.push_back(TreeN);
4159         }
4160         // Retract.
4161         Stack.pop_back();
4162         continue;
4163       }
4164 
4165       // Visit left or right.
4166       Value *NextV = TreeN->getOperand(EdgeToVist);
4167       // We currently only allow BinaryOperator's and SelectInst's as reduction
4168       // values in our tree.
4169       if (isa<BinaryOperator>(NextV) || isa<SelectInst>(NextV))
4170         Stack.push_back(std::make_pair(cast<Instruction>(NextV), 0));
4171       else if (NextV != Phi)
4172         return false;
4173     }
4174     return true;
4175   }
4176 
4177   /// \brief Attempt to vectorize the tree found by
4178   /// matchAssociativeReduction.
4179   bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
4180     if (ReducedVals.empty())
4181       return false;
4182 
4183     unsigned NumReducedVals = ReducedVals.size();
4184     if (NumReducedVals < ReduxWidth)
4185       return false;
4186 
4187     Value *VectorizedTree = nullptr;
4188     IRBuilder<> Builder(ReductionRoot);
4189     FastMathFlags Unsafe;
4190     Unsafe.setUnsafeAlgebra();
4191     Builder.setFastMathFlags(Unsafe);
4192     unsigned i = 0;
4193 
4194     for (; i < NumReducedVals - ReduxWidth + 1; i += ReduxWidth) {
4195       auto VL = makeArrayRef(&ReducedVals[i], ReduxWidth);
4196       V.buildTree(VL, ReductionOps);
4197       if (V.shouldReorder()) {
4198         SmallVector<Value *, 8> Reversed(VL.rbegin(), VL.rend());
4199         V.buildTree(Reversed, ReductionOps);
4200       }
4201       if (V.isTreeTinyAndNotFullyVectorizable())
4202         continue;
4203 
4204       V.computeMinimumValueSizes();
4205 
4206       // Estimate cost.
4207       int Cost = V.getTreeCost() + getReductionCost(TTI, ReducedVals[i]);
4208       if (Cost >= -SLPCostThreshold)
4209         break;
4210 
4211       DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" << Cost
4212                    << ". (HorRdx)\n");
4213 
4214       // Vectorize a tree.
4215       DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
4216       Value *VectorizedRoot = V.vectorizeTree();
4217 
4218       // Emit a reduction.
4219       Value *ReducedSubTree = emitReduction(VectorizedRoot, Builder);
4220       if (VectorizedTree) {
4221         Builder.SetCurrentDebugLocation(Loc);
4222         VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
4223                                      ReducedSubTree, "bin.rdx");
4224       } else
4225         VectorizedTree = ReducedSubTree;
4226     }
4227 
4228     if (VectorizedTree) {
4229       // Finish the reduction.
4230       for (; i < NumReducedVals; ++i) {
4231         Builder.SetCurrentDebugLocation(
4232           cast<Instruction>(ReducedVals[i])->getDebugLoc());
4233         VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
4234                                      ReducedVals[i]);
4235       }
4236       // Update users.
4237       if (ReductionPHI) {
4238         assert(ReductionRoot && "Need a reduction operation");
4239         ReductionRoot->setOperand(0, VectorizedTree);
4240         ReductionRoot->setOperand(1, ReductionPHI);
4241       } else
4242         ReductionRoot->replaceAllUsesWith(VectorizedTree);
4243     }
4244     return VectorizedTree != nullptr;
4245   }
4246 
4247   unsigned numReductionValues() const {
4248     return ReducedVals.size();
4249   }
4250 
4251 private:
4252   /// \brief Calculate the cost of a reduction.
4253   int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal) {
4254     Type *ScalarTy = FirstReducedVal->getType();
4255     Type *VecTy = VectorType::get(ScalarTy, ReduxWidth);
4256 
4257     int PairwiseRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, true);
4258     int SplittingRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, false);
4259 
4260     IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
4261     int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
4262 
4263     int ScalarReduxCost =
4264         ReduxWidth * TTI->getArithmeticInstrCost(ReductionOpcode, VecTy);
4265 
4266     DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost
4267                  << " for reduction that starts with " << *FirstReducedVal
4268                  << " (It is a "
4269                  << (IsPairwiseReduction ? "pairwise" : "splitting")
4270                  << " reduction)\n");
4271 
4272     return VecReduxCost - ScalarReduxCost;
4273   }
4274 
4275   static Value *createBinOp(IRBuilder<> &Builder, unsigned Opcode, Value *L,
4276                             Value *R, const Twine &Name = "") {
4277     if (Opcode == Instruction::FAdd)
4278       return Builder.CreateFAdd(L, R, Name);
4279     return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, L, R, Name);
4280   }
4281 
4282   /// \brief Emit a horizontal reduction of the vectorized value.
4283   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder) {
4284     assert(VectorizedValue && "Need to have a vectorized tree node");
4285     assert(isPowerOf2_32(ReduxWidth) &&
4286            "We only handle power-of-two reductions for now");
4287 
4288     Value *TmpVec = VectorizedValue;
4289     for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
4290       if (IsPairwiseReduction) {
4291         Value *LeftMask =
4292           createRdxShuffleMask(ReduxWidth, i, true, true, Builder);
4293         Value *RightMask =
4294           createRdxShuffleMask(ReduxWidth, i, true, false, Builder);
4295 
4296         Value *LeftShuf = Builder.CreateShuffleVector(
4297           TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l");
4298         Value *RightShuf = Builder.CreateShuffleVector(
4299           TmpVec, UndefValue::get(TmpVec->getType()), (RightMask),
4300           "rdx.shuf.r");
4301         TmpVec = createBinOp(Builder, ReductionOpcode, LeftShuf, RightShuf,
4302                              "bin.rdx");
4303       } else {
4304         Value *UpperHalf =
4305           createRdxShuffleMask(ReduxWidth, i, false, false, Builder);
4306         Value *Shuf = Builder.CreateShuffleVector(
4307           TmpVec, UndefValue::get(TmpVec->getType()), UpperHalf, "rdx.shuf");
4308         TmpVec = createBinOp(Builder, ReductionOpcode, TmpVec, Shuf, "bin.rdx");
4309       }
4310     }
4311 
4312     // The result is in the first element of the vector.
4313     return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
4314   }
4315 };
4316 } // end anonymous namespace
4317 
4318 /// \brief Recognize construction of vectors like
4319 ///  %ra = insertelement <4 x float> undef, float %s0, i32 0
4320 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
4321 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
4322 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
4323 ///
4324 /// Returns true if it matches
4325 ///
4326 static bool findBuildVector(InsertElementInst *FirstInsertElem,
4327                             SmallVectorImpl<Value *> &BuildVector,
4328                             SmallVectorImpl<Value *> &BuildVectorOpds) {
4329   if (!isa<UndefValue>(FirstInsertElem->getOperand(0)))
4330     return false;
4331 
4332   InsertElementInst *IE = FirstInsertElem;
4333   while (true) {
4334     BuildVector.push_back(IE);
4335     BuildVectorOpds.push_back(IE->getOperand(1));
4336 
4337     if (IE->use_empty())
4338       return false;
4339 
4340     InsertElementInst *NextUse = dyn_cast<InsertElementInst>(IE->user_back());
4341     if (!NextUse)
4342       return true;
4343 
4344     // If this isn't the final use, make sure the next insertelement is the only
4345     // use. It's OK if the final constructed vector is used multiple times
4346     if (!IE->hasOneUse())
4347       return false;
4348 
4349     IE = NextUse;
4350   }
4351 
4352   return false;
4353 }
4354 
4355 /// \brief Like findBuildVector, but looks backwards for construction of aggregate.
4356 ///
4357 /// \return true if it matches.
4358 static bool findBuildAggregate(InsertValueInst *IV,
4359                                SmallVectorImpl<Value *> &BuildVector,
4360                                SmallVectorImpl<Value *> &BuildVectorOpds) {
4361   if (!IV->hasOneUse())
4362     return false;
4363   Value *V = IV->getAggregateOperand();
4364   if (!isa<UndefValue>(V)) {
4365     InsertValueInst *I = dyn_cast<InsertValueInst>(V);
4366     if (!I || !findBuildAggregate(I, BuildVector, BuildVectorOpds))
4367       return false;
4368   }
4369   BuildVector.push_back(IV);
4370   BuildVectorOpds.push_back(IV->getInsertedValueOperand());
4371   return true;
4372 }
4373 
4374 static bool PhiTypeSorterFunc(Value *V, Value *V2) {
4375   return V->getType() < V2->getType();
4376 }
4377 
4378 /// \brief Try and get a reduction value from a phi node.
4379 ///
4380 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
4381 /// if they come from either \p ParentBB or a containing loop latch.
4382 ///
4383 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
4384 /// if not possible.
4385 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
4386                                 BasicBlock *ParentBB, LoopInfo *LI) {
4387   // There are situations where the reduction value is not dominated by the
4388   // reduction phi. Vectorizing such cases has been reported to cause
4389   // miscompiles. See PR25787.
4390   auto DominatedReduxValue = [&](Value *R) {
4391     return (
4392         dyn_cast<Instruction>(R) &&
4393         DT->dominates(P->getParent(), dyn_cast<Instruction>(R)->getParent()));
4394   };
4395 
4396   Value *Rdx = nullptr;
4397 
4398   // Return the incoming value if it comes from the same BB as the phi node.
4399   if (P->getIncomingBlock(0) == ParentBB) {
4400     Rdx = P->getIncomingValue(0);
4401   } else if (P->getIncomingBlock(1) == ParentBB) {
4402     Rdx = P->getIncomingValue(1);
4403   }
4404 
4405   if (Rdx && DominatedReduxValue(Rdx))
4406     return Rdx;
4407 
4408   // Otherwise, check whether we have a loop latch to look at.
4409   Loop *BBL = LI->getLoopFor(ParentBB);
4410   if (!BBL)
4411     return nullptr;
4412   BasicBlock *BBLatch = BBL->getLoopLatch();
4413   if (!BBLatch)
4414     return nullptr;
4415 
4416   // There is a loop latch, return the incoming value if it comes from
4417   // that. This reduction pattern occassionaly turns up.
4418   if (P->getIncomingBlock(0) == BBLatch) {
4419     Rdx = P->getIncomingValue(0);
4420   } else if (P->getIncomingBlock(1) == BBLatch) {
4421     Rdx = P->getIncomingValue(1);
4422   }
4423 
4424   if (Rdx && DominatedReduxValue(Rdx))
4425     return Rdx;
4426 
4427   return nullptr;
4428 }
4429 
4430 /// \brief Attempt to reduce a horizontal reduction.
4431 /// If it is legal to match a horizontal reduction feeding
4432 /// the phi node P with reduction operators BI, then check if it
4433 /// can be done.
4434 /// \returns true if a horizontal reduction was matched and reduced.
4435 /// \returns false if a horizontal reduction was not matched.
4436 static bool canMatchHorizontalReduction(PHINode *P, BinaryOperator *BI,
4437                                         BoUpSLP &R, TargetTransformInfo *TTI,
4438                                         unsigned MinRegSize) {
4439   if (!ShouldVectorizeHor)
4440     return false;
4441 
4442   HorizontalReduction HorRdx(MinRegSize);
4443   if (!HorRdx.matchAssociativeReduction(P, BI))
4444     return false;
4445 
4446   // If there is a sufficient number of reduction values, reduce
4447   // to a nearby power-of-2. Can safely generate oversized
4448   // vectors and rely on the backend to split them to legal sizes.
4449   HorRdx.ReduxWidth =
4450     std::max((uint64_t)4, PowerOf2Floor(HorRdx.numReductionValues()));
4451 
4452   return HorRdx.tryToReduce(R, TTI);
4453 }
4454 
4455 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
4456   bool Changed = false;
4457   SmallVector<Value *, 4> Incoming;
4458   SmallSet<Value *, 16> VisitedInstrs;
4459 
4460   bool HaveVectorizedPhiNodes = true;
4461   while (HaveVectorizedPhiNodes) {
4462     HaveVectorizedPhiNodes = false;
4463 
4464     // Collect the incoming values from the PHIs.
4465     Incoming.clear();
4466     for (Instruction &I : *BB) {
4467       PHINode *P = dyn_cast<PHINode>(&I);
4468       if (!P)
4469         break;
4470 
4471       if (!VisitedInstrs.count(P))
4472         Incoming.push_back(P);
4473     }
4474 
4475     // Sort by type.
4476     std::stable_sort(Incoming.begin(), Incoming.end(), PhiTypeSorterFunc);
4477 
4478     // Try to vectorize elements base on their type.
4479     for (SmallVector<Value *, 4>::iterator IncIt = Incoming.begin(),
4480                                            E = Incoming.end();
4481          IncIt != E;) {
4482 
4483       // Look for the next elements with the same type.
4484       SmallVector<Value *, 4>::iterator SameTypeIt = IncIt;
4485       while (SameTypeIt != E &&
4486              (*SameTypeIt)->getType() == (*IncIt)->getType()) {
4487         VisitedInstrs.insert(*SameTypeIt);
4488         ++SameTypeIt;
4489       }
4490 
4491       // Try to vectorize them.
4492       unsigned NumElts = (SameTypeIt - IncIt);
4493       DEBUG(errs() << "SLP: Trying to vectorize starting at PHIs (" << NumElts << ")\n");
4494       if (NumElts > 1 && tryToVectorizeList(makeArrayRef(IncIt, NumElts), R)) {
4495         // Success start over because instructions might have been changed.
4496         HaveVectorizedPhiNodes = true;
4497         Changed = true;
4498         break;
4499       }
4500 
4501       // Start over at the next instruction of a different type (or the end).
4502       IncIt = SameTypeIt;
4503     }
4504   }
4505 
4506   VisitedInstrs.clear();
4507 
4508   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) {
4509     // We may go through BB multiple times so skip the one we have checked.
4510     if (!VisitedInstrs.insert(&*it).second)
4511       continue;
4512 
4513     if (isa<DbgInfoIntrinsic>(it))
4514       continue;
4515 
4516     // Try to vectorize reductions that use PHINodes.
4517     if (PHINode *P = dyn_cast<PHINode>(it)) {
4518       // Check that the PHI is a reduction PHI.
4519       if (P->getNumIncomingValues() != 2)
4520         return Changed;
4521 
4522       Value *Rdx = getReductionValue(DT, P, BB, LI);
4523 
4524       // Check if this is a Binary Operator.
4525       BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx);
4526       if (!BI)
4527         continue;
4528 
4529       // Try to match and vectorize a horizontal reduction.
4530       if (canMatchHorizontalReduction(P, BI, R, TTI, R.getMinVecRegSize())) {
4531         Changed = true;
4532         it = BB->begin();
4533         e = BB->end();
4534         continue;
4535       }
4536 
4537      Value *Inst = BI->getOperand(0);
4538       if (Inst == P)
4539         Inst = BI->getOperand(1);
4540 
4541       if (tryToVectorize(dyn_cast<BinaryOperator>(Inst), R)) {
4542         // We would like to start over since some instructions are deleted
4543         // and the iterator may become invalid value.
4544         Changed = true;
4545         it = BB->begin();
4546         e = BB->end();
4547         continue;
4548       }
4549 
4550       continue;
4551     }
4552 
4553     if (ShouldStartVectorizeHorAtStore)
4554       if (StoreInst *SI = dyn_cast<StoreInst>(it))
4555         if (BinaryOperator *BinOp =
4556                 dyn_cast<BinaryOperator>(SI->getValueOperand())) {
4557           if (canMatchHorizontalReduction(nullptr, BinOp, R, TTI,
4558                                           R.getMinVecRegSize()) ||
4559               tryToVectorize(BinOp, R)) {
4560             Changed = true;
4561             it = BB->begin();
4562             e = BB->end();
4563             continue;
4564           }
4565         }
4566 
4567     // Try to vectorize horizontal reductions feeding into a return.
4568     if (ReturnInst *RI = dyn_cast<ReturnInst>(it))
4569       if (RI->getNumOperands() != 0)
4570         if (BinaryOperator *BinOp =
4571                 dyn_cast<BinaryOperator>(RI->getOperand(0))) {
4572           DEBUG(dbgs() << "SLP: Found a return to vectorize.\n");
4573           if (tryToVectorizePair(BinOp->getOperand(0),
4574                                  BinOp->getOperand(1), R)) {
4575             Changed = true;
4576             it = BB->begin();
4577             e = BB->end();
4578             continue;
4579           }
4580         }
4581 
4582     // Try to vectorize trees that start at compare instructions.
4583     if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
4584       if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) {
4585         Changed = true;
4586         // We would like to start over since some instructions are deleted
4587         // and the iterator may become invalid value.
4588         it = BB->begin();
4589         e = BB->end();
4590         continue;
4591       }
4592 
4593       for (int i = 0; i < 2; ++i) {
4594         if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i))) {
4595           if (tryToVectorizePair(BI->getOperand(0), BI->getOperand(1), R)) {
4596             Changed = true;
4597             // We would like to start over since some instructions are deleted
4598             // and the iterator may become invalid value.
4599             it = BB->begin();
4600             e = BB->end();
4601             break;
4602           }
4603         }
4604       }
4605       continue;
4606     }
4607 
4608     // Try to vectorize trees that start at insertelement instructions.
4609     if (InsertElementInst *FirstInsertElem = dyn_cast<InsertElementInst>(it)) {
4610       SmallVector<Value *, 16> BuildVector;
4611       SmallVector<Value *, 16> BuildVectorOpds;
4612       if (!findBuildVector(FirstInsertElem, BuildVector, BuildVectorOpds))
4613         continue;
4614 
4615       // Vectorize starting with the build vector operands ignoring the
4616       // BuildVector instructions for the purpose of scheduling and user
4617       // extraction.
4618       if (tryToVectorizeList(BuildVectorOpds, R, BuildVector)) {
4619         Changed = true;
4620         it = BB->begin();
4621         e = BB->end();
4622       }
4623 
4624       continue;
4625     }
4626 
4627     // Try to vectorize trees that start at insertvalue instructions feeding into
4628     // a store.
4629     if (StoreInst *SI = dyn_cast<StoreInst>(it)) {
4630       if (InsertValueInst *LastInsertValue = dyn_cast<InsertValueInst>(SI->getValueOperand())) {
4631         const DataLayout &DL = BB->getModule()->getDataLayout();
4632         if (R.canMapToVector(SI->getValueOperand()->getType(), DL)) {
4633           SmallVector<Value *, 16> BuildVector;
4634           SmallVector<Value *, 16> BuildVectorOpds;
4635           if (!findBuildAggregate(LastInsertValue, BuildVector, BuildVectorOpds))
4636             continue;
4637 
4638           DEBUG(dbgs() << "SLP: store of array mappable to vector: " << *SI << "\n");
4639           if (tryToVectorizeList(BuildVectorOpds, R, BuildVector, false)) {
4640             Changed = true;
4641             it = BB->begin();
4642             e = BB->end();
4643           }
4644           continue;
4645         }
4646       }
4647     }
4648   }
4649 
4650   return Changed;
4651 }
4652 
4653 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
4654   auto Changed = false;
4655   for (auto &Entry : GEPs) {
4656 
4657     // If the getelementptr list has fewer than two elements, there's nothing
4658     // to do.
4659     if (Entry.second.size() < 2)
4660       continue;
4661 
4662     DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
4663                  << Entry.second.size() << ".\n");
4664 
4665     // We process the getelementptr list in chunks of 16 (like we do for
4666     // stores) to minimize compile-time.
4667     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += 16) {
4668       auto Len = std::min<unsigned>(BE - BI, 16);
4669       auto GEPList = makeArrayRef(&Entry.second[BI], Len);
4670 
4671       // Initialize a set a candidate getelementptrs. Note that we use a
4672       // SetVector here to preserve program order. If the index computations
4673       // are vectorizable and begin with loads, we want to minimize the chance
4674       // of having to reorder them later.
4675       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
4676 
4677       // Some of the candidates may have already been vectorized after we
4678       // initially collected them. If so, the WeakVHs will have nullified the
4679       // values, so remove them from the set of candidates.
4680       Candidates.remove(nullptr);
4681 
4682       // Remove from the set of candidates all pairs of getelementptrs with
4683       // constant differences. Such getelementptrs are likely not good
4684       // candidates for vectorization in a bottom-up phase since one can be
4685       // computed from the other. We also ensure all candidate getelementptr
4686       // indices are unique.
4687       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
4688         auto *GEPI = cast<GetElementPtrInst>(GEPList[I]);
4689         if (!Candidates.count(GEPI))
4690           continue;
4691         auto *SCEVI = SE->getSCEV(GEPList[I]);
4692         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
4693           auto *GEPJ = cast<GetElementPtrInst>(GEPList[J]);
4694           auto *SCEVJ = SE->getSCEV(GEPList[J]);
4695           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
4696             Candidates.remove(GEPList[I]);
4697             Candidates.remove(GEPList[J]);
4698           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
4699             Candidates.remove(GEPList[J]);
4700           }
4701         }
4702       }
4703 
4704       // We break out of the above computation as soon as we know there are
4705       // fewer than two candidates remaining.
4706       if (Candidates.size() < 2)
4707         continue;
4708 
4709       // Add the single, non-constant index of each candidate to the bundle. We
4710       // ensured the indices met these constraints when we originally collected
4711       // the getelementptrs.
4712       SmallVector<Value *, 16> Bundle(Candidates.size());
4713       auto BundleIndex = 0u;
4714       for (auto *V : Candidates) {
4715         auto *GEP = cast<GetElementPtrInst>(V);
4716         auto *GEPIdx = GEP->idx_begin()->get();
4717         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
4718         Bundle[BundleIndex++] = GEPIdx;
4719       }
4720 
4721       // Try and vectorize the indices. We are currently only interested in
4722       // gather-like cases of the form:
4723       //
4724       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
4725       //
4726       // where the loads of "a", the loads of "b", and the subtractions can be
4727       // performed in parallel. It's likely that detecting this pattern in a
4728       // bottom-up phase will be simpler and less costly than building a
4729       // full-blown top-down phase beginning at the consecutive loads.
4730       Changed |= tryToVectorizeList(Bundle, R);
4731     }
4732   }
4733   return Changed;
4734 }
4735 
4736 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
4737   bool Changed = false;
4738   // Attempt to sort and vectorize each of the store-groups.
4739   for (StoreListMap::iterator it = Stores.begin(), e = Stores.end(); it != e;
4740        ++it) {
4741     if (it->second.size() < 2)
4742       continue;
4743 
4744     DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
4745           << it->second.size() << ".\n");
4746 
4747     // Process the stores in chunks of 16.
4748     // TODO: The limit of 16 inhibits greater vectorization factors.
4749     //       For example, AVX2 supports v32i8. Increasing this limit, however,
4750     //       may cause a significant compile-time increase.
4751     for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI+=16) {
4752       unsigned Len = std::min<unsigned>(CE - CI, 16);
4753       Changed |= vectorizeStores(makeArrayRef(&it->second[CI], Len),
4754                                  -SLPCostThreshold, 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