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