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     break;
4021   case Instruction::ZExt:
4022   case Instruction::SExt:
4023     break;
4024 
4025   // We can demote certain binary operations if we can demote both of their
4026   // operands.
4027   case Instruction::Add:
4028   case Instruction::Sub:
4029   case Instruction::Mul:
4030   case Instruction::And:
4031   case Instruction::Or:
4032   case Instruction::Xor:
4033     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
4034         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
4035       return false;
4036     break;
4037 
4038   // We can demote selects if we can demote their true and false values.
4039   case Instruction::Select: {
4040     SelectInst *SI = cast<SelectInst>(I);
4041     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
4042         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
4043       return false;
4044     break;
4045   }
4046 
4047   // We can demote phis if we can demote all their incoming operands. Note that
4048   // we don't need to worry about cycles since we ensure single use above.
4049   case Instruction::PHI: {
4050     PHINode *PN = cast<PHINode>(I);
4051     for (Value *IncValue : PN->incoming_values())
4052       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
4053         return false;
4054     break;
4055   }
4056 
4057   // Otherwise, conservatively give up.
4058   default:
4059     return false;
4060   }
4061 
4062   // Record the value that we can demote.
4063   ToDemote.push_back(V);
4064   return true;
4065 }
4066 
4067 void BoUpSLP::computeMinimumValueSizes() {
4068   // If there are no external uses, the expression tree must be rooted by a
4069   // store. We can't demote in-memory values, so there is nothing to do here.
4070   if (ExternalUses.empty())
4071     return;
4072 
4073   // We only attempt to truncate integer expressions.
4074   auto &TreeRoot = VectorizableTree[0].Scalars;
4075   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
4076   if (!TreeRootIT)
4077     return;
4078 
4079   // If the expression is not rooted by a store, these roots should have
4080   // external uses. We will rely on InstCombine to rewrite the expression in
4081   // the narrower type. However, InstCombine only rewrites single-use values.
4082   // This means that if a tree entry other than a root is used externally, it
4083   // must have multiple uses and InstCombine will not rewrite it. The code
4084   // below ensures that only the roots are used externally.
4085   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
4086   for (auto &EU : ExternalUses)
4087     if (!Expr.erase(EU.Scalar))
4088       return;
4089   if (!Expr.empty())
4090     return;
4091 
4092   // Collect the scalar values of the vectorizable expression. We will use this
4093   // context to determine which values can be demoted. If we see a truncation,
4094   // we mark it as seeding another demotion.
4095   for (auto &Entry : VectorizableTree)
4096     Expr.insert(Entry.Scalars.begin(), Entry.Scalars.end());
4097 
4098   // Ensure the roots of the vectorizable tree don't form a cycle. They must
4099   // have a single external user that is not in the vectorizable tree.
4100   for (auto *Root : TreeRoot)
4101     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
4102       return;
4103 
4104   // Conservatively determine if we can actually truncate the roots of the
4105   // expression. Collect the values that can be demoted in ToDemote and
4106   // additional roots that require investigating in Roots.
4107   SmallVector<Value *, 32> ToDemote;
4108   SmallVector<Value *, 4> Roots;
4109   for (auto *Root : TreeRoot)
4110     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
4111       return;
4112 
4113   // The maximum bit width required to represent all the values that can be
4114   // demoted without loss of precision. It would be safe to truncate the roots
4115   // of the expression to this width.
4116   auto MaxBitWidth = 8u;
4117 
4118   // We first check if all the bits of the roots are demanded. If they're not,
4119   // we can truncate the roots to this narrower type.
4120   for (auto *Root : TreeRoot) {
4121     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
4122     MaxBitWidth = std::max<unsigned>(
4123         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
4124   }
4125 
4126   // True if the roots can be zero-extended back to their original type, rather
4127   // than sign-extended. We know that if the leading bits are not demanded, we
4128   // can safely zero-extend. So we initialize IsKnownPositive to True.
4129   bool IsKnownPositive = true;
4130 
4131   // If all the bits of the roots are demanded, we can try a little harder to
4132   // compute a narrower type. This can happen, for example, if the roots are
4133   // getelementptr indices. InstCombine promotes these indices to the pointer
4134   // width. Thus, all their bits are technically demanded even though the
4135   // address computation might be vectorized in a smaller type.
4136   //
4137   // We start by looking at each entry that can be demoted. We compute the
4138   // maximum bit width required to store the scalar by using ValueTracking to
4139   // compute the number of high-order bits we can truncate.
4140   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType())) {
4141     MaxBitWidth = 8u;
4142 
4143     // Determine if the sign bit of all the roots is known to be zero. If not,
4144     // IsKnownPositive is set to False.
4145     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
4146       KnownBits Known = computeKnownBits(R, *DL);
4147       return Known.isNonNegative();
4148     });
4149 
4150     // Determine the maximum number of bits required to store the scalar
4151     // values.
4152     for (auto *Scalar : ToDemote) {
4153       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
4154       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
4155       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
4156     }
4157 
4158     // If we can't prove that the sign bit is zero, we must add one to the
4159     // maximum bit width to account for the unknown sign bit. This preserves
4160     // the existing sign bit so we can safely sign-extend the root back to the
4161     // original type. Otherwise, if we know the sign bit is zero, we will
4162     // zero-extend the root instead.
4163     //
4164     // FIXME: This is somewhat suboptimal, as there will be cases where adding
4165     //        one to the maximum bit width will yield a larger-than-necessary
4166     //        type. In general, we need to add an extra bit only if we can't
4167     //        prove that the upper bit of the original type is equal to the
4168     //        upper bit of the proposed smaller type. If these two bits are the
4169     //        same (either zero or one) we know that sign-extending from the
4170     //        smaller type will result in the same value. Here, since we can't
4171     //        yet prove this, we are just making the proposed smaller type
4172     //        larger to ensure correctness.
4173     if (!IsKnownPositive)
4174       ++MaxBitWidth;
4175   }
4176 
4177   // Round MaxBitWidth up to the next power-of-two.
4178   if (!isPowerOf2_64(MaxBitWidth))
4179     MaxBitWidth = NextPowerOf2(MaxBitWidth);
4180 
4181   // If the maximum bit width we compute is less than the with of the roots'
4182   // type, we can proceed with the narrowing. Otherwise, do nothing.
4183   if (MaxBitWidth >= TreeRootIT->getBitWidth())
4184     return;
4185 
4186   // If we can truncate the root, we must collect additional values that might
4187   // be demoted as a result. That is, those seeded by truncations we will
4188   // modify.
4189   while (!Roots.empty())
4190     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
4191 
4192   // Finally, map the values we can demote to the maximum bit with we computed.
4193   for (auto *Scalar : ToDemote)
4194     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
4195 }
4196 
4197 namespace {
4198 
4199 /// The SLPVectorizer Pass.
4200 struct SLPVectorizer : public FunctionPass {
4201   SLPVectorizerPass Impl;
4202 
4203   /// Pass identification, replacement for typeid
4204   static char ID;
4205 
4206   explicit SLPVectorizer() : FunctionPass(ID) {
4207     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
4208   }
4209 
4210   bool doInitialization(Module &M) override {
4211     return false;
4212   }
4213 
4214   bool runOnFunction(Function &F) override {
4215     if (skipFunction(F))
4216       return false;
4217 
4218     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4219     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
4220     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
4221     auto *TLI = TLIP ? &TLIP->getTLI() : nullptr;
4222     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
4223     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4224     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
4225     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
4226     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
4227     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
4228 
4229     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
4230   }
4231 
4232   void getAnalysisUsage(AnalysisUsage &AU) const override {
4233     FunctionPass::getAnalysisUsage(AU);
4234     AU.addRequired<AssumptionCacheTracker>();
4235     AU.addRequired<ScalarEvolutionWrapperPass>();
4236     AU.addRequired<AAResultsWrapperPass>();
4237     AU.addRequired<TargetTransformInfoWrapperPass>();
4238     AU.addRequired<LoopInfoWrapperPass>();
4239     AU.addRequired<DominatorTreeWrapperPass>();
4240     AU.addRequired<DemandedBitsWrapperPass>();
4241     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
4242     AU.addPreserved<LoopInfoWrapperPass>();
4243     AU.addPreserved<DominatorTreeWrapperPass>();
4244     AU.addPreserved<AAResultsWrapperPass>();
4245     AU.addPreserved<GlobalsAAWrapperPass>();
4246     AU.setPreservesCFG();
4247   }
4248 };
4249 
4250 } // end anonymous namespace
4251 
4252 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
4253   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
4254   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
4255   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
4256   auto *AA = &AM.getResult<AAManager>(F);
4257   auto *LI = &AM.getResult<LoopAnalysis>(F);
4258   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
4259   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
4260   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
4261   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
4262 
4263   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
4264   if (!Changed)
4265     return PreservedAnalyses::all();
4266 
4267   PreservedAnalyses PA;
4268   PA.preserveSet<CFGAnalyses>();
4269   PA.preserve<AAManager>();
4270   PA.preserve<GlobalsAA>();
4271   return PA;
4272 }
4273 
4274 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
4275                                 TargetTransformInfo *TTI_,
4276                                 TargetLibraryInfo *TLI_, AliasAnalysis *AA_,
4277                                 LoopInfo *LI_, DominatorTree *DT_,
4278                                 AssumptionCache *AC_, DemandedBits *DB_,
4279                                 OptimizationRemarkEmitter *ORE_) {
4280   SE = SE_;
4281   TTI = TTI_;
4282   TLI = TLI_;
4283   AA = AA_;
4284   LI = LI_;
4285   DT = DT_;
4286   AC = AC_;
4287   DB = DB_;
4288   DL = &F.getParent()->getDataLayout();
4289 
4290   Stores.clear();
4291   GEPs.clear();
4292   bool Changed = false;
4293 
4294   // If the target claims to have no vector registers don't attempt
4295   // vectorization.
4296   if (!TTI->getNumberOfRegisters(true))
4297     return false;
4298 
4299   // Don't vectorize when the attribute NoImplicitFloat is used.
4300   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
4301     return false;
4302 
4303   DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
4304 
4305   // Use the bottom up slp vectorizer to construct chains that start with
4306   // store instructions.
4307   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
4308 
4309   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
4310   // delete instructions.
4311 
4312   // Scan the blocks in the function in post order.
4313   for (auto BB : post_order(&F.getEntryBlock())) {
4314     collectSeedInstructions(BB);
4315 
4316     // Vectorize trees that end at stores.
4317     if (!Stores.empty()) {
4318       DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
4319                    << " underlying objects.\n");
4320       Changed |= vectorizeStoreChains(R);
4321     }
4322 
4323     // Vectorize trees that end at reductions.
4324     Changed |= vectorizeChainsInBlock(BB, R);
4325 
4326     // Vectorize the index computations of getelementptr instructions. This
4327     // is primarily intended to catch gather-like idioms ending at
4328     // non-consecutive loads.
4329     if (!GEPs.empty()) {
4330       DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
4331                    << " underlying objects.\n");
4332       Changed |= vectorizeGEPIndices(BB, R);
4333     }
4334   }
4335 
4336   if (Changed) {
4337     R.optimizeGatherSequence(F);
4338     DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
4339     DEBUG(verifyFunction(F));
4340   }
4341   return Changed;
4342 }
4343 
4344 /// \brief Check that the Values in the slice in VL array are still existent in
4345 /// the WeakTrackingVH array.
4346 /// Vectorization of part of the VL array may cause later values in the VL array
4347 /// to become invalid. We track when this has happened in the WeakTrackingVH
4348 /// array.
4349 static bool hasValueBeenRAUWed(ArrayRef<Value *> VL,
4350                                ArrayRef<WeakTrackingVH> VH, unsigned SliceBegin,
4351                                unsigned SliceSize) {
4352   VL = VL.slice(SliceBegin, SliceSize);
4353   VH = VH.slice(SliceBegin, SliceSize);
4354   return !std::equal(VL.begin(), VL.end(), VH.begin());
4355 }
4356 
4357 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
4358                                             unsigned VecRegSize) {
4359   unsigned ChainLen = Chain.size();
4360   DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
4361         << "\n");
4362   unsigned Sz = R.getVectorElementSize(Chain[0]);
4363   unsigned VF = VecRegSize / Sz;
4364 
4365   if (!isPowerOf2_32(Sz) || VF < 2)
4366     return false;
4367 
4368   // Keep track of values that were deleted by vectorizing in the loop below.
4369   SmallVector<WeakTrackingVH, 8> TrackValues(Chain.begin(), Chain.end());
4370 
4371   bool Changed = false;
4372   // Look for profitable vectorizable trees at all offsets, starting at zero.
4373   for (unsigned i = 0, e = ChainLen; i < e; ++i) {
4374     if (i + VF > e)
4375       break;
4376 
4377     // Check that a previous iteration of this loop did not delete the Value.
4378     if (hasValueBeenRAUWed(Chain, TrackValues, i, VF))
4379       continue;
4380 
4381     DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
4382           << "\n");
4383     ArrayRef<Value *> Operands = Chain.slice(i, VF);
4384 
4385     R.buildTree(Operands);
4386     if (R.isTreeTinyAndNotFullyVectorizable())
4387       continue;
4388 
4389     R.computeMinimumValueSizes();
4390 
4391     int Cost = R.getTreeCost();
4392 
4393     DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
4394     if (Cost < -SLPCostThreshold) {
4395       DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
4396 
4397       using namespace ore;
4398 
4399       R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
4400                                           cast<StoreInst>(Chain[i]))
4401                        << "Stores SLP vectorized with cost " << NV("Cost", Cost)
4402                        << " and with tree size "
4403                        << NV("TreeSize", R.getTreeSize()));
4404 
4405       R.vectorizeTree();
4406 
4407       // Move to the next bundle.
4408       i += VF - 1;
4409       Changed = true;
4410     }
4411   }
4412 
4413   return Changed;
4414 }
4415 
4416 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
4417                                         BoUpSLP &R) {
4418   SetVector<StoreInst *> Heads;
4419   SmallDenseSet<StoreInst *> Tails;
4420   SmallDenseMap<StoreInst *, StoreInst *> ConsecutiveChain;
4421 
4422   // We may run into multiple chains that merge into a single chain. We mark the
4423   // stores that we vectorized so that we don't visit the same store twice.
4424   BoUpSLP::ValueSet VectorizedStores;
4425   bool Changed = false;
4426 
4427   // Do a quadratic search on all of the given stores in reverse order and find
4428   // all of the pairs of stores that follow each other.
4429   SmallVector<unsigned, 16> IndexQueue;
4430   unsigned E = Stores.size();
4431   IndexQueue.resize(E - 1);
4432   for (unsigned I = E; I > 0; --I) {
4433     unsigned Idx = I - 1;
4434     // If a store has multiple consecutive store candidates, search Stores
4435     // array according to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
4436     // This is because usually pairing with immediate succeeding or preceding
4437     // candidate create the best chance to find slp vectorization opportunity.
4438     unsigned Offset = 1;
4439     unsigned Cnt = 0;
4440     for (unsigned J = 0; J < E - 1; ++J, ++Offset) {
4441       if (Idx >= Offset) {
4442         IndexQueue[Cnt] = Idx - Offset;
4443         ++Cnt;
4444       }
4445       if (Idx + Offset < E) {
4446         IndexQueue[Cnt] = Idx + Offset;
4447         ++Cnt;
4448       }
4449     }
4450 
4451     for (auto K : IndexQueue) {
4452       if (isConsecutiveAccess(Stores[K], Stores[Idx], *DL, *SE)) {
4453         Tails.insert(Stores[Idx]);
4454         Heads.insert(Stores[K]);
4455         ConsecutiveChain[Stores[K]] = Stores[Idx];
4456         break;
4457       }
4458     }
4459   }
4460 
4461   // For stores that start but don't end a link in the chain:
4462   for (auto *SI : llvm::reverse(Heads)) {
4463     if (Tails.count(SI))
4464       continue;
4465 
4466     // We found a store instr that starts a chain. Now follow the chain and try
4467     // to vectorize it.
4468     BoUpSLP::ValueList Operands;
4469     StoreInst *I = SI;
4470     // Collect the chain into a list.
4471     while ((Tails.count(I) || Heads.count(I)) && !VectorizedStores.count(I)) {
4472       Operands.push_back(I);
4473       // Move to the next value in the chain.
4474       I = ConsecutiveChain[I];
4475     }
4476 
4477     // FIXME: Is division-by-2 the correct step? Should we assert that the
4478     // register size is a power-of-2?
4479     for (unsigned Size = R.getMaxVecRegSize(); Size >= R.getMinVecRegSize();
4480          Size /= 2) {
4481       if (vectorizeStoreChain(Operands, R, Size)) {
4482         // Mark the vectorized stores so that we don't vectorize them again.
4483         VectorizedStores.insert(Operands.begin(), Operands.end());
4484         Changed = true;
4485         break;
4486       }
4487     }
4488   }
4489 
4490   return Changed;
4491 }
4492 
4493 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
4494   // Initialize the collections. We will make a single pass over the block.
4495   Stores.clear();
4496   GEPs.clear();
4497 
4498   // Visit the store and getelementptr instructions in BB and organize them in
4499   // Stores and GEPs according to the underlying objects of their pointer
4500   // operands.
4501   for (Instruction &I : *BB) {
4502     // Ignore store instructions that are volatile or have a pointer operand
4503     // that doesn't point to a scalar type.
4504     if (auto *SI = dyn_cast<StoreInst>(&I)) {
4505       if (!SI->isSimple())
4506         continue;
4507       if (!isValidElementType(SI->getValueOperand()->getType()))
4508         continue;
4509       Stores[GetUnderlyingObject(SI->getPointerOperand(), *DL)].push_back(SI);
4510     }
4511 
4512     // Ignore getelementptr instructions that have more than one index, a
4513     // constant index, or a pointer operand that doesn't point to a scalar
4514     // type.
4515     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
4516       auto Idx = GEP->idx_begin()->get();
4517       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
4518         continue;
4519       if (!isValidElementType(Idx->getType()))
4520         continue;
4521       if (GEP->getType()->isVectorTy())
4522         continue;
4523       GEPs[GetUnderlyingObject(GEP->getPointerOperand(), *DL)].push_back(GEP);
4524     }
4525   }
4526 }
4527 
4528 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
4529   if (!A || !B)
4530     return false;
4531   Value *VL[] = { A, B };
4532   return tryToVectorizeList(VL, R, None, true);
4533 }
4534 
4535 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
4536                                            ArrayRef<Value *> BuildVector,
4537                                            bool AllowReorder,
4538                                            bool NeedExtraction) {
4539   if (VL.size() < 2)
4540     return false;
4541 
4542   DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = " << VL.size()
4543                << ".\n");
4544 
4545   // Check that all of the parts are scalar instructions of the same type.
4546   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
4547   if (!I0)
4548     return false;
4549 
4550   unsigned Opcode0 = I0->getOpcode();
4551 
4552   unsigned Sz = R.getVectorElementSize(I0);
4553   unsigned MinVF = std::max(2U, R.getMinVecRegSize() / Sz);
4554   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
4555   if (MaxVF < 2) {
4556      R.getORE()->emit([&]() {
4557          return OptimizationRemarkMissed(
4558                     SV_NAME, "SmallVF", I0)
4559                 << "Cannot SLP vectorize list: vectorization factor "
4560                 << "less than 2 is not supported";
4561      });
4562      return false;
4563   }
4564 
4565   for (Value *V : VL) {
4566     Type *Ty = V->getType();
4567     if (!isValidElementType(Ty)) {
4568       // NOTE: the following will give user internal llvm type name, which may not be useful
4569       R.getORE()->emit([&]() {
4570           std::string type_str;
4571           llvm::raw_string_ostream rso(type_str);
4572           Ty->print(rso);
4573           return OptimizationRemarkMissed(
4574                      SV_NAME, "UnsupportedType", I0)
4575                  << "Cannot SLP vectorize list: type "
4576                  << rso.str() + " is unsupported by vectorizer";
4577       });
4578       return false;
4579     }
4580     Instruction *Inst = dyn_cast<Instruction>(V);
4581 
4582     if (!Inst)
4583         return false;
4584     if (Inst->getOpcode() != Opcode0) {
4585       R.getORE()->emit([&]() {
4586           return OptimizationRemarkMissed(
4587                      SV_NAME, "InequableTypes", I0)
4588                  << "Cannot SLP vectorize list: not all of the "
4589                  << "parts of scalar instructions are of the same type: "
4590                  << ore::NV("Instruction1Opcode", I0) << " and "
4591                  << ore::NV("Instruction2Opcode", Inst);
4592       });
4593       return false;
4594     }
4595   }
4596 
4597   bool Changed = false;
4598   bool CandidateFound = false;
4599   int MinCost = SLPCostThreshold;
4600 
4601   // Keep track of values that were deleted by vectorizing in the loop below.
4602   SmallVector<WeakTrackingVH, 8> TrackValues(VL.begin(), VL.end());
4603 
4604   unsigned NextInst = 0, MaxInst = VL.size();
4605   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF;
4606        VF /= 2) {
4607     // No actual vectorization should happen, if number of parts is the same as
4608     // provided vectorization factor (i.e. the scalar type is used for vector
4609     // code during codegen).
4610     auto *VecTy = VectorType::get(VL[0]->getType(), VF);
4611     if (TTI->getNumberOfParts(VecTy) == VF)
4612       continue;
4613     for (unsigned I = NextInst; I < MaxInst; ++I) {
4614       unsigned OpsWidth = 0;
4615 
4616       if (I + VF > MaxInst)
4617         OpsWidth = MaxInst - I;
4618       else
4619         OpsWidth = VF;
4620 
4621       if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
4622         break;
4623 
4624       // Check that a previous iteration of this loop did not delete the Value.
4625       if (hasValueBeenRAUWed(VL, TrackValues, I, OpsWidth))
4626         continue;
4627 
4628       DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
4629                    << "\n");
4630       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
4631 
4632       ArrayRef<Value *> EmptyArray;
4633       ArrayRef<Value *> BuildVectorSlice;
4634       if (!BuildVector.empty())
4635         BuildVectorSlice = BuildVector.slice(I, OpsWidth);
4636 
4637       R.buildTree(Ops, NeedExtraction ? EmptyArray : BuildVectorSlice);
4638       // TODO: check if we can allow reordering for more cases.
4639       if (AllowReorder && R.shouldReorder()) {
4640         // Conceptually, there is nothing actually preventing us from trying to
4641         // reorder a larger list. In fact, we do exactly this when vectorizing
4642         // reductions. However, at this point, we only expect to get here when
4643         // there are exactly two operations.
4644         assert(Ops.size() == 2);
4645         assert(BuildVectorSlice.empty());
4646         Value *ReorderedOps[] = {Ops[1], Ops[0]};
4647         R.buildTree(ReorderedOps, None);
4648       }
4649       if (R.isTreeTinyAndNotFullyVectorizable())
4650         continue;
4651 
4652       R.computeMinimumValueSizes();
4653       int Cost = R.getTreeCost();
4654       CandidateFound = true;
4655       MinCost = std::min(MinCost, Cost);
4656 
4657       if (Cost < -SLPCostThreshold) {
4658         DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
4659         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
4660                                                     cast<Instruction>(Ops[0]))
4661                                  << "SLP vectorized with cost " << ore::NV("Cost", Cost)
4662                                  << " and with tree size "
4663                                  << ore::NV("TreeSize", R.getTreeSize()));
4664 
4665         Value *VectorizedRoot = R.vectorizeTree();
4666 
4667         // Reconstruct the build vector by extracting the vectorized root. This
4668         // way we handle the case where some elements of the vector are
4669         // undefined.
4670         //  (return (inserelt <4 xi32> (insertelt undef (opd0) 0) (opd1) 2))
4671         if (!BuildVectorSlice.empty()) {
4672           // The insert point is the last build vector instruction. The
4673           // vectorized root will precede it. This guarantees that we get an
4674           // instruction. The vectorized tree could have been constant folded.
4675           Instruction *InsertAfter = cast<Instruction>(BuildVectorSlice.back());
4676           unsigned VecIdx = 0;
4677           for (auto &V : BuildVectorSlice) {
4678             IRBuilder<NoFolder> Builder(InsertAfter->getParent(),
4679                                         ++BasicBlock::iterator(InsertAfter));
4680             Instruction *I = cast<Instruction>(V);
4681             assert(isa<InsertElementInst>(I) || isa<InsertValueInst>(I));
4682             Instruction *Extract =
4683                 cast<Instruction>(Builder.CreateExtractElement(
4684                     VectorizedRoot, Builder.getInt32(VecIdx++)));
4685             I->setOperand(1, Extract);
4686             I->moveAfter(Extract);
4687             InsertAfter = I;
4688           }
4689         }
4690         // Move to the next bundle.
4691         I += VF - 1;
4692         NextInst = I + 1;
4693         Changed = true;
4694       }
4695     }
4696   }
4697 
4698   if (!Changed && CandidateFound) {
4699     R.getORE()->emit([&]() {
4700         return OptimizationRemarkMissed(
4701                    SV_NAME, "NotBeneficial",  I0)
4702                << "List vectorization was possible but not beneficial with cost "
4703                << ore::NV("Cost", MinCost) << " >= "
4704                << ore::NV("Treshold", -SLPCostThreshold);
4705     });
4706   } else if (!Changed) {
4707     R.getORE()->emit([&]() {
4708         return OptimizationRemarkMissed(
4709                    SV_NAME, "NotPossible", I0)
4710                << "Cannot SLP vectorize list: vectorization was impossible"
4711                << " with available vectorization factors";
4712     });
4713   }
4714   return Changed;
4715 }
4716 
4717 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
4718   if (!I)
4719     return false;
4720 
4721   if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I))
4722     return false;
4723 
4724   Value *P = I->getParent();
4725 
4726   // Vectorize in current basic block only.
4727   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
4728   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
4729   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
4730     return false;
4731 
4732   // Try to vectorize V.
4733   if (tryToVectorizePair(Op0, Op1, R))
4734     return true;
4735 
4736   auto *A = dyn_cast<BinaryOperator>(Op0);
4737   auto *B = dyn_cast<BinaryOperator>(Op1);
4738   // Try to skip B.
4739   if (B && B->hasOneUse()) {
4740     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
4741     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
4742     if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
4743       return true;
4744     if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
4745       return true;
4746   }
4747 
4748   // Try to skip A.
4749   if (A && A->hasOneUse()) {
4750     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
4751     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
4752     if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
4753       return true;
4754     if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
4755       return true;
4756   }
4757   return false;
4758 }
4759 
4760 /// \brief Generate a shuffle mask to be used in a reduction tree.
4761 ///
4762 /// \param VecLen The length of the vector to be reduced.
4763 /// \param NumEltsToRdx The number of elements that should be reduced in the
4764 ///        vector.
4765 /// \param IsPairwise Whether the reduction is a pairwise or splitting
4766 ///        reduction. A pairwise reduction will generate a mask of
4767 ///        <0,2,...> or <1,3,..> while a splitting reduction will generate
4768 ///        <2,3, undef,undef> for a vector of 4 and NumElts = 2.
4769 /// \param IsLeft True will generate a mask of even elements, odd otherwise.
4770 static Value *createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx,
4771                                    bool IsPairwise, bool IsLeft,
4772                                    IRBuilder<> &Builder) {
4773   assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask");
4774 
4775   SmallVector<Constant *, 32> ShuffleMask(
4776       VecLen, UndefValue::get(Builder.getInt32Ty()));
4777 
4778   if (IsPairwise)
4779     // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
4780     for (unsigned i = 0; i != NumEltsToRdx; ++i)
4781       ShuffleMask[i] = Builder.getInt32(2 * i + !IsLeft);
4782   else
4783     // Move the upper half of the vector to the lower half.
4784     for (unsigned i = 0; i != NumEltsToRdx; ++i)
4785       ShuffleMask[i] = Builder.getInt32(NumEltsToRdx + i);
4786 
4787   return ConstantVector::get(ShuffleMask);
4788 }
4789 
4790 namespace {
4791 
4792 /// Model horizontal reductions.
4793 ///
4794 /// A horizontal reduction is a tree of reduction operations (currently add and
4795 /// fadd) that has operations that can be put into a vector as its leaf.
4796 /// For example, this tree:
4797 ///
4798 /// mul mul mul mul
4799 ///  \  /    \  /
4800 ///   +       +
4801 ///    \     /
4802 ///       +
4803 /// This tree has "mul" as its reduced values and "+" as its reduction
4804 /// operations. A reduction might be feeding into a store or a binary operation
4805 /// feeding a phi.
4806 ///    ...
4807 ///    \  /
4808 ///     +
4809 ///     |
4810 ///  phi +=
4811 ///
4812 ///  Or:
4813 ///    ...
4814 ///    \  /
4815 ///     +
4816 ///     |
4817 ///   *p =
4818 ///
4819 class HorizontalReduction {
4820   using ReductionOpsType = SmallVector<Value *, 16>;
4821   using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
4822   ReductionOpsListType  ReductionOps;
4823   SmallVector<Value *, 32> ReducedVals;
4824   // Use map vector to make stable output.
4825   MapVector<Instruction *, Value *> ExtraArgs;
4826 
4827   /// Kind of the reduction data.
4828   enum ReductionKind {
4829     RK_None,       /// Not a reduction.
4830     RK_Arithmetic, /// Binary reduction data.
4831     RK_Min,        /// Minimum reduction data.
4832     RK_UMin,       /// Unsigned minimum reduction data.
4833     RK_Max,        /// Maximum reduction data.
4834     RK_UMax,       /// Unsigned maximum reduction data.
4835   };
4836 
4837   /// Contains info about operation, like its opcode, left and right operands.
4838   class OperationData {
4839     /// Opcode of the instruction.
4840     unsigned Opcode = 0;
4841 
4842     /// Left operand of the reduction operation.
4843     Value *LHS = nullptr;
4844 
4845     /// Right operand of the reduction operation.
4846     Value *RHS = nullptr;
4847 
4848     /// Kind of the reduction operation.
4849     ReductionKind Kind = RK_None;
4850 
4851     /// True if float point min/max reduction has no NaNs.
4852     bool NoNaN = false;
4853 
4854     /// Checks if the reduction operation can be vectorized.
4855     bool isVectorizable() const {
4856       return LHS && RHS &&
4857              // We currently only support adds && min/max reductions.
4858              ((Kind == RK_Arithmetic &&
4859                (Opcode == Instruction::Add || Opcode == Instruction::FAdd)) ||
4860               ((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
4861                (Kind == RK_Min || Kind == RK_Max)) ||
4862               (Opcode == Instruction::ICmp &&
4863                (Kind == RK_UMin || Kind == RK_UMax)));
4864     }
4865 
4866     /// Creates reduction operation with the current opcode.
4867     Value *createOp(IRBuilder<> &Builder, const Twine &Name) const {
4868       assert(isVectorizable() &&
4869              "Expected add|fadd or min/max reduction operation.");
4870       Value *Cmp;
4871       switch (Kind) {
4872       case RK_Arithmetic:
4873         return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, LHS, RHS,
4874                                    Name);
4875       case RK_Min:
4876         Cmp = Opcode == Instruction::ICmp ? Builder.CreateICmpSLT(LHS, RHS)
4877                                           : Builder.CreateFCmpOLT(LHS, RHS);
4878         break;
4879       case RK_Max:
4880         Cmp = Opcode == Instruction::ICmp ? Builder.CreateICmpSGT(LHS, RHS)
4881                                           : Builder.CreateFCmpOGT(LHS, RHS);
4882         break;
4883       case RK_UMin:
4884         assert(Opcode == Instruction::ICmp && "Expected integer types.");
4885         Cmp = Builder.CreateICmpULT(LHS, RHS);
4886         break;
4887       case RK_UMax:
4888         assert(Opcode == Instruction::ICmp && "Expected integer types.");
4889         Cmp = Builder.CreateICmpUGT(LHS, RHS);
4890         break;
4891       case RK_None:
4892         llvm_unreachable("Unknown reduction operation.");
4893       }
4894       return Builder.CreateSelect(Cmp, LHS, RHS, Name);
4895     }
4896 
4897   public:
4898     explicit OperationData() = default;
4899 
4900     /// Construction for reduced values. They are identified by opcode only and
4901     /// don't have associated LHS/RHS values.
4902     explicit OperationData(Value *V) {
4903       if (auto *I = dyn_cast<Instruction>(V))
4904         Opcode = I->getOpcode();
4905     }
4906 
4907     /// Constructor for reduction operations with opcode and its left and
4908     /// right operands.
4909     OperationData(unsigned Opcode, Value *LHS, Value *RHS, ReductionKind Kind,
4910                   bool NoNaN = false)
4911         : Opcode(Opcode), LHS(LHS), RHS(RHS), Kind(Kind), NoNaN(NoNaN) {
4912       assert(Kind != RK_None && "One of the reduction operations is expected.");
4913     }
4914 
4915     explicit operator bool() const { return Opcode; }
4916 
4917     /// Get the index of the first operand.
4918     unsigned getFirstOperandIndex() const {
4919       assert(!!*this && "The opcode is not set.");
4920       switch (Kind) {
4921       case RK_Min:
4922       case RK_UMin:
4923       case RK_Max:
4924       case RK_UMax:
4925         return 1;
4926       case RK_Arithmetic:
4927       case RK_None:
4928         break;
4929       }
4930       return 0;
4931     }
4932 
4933     /// Total number of operands in the reduction operation.
4934     unsigned getNumberOfOperands() const {
4935       assert(Kind != RK_None && !!*this && LHS && RHS &&
4936              "Expected reduction operation.");
4937       switch (Kind) {
4938       case RK_Arithmetic:
4939         return 2;
4940       case RK_Min:
4941       case RK_UMin:
4942       case RK_Max:
4943       case RK_UMax:
4944         return 3;
4945       case RK_None:
4946         break;
4947       }
4948       llvm_unreachable("Reduction kind is not set");
4949     }
4950 
4951     /// Checks if the operation has the same parent as \p P.
4952     bool hasSameParent(Instruction *I, Value *P, bool IsRedOp) const {
4953       assert(Kind != RK_None && !!*this && LHS && RHS &&
4954              "Expected reduction operation.");
4955       if (!IsRedOp)
4956         return I->getParent() == P;
4957       switch (Kind) {
4958       case RK_Arithmetic:
4959         // Arithmetic reduction operation must be used once only.
4960         return I->getParent() == P;
4961       case RK_Min:
4962       case RK_UMin:
4963       case RK_Max:
4964       case RK_UMax: {
4965         // SelectInst must be used twice while the condition op must have single
4966         // use only.
4967         auto *Cmp = cast<Instruction>(cast<SelectInst>(I)->getCondition());
4968         return I->getParent() == P && Cmp && Cmp->getParent() == P;
4969       }
4970       case RK_None:
4971         break;
4972       }
4973       llvm_unreachable("Reduction kind is not set");
4974     }
4975     /// Expected number of uses for reduction operations/reduced values.
4976     bool hasRequiredNumberOfUses(Instruction *I, bool IsReductionOp) const {
4977       assert(Kind != RK_None && !!*this && LHS && RHS &&
4978              "Expected reduction operation.");
4979       switch (Kind) {
4980       case RK_Arithmetic:
4981         return I->hasOneUse();
4982       case RK_Min:
4983       case RK_UMin:
4984       case RK_Max:
4985       case RK_UMax:
4986         return I->hasNUses(2) &&
4987                (!IsReductionOp ||
4988                 cast<SelectInst>(I)->getCondition()->hasOneUse());
4989       case RK_None:
4990         break;
4991       }
4992       llvm_unreachable("Reduction kind is not set");
4993     }
4994 
4995     /// Initializes the list of reduction operations.
4996     void initReductionOps(ReductionOpsListType &ReductionOps) {
4997       assert(Kind != RK_None && !!*this && LHS && RHS &&
4998              "Expected reduction operation.");
4999       switch (Kind) {
5000       case RK_Arithmetic:
5001         ReductionOps.assign(1, ReductionOpsType());
5002         break;
5003       case RK_Min:
5004       case RK_UMin:
5005       case RK_Max:
5006       case RK_UMax:
5007         ReductionOps.assign(2, ReductionOpsType());
5008         break;
5009       case RK_None:
5010         llvm_unreachable("Reduction kind is not set");
5011       }
5012     }
5013     /// Add all reduction operations for the reduction instruction \p I.
5014     void addReductionOps(Instruction *I, ReductionOpsListType &ReductionOps) {
5015       assert(Kind != RK_None && !!*this && LHS && RHS &&
5016              "Expected reduction operation.");
5017       switch (Kind) {
5018       case RK_Arithmetic:
5019         ReductionOps[0].emplace_back(I);
5020         break;
5021       case RK_Min:
5022       case RK_UMin:
5023       case RK_Max:
5024       case RK_UMax:
5025         ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
5026         ReductionOps[1].emplace_back(I);
5027         break;
5028       case RK_None:
5029         llvm_unreachable("Reduction kind is not set");
5030       }
5031     }
5032 
5033     /// Checks if instruction is associative and can be vectorized.
5034     bool isAssociative(Instruction *I) const {
5035       assert(Kind != RK_None && *this && LHS && RHS &&
5036              "Expected reduction operation.");
5037       switch (Kind) {
5038       case RK_Arithmetic:
5039         return I->isAssociative();
5040       case RK_Min:
5041       case RK_Max:
5042         return Opcode == Instruction::ICmp ||
5043                cast<Instruction>(I->getOperand(0))->isFast();
5044       case RK_UMin:
5045       case RK_UMax:
5046         assert(Opcode == Instruction::ICmp &&
5047                "Only integer compare operation is expected.");
5048         return true;
5049       case RK_None:
5050         break;
5051       }
5052       llvm_unreachable("Reduction kind is not set");
5053     }
5054 
5055     /// Checks if the reduction operation can be vectorized.
5056     bool isVectorizable(Instruction *I) const {
5057       return isVectorizable() && isAssociative(I);
5058     }
5059 
5060     /// Checks if two operation data are both a reduction op or both a reduced
5061     /// value.
5062     bool operator==(const OperationData &OD) {
5063       assert(((Kind != OD.Kind) || ((!LHS == !OD.LHS) && (!RHS == !OD.RHS))) &&
5064              "One of the comparing operations is incorrect.");
5065       return this == &OD || (Kind == OD.Kind && Opcode == OD.Opcode);
5066     }
5067     bool operator!=(const OperationData &OD) { return !(*this == OD); }
5068     void clear() {
5069       Opcode = 0;
5070       LHS = nullptr;
5071       RHS = nullptr;
5072       Kind = RK_None;
5073       NoNaN = false;
5074     }
5075 
5076     /// Get the opcode of the reduction operation.
5077     unsigned getOpcode() const {
5078       assert(isVectorizable() && "Expected vectorizable operation.");
5079       return Opcode;
5080     }
5081 
5082     /// Get kind of reduction data.
5083     ReductionKind getKind() const { return Kind; }
5084     Value *getLHS() const { return LHS; }
5085     Value *getRHS() const { return RHS; }
5086     Type *getConditionType() const {
5087       switch (Kind) {
5088       case RK_Arithmetic:
5089         return nullptr;
5090       case RK_Min:
5091       case RK_Max:
5092       case RK_UMin:
5093       case RK_UMax:
5094         return CmpInst::makeCmpResultType(LHS->getType());
5095       case RK_None:
5096         break;
5097       }
5098       llvm_unreachable("Reduction kind is not set");
5099     }
5100 
5101     /// Creates reduction operation with the current opcode with the IR flags
5102     /// from \p ReductionOps.
5103     Value *createOp(IRBuilder<> &Builder, const Twine &Name,
5104                     const ReductionOpsListType &ReductionOps) const {
5105       assert(isVectorizable() &&
5106              "Expected add|fadd or min/max reduction operation.");
5107       auto *Op = createOp(Builder, Name);
5108       switch (Kind) {
5109       case RK_Arithmetic:
5110         propagateIRFlags(Op, ReductionOps[0]);
5111         return Op;
5112       case RK_Min:
5113       case RK_Max:
5114       case RK_UMin:
5115       case RK_UMax:
5116         if (auto *SI = dyn_cast<SelectInst>(Op))
5117           propagateIRFlags(SI->getCondition(), ReductionOps[0]);
5118         propagateIRFlags(Op, ReductionOps[1]);
5119         return Op;
5120       case RK_None:
5121         break;
5122       }
5123       llvm_unreachable("Unknown reduction operation.");
5124     }
5125     /// Creates reduction operation with the current opcode with the IR flags
5126     /// from \p I.
5127     Value *createOp(IRBuilder<> &Builder, const Twine &Name,
5128                     Instruction *I) const {
5129       assert(isVectorizable() &&
5130              "Expected add|fadd or min/max reduction operation.");
5131       auto *Op = createOp(Builder, Name);
5132       switch (Kind) {
5133       case RK_Arithmetic:
5134         propagateIRFlags(Op, I);
5135         return Op;
5136       case RK_Min:
5137       case RK_Max:
5138       case RK_UMin:
5139       case RK_UMax:
5140         if (auto *SI = dyn_cast<SelectInst>(Op)) {
5141           propagateIRFlags(SI->getCondition(),
5142                            cast<SelectInst>(I)->getCondition());
5143         }
5144         propagateIRFlags(Op, I);
5145         return Op;
5146       case RK_None:
5147         break;
5148       }
5149       llvm_unreachable("Unknown reduction operation.");
5150     }
5151 
5152     TargetTransformInfo::ReductionFlags getFlags() const {
5153       TargetTransformInfo::ReductionFlags Flags;
5154       Flags.NoNaN = NoNaN;
5155       switch (Kind) {
5156       case RK_Arithmetic:
5157         break;
5158       case RK_Min:
5159         Flags.IsSigned = Opcode == Instruction::ICmp;
5160         Flags.IsMaxOp = false;
5161         break;
5162       case RK_Max:
5163         Flags.IsSigned = Opcode == Instruction::ICmp;
5164         Flags.IsMaxOp = true;
5165         break;
5166       case RK_UMin:
5167         Flags.IsSigned = false;
5168         Flags.IsMaxOp = false;
5169         break;
5170       case RK_UMax:
5171         Flags.IsSigned = false;
5172         Flags.IsMaxOp = true;
5173         break;
5174       case RK_None:
5175         llvm_unreachable("Reduction kind is not set");
5176       }
5177       return Flags;
5178     }
5179   };
5180 
5181   Instruction *ReductionRoot = nullptr;
5182 
5183   /// The operation data of the reduction operation.
5184   OperationData ReductionData;
5185 
5186   /// The operation data of the values we perform a reduction on.
5187   OperationData ReducedValueData;
5188 
5189   /// Should we model this reduction as a pairwise reduction tree or a tree that
5190   /// splits the vector in halves and adds those halves.
5191   bool IsPairwiseReduction = false;
5192 
5193   /// Checks if the ParentStackElem.first should be marked as a reduction
5194   /// operation with an extra argument or as extra argument itself.
5195   void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem,
5196                     Value *ExtraArg) {
5197     if (ExtraArgs.count(ParentStackElem.first)) {
5198       ExtraArgs[ParentStackElem.first] = nullptr;
5199       // We ran into something like:
5200       // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg.
5201       // The whole ParentStackElem.first should be considered as an extra value
5202       // in this case.
5203       // Do not perform analysis of remaining operands of ParentStackElem.first
5204       // instruction, this whole instruction is an extra argument.
5205       ParentStackElem.second = ParentStackElem.first->getNumOperands();
5206     } else {
5207       // We ran into something like:
5208       // ParentStackElem.first += ... + ExtraArg + ...
5209       ExtraArgs[ParentStackElem.first] = ExtraArg;
5210     }
5211   }
5212 
5213   static OperationData getOperationData(Value *V) {
5214     if (!V)
5215       return OperationData();
5216 
5217     Value *LHS;
5218     Value *RHS;
5219     if (m_BinOp(m_Value(LHS), m_Value(RHS)).match(V)) {
5220       return OperationData(cast<BinaryOperator>(V)->getOpcode(), LHS, RHS,
5221                            RK_Arithmetic);
5222     }
5223     if (auto *Select = dyn_cast<SelectInst>(V)) {
5224       // Look for a min/max pattern.
5225       if (m_UMin(m_Value(LHS), m_Value(RHS)).match(Select)) {
5226         return OperationData(Instruction::ICmp, LHS, RHS, RK_UMin);
5227       } else if (m_SMin(m_Value(LHS), m_Value(RHS)).match(Select)) {
5228         return OperationData(Instruction::ICmp, LHS, RHS, RK_Min);
5229       } else if (m_OrdFMin(m_Value(LHS), m_Value(RHS)).match(Select) ||
5230                  m_UnordFMin(m_Value(LHS), m_Value(RHS)).match(Select)) {
5231         return OperationData(
5232             Instruction::FCmp, LHS, RHS, RK_Min,
5233             cast<Instruction>(Select->getCondition())->hasNoNaNs());
5234       } else if (m_UMax(m_Value(LHS), m_Value(RHS)).match(Select)) {
5235         return OperationData(Instruction::ICmp, LHS, RHS, RK_UMax);
5236       } else if (m_SMax(m_Value(LHS), m_Value(RHS)).match(Select)) {
5237         return OperationData(Instruction::ICmp, LHS, RHS, RK_Max);
5238       } else if (m_OrdFMax(m_Value(LHS), m_Value(RHS)).match(Select) ||
5239                  m_UnordFMax(m_Value(LHS), m_Value(RHS)).match(Select)) {
5240         return OperationData(
5241             Instruction::FCmp, LHS, RHS, RK_Max,
5242             cast<Instruction>(Select->getCondition())->hasNoNaNs());
5243       }
5244     }
5245     return OperationData(V);
5246   }
5247 
5248 public:
5249   HorizontalReduction() = default;
5250 
5251   /// \brief Try to find a reduction tree.
5252   bool matchAssociativeReduction(PHINode *Phi, Instruction *B) {
5253     assert((!Phi || is_contained(Phi->operands(), B)) &&
5254            "Thi phi needs to use the binary operator");
5255 
5256     ReductionData = getOperationData(B);
5257 
5258     // We could have a initial reductions that is not an add.
5259     //  r *= v1 + v2 + v3 + v4
5260     // In such a case start looking for a tree rooted in the first '+'.
5261     if (Phi) {
5262       if (ReductionData.getLHS() == Phi) {
5263         Phi = nullptr;
5264         B = dyn_cast<Instruction>(ReductionData.getRHS());
5265         ReductionData = getOperationData(B);
5266       } else if (ReductionData.getRHS() == Phi) {
5267         Phi = nullptr;
5268         B = dyn_cast<Instruction>(ReductionData.getLHS());
5269         ReductionData = getOperationData(B);
5270       }
5271     }
5272 
5273     if (!ReductionData.isVectorizable(B))
5274       return false;
5275 
5276     Type *Ty = B->getType();
5277     if (!isValidElementType(Ty))
5278       return false;
5279 
5280     ReducedValueData.clear();
5281     ReductionRoot = B;
5282 
5283     // Post order traverse the reduction tree starting at B. We only handle true
5284     // trees containing only binary operators.
5285     SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
5286     Stack.push_back(std::make_pair(B, ReductionData.getFirstOperandIndex()));
5287     ReductionData.initReductionOps(ReductionOps);
5288     while (!Stack.empty()) {
5289       Instruction *TreeN = Stack.back().first;
5290       unsigned EdgeToVist = Stack.back().second++;
5291       OperationData OpData = getOperationData(TreeN);
5292       bool IsReducedValue = OpData != ReductionData;
5293 
5294       // Postorder vist.
5295       if (IsReducedValue || EdgeToVist == OpData.getNumberOfOperands()) {
5296         if (IsReducedValue)
5297           ReducedVals.push_back(TreeN);
5298         else {
5299           auto I = ExtraArgs.find(TreeN);
5300           if (I != ExtraArgs.end() && !I->second) {
5301             // Check if TreeN is an extra argument of its parent operation.
5302             if (Stack.size() <= 1) {
5303               // TreeN can't be an extra argument as it is a root reduction
5304               // operation.
5305               return false;
5306             }
5307             // Yes, TreeN is an extra argument, do not add it to a list of
5308             // reduction operations.
5309             // Stack[Stack.size() - 2] always points to the parent operation.
5310             markExtraArg(Stack[Stack.size() - 2], TreeN);
5311             ExtraArgs.erase(TreeN);
5312           } else
5313             ReductionData.addReductionOps(TreeN, ReductionOps);
5314         }
5315         // Retract.
5316         Stack.pop_back();
5317         continue;
5318       }
5319 
5320       // Visit left or right.
5321       Value *NextV = TreeN->getOperand(EdgeToVist);
5322       if (NextV != Phi) {
5323         auto *I = dyn_cast<Instruction>(NextV);
5324         OpData = getOperationData(I);
5325         // Continue analysis if the next operand is a reduction operation or
5326         // (possibly) a reduced value. If the reduced value opcode is not set,
5327         // the first met operation != reduction operation is considered as the
5328         // reduced value class.
5329         if (I && (!ReducedValueData || OpData == ReducedValueData ||
5330                   OpData == ReductionData)) {
5331           const bool IsReductionOperation = OpData == ReductionData;
5332           // Only handle trees in the current basic block.
5333           if (!ReductionData.hasSameParent(I, B->getParent(),
5334                                            IsReductionOperation)) {
5335             // I is an extra argument for TreeN (its parent operation).
5336             markExtraArg(Stack.back(), I);
5337             continue;
5338           }
5339 
5340           // Each tree node needs to have minimal number of users except for the
5341           // ultimate reduction.
5342           if (!ReductionData.hasRequiredNumberOfUses(I,
5343                                                      OpData == ReductionData) &&
5344               I != B) {
5345             // I is an extra argument for TreeN (its parent operation).
5346             markExtraArg(Stack.back(), I);
5347             continue;
5348           }
5349 
5350           if (IsReductionOperation) {
5351             // We need to be able to reassociate the reduction operations.
5352             if (!OpData.isAssociative(I)) {
5353               // I is an extra argument for TreeN (its parent operation).
5354               markExtraArg(Stack.back(), I);
5355               continue;
5356             }
5357           } else if (ReducedValueData &&
5358                      ReducedValueData != OpData) {
5359             // Make sure that the opcodes of the operations that we are going to
5360             // reduce match.
5361             // I is an extra argument for TreeN (its parent operation).
5362             markExtraArg(Stack.back(), I);
5363             continue;
5364           } else if (!ReducedValueData)
5365             ReducedValueData = OpData;
5366 
5367           Stack.push_back(std::make_pair(I, OpData.getFirstOperandIndex()));
5368           continue;
5369         }
5370       }
5371       // NextV is an extra argument for TreeN (its parent operation).
5372       markExtraArg(Stack.back(), NextV);
5373     }
5374     return true;
5375   }
5376 
5377   /// \brief Attempt to vectorize the tree found by
5378   /// matchAssociativeReduction.
5379   bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
5380     if (ReducedVals.empty())
5381       return false;
5382 
5383     // If there is a sufficient number of reduction values, reduce
5384     // to a nearby power-of-2. Can safely generate oversized
5385     // vectors and rely on the backend to split them to legal sizes.
5386     unsigned NumReducedVals = ReducedVals.size();
5387     if (NumReducedVals < 4)
5388       return false;
5389 
5390     unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
5391 
5392     Value *VectorizedTree = nullptr;
5393     IRBuilder<> Builder(ReductionRoot);
5394     FastMathFlags Unsafe;
5395     Unsafe.setFast();
5396     Builder.setFastMathFlags(Unsafe);
5397     unsigned i = 0;
5398 
5399     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
5400     // The same extra argument may be used several time, so log each attempt
5401     // to use it.
5402     for (auto &Pair : ExtraArgs)
5403       ExternallyUsedValues[Pair.second].push_back(Pair.first);
5404     SmallVector<Value *, 16> IgnoreList;
5405     for (auto &V : ReductionOps)
5406       IgnoreList.append(V.begin(), V.end());
5407     while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) {
5408       auto VL = makeArrayRef(&ReducedVals[i], ReduxWidth);
5409       V.buildTree(VL, ExternallyUsedValues, IgnoreList);
5410       if (V.shouldReorder()) {
5411         SmallVector<Value *, 8> Reversed(VL.rbegin(), VL.rend());
5412         V.buildTree(Reversed, ExternallyUsedValues, IgnoreList);
5413       }
5414       if (V.isTreeTinyAndNotFullyVectorizable())
5415         break;
5416 
5417       V.computeMinimumValueSizes();
5418 
5419       // Estimate cost.
5420       int Cost =
5421           V.getTreeCost() + getReductionCost(TTI, ReducedVals[i], ReduxWidth);
5422       if (Cost >= -SLPCostThreshold) {
5423           V.getORE()->emit([&]() {
5424               return OptimizationRemarkMissed(
5425                          SV_NAME, "HorSLPNotBeneficial", cast<Instruction>(VL[0]))
5426                      << "Vectorizing horizontal reduction is possible"
5427                      << "but not beneficial with cost "
5428                      << ore::NV("Cost", Cost) << " and threshold "
5429                      << ore::NV("Threshold", -SLPCostThreshold);
5430           });
5431           break;
5432       }
5433 
5434       DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" << Cost
5435                    << ". (HorRdx)\n");
5436       V.getORE()->emit([&]() {
5437           return OptimizationRemark(
5438                      SV_NAME, "VectorizedHorizontalReduction", cast<Instruction>(VL[0]))
5439           << "Vectorized horizontal reduction with cost "
5440           << ore::NV("Cost", Cost) << " and with tree size "
5441           << ore::NV("TreeSize", V.getTreeSize());
5442       });
5443 
5444       // Vectorize a tree.
5445       DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
5446       Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues);
5447 
5448       // Emit a reduction.
5449       Value *ReducedSubTree =
5450           emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
5451       if (VectorizedTree) {
5452         Builder.SetCurrentDebugLocation(Loc);
5453         OperationData VectReductionData(ReductionData.getOpcode(),
5454                                         VectorizedTree, ReducedSubTree,
5455                                         ReductionData.getKind());
5456         VectorizedTree =
5457             VectReductionData.createOp(Builder, "op.rdx", ReductionOps);
5458       } else
5459         VectorizedTree = ReducedSubTree;
5460       i += ReduxWidth;
5461       ReduxWidth = PowerOf2Floor(NumReducedVals - i);
5462     }
5463 
5464     if (VectorizedTree) {
5465       // Finish the reduction.
5466       for (; i < NumReducedVals; ++i) {
5467         auto *I = cast<Instruction>(ReducedVals[i]);
5468         Builder.SetCurrentDebugLocation(I->getDebugLoc());
5469         OperationData VectReductionData(ReductionData.getOpcode(),
5470                                         VectorizedTree, I,
5471                                         ReductionData.getKind());
5472         VectorizedTree = VectReductionData.createOp(Builder, "", ReductionOps);
5473       }
5474       for (auto &Pair : ExternallyUsedValues) {
5475         assert(!Pair.second.empty() &&
5476                "At least one DebugLoc must be inserted");
5477         // Add each externally used value to the final reduction.
5478         for (auto *I : Pair.second) {
5479           Builder.SetCurrentDebugLocation(I->getDebugLoc());
5480           OperationData VectReductionData(ReductionData.getOpcode(),
5481                                           VectorizedTree, Pair.first,
5482                                           ReductionData.getKind());
5483           VectorizedTree = VectReductionData.createOp(Builder, "op.extra", I);
5484         }
5485       }
5486       // Update users.
5487       ReductionRoot->replaceAllUsesWith(VectorizedTree);
5488     }
5489     return VectorizedTree != nullptr;
5490   }
5491 
5492   unsigned numReductionValues() const {
5493     return ReducedVals.size();
5494   }
5495 
5496 private:
5497   /// \brief Calculate the cost of a reduction.
5498   int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal,
5499                        unsigned ReduxWidth) {
5500     Type *ScalarTy = FirstReducedVal->getType();
5501     Type *VecTy = VectorType::get(ScalarTy, ReduxWidth);
5502 
5503     int PairwiseRdxCost;
5504     int SplittingRdxCost;
5505     switch (ReductionData.getKind()) {
5506     case RK_Arithmetic:
5507       PairwiseRdxCost =
5508           TTI->getArithmeticReductionCost(ReductionData.getOpcode(), VecTy,
5509                                           /*IsPairwiseForm=*/true);
5510       SplittingRdxCost =
5511           TTI->getArithmeticReductionCost(ReductionData.getOpcode(), VecTy,
5512                                           /*IsPairwiseForm=*/false);
5513       break;
5514     case RK_Min:
5515     case RK_Max:
5516     case RK_UMin:
5517     case RK_UMax: {
5518       Type *VecCondTy = CmpInst::makeCmpResultType(VecTy);
5519       bool IsUnsigned = ReductionData.getKind() == RK_UMin ||
5520                         ReductionData.getKind() == RK_UMax;
5521       PairwiseRdxCost =
5522           TTI->getMinMaxReductionCost(VecTy, VecCondTy,
5523                                       /*IsPairwiseForm=*/true, IsUnsigned);
5524       SplittingRdxCost =
5525           TTI->getMinMaxReductionCost(VecTy, VecCondTy,
5526                                       /*IsPairwiseForm=*/false, IsUnsigned);
5527       break;
5528     }
5529     case RK_None:
5530       llvm_unreachable("Expected arithmetic or min/max reduction operation");
5531     }
5532 
5533     IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
5534     int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
5535 
5536     int ScalarReduxCost;
5537     switch (ReductionData.getKind()) {
5538     case RK_Arithmetic:
5539       ScalarReduxCost =
5540           TTI->getArithmeticInstrCost(ReductionData.getOpcode(), ScalarTy);
5541       break;
5542     case RK_Min:
5543     case RK_Max:
5544     case RK_UMin:
5545     case RK_UMax:
5546       ScalarReduxCost =
5547           TTI->getCmpSelInstrCost(ReductionData.getOpcode(), ScalarTy) +
5548           TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
5549                                   CmpInst::makeCmpResultType(ScalarTy));
5550       break;
5551     case RK_None:
5552       llvm_unreachable("Expected arithmetic or min/max reduction operation");
5553     }
5554     ScalarReduxCost *= (ReduxWidth - 1);
5555 
5556     DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost
5557                  << " for reduction that starts with " << *FirstReducedVal
5558                  << " (It is a "
5559                  << (IsPairwiseReduction ? "pairwise" : "splitting")
5560                  << " reduction)\n");
5561 
5562     return VecReduxCost - ScalarReduxCost;
5563   }
5564 
5565   /// \brief Emit a horizontal reduction of the vectorized value.
5566   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
5567                        unsigned ReduxWidth, const TargetTransformInfo *TTI) {
5568     assert(VectorizedValue && "Need to have a vectorized tree node");
5569     assert(isPowerOf2_32(ReduxWidth) &&
5570            "We only handle power-of-two reductions for now");
5571 
5572     if (!IsPairwiseReduction)
5573       return createSimpleTargetReduction(
5574           Builder, TTI, ReductionData.getOpcode(), VectorizedValue,
5575           ReductionData.getFlags(), ReductionOps.back());
5576 
5577     Value *TmpVec = VectorizedValue;
5578     for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
5579       Value *LeftMask =
5580           createRdxShuffleMask(ReduxWidth, i, true, true, Builder);
5581       Value *RightMask =
5582           createRdxShuffleMask(ReduxWidth, i, true, false, Builder);
5583 
5584       Value *LeftShuf = Builder.CreateShuffleVector(
5585           TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l");
5586       Value *RightShuf = Builder.CreateShuffleVector(
5587           TmpVec, UndefValue::get(TmpVec->getType()), (RightMask),
5588           "rdx.shuf.r");
5589       OperationData VectReductionData(ReductionData.getOpcode(), LeftShuf,
5590                                       RightShuf, ReductionData.getKind());
5591       TmpVec = VectReductionData.createOp(Builder, "op.rdx", ReductionOps);
5592     }
5593 
5594     // The result is in the first element of the vector.
5595     return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
5596   }
5597 };
5598 
5599 } // end anonymous namespace
5600 
5601 /// \brief Recognize construction of vectors like
5602 ///  %ra = insertelement <4 x float> undef, float %s0, i32 0
5603 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
5604 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
5605 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
5606 ///  starting from the last insertelement instruction.
5607 ///
5608 /// Returns true if it matches
5609 static bool findBuildVector(InsertElementInst *LastInsertElem,
5610                             SmallVectorImpl<Value *> &BuildVector,
5611                             SmallVectorImpl<Value *> &BuildVectorOpds) {
5612   Value *V = nullptr;
5613   do {
5614     BuildVector.push_back(LastInsertElem);
5615     BuildVectorOpds.push_back(LastInsertElem->getOperand(1));
5616     V = LastInsertElem->getOperand(0);
5617     if (isa<UndefValue>(V))
5618       break;
5619     LastInsertElem = dyn_cast<InsertElementInst>(V);
5620     if (!LastInsertElem || !LastInsertElem->hasOneUse())
5621       return false;
5622   } while (true);
5623   std::reverse(BuildVector.begin(), BuildVector.end());
5624   std::reverse(BuildVectorOpds.begin(), BuildVectorOpds.end());
5625   return true;
5626 }
5627 
5628 /// \brief Like findBuildVector, but looks for construction of aggregate.
5629 ///
5630 /// \return true if it matches.
5631 static bool findBuildAggregate(InsertValueInst *IV,
5632                                SmallVectorImpl<Value *> &BuildVector,
5633                                SmallVectorImpl<Value *> &BuildVectorOpds) {
5634   Value *V;
5635   do {
5636     BuildVector.push_back(IV);
5637     BuildVectorOpds.push_back(IV->getInsertedValueOperand());
5638     V = IV->getAggregateOperand();
5639     if (isa<UndefValue>(V))
5640       break;
5641     IV = dyn_cast<InsertValueInst>(V);
5642     if (!IV || !IV->hasOneUse())
5643       return false;
5644   } while (true);
5645   std::reverse(BuildVector.begin(), BuildVector.end());
5646   std::reverse(BuildVectorOpds.begin(), BuildVectorOpds.end());
5647   return true;
5648 }
5649 
5650 static bool PhiTypeSorterFunc(Value *V, Value *V2) {
5651   return V->getType() < V2->getType();
5652 }
5653 
5654 /// \brief Try and get a reduction value from a phi node.
5655 ///
5656 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
5657 /// if they come from either \p ParentBB or a containing loop latch.
5658 ///
5659 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
5660 /// if not possible.
5661 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
5662                                 BasicBlock *ParentBB, LoopInfo *LI) {
5663   // There are situations where the reduction value is not dominated by the
5664   // reduction phi. Vectorizing such cases has been reported to cause
5665   // miscompiles. See PR25787.
5666   auto DominatedReduxValue = [&](Value *R) {
5667     return (
5668         dyn_cast<Instruction>(R) &&
5669         DT->dominates(P->getParent(), dyn_cast<Instruction>(R)->getParent()));
5670   };
5671 
5672   Value *Rdx = nullptr;
5673 
5674   // Return the incoming value if it comes from the same BB as the phi node.
5675   if (P->getIncomingBlock(0) == ParentBB) {
5676     Rdx = P->getIncomingValue(0);
5677   } else if (P->getIncomingBlock(1) == ParentBB) {
5678     Rdx = P->getIncomingValue(1);
5679   }
5680 
5681   if (Rdx && DominatedReduxValue(Rdx))
5682     return Rdx;
5683 
5684   // Otherwise, check whether we have a loop latch to look at.
5685   Loop *BBL = LI->getLoopFor(ParentBB);
5686   if (!BBL)
5687     return nullptr;
5688   BasicBlock *BBLatch = BBL->getLoopLatch();
5689   if (!BBLatch)
5690     return nullptr;
5691 
5692   // There is a loop latch, return the incoming value if it comes from
5693   // that. This reduction pattern occasionally turns up.
5694   if (P->getIncomingBlock(0) == BBLatch) {
5695     Rdx = P->getIncomingValue(0);
5696   } else if (P->getIncomingBlock(1) == BBLatch) {
5697     Rdx = P->getIncomingValue(1);
5698   }
5699 
5700   if (Rdx && DominatedReduxValue(Rdx))
5701     return Rdx;
5702 
5703   return nullptr;
5704 }
5705 
5706 /// Attempt to reduce a horizontal reduction.
5707 /// If it is legal to match a horizontal reduction feeding the phi node \a P
5708 /// with reduction operators \a Root (or one of its operands) in a basic block
5709 /// \a BB, then check if it can be done. If horizontal reduction is not found
5710 /// and root instruction is a binary operation, vectorization of the operands is
5711 /// attempted.
5712 /// \returns true if a horizontal reduction was matched and reduced or operands
5713 /// of one of the binary instruction were vectorized.
5714 /// \returns false if a horizontal reduction was not matched (or not possible)
5715 /// or no vectorization of any binary operation feeding \a Root instruction was
5716 /// performed.
5717 static bool tryToVectorizeHorReductionOrInstOperands(
5718     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
5719     TargetTransformInfo *TTI,
5720     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
5721   if (!ShouldVectorizeHor)
5722     return false;
5723 
5724   if (!Root)
5725     return false;
5726 
5727   if (Root->getParent() != BB || isa<PHINode>(Root))
5728     return false;
5729   // Start analysis starting from Root instruction. If horizontal reduction is
5730   // found, try to vectorize it. If it is not a horizontal reduction or
5731   // vectorization is not possible or not effective, and currently analyzed
5732   // instruction is a binary operation, try to vectorize the operands, using
5733   // pre-order DFS traversal order. If the operands were not vectorized, repeat
5734   // the same procedure considering each operand as a possible root of the
5735   // horizontal reduction.
5736   // Interrupt the process if the Root instruction itself was vectorized or all
5737   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
5738   SmallVector<std::pair<WeakTrackingVH, unsigned>, 8> Stack(1, {Root, 0});
5739   SmallSet<Value *, 8> VisitedInstrs;
5740   bool Res = false;
5741   while (!Stack.empty()) {
5742     Value *V;
5743     unsigned Level;
5744     std::tie(V, Level) = Stack.pop_back_val();
5745     if (!V)
5746       continue;
5747     auto *Inst = dyn_cast<Instruction>(V);
5748     if (!Inst)
5749       continue;
5750     auto *BI = dyn_cast<BinaryOperator>(Inst);
5751     auto *SI = dyn_cast<SelectInst>(Inst);
5752     if (BI || SI) {
5753       HorizontalReduction HorRdx;
5754       if (HorRdx.matchAssociativeReduction(P, Inst)) {
5755         if (HorRdx.tryToReduce(R, TTI)) {
5756           Res = true;
5757           // Set P to nullptr to avoid re-analysis of phi node in
5758           // matchAssociativeReduction function unless this is the root node.
5759           P = nullptr;
5760           continue;
5761         }
5762       }
5763       if (P && BI) {
5764         Inst = dyn_cast<Instruction>(BI->getOperand(0));
5765         if (Inst == P)
5766           Inst = dyn_cast<Instruction>(BI->getOperand(1));
5767         if (!Inst) {
5768           // Set P to nullptr to avoid re-analysis of phi node in
5769           // matchAssociativeReduction function unless this is the root node.
5770           P = nullptr;
5771           continue;
5772         }
5773       }
5774     }
5775     // Set P to nullptr to avoid re-analysis of phi node in
5776     // matchAssociativeReduction function unless this is the root node.
5777     P = nullptr;
5778     if (Vectorize(Inst, R)) {
5779       Res = true;
5780       continue;
5781     }
5782 
5783     // Try to vectorize operands.
5784     // Continue analysis for the instruction from the same basic block only to
5785     // save compile time.
5786     if (++Level < RecursionMaxDepth)
5787       for (auto *Op : Inst->operand_values())
5788         if (VisitedInstrs.insert(Op).second)
5789           if (auto *I = dyn_cast<Instruction>(Op))
5790             if (!isa<PHINode>(I) && I->getParent() == BB)
5791               Stack.emplace_back(Op, Level);
5792   }
5793   return Res;
5794 }
5795 
5796 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
5797                                                  BasicBlock *BB, BoUpSLP &R,
5798                                                  TargetTransformInfo *TTI) {
5799   if (!V)
5800     return false;
5801   auto *I = dyn_cast<Instruction>(V);
5802   if (!I)
5803     return false;
5804 
5805   if (!isa<BinaryOperator>(I))
5806     P = nullptr;
5807   // Try to match and vectorize a horizontal reduction.
5808   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
5809     return tryToVectorize(I, R);
5810   };
5811   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI,
5812                                                   ExtraVectorization);
5813 }
5814 
5815 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
5816                                                  BasicBlock *BB, BoUpSLP &R) {
5817   const DataLayout &DL = BB->getModule()->getDataLayout();
5818   if (!R.canMapToVector(IVI->getType(), DL))
5819     return false;
5820 
5821   SmallVector<Value *, 16> BuildVector;
5822   SmallVector<Value *, 16> BuildVectorOpds;
5823   if (!findBuildAggregate(IVI, BuildVector, BuildVectorOpds))
5824     return false;
5825 
5826   DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
5827   // Aggregate value is unlikely to be processed in vector register, we need to
5828   // extract scalars into scalar registers, so NeedExtraction is set true.
5829   return tryToVectorizeList(BuildVectorOpds, R, BuildVector, false, true);
5830 }
5831 
5832 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
5833                                                    BasicBlock *BB, BoUpSLP &R) {
5834   SmallVector<Value *, 16> BuildVector;
5835   SmallVector<Value *, 16> BuildVectorOpds;
5836   if (!findBuildVector(IEI, BuildVector, BuildVectorOpds))
5837     return false;
5838 
5839   // Vectorize starting with the build vector operands ignoring the BuildVector
5840   // instructions for the purpose of scheduling and user extraction.
5841   return tryToVectorizeList(BuildVectorOpds, R, BuildVector);
5842 }
5843 
5844 bool SLPVectorizerPass::vectorizeCmpInst(CmpInst *CI, BasicBlock *BB,
5845                                          BoUpSLP &R) {
5846   if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R))
5847     return true;
5848 
5849   bool OpsChanged = false;
5850   for (int Idx = 0; Idx < 2; ++Idx) {
5851     OpsChanged |=
5852         vectorizeRootInstruction(nullptr, CI->getOperand(Idx), BB, R, TTI);
5853   }
5854   return OpsChanged;
5855 }
5856 
5857 bool SLPVectorizerPass::vectorizeSimpleInstructions(
5858     SmallVectorImpl<WeakVH> &Instructions, BasicBlock *BB, BoUpSLP &R) {
5859   bool OpsChanged = false;
5860   for (auto &VH : reverse(Instructions)) {
5861     auto *I = dyn_cast_or_null<Instruction>(VH);
5862     if (!I)
5863       continue;
5864     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I))
5865       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
5866     else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I))
5867       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
5868     else if (auto *CI = dyn_cast<CmpInst>(I))
5869       OpsChanged |= vectorizeCmpInst(CI, BB, R);
5870   }
5871   Instructions.clear();
5872   return OpsChanged;
5873 }
5874 
5875 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
5876   bool Changed = false;
5877   SmallVector<Value *, 4> Incoming;
5878   SmallSet<Value *, 16> VisitedInstrs;
5879 
5880   bool HaveVectorizedPhiNodes = true;
5881   while (HaveVectorizedPhiNodes) {
5882     HaveVectorizedPhiNodes = false;
5883 
5884     // Collect the incoming values from the PHIs.
5885     Incoming.clear();
5886     for (Instruction &I : *BB) {
5887       PHINode *P = dyn_cast<PHINode>(&I);
5888       if (!P)
5889         break;
5890 
5891       if (!VisitedInstrs.count(P))
5892         Incoming.push_back(P);
5893     }
5894 
5895     // Sort by type.
5896     std::stable_sort(Incoming.begin(), Incoming.end(), PhiTypeSorterFunc);
5897 
5898     // Try to vectorize elements base on their type.
5899     for (SmallVector<Value *, 4>::iterator IncIt = Incoming.begin(),
5900                                            E = Incoming.end();
5901          IncIt != E;) {
5902 
5903       // Look for the next elements with the same type.
5904       SmallVector<Value *, 4>::iterator SameTypeIt = IncIt;
5905       while (SameTypeIt != E &&
5906              (*SameTypeIt)->getType() == (*IncIt)->getType()) {
5907         VisitedInstrs.insert(*SameTypeIt);
5908         ++SameTypeIt;
5909       }
5910 
5911       // Try to vectorize them.
5912       unsigned NumElts = (SameTypeIt - IncIt);
5913       DEBUG(errs() << "SLP: Trying to vectorize starting at PHIs (" << NumElts << ")\n");
5914       // The order in which the phi nodes appear in the program does not matter.
5915       // So allow tryToVectorizeList to reorder them if it is beneficial. This
5916       // is done when there are exactly two elements since tryToVectorizeList
5917       // asserts that there are only two values when AllowReorder is true.
5918       bool AllowReorder = NumElts == 2;
5919       if (NumElts > 1 && tryToVectorizeList(makeArrayRef(IncIt, NumElts), R,
5920                                             None, AllowReorder)) {
5921         // Success start over because instructions might have been changed.
5922         HaveVectorizedPhiNodes = true;
5923         Changed = true;
5924         break;
5925       }
5926 
5927       // Start over at the next instruction of a different type (or the end).
5928       IncIt = SameTypeIt;
5929     }
5930   }
5931 
5932   VisitedInstrs.clear();
5933 
5934   SmallVector<WeakVH, 8> PostProcessInstructions;
5935   SmallDenseSet<Instruction *, 4> KeyNodes;
5936   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) {
5937     // We may go through BB multiple times so skip the one we have checked.
5938     if (!VisitedInstrs.insert(&*it).second) {
5939       if (it->use_empty() && KeyNodes.count(&*it) > 0 &&
5940           vectorizeSimpleInstructions(PostProcessInstructions, BB, R)) {
5941         // We would like to start over since some instructions are deleted
5942         // and the iterator may become invalid value.
5943         Changed = true;
5944         it = BB->begin();
5945         e = BB->end();
5946       }
5947       continue;
5948     }
5949 
5950     if (isa<DbgInfoIntrinsic>(it))
5951       continue;
5952 
5953     // Try to vectorize reductions that use PHINodes.
5954     if (PHINode *P = dyn_cast<PHINode>(it)) {
5955       // Check that the PHI is a reduction PHI.
5956       if (P->getNumIncomingValues() != 2)
5957         return Changed;
5958 
5959       // Try to match and vectorize a horizontal reduction.
5960       if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
5961                                    TTI)) {
5962         Changed = true;
5963         it = BB->begin();
5964         e = BB->end();
5965         continue;
5966       }
5967       continue;
5968     }
5969 
5970     // Ran into an instruction without users, like terminator, or function call
5971     // with ignored return value, store. Ignore unused instructions (basing on
5972     // instruction type, except for CallInst and InvokeInst).
5973     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
5974                             isa<InvokeInst>(it))) {
5975       KeyNodes.insert(&*it);
5976       bool OpsChanged = false;
5977       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
5978         for (auto *V : it->operand_values()) {
5979           // Try to match and vectorize a horizontal reduction.
5980           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
5981         }
5982       }
5983       // Start vectorization of post-process list of instructions from the
5984       // top-tree instructions to try to vectorize as many instructions as
5985       // possible.
5986       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R);
5987       if (OpsChanged) {
5988         // We would like to start over since some instructions are deleted
5989         // and the iterator may become invalid value.
5990         Changed = true;
5991         it = BB->begin();
5992         e = BB->end();
5993         continue;
5994       }
5995     }
5996 
5997     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
5998         isa<InsertValueInst>(it))
5999       PostProcessInstructions.push_back(&*it);
6000 
6001   }
6002 
6003   return Changed;
6004 }
6005 
6006 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
6007   auto Changed = false;
6008   for (auto &Entry : GEPs) {
6009     // If the getelementptr list has fewer than two elements, there's nothing
6010     // to do.
6011     if (Entry.second.size() < 2)
6012       continue;
6013 
6014     DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
6015                  << Entry.second.size() << ".\n");
6016 
6017     // We process the getelementptr list in chunks of 16 (like we do for
6018     // stores) to minimize compile-time.
6019     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += 16) {
6020       auto Len = std::min<unsigned>(BE - BI, 16);
6021       auto GEPList = makeArrayRef(&Entry.second[BI], Len);
6022 
6023       // Initialize a set a candidate getelementptrs. Note that we use a
6024       // SetVector here to preserve program order. If the index computations
6025       // are vectorizable and begin with loads, we want to minimize the chance
6026       // of having to reorder them later.
6027       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
6028 
6029       // Some of the candidates may have already been vectorized after we
6030       // initially collected them. If so, the WeakTrackingVHs will have
6031       // nullified the
6032       // values, so remove them from the set of candidates.
6033       Candidates.remove(nullptr);
6034 
6035       // Remove from the set of candidates all pairs of getelementptrs with
6036       // constant differences. Such getelementptrs are likely not good
6037       // candidates for vectorization in a bottom-up phase since one can be
6038       // computed from the other. We also ensure all candidate getelementptr
6039       // indices are unique.
6040       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
6041         auto *GEPI = cast<GetElementPtrInst>(GEPList[I]);
6042         if (!Candidates.count(GEPI))
6043           continue;
6044         auto *SCEVI = SE->getSCEV(GEPList[I]);
6045         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
6046           auto *GEPJ = cast<GetElementPtrInst>(GEPList[J]);
6047           auto *SCEVJ = SE->getSCEV(GEPList[J]);
6048           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
6049             Candidates.remove(GEPList[I]);
6050             Candidates.remove(GEPList[J]);
6051           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
6052             Candidates.remove(GEPList[J]);
6053           }
6054         }
6055       }
6056 
6057       // We break out of the above computation as soon as we know there are
6058       // fewer than two candidates remaining.
6059       if (Candidates.size() < 2)
6060         continue;
6061 
6062       // Add the single, non-constant index of each candidate to the bundle. We
6063       // ensured the indices met these constraints when we originally collected
6064       // the getelementptrs.
6065       SmallVector<Value *, 16> Bundle(Candidates.size());
6066       auto BundleIndex = 0u;
6067       for (auto *V : Candidates) {
6068         auto *GEP = cast<GetElementPtrInst>(V);
6069         auto *GEPIdx = GEP->idx_begin()->get();
6070         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
6071         Bundle[BundleIndex++] = GEPIdx;
6072       }
6073 
6074       // Try and vectorize the indices. We are currently only interested in
6075       // gather-like cases of the form:
6076       //
6077       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
6078       //
6079       // where the loads of "a", the loads of "b", and the subtractions can be
6080       // performed in parallel. It's likely that detecting this pattern in a
6081       // bottom-up phase will be simpler and less costly than building a
6082       // full-blown top-down phase beginning at the consecutive loads.
6083       Changed |= tryToVectorizeList(Bundle, R);
6084     }
6085   }
6086   return Changed;
6087 }
6088 
6089 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
6090   bool Changed = false;
6091   // Attempt to sort and vectorize each of the store-groups.
6092   for (StoreListMap::iterator it = Stores.begin(), e = Stores.end(); it != e;
6093        ++it) {
6094     if (it->second.size() < 2)
6095       continue;
6096 
6097     DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
6098           << it->second.size() << ".\n");
6099 
6100     // Process the stores in chunks of 16.
6101     // TODO: The limit of 16 inhibits greater vectorization factors.
6102     //       For example, AVX2 supports v32i8. Increasing this limit, however,
6103     //       may cause a significant compile-time increase.
6104     for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI+=16) {
6105       unsigned Len = std::min<unsigned>(CE - CI, 16);
6106       Changed |= vectorizeStores(makeArrayRef(&it->second[CI], Len), R);
6107     }
6108   }
6109   return Changed;
6110 }
6111 
6112 char SLPVectorizer::ID = 0;
6113 
6114 static const char lv_name[] = "SLP Vectorizer";
6115 
6116 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
6117 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
6118 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
6119 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
6120 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
6121 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
6122 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
6123 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
6124 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
6125 
6126 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
6127