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