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