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