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