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);
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_ExtractElt(m_Value(EV), m_ConstantInt(Ex1Idx))) &&
847           match(V2, m_ExtractElt(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   /// Maps a value to the proposed vectorizable size.
1719   SmallDenseMap<Value *, unsigned> InstrElementSize;
1720 
1721   /// A list of scalars that we found that we need to keep as scalars.
1722   ValueSet MustGather;
1723 
1724   /// This POD struct describes one external user in the vectorized tree.
1725   struct ExternalUser {
1726     ExternalUser(Value *S, llvm::User *U, int L)
1727         : Scalar(S), User(U), Lane(L) {}
1728 
1729     // Which scalar in our function.
1730     Value *Scalar;
1731 
1732     // Which user that uses the scalar.
1733     llvm::User *User;
1734 
1735     // Which lane does the scalar belong to.
1736     int Lane;
1737   };
1738   using UserList = SmallVector<ExternalUser, 16>;
1739 
1740   /// Checks if two instructions may access the same memory.
1741   ///
1742   /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
1743   /// is invariant in the calling loop.
1744   bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
1745                  Instruction *Inst2) {
1746     // First check if the result is already in the cache.
1747     AliasCacheKey key = std::make_pair(Inst1, Inst2);
1748     Optional<bool> &result = AliasCache[key];
1749     if (result.hasValue()) {
1750       return result.getValue();
1751     }
1752     MemoryLocation Loc2 = getLocation(Inst2, AA);
1753     bool aliased = true;
1754     if (Loc1.Ptr && Loc2.Ptr && isSimple(Inst1) && isSimple(Inst2)) {
1755       // Do the alias check.
1756       aliased = AA->alias(Loc1, Loc2);
1757     }
1758     // Store the result in the cache.
1759     result = aliased;
1760     return aliased;
1761   }
1762 
1763   using AliasCacheKey = std::pair<Instruction *, Instruction *>;
1764 
1765   /// Cache for alias results.
1766   /// TODO: consider moving this to the AliasAnalysis itself.
1767   DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
1768 
1769   /// Removes an instruction from its block and eventually deletes it.
1770   /// It's like Instruction::eraseFromParent() except that the actual deletion
1771   /// is delayed until BoUpSLP is destructed.
1772   /// This is required to ensure that there are no incorrect collisions in the
1773   /// AliasCache, which can happen if a new instruction is allocated at the
1774   /// same address as a previously deleted instruction.
1775   void eraseInstruction(Instruction *I, bool ReplaceOpsWithUndef = false) {
1776     auto It = DeletedInstructions.try_emplace(I, ReplaceOpsWithUndef).first;
1777     It->getSecond() = It->getSecond() && ReplaceOpsWithUndef;
1778   }
1779 
1780   /// Temporary store for deleted instructions. Instructions will be deleted
1781   /// eventually when the BoUpSLP is destructed.
1782   DenseMap<Instruction *, bool> DeletedInstructions;
1783 
1784   /// A list of values that need to extracted out of the tree.
1785   /// This list holds pairs of (Internal Scalar : External User). External User
1786   /// can be nullptr, it means that this Internal Scalar will be used later,
1787   /// after vectorization.
1788   UserList ExternalUses;
1789 
1790   /// Values used only by @llvm.assume calls.
1791   SmallPtrSet<const Value *, 32> EphValues;
1792 
1793   /// Holds all of the instructions that we gathered.
1794   SetVector<Instruction *> GatherSeq;
1795 
1796   /// A list of blocks that we are going to CSE.
1797   SetVector<BasicBlock *> CSEBlocks;
1798 
1799   /// Contains all scheduling relevant data for an instruction.
1800   /// A ScheduleData either represents a single instruction or a member of an
1801   /// instruction bundle (= a group of instructions which is combined into a
1802   /// vector instruction).
1803   struct ScheduleData {
1804     // The initial value for the dependency counters. It means that the
1805     // dependencies are not calculated yet.
1806     enum { InvalidDeps = -1 };
1807 
1808     ScheduleData() = default;
1809 
1810     void init(int BlockSchedulingRegionID, Value *OpVal) {
1811       FirstInBundle = this;
1812       NextInBundle = nullptr;
1813       NextLoadStore = nullptr;
1814       IsScheduled = false;
1815       SchedulingRegionID = BlockSchedulingRegionID;
1816       UnscheduledDepsInBundle = UnscheduledDeps;
1817       clearDependencies();
1818       OpValue = OpVal;
1819       TE = nullptr;
1820       Lane = -1;
1821     }
1822 
1823     /// Returns true if the dependency information has been calculated.
1824     bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
1825 
1826     /// Returns true for single instructions and for bundle representatives
1827     /// (= the head of a bundle).
1828     bool isSchedulingEntity() const { return FirstInBundle == this; }
1829 
1830     /// Returns true if it represents an instruction bundle and not only a
1831     /// single instruction.
1832     bool isPartOfBundle() const {
1833       return NextInBundle != nullptr || FirstInBundle != this;
1834     }
1835 
1836     /// Returns true if it is ready for scheduling, i.e. it has no more
1837     /// unscheduled depending instructions/bundles.
1838     bool isReady() const {
1839       assert(isSchedulingEntity() &&
1840              "can't consider non-scheduling entity for ready list");
1841       return UnscheduledDepsInBundle == 0 && !IsScheduled;
1842     }
1843 
1844     /// Modifies the number of unscheduled dependencies, also updating it for
1845     /// the whole bundle.
1846     int incrementUnscheduledDeps(int Incr) {
1847       UnscheduledDeps += Incr;
1848       return FirstInBundle->UnscheduledDepsInBundle += Incr;
1849     }
1850 
1851     /// Sets the number of unscheduled dependencies to the number of
1852     /// dependencies.
1853     void resetUnscheduledDeps() {
1854       incrementUnscheduledDeps(Dependencies - UnscheduledDeps);
1855     }
1856 
1857     /// Clears all dependency information.
1858     void clearDependencies() {
1859       Dependencies = InvalidDeps;
1860       resetUnscheduledDeps();
1861       MemoryDependencies.clear();
1862     }
1863 
1864     void dump(raw_ostream &os) const {
1865       if (!isSchedulingEntity()) {
1866         os << "/ " << *Inst;
1867       } else if (NextInBundle) {
1868         os << '[' << *Inst;
1869         ScheduleData *SD = NextInBundle;
1870         while (SD) {
1871           os << ';' << *SD->Inst;
1872           SD = SD->NextInBundle;
1873         }
1874         os << ']';
1875       } else {
1876         os << *Inst;
1877       }
1878     }
1879 
1880     Instruction *Inst = nullptr;
1881 
1882     /// Points to the head in an instruction bundle (and always to this for
1883     /// single instructions).
1884     ScheduleData *FirstInBundle = nullptr;
1885 
1886     /// Single linked list of all instructions in a bundle. Null if it is a
1887     /// single instruction.
1888     ScheduleData *NextInBundle = nullptr;
1889 
1890     /// Single linked list of all memory instructions (e.g. load, store, call)
1891     /// in the block - until the end of the scheduling region.
1892     ScheduleData *NextLoadStore = nullptr;
1893 
1894     /// The dependent memory instructions.
1895     /// This list is derived on demand in calculateDependencies().
1896     SmallVector<ScheduleData *, 4> MemoryDependencies;
1897 
1898     /// This ScheduleData is in the current scheduling region if this matches
1899     /// the current SchedulingRegionID of BlockScheduling.
1900     int SchedulingRegionID = 0;
1901 
1902     /// Used for getting a "good" final ordering of instructions.
1903     int SchedulingPriority = 0;
1904 
1905     /// The number of dependencies. Constitutes of the number of users of the
1906     /// instruction plus the number of dependent memory instructions (if any).
1907     /// This value is calculated on demand.
1908     /// If InvalidDeps, the number of dependencies is not calculated yet.
1909     int Dependencies = InvalidDeps;
1910 
1911     /// The number of dependencies minus the number of dependencies of scheduled
1912     /// instructions. As soon as this is zero, the instruction/bundle gets ready
1913     /// for scheduling.
1914     /// Note that this is negative as long as Dependencies is not calculated.
1915     int UnscheduledDeps = InvalidDeps;
1916 
1917     /// The sum of UnscheduledDeps in a bundle. Equals to UnscheduledDeps for
1918     /// single instructions.
1919     int UnscheduledDepsInBundle = InvalidDeps;
1920 
1921     /// True if this instruction is scheduled (or considered as scheduled in the
1922     /// dry-run).
1923     bool IsScheduled = false;
1924 
1925     /// Opcode of the current instruction in the schedule data.
1926     Value *OpValue = nullptr;
1927 
1928     /// The TreeEntry that this instruction corresponds to.
1929     TreeEntry *TE = nullptr;
1930 
1931     /// The lane of this node in the TreeEntry.
1932     int Lane = -1;
1933   };
1934 
1935 #ifndef NDEBUG
1936   friend inline raw_ostream &operator<<(raw_ostream &os,
1937                                         const BoUpSLP::ScheduleData &SD) {
1938     SD.dump(os);
1939     return os;
1940   }
1941 #endif
1942 
1943   friend struct GraphTraits<BoUpSLP *>;
1944   friend struct DOTGraphTraits<BoUpSLP *>;
1945 
1946   /// Contains all scheduling data for a basic block.
1947   struct BlockScheduling {
1948     BlockScheduling(BasicBlock *BB)
1949         : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
1950 
1951     void clear() {
1952       ReadyInsts.clear();
1953       ScheduleStart = nullptr;
1954       ScheduleEnd = nullptr;
1955       FirstLoadStoreInRegion = nullptr;
1956       LastLoadStoreInRegion = nullptr;
1957 
1958       // Reduce the maximum schedule region size by the size of the
1959       // previous scheduling run.
1960       ScheduleRegionSizeLimit -= ScheduleRegionSize;
1961       if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
1962         ScheduleRegionSizeLimit = MinScheduleRegionSize;
1963       ScheduleRegionSize = 0;
1964 
1965       // Make a new scheduling region, i.e. all existing ScheduleData is not
1966       // in the new region yet.
1967       ++SchedulingRegionID;
1968     }
1969 
1970     ScheduleData *getScheduleData(Value *V) {
1971       ScheduleData *SD = ScheduleDataMap[V];
1972       if (SD && SD->SchedulingRegionID == SchedulingRegionID)
1973         return SD;
1974       return nullptr;
1975     }
1976 
1977     ScheduleData *getScheduleData(Value *V, Value *Key) {
1978       if (V == Key)
1979         return getScheduleData(V);
1980       auto I = ExtraScheduleDataMap.find(V);
1981       if (I != ExtraScheduleDataMap.end()) {
1982         ScheduleData *SD = I->second[Key];
1983         if (SD && SD->SchedulingRegionID == SchedulingRegionID)
1984           return SD;
1985       }
1986       return nullptr;
1987     }
1988 
1989     bool isInSchedulingRegion(ScheduleData *SD) const {
1990       return SD->SchedulingRegionID == SchedulingRegionID;
1991     }
1992 
1993     /// Marks an instruction as scheduled and puts all dependent ready
1994     /// instructions into the ready-list.
1995     template <typename ReadyListType>
1996     void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
1997       SD->IsScheduled = true;
1998       LLVM_DEBUG(dbgs() << "SLP:   schedule " << *SD << "\n");
1999 
2000       ScheduleData *BundleMember = SD;
2001       while (BundleMember) {
2002         if (BundleMember->Inst != BundleMember->OpValue) {
2003           BundleMember = BundleMember->NextInBundle;
2004           continue;
2005         }
2006         // Handle the def-use chain dependencies.
2007 
2008         // Decrement the unscheduled counter and insert to ready list if ready.
2009         auto &&DecrUnsched = [this, &ReadyList](Instruction *I) {
2010           doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
2011             if (OpDef && OpDef->hasValidDependencies() &&
2012                 OpDef->incrementUnscheduledDeps(-1) == 0) {
2013               // There are no more unscheduled dependencies after
2014               // decrementing, so we can put the dependent instruction
2015               // into the ready list.
2016               ScheduleData *DepBundle = OpDef->FirstInBundle;
2017               assert(!DepBundle->IsScheduled &&
2018                      "already scheduled bundle gets ready");
2019               ReadyList.insert(DepBundle);
2020               LLVM_DEBUG(dbgs()
2021                          << "SLP:    gets ready (def): " << *DepBundle << "\n");
2022             }
2023           });
2024         };
2025 
2026         // If BundleMember is a vector bundle, its operands may have been
2027         // reordered duiring buildTree(). We therefore need to get its operands
2028         // through the TreeEntry.
2029         if (TreeEntry *TE = BundleMember->TE) {
2030           int Lane = BundleMember->Lane;
2031           assert(Lane >= 0 && "Lane not set");
2032 
2033           // Since vectorization tree is being built recursively this assertion
2034           // ensures that the tree entry has all operands set before reaching
2035           // this code. Couple of exceptions known at the moment are extracts
2036           // where their second (immediate) operand is not added. Since
2037           // immediates do not affect scheduler behavior this is considered
2038           // okay.
2039           auto *In = TE->getMainOp();
2040           assert(In &&
2041                  (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) ||
2042                   In->getNumOperands() == TE->getNumOperands()) &&
2043                  "Missed TreeEntry operands?");
2044           (void)In; // fake use to avoid build failure when assertions disabled
2045 
2046           for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands();
2047                OpIdx != NumOperands; ++OpIdx)
2048             if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane]))
2049               DecrUnsched(I);
2050         } else {
2051           // If BundleMember is a stand-alone instruction, no operand reordering
2052           // has taken place, so we directly access its operands.
2053           for (Use &U : BundleMember->Inst->operands())
2054             if (auto *I = dyn_cast<Instruction>(U.get()))
2055               DecrUnsched(I);
2056         }
2057         // Handle the memory dependencies.
2058         for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
2059           if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
2060             // There are no more unscheduled dependencies after decrementing,
2061             // so we can put the dependent instruction into the ready list.
2062             ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
2063             assert(!DepBundle->IsScheduled &&
2064                    "already scheduled bundle gets ready");
2065             ReadyList.insert(DepBundle);
2066             LLVM_DEBUG(dbgs()
2067                        << "SLP:    gets ready (mem): " << *DepBundle << "\n");
2068           }
2069         }
2070         BundleMember = BundleMember->NextInBundle;
2071       }
2072     }
2073 
2074     void doForAllOpcodes(Value *V,
2075                          function_ref<void(ScheduleData *SD)> Action) {
2076       if (ScheduleData *SD = getScheduleData(V))
2077         Action(SD);
2078       auto I = ExtraScheduleDataMap.find(V);
2079       if (I != ExtraScheduleDataMap.end())
2080         for (auto &P : I->second)
2081           if (P.second->SchedulingRegionID == SchedulingRegionID)
2082             Action(P.second);
2083     }
2084 
2085     /// Put all instructions into the ReadyList which are ready for scheduling.
2086     template <typename ReadyListType>
2087     void initialFillReadyList(ReadyListType &ReadyList) {
2088       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2089         doForAllOpcodes(I, [&](ScheduleData *SD) {
2090           if (SD->isSchedulingEntity() && SD->isReady()) {
2091             ReadyList.insert(SD);
2092             LLVM_DEBUG(dbgs()
2093                        << "SLP:    initially in ready list: " << *I << "\n");
2094           }
2095         });
2096       }
2097     }
2098 
2099     /// Checks if a bundle of instructions can be scheduled, i.e. has no
2100     /// cyclic dependencies. This is only a dry-run, no instructions are
2101     /// actually moved at this stage.
2102     /// \returns the scheduling bundle. The returned Optional value is non-None
2103     /// if \p VL is allowed to be scheduled.
2104     Optional<ScheduleData *>
2105     tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
2106                       const InstructionsState &S);
2107 
2108     /// Un-bundles a group of instructions.
2109     void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
2110 
2111     /// Allocates schedule data chunk.
2112     ScheduleData *allocateScheduleDataChunks();
2113 
2114     /// Extends the scheduling region so that V is inside the region.
2115     /// \returns true if the region size is within the limit.
2116     bool extendSchedulingRegion(Value *V, const InstructionsState &S);
2117 
2118     /// Initialize the ScheduleData structures for new instructions in the
2119     /// scheduling region.
2120     void initScheduleData(Instruction *FromI, Instruction *ToI,
2121                           ScheduleData *PrevLoadStore,
2122                           ScheduleData *NextLoadStore);
2123 
2124     /// Updates the dependency information of a bundle and of all instructions/
2125     /// bundles which depend on the original bundle.
2126     void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
2127                                BoUpSLP *SLP);
2128 
2129     /// Sets all instruction in the scheduling region to un-scheduled.
2130     void resetSchedule();
2131 
2132     BasicBlock *BB;
2133 
2134     /// Simple memory allocation for ScheduleData.
2135     std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
2136 
2137     /// The size of a ScheduleData array in ScheduleDataChunks.
2138     int ChunkSize;
2139 
2140     /// The allocator position in the current chunk, which is the last entry
2141     /// of ScheduleDataChunks.
2142     int ChunkPos;
2143 
2144     /// Attaches ScheduleData to Instruction.
2145     /// Note that the mapping survives during all vectorization iterations, i.e.
2146     /// ScheduleData structures are recycled.
2147     DenseMap<Value *, ScheduleData *> ScheduleDataMap;
2148 
2149     /// Attaches ScheduleData to Instruction with the leading key.
2150     DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
2151         ExtraScheduleDataMap;
2152 
2153     struct ReadyList : SmallVector<ScheduleData *, 8> {
2154       void insert(ScheduleData *SD) { push_back(SD); }
2155     };
2156 
2157     /// The ready-list for scheduling (only used for the dry-run).
2158     ReadyList ReadyInsts;
2159 
2160     /// The first instruction of the scheduling region.
2161     Instruction *ScheduleStart = nullptr;
2162 
2163     /// The first instruction _after_ the scheduling region.
2164     Instruction *ScheduleEnd = nullptr;
2165 
2166     /// The first memory accessing instruction in the scheduling region
2167     /// (can be null).
2168     ScheduleData *FirstLoadStoreInRegion = nullptr;
2169 
2170     /// The last memory accessing instruction in the scheduling region
2171     /// (can be null).
2172     ScheduleData *LastLoadStoreInRegion = nullptr;
2173 
2174     /// The current size of the scheduling region.
2175     int ScheduleRegionSize = 0;
2176 
2177     /// The maximum size allowed for the scheduling region.
2178     int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
2179 
2180     /// The ID of the scheduling region. For a new vectorization iteration this
2181     /// is incremented which "removes" all ScheduleData from the region.
2182     // Make sure that the initial SchedulingRegionID is greater than the
2183     // initial SchedulingRegionID in ScheduleData (which is 0).
2184     int SchedulingRegionID = 1;
2185   };
2186 
2187   /// Attaches the BlockScheduling structures to basic blocks.
2188   MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
2189 
2190   /// Performs the "real" scheduling. Done before vectorization is actually
2191   /// performed in a basic block.
2192   void scheduleBlock(BlockScheduling *BS);
2193 
2194   /// List of users to ignore during scheduling and that don't need extracting.
2195   ArrayRef<Value *> UserIgnoreList;
2196 
2197   using OrdersType = SmallVector<unsigned, 4>;
2198   /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
2199   /// sorted SmallVectors of unsigned.
2200   struct OrdersTypeDenseMapInfo {
2201     static OrdersType getEmptyKey() {
2202       OrdersType V;
2203       V.push_back(~1U);
2204       return V;
2205     }
2206 
2207     static OrdersType getTombstoneKey() {
2208       OrdersType V;
2209       V.push_back(~2U);
2210       return V;
2211     }
2212 
2213     static unsigned getHashValue(const OrdersType &V) {
2214       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
2215     }
2216 
2217     static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
2218       return LHS == RHS;
2219     }
2220   };
2221 
2222   /// Contains orders of operations along with the number of bundles that have
2223   /// operations in this order. It stores only those orders that require
2224   /// reordering, if reordering is not required it is counted using \a
2225   /// NumOpsWantToKeepOriginalOrder.
2226   DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo> NumOpsWantToKeepOrder;
2227   /// Number of bundles that do not require reordering.
2228   unsigned NumOpsWantToKeepOriginalOrder = 0;
2229 
2230   // Analysis and block reference.
2231   Function *F;
2232   ScalarEvolution *SE;
2233   TargetTransformInfo *TTI;
2234   TargetLibraryInfo *TLI;
2235   AliasAnalysis *AA;
2236   LoopInfo *LI;
2237   DominatorTree *DT;
2238   AssumptionCache *AC;
2239   DemandedBits *DB;
2240   const DataLayout *DL;
2241   OptimizationRemarkEmitter *ORE;
2242 
2243   unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
2244   unsigned MinVecRegSize; // Set by cl::opt (default: 128).
2245 
2246   /// Instruction builder to construct the vectorized tree.
2247   IRBuilder<> Builder;
2248 
2249   /// A map of scalar integer values to the smallest bit width with which they
2250   /// can legally be represented. The values map to (width, signed) pairs,
2251   /// where "width" indicates the minimum bit width and "signed" is True if the
2252   /// value must be signed-extended, rather than zero-extended, back to its
2253   /// original width.
2254   MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
2255 };
2256 
2257 } // end namespace slpvectorizer
2258 
2259 template <> struct GraphTraits<BoUpSLP *> {
2260   using TreeEntry = BoUpSLP::TreeEntry;
2261 
2262   /// NodeRef has to be a pointer per the GraphWriter.
2263   using NodeRef = TreeEntry *;
2264 
2265   using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy;
2266 
2267   /// Add the VectorizableTree to the index iterator to be able to return
2268   /// TreeEntry pointers.
2269   struct ChildIteratorType
2270       : public iterator_adaptor_base<
2271             ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
2272     ContainerTy &VectorizableTree;
2273 
2274     ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W,
2275                       ContainerTy &VT)
2276         : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
2277 
2278     NodeRef operator*() { return I->UserTE; }
2279   };
2280 
2281   static NodeRef getEntryNode(BoUpSLP &R) {
2282     return R.VectorizableTree[0].get();
2283   }
2284 
2285   static ChildIteratorType child_begin(NodeRef N) {
2286     return {N->UserTreeIndices.begin(), N->Container};
2287   }
2288 
2289   static ChildIteratorType child_end(NodeRef N) {
2290     return {N->UserTreeIndices.end(), N->Container};
2291   }
2292 
2293   /// For the node iterator we just need to turn the TreeEntry iterator into a
2294   /// TreeEntry* iterator so that it dereferences to NodeRef.
2295   class nodes_iterator {
2296     using ItTy = ContainerTy::iterator;
2297     ItTy It;
2298 
2299   public:
2300     nodes_iterator(const ItTy &It2) : It(It2) {}
2301     NodeRef operator*() { return It->get(); }
2302     nodes_iterator operator++() {
2303       ++It;
2304       return *this;
2305     }
2306     bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
2307   };
2308 
2309   static nodes_iterator nodes_begin(BoUpSLP *R) {
2310     return nodes_iterator(R->VectorizableTree.begin());
2311   }
2312 
2313   static nodes_iterator nodes_end(BoUpSLP *R) {
2314     return nodes_iterator(R->VectorizableTree.end());
2315   }
2316 
2317   static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
2318 };
2319 
2320 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
2321   using TreeEntry = BoUpSLP::TreeEntry;
2322 
2323   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
2324 
2325   std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
2326     std::string Str;
2327     raw_string_ostream OS(Str);
2328     if (isSplat(Entry->Scalars)) {
2329       OS << "<splat> " << *Entry->Scalars[0];
2330       return Str;
2331     }
2332     for (auto V : Entry->Scalars) {
2333       OS << *V;
2334       if (std::any_of(
2335               R->ExternalUses.begin(), R->ExternalUses.end(),
2336               [&](const BoUpSLP::ExternalUser &EU) { return EU.Scalar == V; }))
2337         OS << " <extract>";
2338       OS << "\n";
2339     }
2340     return Str;
2341   }
2342 
2343   static std::string getNodeAttributes(const TreeEntry *Entry,
2344                                        const BoUpSLP *) {
2345     if (Entry->State == TreeEntry::NeedToGather)
2346       return "color=red";
2347     return "";
2348   }
2349 };
2350 
2351 } // end namespace llvm
2352 
2353 BoUpSLP::~BoUpSLP() {
2354   for (const auto &Pair : DeletedInstructions) {
2355     // Replace operands of ignored instructions with Undefs in case if they were
2356     // marked for deletion.
2357     if (Pair.getSecond()) {
2358       Value *Undef = UndefValue::get(Pair.getFirst()->getType());
2359       Pair.getFirst()->replaceAllUsesWith(Undef);
2360     }
2361     Pair.getFirst()->dropAllReferences();
2362   }
2363   for (const auto &Pair : DeletedInstructions) {
2364     assert(Pair.getFirst()->use_empty() &&
2365            "trying to erase instruction with users.");
2366     Pair.getFirst()->eraseFromParent();
2367   }
2368   assert(!verifyFunction(*F, &dbgs()));
2369 }
2370 
2371 void BoUpSLP::eraseInstructions(ArrayRef<Value *> AV) {
2372   for (auto *V : AV) {
2373     if (auto *I = dyn_cast<Instruction>(V))
2374       eraseInstruction(I, /*ReplaceWithUndef=*/true);
2375   };
2376 }
2377 
2378 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
2379                         ArrayRef<Value *> UserIgnoreLst) {
2380   ExtraValueToDebugLocsMap ExternallyUsedValues;
2381   buildTree(Roots, ExternallyUsedValues, UserIgnoreLst);
2382 }
2383 
2384 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
2385                         ExtraValueToDebugLocsMap &ExternallyUsedValues,
2386                         ArrayRef<Value *> UserIgnoreLst) {
2387   deleteTree();
2388   UserIgnoreList = UserIgnoreLst;
2389   if (!allSameType(Roots))
2390     return;
2391   buildTree_rec(Roots, 0, EdgeInfo());
2392 
2393   // Collect the values that we need to extract from the tree.
2394   for (auto &TEPtr : VectorizableTree) {
2395     TreeEntry *Entry = TEPtr.get();
2396 
2397     // No need to handle users of gathered values.
2398     if (Entry->State == TreeEntry::NeedToGather)
2399       continue;
2400 
2401     // For each lane:
2402     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
2403       Value *Scalar = Entry->Scalars[Lane];
2404       int FoundLane = Lane;
2405       if (!Entry->ReuseShuffleIndices.empty()) {
2406         FoundLane =
2407             std::distance(Entry->ReuseShuffleIndices.begin(),
2408                           llvm::find(Entry->ReuseShuffleIndices, FoundLane));
2409       }
2410 
2411       // Check if the scalar is externally used as an extra arg.
2412       auto ExtI = ExternallyUsedValues.find(Scalar);
2413       if (ExtI != ExternallyUsedValues.end()) {
2414         LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
2415                           << Lane << " from " << *Scalar << ".\n");
2416         ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
2417       }
2418       for (User *U : Scalar->users()) {
2419         LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
2420 
2421         Instruction *UserInst = dyn_cast<Instruction>(U);
2422         if (!UserInst)
2423           continue;
2424 
2425         // Skip in-tree scalars that become vectors
2426         if (TreeEntry *UseEntry = getTreeEntry(U)) {
2427           Value *UseScalar = UseEntry->Scalars[0];
2428           // Some in-tree scalars will remain as scalar in vectorized
2429           // instructions. If that is the case, the one in Lane 0 will
2430           // be used.
2431           if (UseScalar != U ||
2432               !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
2433             LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
2434                               << ".\n");
2435             assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state");
2436             continue;
2437           }
2438         }
2439 
2440         // Ignore users in the user ignore list.
2441         if (is_contained(UserIgnoreList, UserInst))
2442           continue;
2443 
2444         LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
2445                           << Lane << " from " << *Scalar << ".\n");
2446         ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
2447       }
2448     }
2449   }
2450 }
2451 
2452 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
2453                             const EdgeInfo &UserTreeIdx) {
2454   assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
2455 
2456   InstructionsState S = getSameOpcode(VL);
2457   if (Depth == RecursionMaxDepth) {
2458     LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
2459     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
2460     return;
2461   }
2462 
2463   // Don't handle vectors.
2464   if (S.OpValue->getType()->isVectorTy()) {
2465     LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
2466     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
2467     return;
2468   }
2469 
2470   if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
2471     if (SI->getValueOperand()->getType()->isVectorTy()) {
2472       LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
2473       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
2474       return;
2475     }
2476 
2477   // If all of the operands are identical or constant we have a simple solution.
2478   if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode()) {
2479     LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
2480     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
2481     return;
2482   }
2483 
2484   // We now know that this is a vector of instructions of the same type from
2485   // the same block.
2486 
2487   // Don't vectorize ephemeral values.
2488   for (Value *V : VL) {
2489     if (EphValues.count(V)) {
2490       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
2491                         << ") is ephemeral.\n");
2492       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
2493       return;
2494     }
2495   }
2496 
2497   // Check if this is a duplicate of another entry.
2498   if (TreeEntry *E = getTreeEntry(S.OpValue)) {
2499     LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n");
2500     if (!E->isSame(VL)) {
2501       LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
2502       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
2503       return;
2504     }
2505     // Record the reuse of the tree node.  FIXME, currently this is only used to
2506     // properly draw the graph rather than for the actual vectorization.
2507     E->UserTreeIndices.push_back(UserTreeIdx);
2508     LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue
2509                       << ".\n");
2510     return;
2511   }
2512 
2513   // Check that none of the instructions in the bundle are already in the tree.
2514   for (Value *V : VL) {
2515     auto *I = dyn_cast<Instruction>(V);
2516     if (!I)
2517       continue;
2518     if (getTreeEntry(I)) {
2519       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
2520                         << ") is already in tree.\n");
2521       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
2522       return;
2523     }
2524   }
2525 
2526   // If any of the scalars is marked as a value that needs to stay scalar, then
2527   // we need to gather the scalars.
2528   // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
2529   for (Value *V : VL) {
2530     if (MustGather.count(V) || is_contained(UserIgnoreList, V)) {
2531       LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
2532       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
2533       return;
2534     }
2535   }
2536 
2537   // Check that all of the users of the scalars that we want to vectorize are
2538   // schedulable.
2539   auto *VL0 = cast<Instruction>(S.OpValue);
2540   BasicBlock *BB = VL0->getParent();
2541 
2542   if (!DT->isReachableFromEntry(BB)) {
2543     // Don't go into unreachable blocks. They may contain instructions with
2544     // dependency cycles which confuse the final scheduling.
2545     LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
2546     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
2547     return;
2548   }
2549 
2550   // Check that every instruction appears once in this bundle.
2551   SmallVector<unsigned, 4> ReuseShuffleIndicies;
2552   SmallVector<Value *, 4> UniqueValues;
2553   DenseMap<Value *, unsigned> UniquePositions;
2554   for (Value *V : VL) {
2555     auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
2556     ReuseShuffleIndicies.emplace_back(Res.first->second);
2557     if (Res.second)
2558       UniqueValues.emplace_back(V);
2559   }
2560   size_t NumUniqueScalarValues = UniqueValues.size();
2561   if (NumUniqueScalarValues == VL.size()) {
2562     ReuseShuffleIndicies.clear();
2563   } else {
2564     LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
2565     if (NumUniqueScalarValues <= 1 ||
2566         !llvm::isPowerOf2_32(NumUniqueScalarValues)) {
2567       LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
2568       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
2569       return;
2570     }
2571     VL = UniqueValues;
2572   }
2573 
2574   auto &BSRef = BlocksSchedules[BB];
2575   if (!BSRef)
2576     BSRef = std::make_unique<BlockScheduling>(BB);
2577 
2578   BlockScheduling &BS = *BSRef.get();
2579 
2580   Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S);
2581   if (!Bundle) {
2582     LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
2583     assert((!BS.getScheduleData(VL0) ||
2584             !BS.getScheduleData(VL0)->isPartOfBundle()) &&
2585            "tryScheduleBundle should cancelScheduling on failure");
2586     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
2587                  ReuseShuffleIndicies);
2588     return;
2589   }
2590   LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
2591 
2592   unsigned ShuffleOrOp = S.isAltShuffle() ?
2593                 (unsigned) Instruction::ShuffleVector : S.getOpcode();
2594   switch (ShuffleOrOp) {
2595     case Instruction::PHI: {
2596       auto *PH = cast<PHINode>(VL0);
2597 
2598       // Check for terminator values (e.g. invoke).
2599       for (unsigned j = 0; j < VL.size(); ++j)
2600         for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
2601           Instruction *Term = dyn_cast<Instruction>(
2602               cast<PHINode>(VL[j])->getIncomingValueForBlock(
2603                   PH->getIncomingBlock(i)));
2604           if (Term && Term->isTerminator()) {
2605             LLVM_DEBUG(dbgs()
2606                        << "SLP: Need to swizzle PHINodes (terminator use).\n");
2607             BS.cancelScheduling(VL, VL0);
2608             newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
2609                          ReuseShuffleIndicies);
2610             return;
2611           }
2612         }
2613 
2614       TreeEntry *TE =
2615           newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies);
2616       LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
2617 
2618       // Keeps the reordered operands to avoid code duplication.
2619       SmallVector<ValueList, 2> OperandsVec;
2620       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
2621         ValueList Operands;
2622         // Prepare the operand vector.
2623         for (Value *j : VL)
2624           Operands.push_back(cast<PHINode>(j)->getIncomingValueForBlock(
2625               PH->getIncomingBlock(i)));
2626         TE->setOperand(i, Operands);
2627         OperandsVec.push_back(Operands);
2628       }
2629       for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx)
2630         buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx});
2631       return;
2632     }
2633     case Instruction::ExtractValue:
2634     case Instruction::ExtractElement: {
2635       OrdersType CurrentOrder;
2636       bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
2637       if (Reuse) {
2638         LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
2639         ++NumOpsWantToKeepOriginalOrder;
2640         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
2641                      ReuseShuffleIndicies);
2642         // This is a special case, as it does not gather, but at the same time
2643         // we are not extending buildTree_rec() towards the operands.
2644         ValueList Op0;
2645         Op0.assign(VL.size(), VL0->getOperand(0));
2646         VectorizableTree.back()->setOperand(0, Op0);
2647         return;
2648       }
2649       if (!CurrentOrder.empty()) {
2650         LLVM_DEBUG({
2651           dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
2652                     "with order";
2653           for (unsigned Idx : CurrentOrder)
2654             dbgs() << " " << Idx;
2655           dbgs() << "\n";
2656         });
2657         // Insert new order with initial value 0, if it does not exist,
2658         // otherwise return the iterator to the existing one.
2659         auto StoredCurrentOrderAndNum =
2660             NumOpsWantToKeepOrder.try_emplace(CurrentOrder).first;
2661         ++StoredCurrentOrderAndNum->getSecond();
2662         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
2663                      ReuseShuffleIndicies,
2664                      StoredCurrentOrderAndNum->getFirst());
2665         // This is a special case, as it does not gather, but at the same time
2666         // we are not extending buildTree_rec() towards the operands.
2667         ValueList Op0;
2668         Op0.assign(VL.size(), VL0->getOperand(0));
2669         VectorizableTree.back()->setOperand(0, Op0);
2670         return;
2671       }
2672       LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
2673       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
2674                    ReuseShuffleIndicies);
2675       BS.cancelScheduling(VL, VL0);
2676       return;
2677     }
2678     case Instruction::Load: {
2679       // Check that a vectorized load would load the same memory as a scalar
2680       // load. For example, we don't want to vectorize loads that are smaller
2681       // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
2682       // treats loading/storing it as an i8 struct. If we vectorize loads/stores
2683       // from such a struct, we read/write packed bits disagreeing with the
2684       // unvectorized version.
2685       Type *ScalarTy = VL0->getType();
2686 
2687       if (DL->getTypeSizeInBits(ScalarTy) !=
2688           DL->getTypeAllocSizeInBits(ScalarTy)) {
2689         BS.cancelScheduling(VL, VL0);
2690         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
2691                      ReuseShuffleIndicies);
2692         LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
2693         return;
2694       }
2695 
2696       // Make sure all loads in the bundle are simple - we can't vectorize
2697       // atomic or volatile loads.
2698       SmallVector<Value *, 4> PointerOps(VL.size());
2699       auto POIter = PointerOps.begin();
2700       for (Value *V : VL) {
2701         auto *L = cast<LoadInst>(V);
2702         if (!L->isSimple()) {
2703           BS.cancelScheduling(VL, VL0);
2704           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
2705                        ReuseShuffleIndicies);
2706           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
2707           return;
2708         }
2709         *POIter = L->getPointerOperand();
2710         ++POIter;
2711       }
2712 
2713       OrdersType CurrentOrder;
2714       // Check the order of pointer operands.
2715       if (llvm::sortPtrAccesses(PointerOps, *DL, *SE, CurrentOrder)) {
2716         Value *Ptr0;
2717         Value *PtrN;
2718         if (CurrentOrder.empty()) {
2719           Ptr0 = PointerOps.front();
2720           PtrN = PointerOps.back();
2721         } else {
2722           Ptr0 = PointerOps[CurrentOrder.front()];
2723           PtrN = PointerOps[CurrentOrder.back()];
2724         }
2725         const SCEV *Scev0 = SE->getSCEV(Ptr0);
2726         const SCEV *ScevN = SE->getSCEV(PtrN);
2727         const auto *Diff =
2728             dyn_cast<SCEVConstant>(SE->getMinusSCEV(ScevN, Scev0));
2729         uint64_t Size = DL->getTypeAllocSize(ScalarTy);
2730         // Check that the sorted loads are consecutive.
2731         if (Diff && Diff->getAPInt() == (VL.size() - 1) * Size) {
2732           if (CurrentOrder.empty()) {
2733             // Original loads are consecutive and does not require reordering.
2734             ++NumOpsWantToKeepOriginalOrder;
2735             TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
2736                                          UserTreeIdx, ReuseShuffleIndicies);
2737             TE->setOperandsInOrder();
2738             LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
2739           } else {
2740             // Need to reorder.
2741             auto I = NumOpsWantToKeepOrder.try_emplace(CurrentOrder).first;
2742             ++I->getSecond();
2743             TreeEntry *TE =
2744                 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
2745                              ReuseShuffleIndicies, I->getFirst());
2746             TE->setOperandsInOrder();
2747             LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
2748           }
2749           return;
2750         }
2751       }
2752 
2753       LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
2754       BS.cancelScheduling(VL, VL0);
2755       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
2756                    ReuseShuffleIndicies);
2757       return;
2758     }
2759     case Instruction::ZExt:
2760     case Instruction::SExt:
2761     case Instruction::FPToUI:
2762     case Instruction::FPToSI:
2763     case Instruction::FPExt:
2764     case Instruction::PtrToInt:
2765     case Instruction::IntToPtr:
2766     case Instruction::SIToFP:
2767     case Instruction::UIToFP:
2768     case Instruction::Trunc:
2769     case Instruction::FPTrunc:
2770     case Instruction::BitCast: {
2771       Type *SrcTy = VL0->getOperand(0)->getType();
2772       for (Value *V : VL) {
2773         Type *Ty = cast<Instruction>(V)->getOperand(0)->getType();
2774         if (Ty != SrcTy || !isValidElementType(Ty)) {
2775           BS.cancelScheduling(VL, VL0);
2776           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
2777                        ReuseShuffleIndicies);
2778           LLVM_DEBUG(dbgs()
2779                      << "SLP: Gathering casts with different src types.\n");
2780           return;
2781         }
2782       }
2783       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
2784                                    ReuseShuffleIndicies);
2785       LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
2786 
2787       TE->setOperandsInOrder();
2788       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
2789         ValueList Operands;
2790         // Prepare the operand vector.
2791         for (Value *V : VL)
2792           Operands.push_back(cast<Instruction>(V)->getOperand(i));
2793 
2794         buildTree_rec(Operands, Depth + 1, {TE, i});
2795       }
2796       return;
2797     }
2798     case Instruction::ICmp:
2799     case Instruction::FCmp: {
2800       // Check that all of the compares have the same predicate.
2801       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
2802       CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0);
2803       Type *ComparedTy = VL0->getOperand(0)->getType();
2804       for (Value *V : VL) {
2805         CmpInst *Cmp = cast<CmpInst>(V);
2806         if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) ||
2807             Cmp->getOperand(0)->getType() != ComparedTy) {
2808           BS.cancelScheduling(VL, VL0);
2809           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
2810                        ReuseShuffleIndicies);
2811           LLVM_DEBUG(dbgs()
2812                      << "SLP: Gathering cmp with different predicate.\n");
2813           return;
2814         }
2815       }
2816 
2817       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
2818                                    ReuseShuffleIndicies);
2819       LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
2820 
2821       ValueList Left, Right;
2822       if (cast<CmpInst>(VL0)->isCommutative()) {
2823         // Commutative predicate - collect + sort operands of the instructions
2824         // so that each side is more likely to have the same opcode.
2825         assert(P0 == SwapP0 && "Commutative Predicate mismatch");
2826         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
2827       } else {
2828         // Collect operands - commute if it uses the swapped predicate.
2829         for (Value *V : VL) {
2830           auto *Cmp = cast<CmpInst>(V);
2831           Value *LHS = Cmp->getOperand(0);
2832           Value *RHS = Cmp->getOperand(1);
2833           if (Cmp->getPredicate() != P0)
2834             std::swap(LHS, RHS);
2835           Left.push_back(LHS);
2836           Right.push_back(RHS);
2837         }
2838       }
2839       TE->setOperand(0, Left);
2840       TE->setOperand(1, Right);
2841       buildTree_rec(Left, Depth + 1, {TE, 0});
2842       buildTree_rec(Right, Depth + 1, {TE, 1});
2843       return;
2844     }
2845     case Instruction::Select:
2846     case Instruction::FNeg:
2847     case Instruction::Add:
2848     case Instruction::FAdd:
2849     case Instruction::Sub:
2850     case Instruction::FSub:
2851     case Instruction::Mul:
2852     case Instruction::FMul:
2853     case Instruction::UDiv:
2854     case Instruction::SDiv:
2855     case Instruction::FDiv:
2856     case Instruction::URem:
2857     case Instruction::SRem:
2858     case Instruction::FRem:
2859     case Instruction::Shl:
2860     case Instruction::LShr:
2861     case Instruction::AShr:
2862     case Instruction::And:
2863     case Instruction::Or:
2864     case Instruction::Xor: {
2865       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
2866                                    ReuseShuffleIndicies);
2867       LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n");
2868 
2869       // Sort operands of the instructions so that each side is more likely to
2870       // have the same opcode.
2871       if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
2872         ValueList Left, Right;
2873         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
2874         TE->setOperand(0, Left);
2875         TE->setOperand(1, Right);
2876         buildTree_rec(Left, Depth + 1, {TE, 0});
2877         buildTree_rec(Right, Depth + 1, {TE, 1});
2878         return;
2879       }
2880 
2881       TE->setOperandsInOrder();
2882       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
2883         ValueList Operands;
2884         // Prepare the operand vector.
2885         for (Value *j : VL)
2886           Operands.push_back(cast<Instruction>(j)->getOperand(i));
2887 
2888         buildTree_rec(Operands, Depth + 1, {TE, i});
2889       }
2890       return;
2891     }
2892     case Instruction::GetElementPtr: {
2893       // We don't combine GEPs with complicated (nested) indexing.
2894       for (Value *V : VL) {
2895         if (cast<Instruction>(V)->getNumOperands() != 2) {
2896           LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
2897           BS.cancelScheduling(VL, VL0);
2898           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
2899                        ReuseShuffleIndicies);
2900           return;
2901         }
2902       }
2903 
2904       // We can't combine several GEPs into one vector if they operate on
2905       // different types.
2906       Type *Ty0 = VL0->getOperand(0)->getType();
2907       for (Value *V : VL) {
2908         Type *CurTy = cast<Instruction>(V)->getOperand(0)->getType();
2909         if (Ty0 != CurTy) {
2910           LLVM_DEBUG(dbgs()
2911                      << "SLP: not-vectorizable GEP (different types).\n");
2912           BS.cancelScheduling(VL, VL0);
2913           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
2914                        ReuseShuffleIndicies);
2915           return;
2916         }
2917       }
2918 
2919       // We don't combine GEPs with non-constant indexes.
2920       Type *Ty1 = VL0->getOperand(1)->getType();
2921       for (Value *V : VL) {
2922         auto Op = cast<Instruction>(V)->getOperand(1);
2923         if (!isa<ConstantInt>(Op) ||
2924             (Op->getType() != Ty1 &&
2925              Op->getType()->getScalarSizeInBits() >
2926                  DL->getIndexSizeInBits(
2927                      V->getType()->getPointerAddressSpace()))) {
2928           LLVM_DEBUG(dbgs()
2929                      << "SLP: not-vectorizable GEP (non-constant indexes).\n");
2930           BS.cancelScheduling(VL, VL0);
2931           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
2932                        ReuseShuffleIndicies);
2933           return;
2934         }
2935       }
2936 
2937       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
2938                                    ReuseShuffleIndicies);
2939       LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
2940       TE->setOperandsInOrder();
2941       for (unsigned i = 0, e = 2; i < e; ++i) {
2942         ValueList Operands;
2943         // Prepare the operand vector.
2944         for (Value *V : VL)
2945           Operands.push_back(cast<Instruction>(V)->getOperand(i));
2946 
2947         buildTree_rec(Operands, Depth + 1, {TE, i});
2948       }
2949       return;
2950     }
2951     case Instruction::Store: {
2952       // Check if the stores are consecutive or if we need to swizzle them.
2953       llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType();
2954       // Make sure all stores in the bundle are simple - we can't vectorize
2955       // atomic or volatile stores.
2956       SmallVector<Value *, 4> PointerOps(VL.size());
2957       ValueList Operands(VL.size());
2958       auto POIter = PointerOps.begin();
2959       auto OIter = Operands.begin();
2960       for (Value *V : VL) {
2961         auto *SI = cast<StoreInst>(V);
2962         if (!SI->isSimple()) {
2963           BS.cancelScheduling(VL, VL0);
2964           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
2965                        ReuseShuffleIndicies);
2966           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n");
2967           return;
2968         }
2969         *POIter = SI->getPointerOperand();
2970         *OIter = SI->getValueOperand();
2971         ++POIter;
2972         ++OIter;
2973       }
2974 
2975       OrdersType CurrentOrder;
2976       // Check the order of pointer operands.
2977       if (llvm::sortPtrAccesses(PointerOps, *DL, *SE, CurrentOrder)) {
2978         Value *Ptr0;
2979         Value *PtrN;
2980         if (CurrentOrder.empty()) {
2981           Ptr0 = PointerOps.front();
2982           PtrN = PointerOps.back();
2983         } else {
2984           Ptr0 = PointerOps[CurrentOrder.front()];
2985           PtrN = PointerOps[CurrentOrder.back()];
2986         }
2987         const SCEV *Scev0 = SE->getSCEV(Ptr0);
2988         const SCEV *ScevN = SE->getSCEV(PtrN);
2989         const auto *Diff =
2990             dyn_cast<SCEVConstant>(SE->getMinusSCEV(ScevN, Scev0));
2991         uint64_t Size = DL->getTypeAllocSize(ScalarTy);
2992         // Check that the sorted pointer operands are consecutive.
2993         if (Diff && Diff->getAPInt() == (VL.size() - 1) * Size) {
2994           if (CurrentOrder.empty()) {
2995             // Original stores are consecutive and does not require reordering.
2996             ++NumOpsWantToKeepOriginalOrder;
2997             TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
2998                                          UserTreeIdx, ReuseShuffleIndicies);
2999             TE->setOperandsInOrder();
3000             buildTree_rec(Operands, Depth + 1, {TE, 0});
3001             LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
3002           } else {
3003             // Need to reorder.
3004             auto I = NumOpsWantToKeepOrder.try_emplace(CurrentOrder).first;
3005             ++(I->getSecond());
3006             TreeEntry *TE =
3007                 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3008                              ReuseShuffleIndicies, I->getFirst());
3009             TE->setOperandsInOrder();
3010             buildTree_rec(Operands, Depth + 1, {TE, 0});
3011             LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n");
3012           }
3013           return;
3014         }
3015       }
3016 
3017       BS.cancelScheduling(VL, VL0);
3018       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3019                    ReuseShuffleIndicies);
3020       LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
3021       return;
3022     }
3023     case Instruction::Call: {
3024       // Check if the calls are all to the same vectorizable intrinsic.
3025       CallInst *CI = cast<CallInst>(VL0);
3026       // Check if this is an Intrinsic call or something that can be
3027       // represented by an intrinsic call
3028       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
3029       if (!isTriviallyVectorizable(ID)) {
3030         BS.cancelScheduling(VL, VL0);
3031         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3032                      ReuseShuffleIndicies);
3033         LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
3034         return;
3035       }
3036       Function *Int = CI->getCalledFunction();
3037       unsigned NumArgs = CI->getNumArgOperands();
3038       SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr);
3039       for (unsigned j = 0; j != NumArgs; ++j)
3040         if (hasVectorInstrinsicScalarOpd(ID, j))
3041           ScalarArgs[j] = CI->getArgOperand(j);
3042       for (Value *V : VL) {
3043         CallInst *CI2 = dyn_cast<CallInst>(V);
3044         if (!CI2 || CI2->getCalledFunction() != Int ||
3045             getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
3046             !CI->hasIdenticalOperandBundleSchema(*CI2)) {
3047           BS.cancelScheduling(VL, VL0);
3048           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3049                        ReuseShuffleIndicies);
3050           LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V
3051                             << "\n");
3052           return;
3053         }
3054         // Some intrinsics have scalar arguments and should be same in order for
3055         // them to be vectorized.
3056         for (unsigned j = 0; j != NumArgs; ++j) {
3057           if (hasVectorInstrinsicScalarOpd(ID, j)) {
3058             Value *A1J = CI2->getArgOperand(j);
3059             if (ScalarArgs[j] != A1J) {
3060               BS.cancelScheduling(VL, VL0);
3061               newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3062                            ReuseShuffleIndicies);
3063               LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
3064                                 << " argument " << ScalarArgs[j] << "!=" << A1J
3065                                 << "\n");
3066               return;
3067             }
3068           }
3069         }
3070         // Verify that the bundle operands are identical between the two calls.
3071         if (CI->hasOperandBundles() &&
3072             !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
3073                         CI->op_begin() + CI->getBundleOperandsEndIndex(),
3074                         CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
3075           BS.cancelScheduling(VL, VL0);
3076           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3077                        ReuseShuffleIndicies);
3078           LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
3079                             << *CI << "!=" << *V << '\n');
3080           return;
3081         }
3082       }
3083 
3084       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3085                                    ReuseShuffleIndicies);
3086       TE->setOperandsInOrder();
3087       for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i) {
3088         ValueList Operands;
3089         // Prepare the operand vector.
3090         for (Value *V : VL) {
3091           auto *CI2 = cast<CallInst>(V);
3092           Operands.push_back(CI2->getArgOperand(i));
3093         }
3094         buildTree_rec(Operands, Depth + 1, {TE, i});
3095       }
3096       return;
3097     }
3098     case Instruction::ShuffleVector: {
3099       // If this is not an alternate sequence of opcode like add-sub
3100       // then do not vectorize this instruction.
3101       if (!S.isAltShuffle()) {
3102         BS.cancelScheduling(VL, VL0);
3103         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3104                      ReuseShuffleIndicies);
3105         LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
3106         return;
3107       }
3108       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3109                                    ReuseShuffleIndicies);
3110       LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
3111 
3112       // Reorder operands if reordering would enable vectorization.
3113       if (isa<BinaryOperator>(VL0)) {
3114         ValueList Left, Right;
3115         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
3116         TE->setOperand(0, Left);
3117         TE->setOperand(1, Right);
3118         buildTree_rec(Left, Depth + 1, {TE, 0});
3119         buildTree_rec(Right, Depth + 1, {TE, 1});
3120         return;
3121       }
3122 
3123       TE->setOperandsInOrder();
3124       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
3125         ValueList Operands;
3126         // Prepare the operand vector.
3127         for (Value *V : VL)
3128           Operands.push_back(cast<Instruction>(V)->getOperand(i));
3129 
3130         buildTree_rec(Operands, Depth + 1, {TE, i});
3131       }
3132       return;
3133     }
3134     default:
3135       BS.cancelScheduling(VL, VL0);
3136       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3137                    ReuseShuffleIndicies);
3138       LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
3139       return;
3140   }
3141 }
3142 
3143 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
3144   unsigned N = 1;
3145   Type *EltTy = T;
3146 
3147   while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) ||
3148          isa<VectorType>(EltTy)) {
3149     if (auto *ST = dyn_cast<StructType>(EltTy)) {
3150       // Check that struct is homogeneous.
3151       for (const auto *Ty : ST->elements())
3152         if (Ty != *ST->element_begin())
3153           return 0;
3154       N *= ST->getNumElements();
3155       EltTy = *ST->element_begin();
3156     } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) {
3157       N *= AT->getNumElements();
3158       EltTy = AT->getElementType();
3159     } else {
3160       auto *VT = cast<VectorType>(EltTy);
3161       N *= VT->getNumElements();
3162       EltTy = VT->getElementType();
3163     }
3164   }
3165 
3166   if (!isValidElementType(EltTy))
3167     return 0;
3168   uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N));
3169   if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
3170     return 0;
3171   return N;
3172 }
3173 
3174 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
3175                               SmallVectorImpl<unsigned> &CurrentOrder) const {
3176   Instruction *E0 = cast<Instruction>(OpValue);
3177   assert(E0->getOpcode() == Instruction::ExtractElement ||
3178          E0->getOpcode() == Instruction::ExtractValue);
3179   assert(E0->getOpcode() == getSameOpcode(VL).getOpcode() && "Invalid opcode");
3180   // Check if all of the extracts come from the same vector and from the
3181   // correct offset.
3182   Value *Vec = E0->getOperand(0);
3183 
3184   CurrentOrder.clear();
3185 
3186   // We have to extract from a vector/aggregate with the same number of elements.
3187   unsigned NElts;
3188   if (E0->getOpcode() == Instruction::ExtractValue) {
3189     const DataLayout &DL = E0->getModule()->getDataLayout();
3190     NElts = canMapToVector(Vec->getType(), DL);
3191     if (!NElts)
3192       return false;
3193     // Check if load can be rewritten as load of vector.
3194     LoadInst *LI = dyn_cast<LoadInst>(Vec);
3195     if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
3196       return false;
3197   } else {
3198     NElts = cast<VectorType>(Vec->getType())->getNumElements();
3199   }
3200 
3201   if (NElts != VL.size())
3202     return false;
3203 
3204   // Check that all of the indices extract from the correct offset.
3205   bool ShouldKeepOrder = true;
3206   unsigned E = VL.size();
3207   // Assign to all items the initial value E + 1 so we can check if the extract
3208   // instruction index was used already.
3209   // Also, later we can check that all the indices are used and we have a
3210   // consecutive access in the extract instructions, by checking that no
3211   // element of CurrentOrder still has value E + 1.
3212   CurrentOrder.assign(E, E + 1);
3213   unsigned I = 0;
3214   for (; I < E; ++I) {
3215     auto *Inst = cast<Instruction>(VL[I]);
3216     if (Inst->getOperand(0) != Vec)
3217       break;
3218     Optional<unsigned> Idx = getExtractIndex(Inst);
3219     if (!Idx)
3220       break;
3221     const unsigned ExtIdx = *Idx;
3222     if (ExtIdx != I) {
3223       if (ExtIdx >= E || CurrentOrder[ExtIdx] != E + 1)
3224         break;
3225       ShouldKeepOrder = false;
3226       CurrentOrder[ExtIdx] = I;
3227     } else {
3228       if (CurrentOrder[I] != E + 1)
3229         break;
3230       CurrentOrder[I] = I;
3231     }
3232   }
3233   if (I < E) {
3234     CurrentOrder.clear();
3235     return false;
3236   }
3237 
3238   return ShouldKeepOrder;
3239 }
3240 
3241 bool BoUpSLP::areAllUsersVectorized(Instruction *I) const {
3242   return I->hasOneUse() ||
3243          std::all_of(I->user_begin(), I->user_end(), [this](User *U) {
3244            return ScalarToTreeEntry.count(U) > 0;
3245          });
3246 }
3247 
3248 static std::pair<unsigned, unsigned>
3249 getVectorCallCosts(CallInst *CI, VectorType *VecTy, TargetTransformInfo *TTI,
3250                    TargetLibraryInfo *TLI) {
3251   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
3252 
3253   // Calculate the cost of the scalar and vector calls.
3254   IntrinsicCostAttributes CostAttrs(ID, *CI, VecTy->getNumElements());
3255   int IntrinsicCost =
3256     TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput);
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           FixedVectorType::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       auto *SrcVecTy = FixedVectorType::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       auto *MaskTy = FixedVectorType::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       Align alignment = cast<LoadInst>(VL0)->getAlign();
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       Align Alignment = SI->getAlign();
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       IntrinsicCostAttributes CostAttrs(ID, *CI, 1, 1);
3588       int ScalarEltCost = TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
3589       if (NeedToShuffleReuses) {
3590         ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
3591       }
3592       int ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
3593 
3594       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
3595       int VecCallCost = std::min(VecCallCosts.first, VecCallCosts.second);
3596 
3597       LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
3598                         << " (" << VecCallCost << "-" << ScalarCallCost << ")"
3599                         << " for " << *CI << "\n");
3600 
3601       return ReuseShuffleCost + VecCallCost - ScalarCallCost;
3602     }
3603     case Instruction::ShuffleVector: {
3604       assert(E->isAltShuffle() &&
3605              ((Instruction::isBinaryOp(E->getOpcode()) &&
3606                Instruction::isBinaryOp(E->getAltOpcode())) ||
3607               (Instruction::isCast(E->getOpcode()) &&
3608                Instruction::isCast(E->getAltOpcode()))) &&
3609              "Invalid Shuffle Vector Operand");
3610       int ScalarCost = 0;
3611       if (NeedToShuffleReuses) {
3612         for (unsigned Idx : E->ReuseShuffleIndices) {
3613           Instruction *I = cast<Instruction>(VL[Idx]);
3614           ReuseShuffleCost -= TTI->getInstructionCost(I, CostKind);
3615         }
3616         for (Value *V : VL) {
3617           Instruction *I = cast<Instruction>(V);
3618           ReuseShuffleCost += TTI->getInstructionCost(I, CostKind);
3619         }
3620       }
3621       for (Value *V : VL) {
3622         Instruction *I = cast<Instruction>(V);
3623         assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
3624         ScalarCost += TTI->getInstructionCost(I, CostKind);
3625       }
3626       // VecCost is equal to sum of the cost of creating 2 vectors
3627       // and the cost of creating shuffle.
3628       int VecCost = 0;
3629       if (Instruction::isBinaryOp(E->getOpcode())) {
3630         VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind);
3631         VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy,
3632                                                CostKind);
3633       } else {
3634         Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
3635         Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
3636         auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size());
3637         auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size());
3638         VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty,
3639                                         CostKind);
3640         VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty,
3641                                          CostKind);
3642       }
3643       VecCost += TTI->getShuffleCost(TargetTransformInfo::SK_Select, VecTy, 0);
3644       return ReuseShuffleCost + VecCost - ScalarCost;
3645     }
3646     default:
3647       llvm_unreachable("Unknown instruction");
3648   }
3649 }
3650 
3651 bool BoUpSLP::isFullyVectorizableTinyTree() const {
3652   LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
3653                     << VectorizableTree.size() << " is fully vectorizable .\n");
3654 
3655   // We only handle trees of heights 1 and 2.
3656   if (VectorizableTree.size() == 1 &&
3657       VectorizableTree[0]->State == TreeEntry::Vectorize)
3658     return true;
3659 
3660   if (VectorizableTree.size() != 2)
3661     return false;
3662 
3663   // Handle splat and all-constants stores.
3664   if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
3665       (allConstant(VectorizableTree[1]->Scalars) ||
3666        isSplat(VectorizableTree[1]->Scalars)))
3667     return true;
3668 
3669   // Gathering cost would be too much for tiny trees.
3670   if (VectorizableTree[0]->State == TreeEntry::NeedToGather ||
3671       VectorizableTree[1]->State == TreeEntry::NeedToGather)
3672     return false;
3673 
3674   return true;
3675 }
3676 
3677 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts,
3678                                        TargetTransformInfo *TTI) {
3679   // Look past the root to find a source value. Arbitrarily follow the
3680   // path through operand 0 of any 'or'. Also, peek through optional
3681   // shift-left-by-constant.
3682   Value *ZextLoad = Root;
3683   while (!isa<ConstantExpr>(ZextLoad) &&
3684          (match(ZextLoad, m_Or(m_Value(), m_Value())) ||
3685           match(ZextLoad, m_Shl(m_Value(), m_Constant()))))
3686     ZextLoad = cast<BinaryOperator>(ZextLoad)->getOperand(0);
3687 
3688   // Check if the input is an extended load of the required or/shift expression.
3689   Value *LoadPtr;
3690   if (ZextLoad == Root || !match(ZextLoad, m_ZExt(m_Load(m_Value(LoadPtr)))))
3691     return false;
3692 
3693   // Require that the total load bit width is a legal integer type.
3694   // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
3695   // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
3696   Type *SrcTy = LoadPtr->getType()->getPointerElementType();
3697   unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts;
3698   if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth)))
3699     return false;
3700 
3701   // Everything matched - assume that we can fold the whole sequence using
3702   // load combining.
3703   LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "
3704              << *(cast<Instruction>(Root)) << "\n");
3705 
3706   return true;
3707 }
3708 
3709 bool BoUpSLP::isLoadCombineReductionCandidate(unsigned RdxOpcode) const {
3710   if (RdxOpcode != Instruction::Or)
3711     return false;
3712 
3713   unsigned NumElts = VectorizableTree[0]->Scalars.size();
3714   Value *FirstReduced = VectorizableTree[0]->Scalars[0];
3715   return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI);
3716 }
3717 
3718 bool BoUpSLP::isLoadCombineCandidate() const {
3719   // Peek through a final sequence of stores and check if all operations are
3720   // likely to be load-combined.
3721   unsigned NumElts = VectorizableTree[0]->Scalars.size();
3722   for (Value *Scalar : VectorizableTree[0]->Scalars) {
3723     Value *X;
3724     if (!match(Scalar, m_Store(m_Value(X), m_Value())) ||
3725         !isLoadCombineCandidateImpl(X, NumElts, TTI))
3726       return false;
3727   }
3728   return true;
3729 }
3730 
3731 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable() const {
3732   // We can vectorize the tree if its size is greater than or equal to the
3733   // minimum size specified by the MinTreeSize command line option.
3734   if (VectorizableTree.size() >= MinTreeSize)
3735     return false;
3736 
3737   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
3738   // can vectorize it if we can prove it fully vectorizable.
3739   if (isFullyVectorizableTinyTree())
3740     return false;
3741 
3742   assert(VectorizableTree.empty()
3743              ? ExternalUses.empty()
3744              : true && "We shouldn't have any external users");
3745 
3746   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
3747   // vectorizable.
3748   return true;
3749 }
3750 
3751 int BoUpSLP::getSpillCost() const {
3752   // Walk from the bottom of the tree to the top, tracking which values are
3753   // live. When we see a call instruction that is not part of our tree,
3754   // query TTI to see if there is a cost to keeping values live over it
3755   // (for example, if spills and fills are required).
3756   unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
3757   int Cost = 0;
3758 
3759   SmallPtrSet<Instruction*, 4> LiveValues;
3760   Instruction *PrevInst = nullptr;
3761 
3762   for (const auto &TEPtr : VectorizableTree) {
3763     Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
3764     if (!Inst)
3765       continue;
3766 
3767     if (!PrevInst) {
3768       PrevInst = Inst;
3769       continue;
3770     }
3771 
3772     // Update LiveValues.
3773     LiveValues.erase(PrevInst);
3774     for (auto &J : PrevInst->operands()) {
3775       if (isa<Instruction>(&*J) && getTreeEntry(&*J))
3776         LiveValues.insert(cast<Instruction>(&*J));
3777     }
3778 
3779     LLVM_DEBUG({
3780       dbgs() << "SLP: #LV: " << LiveValues.size();
3781       for (auto *X : LiveValues)
3782         dbgs() << " " << X->getName();
3783       dbgs() << ", Looking at ";
3784       Inst->dump();
3785     });
3786 
3787     // Now find the sequence of instructions between PrevInst and Inst.
3788     unsigned NumCalls = 0;
3789     BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
3790                                  PrevInstIt =
3791                                      PrevInst->getIterator().getReverse();
3792     while (InstIt != PrevInstIt) {
3793       if (PrevInstIt == PrevInst->getParent()->rend()) {
3794         PrevInstIt = Inst->getParent()->rbegin();
3795         continue;
3796       }
3797 
3798       // Debug information does not impact spill cost.
3799       if ((isa<CallInst>(&*PrevInstIt) &&
3800            !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
3801           &*PrevInstIt != PrevInst)
3802         NumCalls++;
3803 
3804       ++PrevInstIt;
3805     }
3806 
3807     if (NumCalls) {
3808       SmallVector<Type*, 4> V;
3809       for (auto *II : LiveValues)
3810         V.push_back(FixedVectorType::get(II->getType(), BundleWidth));
3811       Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
3812     }
3813 
3814     PrevInst = Inst;
3815   }
3816 
3817   return Cost;
3818 }
3819 
3820 int BoUpSLP::getTreeCost() {
3821   int Cost = 0;
3822   LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
3823                     << VectorizableTree.size() << ".\n");
3824 
3825   unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
3826 
3827   for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
3828     TreeEntry &TE = *VectorizableTree[I].get();
3829 
3830     // We create duplicate tree entries for gather sequences that have multiple
3831     // uses. However, we should not compute the cost of duplicate sequences.
3832     // For example, if we have a build vector (i.e., insertelement sequence)
3833     // that is used by more than one vector instruction, we only need to
3834     // compute the cost of the insertelement instructions once. The redundant
3835     // instructions will be eliminated by CSE.
3836     //
3837     // We should consider not creating duplicate tree entries for gather
3838     // sequences, and instead add additional edges to the tree representing
3839     // their uses. Since such an approach results in fewer total entries,
3840     // existing heuristics based on tree size may yield different results.
3841     //
3842     if (TE.State == TreeEntry::NeedToGather &&
3843         std::any_of(std::next(VectorizableTree.begin(), I + 1),
3844                     VectorizableTree.end(),
3845                     [TE](const std::unique_ptr<TreeEntry> &EntryPtr) {
3846                       return EntryPtr->State == TreeEntry::NeedToGather &&
3847                              EntryPtr->isSame(TE.Scalars);
3848                     }))
3849       continue;
3850 
3851     int C = getEntryCost(&TE);
3852     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
3853                       << " for bundle that starts with " << *TE.Scalars[0]
3854                       << ".\n");
3855     Cost += C;
3856   }
3857 
3858   SmallPtrSet<Value *, 16> ExtractCostCalculated;
3859   int ExtractCost = 0;
3860   for (ExternalUser &EU : ExternalUses) {
3861     // We only add extract cost once for the same scalar.
3862     if (!ExtractCostCalculated.insert(EU.Scalar).second)
3863       continue;
3864 
3865     // Uses by ephemeral values are free (because the ephemeral value will be
3866     // removed prior to code generation, and so the extraction will be
3867     // removed as well).
3868     if (EphValues.count(EU.User))
3869       continue;
3870 
3871     // If we plan to rewrite the tree in a smaller type, we will need to sign
3872     // extend the extracted value back to the original type. Here, we account
3873     // for the extract and the added cost of the sign extend if needed.
3874     auto *VecTy = VectorType::get(EU.Scalar->getType(), BundleWidth);
3875     auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
3876     if (MinBWs.count(ScalarRoot)) {
3877       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
3878       auto Extend =
3879           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
3880       VecTy = VectorType::get(MinTy, BundleWidth);
3881       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
3882                                                    VecTy, EU.Lane);
3883     } else {
3884       ExtractCost +=
3885           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
3886     }
3887   }
3888 
3889   int SpillCost = getSpillCost();
3890   Cost += SpillCost + ExtractCost;
3891 
3892   std::string Str;
3893   {
3894     raw_string_ostream OS(Str);
3895     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
3896        << "SLP: Extract Cost = " << ExtractCost << ".\n"
3897        << "SLP: Total Cost = " << Cost << ".\n";
3898   }
3899   LLVM_DEBUG(dbgs() << Str);
3900 
3901   if (ViewSLPTree)
3902     ViewGraph(this, "SLP" + F->getName(), false, Str);
3903 
3904   return Cost;
3905 }
3906 
3907 int BoUpSLP::getGatherCost(VectorType *Ty,
3908                            const DenseSet<unsigned> &ShuffledIndices) const {
3909   unsigned NumElts = Ty->getNumElements();
3910   APInt DemandedElts = APInt::getNullValue(NumElts);
3911   for (unsigned i = 0; i < NumElts; ++i)
3912     if (!ShuffledIndices.count(i))
3913       DemandedElts.setBit(i);
3914   int Cost = TTI->getScalarizationOverhead(Ty, DemandedElts, /*Insert*/ true,
3915                                            /*Extract*/ false);
3916   if (!ShuffledIndices.empty())
3917     Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
3918   return Cost;
3919 }
3920 
3921 int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
3922   // Find the type of the operands in VL.
3923   Type *ScalarTy = VL[0]->getType();
3924   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
3925     ScalarTy = SI->getValueOperand()->getType();
3926   VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
3927   // Find the cost of inserting/extracting values from the vector.
3928   // Check if the same elements are inserted several times and count them as
3929   // shuffle candidates.
3930   DenseSet<unsigned> ShuffledElements;
3931   DenseSet<Value *> UniqueElements;
3932   // Iterate in reverse order to consider insert elements with the high cost.
3933   for (unsigned I = VL.size(); I > 0; --I) {
3934     unsigned Idx = I - 1;
3935     if (!UniqueElements.insert(VL[Idx]).second)
3936       ShuffledElements.insert(Idx);
3937   }
3938   return getGatherCost(VecTy, ShuffledElements);
3939 }
3940 
3941 // Perform operand reordering on the instructions in VL and return the reordered
3942 // operands in Left and Right.
3943 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
3944                                              SmallVectorImpl<Value *> &Left,
3945                                              SmallVectorImpl<Value *> &Right,
3946                                              const DataLayout &DL,
3947                                              ScalarEvolution &SE,
3948                                              const BoUpSLP &R) {
3949   if (VL.empty())
3950     return;
3951   VLOperands Ops(VL, DL, SE, R);
3952   // Reorder the operands in place.
3953   Ops.reorder();
3954   Left = Ops.getVL(0);
3955   Right = Ops.getVL(1);
3956 }
3957 
3958 void BoUpSLP::setInsertPointAfterBundle(TreeEntry *E) {
3959   // Get the basic block this bundle is in. All instructions in the bundle
3960   // should be in this block.
3961   auto *Front = E->getMainOp();
3962   auto *BB = Front->getParent();
3963   assert(llvm::all_of(make_range(E->Scalars.begin(), E->Scalars.end()),
3964                       [=](Value *V) -> bool {
3965                         auto *I = cast<Instruction>(V);
3966                         return !E->isOpcodeOrAlt(I) || I->getParent() == BB;
3967                       }));
3968 
3969   // The last instruction in the bundle in program order.
3970   Instruction *LastInst = nullptr;
3971 
3972   // Find the last instruction. The common case should be that BB has been
3973   // scheduled, and the last instruction is VL.back(). So we start with
3974   // VL.back() and iterate over schedule data until we reach the end of the
3975   // bundle. The end of the bundle is marked by null ScheduleData.
3976   if (BlocksSchedules.count(BB)) {
3977     auto *Bundle =
3978         BlocksSchedules[BB]->getScheduleData(E->isOneOf(E->Scalars.back()));
3979     if (Bundle && Bundle->isPartOfBundle())
3980       for (; Bundle; Bundle = Bundle->NextInBundle)
3981         if (Bundle->OpValue == Bundle->Inst)
3982           LastInst = Bundle->Inst;
3983   }
3984 
3985   // LastInst can still be null at this point if there's either not an entry
3986   // for BB in BlocksSchedules or there's no ScheduleData available for
3987   // VL.back(). This can be the case if buildTree_rec aborts for various
3988   // reasons (e.g., the maximum recursion depth is reached, the maximum region
3989   // size is reached, etc.). ScheduleData is initialized in the scheduling
3990   // "dry-run".
3991   //
3992   // If this happens, we can still find the last instruction by brute force. We
3993   // iterate forwards from Front (inclusive) until we either see all
3994   // instructions in the bundle or reach the end of the block. If Front is the
3995   // last instruction in program order, LastInst will be set to Front, and we
3996   // will visit all the remaining instructions in the block.
3997   //
3998   // One of the reasons we exit early from buildTree_rec is to place an upper
3999   // bound on compile-time. Thus, taking an additional compile-time hit here is
4000   // not ideal. However, this should be exceedingly rare since it requires that
4001   // we both exit early from buildTree_rec and that the bundle be out-of-order
4002   // (causing us to iterate all the way to the end of the block).
4003   if (!LastInst) {
4004     SmallPtrSet<Value *, 16> Bundle(E->Scalars.begin(), E->Scalars.end());
4005     for (auto &I : make_range(BasicBlock::iterator(Front), BB->end())) {
4006       if (Bundle.erase(&I) && E->isOpcodeOrAlt(&I))
4007         LastInst = &I;
4008       if (Bundle.empty())
4009         break;
4010     }
4011   }
4012   assert(LastInst && "Failed to find last instruction in bundle");
4013 
4014   // Set the insertion point after the last instruction in the bundle. Set the
4015   // debug location to Front.
4016   Builder.SetInsertPoint(BB, ++LastInst->getIterator());
4017   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
4018 }
4019 
4020 Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
4021   Value *Vec = UndefValue::get(Ty);
4022   // Generate the 'InsertElement' instruction.
4023   for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
4024     Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
4025     if (auto *Insrt = dyn_cast<InsertElementInst>(Vec)) {
4026       GatherSeq.insert(Insrt);
4027       CSEBlocks.insert(Insrt->getParent());
4028 
4029       // Add to our 'need-to-extract' list.
4030       if (TreeEntry *E = getTreeEntry(VL[i])) {
4031         // Find which lane we need to extract.
4032         int FoundLane = -1;
4033         for (unsigned Lane = 0, LE = E->Scalars.size(); Lane != LE; ++Lane) {
4034           // Is this the lane of the scalar that we are looking for ?
4035           if (E->Scalars[Lane] == VL[i]) {
4036             FoundLane = Lane;
4037             break;
4038           }
4039         }
4040         assert(FoundLane >= 0 && "Could not find the correct lane");
4041         if (!E->ReuseShuffleIndices.empty()) {
4042           FoundLane =
4043               std::distance(E->ReuseShuffleIndices.begin(),
4044                             llvm::find(E->ReuseShuffleIndices, FoundLane));
4045         }
4046         ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
4047       }
4048     }
4049   }
4050 
4051   return Vec;
4052 }
4053 
4054 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
4055   InstructionsState S = getSameOpcode(VL);
4056   if (S.getOpcode()) {
4057     if (TreeEntry *E = getTreeEntry(S.OpValue)) {
4058       if (E->isSame(VL)) {
4059         Value *V = vectorizeTree(E);
4060         if (VL.size() == E->Scalars.size() && !E->ReuseShuffleIndices.empty()) {
4061           // We need to get the vectorized value but without shuffle.
4062           if (auto *SV = dyn_cast<ShuffleVectorInst>(V)) {
4063             V = SV->getOperand(0);
4064           } else {
4065             // Reshuffle to get only unique values.
4066             SmallVector<int, 4> UniqueIdxs;
4067             SmallSet<int, 4> UsedIdxs;
4068             for (int Idx : E->ReuseShuffleIndices)
4069               if (UsedIdxs.insert(Idx).second)
4070                 UniqueIdxs.emplace_back(Idx);
4071             V = Builder.CreateShuffleVector(V, UndefValue::get(V->getType()),
4072                                             UniqueIdxs);
4073           }
4074         }
4075         return V;
4076       }
4077     }
4078   }
4079 
4080   Type *ScalarTy = S.OpValue->getType();
4081   if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
4082     ScalarTy = SI->getValueOperand()->getType();
4083 
4084   // Check that every instruction appears once in this bundle.
4085   SmallVector<int, 4> ReuseShuffleIndicies;
4086   SmallVector<Value *, 4> UniqueValues;
4087   if (VL.size() > 2) {
4088     DenseMap<Value *, unsigned> UniquePositions;
4089     for (Value *V : VL) {
4090       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
4091       ReuseShuffleIndicies.emplace_back(Res.first->second);
4092       if (Res.second || isa<Constant>(V))
4093         UniqueValues.emplace_back(V);
4094     }
4095     // Do not shuffle single element or if number of unique values is not power
4096     // of 2.
4097     if (UniqueValues.size() == VL.size() || UniqueValues.size() <= 1 ||
4098         !llvm::isPowerOf2_32(UniqueValues.size()))
4099       ReuseShuffleIndicies.clear();
4100     else
4101       VL = UniqueValues;
4102   }
4103   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
4104 
4105   Value *V = Gather(VL, VecTy);
4106   if (!ReuseShuffleIndicies.empty()) {
4107     V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
4108                                     ReuseShuffleIndicies, "shuffle");
4109     if (auto *I = dyn_cast<Instruction>(V)) {
4110       GatherSeq.insert(I);
4111       CSEBlocks.insert(I->getParent());
4112     }
4113   }
4114   return V;
4115 }
4116 
4117 static void inversePermutation(ArrayRef<unsigned> Indices,
4118                                SmallVectorImpl<int> &Mask) {
4119   Mask.clear();
4120   const unsigned E = Indices.size();
4121   Mask.resize(E);
4122   for (unsigned I = 0; I < E; ++I)
4123     Mask[Indices[I]] = I;
4124 }
4125 
4126 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
4127   IRBuilder<>::InsertPointGuard Guard(Builder);
4128 
4129   if (E->VectorizedValue) {
4130     LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
4131     return E->VectorizedValue;
4132   }
4133 
4134   Instruction *VL0 = E->getMainOp();
4135   Type *ScalarTy = VL0->getType();
4136   if (StoreInst *SI = dyn_cast<StoreInst>(VL0))
4137     ScalarTy = SI->getValueOperand()->getType();
4138   auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
4139 
4140   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
4141 
4142   if (E->State == TreeEntry::NeedToGather) {
4143     setInsertPointAfterBundle(E);
4144     auto *V = Gather(E->Scalars, VecTy);
4145     if (NeedToShuffleReuses) {
4146       V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
4147                                       E->ReuseShuffleIndices, "shuffle");
4148       if (auto *I = dyn_cast<Instruction>(V)) {
4149         GatherSeq.insert(I);
4150         CSEBlocks.insert(I->getParent());
4151       }
4152     }
4153     E->VectorizedValue = V;
4154     return V;
4155   }
4156 
4157   assert(E->State == TreeEntry::Vectorize && "Unhandled state");
4158   unsigned ShuffleOrOp =
4159       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
4160   switch (ShuffleOrOp) {
4161     case Instruction::PHI: {
4162       auto *PH = cast<PHINode>(VL0);
4163       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
4164       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
4165       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
4166       Value *V = NewPhi;
4167       if (NeedToShuffleReuses) {
4168         V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
4169                                         E->ReuseShuffleIndices, "shuffle");
4170       }
4171       E->VectorizedValue = V;
4172 
4173       // PHINodes may have multiple entries from the same block. We want to
4174       // visit every block once.
4175       SmallPtrSet<BasicBlock*, 4> VisitedBBs;
4176 
4177       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
4178         ValueList Operands;
4179         BasicBlock *IBB = PH->getIncomingBlock(i);
4180 
4181         if (!VisitedBBs.insert(IBB).second) {
4182           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
4183           continue;
4184         }
4185 
4186         Builder.SetInsertPoint(IBB->getTerminator());
4187         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
4188         Value *Vec = vectorizeTree(E->getOperand(i));
4189         NewPhi->addIncoming(Vec, IBB);
4190       }
4191 
4192       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
4193              "Invalid number of incoming values");
4194       return V;
4195     }
4196 
4197     case Instruction::ExtractElement: {
4198       Value *V = E->getSingleOperand(0);
4199       if (!E->ReorderIndices.empty()) {
4200         SmallVector<int, 4> Mask;
4201         inversePermutation(E->ReorderIndices, Mask);
4202         Builder.SetInsertPoint(VL0);
4203         V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy), Mask,
4204                                         "reorder_shuffle");
4205       }
4206       if (NeedToShuffleReuses) {
4207         // TODO: Merge this shuffle with the ReorderShuffleMask.
4208         if (E->ReorderIndices.empty())
4209           Builder.SetInsertPoint(VL0);
4210         V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
4211                                         E->ReuseShuffleIndices, "shuffle");
4212       }
4213       E->VectorizedValue = V;
4214       return V;
4215     }
4216     case Instruction::ExtractValue: {
4217       LoadInst *LI = cast<LoadInst>(E->getSingleOperand(0));
4218       Builder.SetInsertPoint(LI);
4219       PointerType *PtrTy =
4220           PointerType::get(VecTy, LI->getPointerAddressSpace());
4221       Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
4222       LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
4223       Value *NewV = propagateMetadata(V, E->Scalars);
4224       if (!E->ReorderIndices.empty()) {
4225         SmallVector<int, 4> Mask;
4226         inversePermutation(E->ReorderIndices, Mask);
4227         NewV = Builder.CreateShuffleVector(NewV, UndefValue::get(VecTy), Mask,
4228                                            "reorder_shuffle");
4229       }
4230       if (NeedToShuffleReuses) {
4231         // TODO: Merge this shuffle with the ReorderShuffleMask.
4232         NewV = Builder.CreateShuffleVector(NewV, UndefValue::get(VecTy),
4233                                            E->ReuseShuffleIndices, "shuffle");
4234       }
4235       E->VectorizedValue = NewV;
4236       return NewV;
4237     }
4238     case Instruction::ZExt:
4239     case Instruction::SExt:
4240     case Instruction::FPToUI:
4241     case Instruction::FPToSI:
4242     case Instruction::FPExt:
4243     case Instruction::PtrToInt:
4244     case Instruction::IntToPtr:
4245     case Instruction::SIToFP:
4246     case Instruction::UIToFP:
4247     case Instruction::Trunc:
4248     case Instruction::FPTrunc:
4249     case Instruction::BitCast: {
4250       setInsertPointAfterBundle(E);
4251 
4252       Value *InVec = vectorizeTree(E->getOperand(0));
4253 
4254       if (E->VectorizedValue) {
4255         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
4256         return E->VectorizedValue;
4257       }
4258 
4259       auto *CI = cast<CastInst>(VL0);
4260       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
4261       if (NeedToShuffleReuses) {
4262         V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
4263                                         E->ReuseShuffleIndices, "shuffle");
4264       }
4265       E->VectorizedValue = V;
4266       ++NumVectorInstructions;
4267       return V;
4268     }
4269     case Instruction::FCmp:
4270     case Instruction::ICmp: {
4271       setInsertPointAfterBundle(E);
4272 
4273       Value *L = vectorizeTree(E->getOperand(0));
4274       Value *R = vectorizeTree(E->getOperand(1));
4275 
4276       if (E->VectorizedValue) {
4277         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
4278         return E->VectorizedValue;
4279       }
4280 
4281       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
4282       Value *V;
4283       if (E->getOpcode() == Instruction::FCmp)
4284         V = Builder.CreateFCmp(P0, L, R);
4285       else
4286         V = Builder.CreateICmp(P0, L, R);
4287 
4288       propagateIRFlags(V, E->Scalars, VL0);
4289       if (NeedToShuffleReuses) {
4290         V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
4291                                         E->ReuseShuffleIndices, "shuffle");
4292       }
4293       E->VectorizedValue = V;
4294       ++NumVectorInstructions;
4295       return V;
4296     }
4297     case Instruction::Select: {
4298       setInsertPointAfterBundle(E);
4299 
4300       Value *Cond = vectorizeTree(E->getOperand(0));
4301       Value *True = vectorizeTree(E->getOperand(1));
4302       Value *False = vectorizeTree(E->getOperand(2));
4303 
4304       if (E->VectorizedValue) {
4305         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
4306         return E->VectorizedValue;
4307       }
4308 
4309       Value *V = Builder.CreateSelect(Cond, True, False);
4310       if (NeedToShuffleReuses) {
4311         V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
4312                                         E->ReuseShuffleIndices, "shuffle");
4313       }
4314       E->VectorizedValue = V;
4315       ++NumVectorInstructions;
4316       return V;
4317     }
4318     case Instruction::FNeg: {
4319       setInsertPointAfterBundle(E);
4320 
4321       Value *Op = vectorizeTree(E->getOperand(0));
4322 
4323       if (E->VectorizedValue) {
4324         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
4325         return E->VectorizedValue;
4326       }
4327 
4328       Value *V = Builder.CreateUnOp(
4329           static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
4330       propagateIRFlags(V, E->Scalars, VL0);
4331       if (auto *I = dyn_cast<Instruction>(V))
4332         V = propagateMetadata(I, E->Scalars);
4333 
4334       if (NeedToShuffleReuses) {
4335         V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
4336                                         E->ReuseShuffleIndices, "shuffle");
4337       }
4338       E->VectorizedValue = V;
4339       ++NumVectorInstructions;
4340 
4341       return V;
4342     }
4343     case Instruction::Add:
4344     case Instruction::FAdd:
4345     case Instruction::Sub:
4346     case Instruction::FSub:
4347     case Instruction::Mul:
4348     case Instruction::FMul:
4349     case Instruction::UDiv:
4350     case Instruction::SDiv:
4351     case Instruction::FDiv:
4352     case Instruction::URem:
4353     case Instruction::SRem:
4354     case Instruction::FRem:
4355     case Instruction::Shl:
4356     case Instruction::LShr:
4357     case Instruction::AShr:
4358     case Instruction::And:
4359     case Instruction::Or:
4360     case Instruction::Xor: {
4361       setInsertPointAfterBundle(E);
4362 
4363       Value *LHS = vectorizeTree(E->getOperand(0));
4364       Value *RHS = vectorizeTree(E->getOperand(1));
4365 
4366       if (E->VectorizedValue) {
4367         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
4368         return E->VectorizedValue;
4369       }
4370 
4371       Value *V = Builder.CreateBinOp(
4372           static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
4373           RHS);
4374       propagateIRFlags(V, E->Scalars, VL0);
4375       if (auto *I = dyn_cast<Instruction>(V))
4376         V = propagateMetadata(I, E->Scalars);
4377 
4378       if (NeedToShuffleReuses) {
4379         V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
4380                                         E->ReuseShuffleIndices, "shuffle");
4381       }
4382       E->VectorizedValue = V;
4383       ++NumVectorInstructions;
4384 
4385       return V;
4386     }
4387     case Instruction::Load: {
4388       // Loads are inserted at the head of the tree because we don't want to
4389       // sink them all the way down past store instructions.
4390       bool IsReorder = E->updateStateIfReorder();
4391       if (IsReorder)
4392         VL0 = E->getMainOp();
4393       setInsertPointAfterBundle(E);
4394 
4395       LoadInst *LI = cast<LoadInst>(VL0);
4396       unsigned AS = LI->getPointerAddressSpace();
4397 
4398       Value *VecPtr = Builder.CreateBitCast(LI->getPointerOperand(),
4399                                             VecTy->getPointerTo(AS));
4400 
4401       // The pointer operand uses an in-tree scalar so we add the new BitCast to
4402       // ExternalUses list to make sure that an extract will be generated in the
4403       // future.
4404       Value *PO = LI->getPointerOperand();
4405       if (getTreeEntry(PO))
4406         ExternalUses.push_back(ExternalUser(PO, cast<User>(VecPtr), 0));
4407 
4408       LI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
4409       Value *V = propagateMetadata(LI, E->Scalars);
4410       if (IsReorder) {
4411         SmallVector<int, 4> Mask;
4412         inversePermutation(E->ReorderIndices, Mask);
4413         V = Builder.CreateShuffleVector(V, UndefValue::get(V->getType()),
4414                                         Mask, "reorder_shuffle");
4415       }
4416       if (NeedToShuffleReuses) {
4417         // TODO: Merge this shuffle with the ReorderShuffleMask.
4418         V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
4419                                         E->ReuseShuffleIndices, "shuffle");
4420       }
4421       E->VectorizedValue = V;
4422       ++NumVectorInstructions;
4423       return V;
4424     }
4425     case Instruction::Store: {
4426       bool IsReorder = !E->ReorderIndices.empty();
4427       auto *SI = cast<StoreInst>(
4428           IsReorder ? E->Scalars[E->ReorderIndices.front()] : VL0);
4429       unsigned AS = SI->getPointerAddressSpace();
4430 
4431       setInsertPointAfterBundle(E);
4432 
4433       Value *VecValue = vectorizeTree(E->getOperand(0));
4434       if (IsReorder) {
4435         SmallVector<int, 4> Mask(E->ReorderIndices.begin(),
4436                                  E->ReorderIndices.end());
4437         VecValue = Builder.CreateShuffleVector(
4438             VecValue, UndefValue::get(VecValue->getType()), Mask,
4439             "reorder_shuffle");
4440       }
4441       Value *ScalarPtr = SI->getPointerOperand();
4442       Value *VecPtr = Builder.CreateBitCast(
4443           ScalarPtr, VecValue->getType()->getPointerTo(AS));
4444       StoreInst *ST = Builder.CreateAlignedStore(VecValue, VecPtr,
4445                                                  SI->getAlign());
4446 
4447       // The pointer operand uses an in-tree scalar, so add the new BitCast to
4448       // ExternalUses to make sure that an extract will be generated in the
4449       // future.
4450       if (getTreeEntry(ScalarPtr))
4451         ExternalUses.push_back(ExternalUser(ScalarPtr, cast<User>(VecPtr), 0));
4452 
4453       Value *V = propagateMetadata(ST, E->Scalars);
4454       if (NeedToShuffleReuses) {
4455         V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
4456                                         E->ReuseShuffleIndices, "shuffle");
4457       }
4458       E->VectorizedValue = V;
4459       ++NumVectorInstructions;
4460       return V;
4461     }
4462     case Instruction::GetElementPtr: {
4463       setInsertPointAfterBundle(E);
4464 
4465       Value *Op0 = vectorizeTree(E->getOperand(0));
4466 
4467       std::vector<Value *> OpVecs;
4468       for (int j = 1, e = cast<GetElementPtrInst>(VL0)->getNumOperands(); j < e;
4469            ++j) {
4470         ValueList &VL = E->getOperand(j);
4471         // Need to cast all elements to the same type before vectorization to
4472         // avoid crash.
4473         Type *VL0Ty = VL0->getOperand(j)->getType();
4474         Type *Ty = llvm::all_of(
4475                        VL, [VL0Ty](Value *V) { return VL0Ty == V->getType(); })
4476                        ? VL0Ty
4477                        : DL->getIndexType(cast<GetElementPtrInst>(VL0)
4478                                               ->getPointerOperandType()
4479                                               ->getScalarType());
4480         for (Value *&V : VL) {
4481           auto *CI = cast<ConstantInt>(V);
4482           V = ConstantExpr::getIntegerCast(CI, Ty,
4483                                            CI->getValue().isSignBitSet());
4484         }
4485         Value *OpVec = vectorizeTree(VL);
4486         OpVecs.push_back(OpVec);
4487       }
4488 
4489       Value *V = Builder.CreateGEP(
4490           cast<GetElementPtrInst>(VL0)->getSourceElementType(), Op0, OpVecs);
4491       if (Instruction *I = dyn_cast<Instruction>(V))
4492         V = propagateMetadata(I, E->Scalars);
4493 
4494       if (NeedToShuffleReuses) {
4495         V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
4496                                         E->ReuseShuffleIndices, "shuffle");
4497       }
4498       E->VectorizedValue = V;
4499       ++NumVectorInstructions;
4500 
4501       return V;
4502     }
4503     case Instruction::Call: {
4504       CallInst *CI = cast<CallInst>(VL0);
4505       setInsertPointAfterBundle(E);
4506 
4507       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
4508       if (Function *FI = CI->getCalledFunction())
4509         IID = FI->getIntrinsicID();
4510 
4511       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4512 
4513       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
4514       bool UseIntrinsic = VecCallCosts.first <= VecCallCosts.second;
4515 
4516       Value *ScalarArg = nullptr;
4517       std::vector<Value *> OpVecs;
4518       for (int j = 0, e = CI->getNumArgOperands(); j < e; ++j) {
4519         ValueList OpVL;
4520         // Some intrinsics have scalar arguments. This argument should not be
4521         // vectorized.
4522         if (UseIntrinsic && hasVectorInstrinsicScalarOpd(IID, j)) {
4523           CallInst *CEI = cast<CallInst>(VL0);
4524           ScalarArg = CEI->getArgOperand(j);
4525           OpVecs.push_back(CEI->getArgOperand(j));
4526           continue;
4527         }
4528 
4529         Value *OpVec = vectorizeTree(E->getOperand(j));
4530         LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
4531         OpVecs.push_back(OpVec);
4532       }
4533 
4534       Module *M = F->getParent();
4535       Type *Tys[] = {FixedVectorType::get(CI->getType(), E->Scalars.size())};
4536       Function *CF = Intrinsic::getDeclaration(M, ID, Tys);
4537 
4538       if (!UseIntrinsic) {
4539         VFShape Shape = VFShape::get(
4540             *CI, {static_cast<unsigned>(VecTy->getNumElements()), false},
4541             false /*HasGlobalPred*/);
4542         CF = VFDatabase(*CI).getVectorizedFunction(Shape);
4543       }
4544 
4545       SmallVector<OperandBundleDef, 1> OpBundles;
4546       CI->getOperandBundlesAsDefs(OpBundles);
4547       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
4548 
4549       // The scalar argument uses an in-tree scalar so we add the new vectorized
4550       // call to ExternalUses list to make sure that an extract will be
4551       // generated in the future.
4552       if (ScalarArg && getTreeEntry(ScalarArg))
4553         ExternalUses.push_back(ExternalUser(ScalarArg, cast<User>(V), 0));
4554 
4555       propagateIRFlags(V, E->Scalars, VL0);
4556       if (NeedToShuffleReuses) {
4557         V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
4558                                         E->ReuseShuffleIndices, "shuffle");
4559       }
4560       E->VectorizedValue = V;
4561       ++NumVectorInstructions;
4562       return V;
4563     }
4564     case Instruction::ShuffleVector: {
4565       assert(E->isAltShuffle() &&
4566              ((Instruction::isBinaryOp(E->getOpcode()) &&
4567                Instruction::isBinaryOp(E->getAltOpcode())) ||
4568               (Instruction::isCast(E->getOpcode()) &&
4569                Instruction::isCast(E->getAltOpcode()))) &&
4570              "Invalid Shuffle Vector Operand");
4571 
4572       Value *LHS = nullptr, *RHS = nullptr;
4573       if (Instruction::isBinaryOp(E->getOpcode())) {
4574         setInsertPointAfterBundle(E);
4575         LHS = vectorizeTree(E->getOperand(0));
4576         RHS = vectorizeTree(E->getOperand(1));
4577       } else {
4578         setInsertPointAfterBundle(E);
4579         LHS = vectorizeTree(E->getOperand(0));
4580       }
4581 
4582       if (E->VectorizedValue) {
4583         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
4584         return E->VectorizedValue;
4585       }
4586 
4587       Value *V0, *V1;
4588       if (Instruction::isBinaryOp(E->getOpcode())) {
4589         V0 = Builder.CreateBinOp(
4590             static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
4591         V1 = Builder.CreateBinOp(
4592             static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
4593       } else {
4594         V0 = Builder.CreateCast(
4595             static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
4596         V1 = Builder.CreateCast(
4597             static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
4598       }
4599 
4600       // Create shuffle to take alternate operations from the vector.
4601       // Also, gather up main and alt scalar ops to propagate IR flags to
4602       // each vector operation.
4603       ValueList OpScalars, AltScalars;
4604       unsigned e = E->Scalars.size();
4605       SmallVector<int, 8> Mask(e);
4606       for (unsigned i = 0; i < e; ++i) {
4607         auto *OpInst = cast<Instruction>(E->Scalars[i]);
4608         assert(E->isOpcodeOrAlt(OpInst) && "Unexpected main/alternate opcode");
4609         if (OpInst->getOpcode() == E->getAltOpcode()) {
4610           Mask[i] = e + i;
4611           AltScalars.push_back(E->Scalars[i]);
4612         } else {
4613           Mask[i] = i;
4614           OpScalars.push_back(E->Scalars[i]);
4615         }
4616       }
4617 
4618       propagateIRFlags(V0, OpScalars);
4619       propagateIRFlags(V1, AltScalars);
4620 
4621       Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
4622       if (Instruction *I = dyn_cast<Instruction>(V))
4623         V = propagateMetadata(I, E->Scalars);
4624       if (NeedToShuffleReuses) {
4625         V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
4626                                         E->ReuseShuffleIndices, "shuffle");
4627       }
4628       E->VectorizedValue = V;
4629       ++NumVectorInstructions;
4630 
4631       return V;
4632     }
4633     default:
4634     llvm_unreachable("unknown inst");
4635   }
4636   return nullptr;
4637 }
4638 
4639 Value *BoUpSLP::vectorizeTree() {
4640   ExtraValueToDebugLocsMap ExternallyUsedValues;
4641   return vectorizeTree(ExternallyUsedValues);
4642 }
4643 
4644 Value *
4645 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
4646   // All blocks must be scheduled before any instructions are inserted.
4647   for (auto &BSIter : BlocksSchedules) {
4648     scheduleBlock(BSIter.second.get());
4649   }
4650 
4651   Builder.SetInsertPoint(&F->getEntryBlock().front());
4652   auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
4653 
4654   // If the vectorized tree can be rewritten in a smaller type, we truncate the
4655   // vectorized root. InstCombine will then rewrite the entire expression. We
4656   // sign extend the extracted values below.
4657   auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
4658   if (MinBWs.count(ScalarRoot)) {
4659     if (auto *I = dyn_cast<Instruction>(VectorRoot))
4660       Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
4661     auto BundleWidth = VectorizableTree[0]->Scalars.size();
4662     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
4663     auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
4664     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
4665     VectorizableTree[0]->VectorizedValue = Trunc;
4666   }
4667 
4668   LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
4669                     << " values .\n");
4670 
4671   // If necessary, sign-extend or zero-extend ScalarRoot to the larger type
4672   // specified by ScalarType.
4673   auto extend = [&](Value *ScalarRoot, Value *Ex, Type *ScalarType) {
4674     if (!MinBWs.count(ScalarRoot))
4675       return Ex;
4676     if (MinBWs[ScalarRoot].second)
4677       return Builder.CreateSExt(Ex, ScalarType);
4678     return Builder.CreateZExt(Ex, ScalarType);
4679   };
4680 
4681   // Extract all of the elements with the external uses.
4682   for (const auto &ExternalUse : ExternalUses) {
4683     Value *Scalar = ExternalUse.Scalar;
4684     llvm::User *User = ExternalUse.User;
4685 
4686     // Skip users that we already RAUW. This happens when one instruction
4687     // has multiple uses of the same value.
4688     if (User && !is_contained(Scalar->users(), User))
4689       continue;
4690     TreeEntry *E = getTreeEntry(Scalar);
4691     assert(E && "Invalid scalar");
4692     assert(E->State == TreeEntry::Vectorize && "Extracting from a gather list");
4693 
4694     Value *Vec = E->VectorizedValue;
4695     assert(Vec && "Can't find vectorizable value");
4696 
4697     Value *Lane = Builder.getInt32(ExternalUse.Lane);
4698     // If User == nullptr, the Scalar is used as extra arg. Generate
4699     // ExtractElement instruction and update the record for this scalar in
4700     // ExternallyUsedValues.
4701     if (!User) {
4702       assert(ExternallyUsedValues.count(Scalar) &&
4703              "Scalar with nullptr as an external user must be registered in "
4704              "ExternallyUsedValues map");
4705       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
4706         Builder.SetInsertPoint(VecI->getParent(),
4707                                std::next(VecI->getIterator()));
4708       } else {
4709         Builder.SetInsertPoint(&F->getEntryBlock().front());
4710       }
4711       Value *Ex = Builder.CreateExtractElement(Vec, Lane);
4712       Ex = extend(ScalarRoot, Ex, Scalar->getType());
4713       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
4714       auto &Locs = ExternallyUsedValues[Scalar];
4715       ExternallyUsedValues.insert({Ex, Locs});
4716       ExternallyUsedValues.erase(Scalar);
4717       // Required to update internally referenced instructions.
4718       Scalar->replaceAllUsesWith(Ex);
4719       continue;
4720     }
4721 
4722     // Generate extracts for out-of-tree users.
4723     // Find the insertion point for the extractelement lane.
4724     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
4725       if (PHINode *PH = dyn_cast<PHINode>(User)) {
4726         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
4727           if (PH->getIncomingValue(i) == Scalar) {
4728             Instruction *IncomingTerminator =
4729                 PH->getIncomingBlock(i)->getTerminator();
4730             if (isa<CatchSwitchInst>(IncomingTerminator)) {
4731               Builder.SetInsertPoint(VecI->getParent(),
4732                                      std::next(VecI->getIterator()));
4733             } else {
4734               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
4735             }
4736             Value *Ex = Builder.CreateExtractElement(Vec, Lane);
4737             Ex = extend(ScalarRoot, Ex, Scalar->getType());
4738             CSEBlocks.insert(PH->getIncomingBlock(i));
4739             PH->setOperand(i, Ex);
4740           }
4741         }
4742       } else {
4743         Builder.SetInsertPoint(cast<Instruction>(User));
4744         Value *Ex = Builder.CreateExtractElement(Vec, Lane);
4745         Ex = extend(ScalarRoot, Ex, Scalar->getType());
4746         CSEBlocks.insert(cast<Instruction>(User)->getParent());
4747         User->replaceUsesOfWith(Scalar, Ex);
4748       }
4749     } else {
4750       Builder.SetInsertPoint(&F->getEntryBlock().front());
4751       Value *Ex = Builder.CreateExtractElement(Vec, Lane);
4752       Ex = extend(ScalarRoot, Ex, Scalar->getType());
4753       CSEBlocks.insert(&F->getEntryBlock());
4754       User->replaceUsesOfWith(Scalar, Ex);
4755     }
4756 
4757     LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
4758   }
4759 
4760   // For each vectorized value:
4761   for (auto &TEPtr : VectorizableTree) {
4762     TreeEntry *Entry = TEPtr.get();
4763 
4764     // No need to handle users of gathered values.
4765     if (Entry->State == TreeEntry::NeedToGather)
4766       continue;
4767 
4768     assert(Entry->VectorizedValue && "Can't find vectorizable value");
4769 
4770     // For each lane:
4771     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
4772       Value *Scalar = Entry->Scalars[Lane];
4773 
4774 #ifndef NDEBUG
4775       Type *Ty = Scalar->getType();
4776       if (!Ty->isVoidTy()) {
4777         for (User *U : Scalar->users()) {
4778           LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
4779 
4780           // It is legal to delete users in the ignorelist.
4781           assert((getTreeEntry(U) || is_contained(UserIgnoreList, U)) &&
4782                  "Deleting out-of-tree value");
4783         }
4784       }
4785 #endif
4786       LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
4787       eraseInstruction(cast<Instruction>(Scalar));
4788     }
4789   }
4790 
4791   Builder.ClearInsertionPoint();
4792   InstrElementSize.clear();
4793 
4794   return VectorizableTree[0]->VectorizedValue;
4795 }
4796 
4797 void BoUpSLP::optimizeGatherSequence() {
4798   LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
4799                     << " gather sequences instructions.\n");
4800   // LICM InsertElementInst sequences.
4801   for (Instruction *I : GatherSeq) {
4802     if (isDeleted(I))
4803       continue;
4804 
4805     // Check if this block is inside a loop.
4806     Loop *L = LI->getLoopFor(I->getParent());
4807     if (!L)
4808       continue;
4809 
4810     // Check if it has a preheader.
4811     BasicBlock *PreHeader = L->getLoopPreheader();
4812     if (!PreHeader)
4813       continue;
4814 
4815     // If the vector or the element that we insert into it are
4816     // instructions that are defined in this basic block then we can't
4817     // hoist this instruction.
4818     auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
4819     auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
4820     if (Op0 && L->contains(Op0))
4821       continue;
4822     if (Op1 && L->contains(Op1))
4823       continue;
4824 
4825     // We can hoist this instruction. Move it to the pre-header.
4826     I->moveBefore(PreHeader->getTerminator());
4827   }
4828 
4829   // Make a list of all reachable blocks in our CSE queue.
4830   SmallVector<const DomTreeNode *, 8> CSEWorkList;
4831   CSEWorkList.reserve(CSEBlocks.size());
4832   for (BasicBlock *BB : CSEBlocks)
4833     if (DomTreeNode *N = DT->getNode(BB)) {
4834       assert(DT->isReachableFromEntry(N));
4835       CSEWorkList.push_back(N);
4836     }
4837 
4838   // Sort blocks by domination. This ensures we visit a block after all blocks
4839   // dominating it are visited.
4840   llvm::stable_sort(CSEWorkList,
4841                     [this](const DomTreeNode *A, const DomTreeNode *B) {
4842                       return DT->properlyDominates(A, B);
4843                     });
4844 
4845   // Perform O(N^2) search over the gather sequences and merge identical
4846   // instructions. TODO: We can further optimize this scan if we split the
4847   // instructions into different buckets based on the insert lane.
4848   SmallVector<Instruction *, 16> Visited;
4849   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
4850     assert((I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
4851            "Worklist not sorted properly!");
4852     BasicBlock *BB = (*I)->getBlock();
4853     // For all instructions in blocks containing gather sequences:
4854     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) {
4855       Instruction *In = &*it++;
4856       if (isDeleted(In))
4857         continue;
4858       if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In))
4859         continue;
4860 
4861       // Check if we can replace this instruction with any of the
4862       // visited instructions.
4863       for (Instruction *v : Visited) {
4864         if (In->isIdenticalTo(v) &&
4865             DT->dominates(v->getParent(), In->getParent())) {
4866           In->replaceAllUsesWith(v);
4867           eraseInstruction(In);
4868           In = nullptr;
4869           break;
4870         }
4871       }
4872       if (In) {
4873         assert(!is_contained(Visited, In));
4874         Visited.push_back(In);
4875       }
4876     }
4877   }
4878   CSEBlocks.clear();
4879   GatherSeq.clear();
4880 }
4881 
4882 // Groups the instructions to a bundle (which is then a single scheduling entity)
4883 // and schedules instructions until the bundle gets ready.
4884 Optional<BoUpSLP::ScheduleData *>
4885 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
4886                                             const InstructionsState &S) {
4887   if (isa<PHINode>(S.OpValue))
4888     return nullptr;
4889 
4890   // Initialize the instruction bundle.
4891   Instruction *OldScheduleEnd = ScheduleEnd;
4892   ScheduleData *PrevInBundle = nullptr;
4893   ScheduleData *Bundle = nullptr;
4894   bool ReSchedule = false;
4895   LLVM_DEBUG(dbgs() << "SLP:  bundle: " << *S.OpValue << "\n");
4896 
4897   // Make sure that the scheduling region contains all
4898   // instructions of the bundle.
4899   for (Value *V : VL) {
4900     if (!extendSchedulingRegion(V, S))
4901       return None;
4902   }
4903 
4904   for (Value *V : VL) {
4905     ScheduleData *BundleMember = getScheduleData(V);
4906     assert(BundleMember &&
4907            "no ScheduleData for bundle member (maybe not in same basic block)");
4908     if (BundleMember->IsScheduled) {
4909       // A bundle member was scheduled as single instruction before and now
4910       // needs to be scheduled as part of the bundle. We just get rid of the
4911       // existing schedule.
4912       LLVM_DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
4913                         << " was already scheduled\n");
4914       ReSchedule = true;
4915     }
4916     assert(BundleMember->isSchedulingEntity() &&
4917            "bundle member already part of other bundle");
4918     if (PrevInBundle) {
4919       PrevInBundle->NextInBundle = BundleMember;
4920     } else {
4921       Bundle = BundleMember;
4922     }
4923     BundleMember->UnscheduledDepsInBundle = 0;
4924     Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps;
4925 
4926     // Group the instructions to a bundle.
4927     BundleMember->FirstInBundle = Bundle;
4928     PrevInBundle = BundleMember;
4929   }
4930   if (ScheduleEnd != OldScheduleEnd) {
4931     // The scheduling region got new instructions at the lower end (or it is a
4932     // new region for the first bundle). This makes it necessary to
4933     // recalculate all dependencies.
4934     // It is seldom that this needs to be done a second time after adding the
4935     // initial bundle to the region.
4936     for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
4937       doForAllOpcodes(I, [](ScheduleData *SD) {
4938         SD->clearDependencies();
4939       });
4940     }
4941     ReSchedule = true;
4942   }
4943   if (ReSchedule) {
4944     resetSchedule();
4945     initialFillReadyList(ReadyInsts);
4946   }
4947   assert(Bundle && "Failed to find schedule bundle");
4948 
4949   LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle << " in block "
4950                     << BB->getName() << "\n");
4951 
4952   calculateDependencies(Bundle, true, SLP);
4953 
4954   // Now try to schedule the new bundle. As soon as the bundle is "ready" it
4955   // means that there are no cyclic dependencies and we can schedule it.
4956   // Note that's important that we don't "schedule" the bundle yet (see
4957   // cancelScheduling).
4958   while (!Bundle->isReady() && !ReadyInsts.empty()) {
4959 
4960     ScheduleData *pickedSD = ReadyInsts.back();
4961     ReadyInsts.pop_back();
4962 
4963     if (pickedSD->isSchedulingEntity() && pickedSD->isReady()) {
4964       schedule(pickedSD, ReadyInsts);
4965     }
4966   }
4967   if (!Bundle->isReady()) {
4968     cancelScheduling(VL, S.OpValue);
4969     return None;
4970   }
4971   return Bundle;
4972 }
4973 
4974 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
4975                                                 Value *OpValue) {
4976   if (isa<PHINode>(OpValue))
4977     return;
4978 
4979   ScheduleData *Bundle = getScheduleData(OpValue);
4980   LLVM_DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
4981   assert(!Bundle->IsScheduled &&
4982          "Can't cancel bundle which is already scheduled");
4983   assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
4984          "tried to unbundle something which is not a bundle");
4985 
4986   // Un-bundle: make single instructions out of the bundle.
4987   ScheduleData *BundleMember = Bundle;
4988   while (BundleMember) {
4989     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
4990     BundleMember->FirstInBundle = BundleMember;
4991     ScheduleData *Next = BundleMember->NextInBundle;
4992     BundleMember->NextInBundle = nullptr;
4993     BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps;
4994     if (BundleMember->UnscheduledDepsInBundle == 0) {
4995       ReadyInsts.insert(BundleMember);
4996     }
4997     BundleMember = Next;
4998   }
4999 }
5000 
5001 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
5002   // Allocate a new ScheduleData for the instruction.
5003   if (ChunkPos >= ChunkSize) {
5004     ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
5005     ChunkPos = 0;
5006   }
5007   return &(ScheduleDataChunks.back()[ChunkPos++]);
5008 }
5009 
5010 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
5011                                                       const InstructionsState &S) {
5012   if (getScheduleData(V, isOneOf(S, V)))
5013     return true;
5014   Instruction *I = dyn_cast<Instruction>(V);
5015   assert(I && "bundle member must be an instruction");
5016   assert(!isa<PHINode>(I) && "phi nodes don't need to be scheduled");
5017   auto &&CheckSheduleForI = [this, &S](Instruction *I) -> bool {
5018     ScheduleData *ISD = getScheduleData(I);
5019     if (!ISD)
5020       return false;
5021     assert(isInSchedulingRegion(ISD) &&
5022            "ScheduleData not in scheduling region");
5023     ScheduleData *SD = allocateScheduleDataChunks();
5024     SD->Inst = I;
5025     SD->init(SchedulingRegionID, S.OpValue);
5026     ExtraScheduleDataMap[I][S.OpValue] = SD;
5027     return true;
5028   };
5029   if (CheckSheduleForI(I))
5030     return true;
5031   if (!ScheduleStart) {
5032     // It's the first instruction in the new region.
5033     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
5034     ScheduleStart = I;
5035     ScheduleEnd = I->getNextNode();
5036     if (isOneOf(S, I) != I)
5037       CheckSheduleForI(I);
5038     assert(ScheduleEnd && "tried to vectorize a terminator?");
5039     LLVM_DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
5040     return true;
5041   }
5042   // Search up and down at the same time, because we don't know if the new
5043   // instruction is above or below the existing scheduling region.
5044   BasicBlock::reverse_iterator UpIter =
5045       ++ScheduleStart->getIterator().getReverse();
5046   BasicBlock::reverse_iterator UpperEnd = BB->rend();
5047   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
5048   BasicBlock::iterator LowerEnd = BB->end();
5049   while (true) {
5050     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
5051       LLVM_DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
5052       return false;
5053     }
5054 
5055     if (UpIter != UpperEnd) {
5056       if (&*UpIter == I) {
5057         initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
5058         ScheduleStart = I;
5059         if (isOneOf(S, I) != I)
5060           CheckSheduleForI(I);
5061         LLVM_DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I
5062                           << "\n");
5063         return true;
5064       }
5065       ++UpIter;
5066     }
5067     if (DownIter != LowerEnd) {
5068       if (&*DownIter == I) {
5069         initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
5070                          nullptr);
5071         ScheduleEnd = I->getNextNode();
5072         if (isOneOf(S, I) != I)
5073           CheckSheduleForI(I);
5074         assert(ScheduleEnd && "tried to vectorize a terminator?");
5075         LLVM_DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I
5076                           << "\n");
5077         return true;
5078       }
5079       ++DownIter;
5080     }
5081     assert((UpIter != UpperEnd || DownIter != LowerEnd) &&
5082            "instruction not found in block");
5083   }
5084   return true;
5085 }
5086 
5087 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
5088                                                 Instruction *ToI,
5089                                                 ScheduleData *PrevLoadStore,
5090                                                 ScheduleData *NextLoadStore) {
5091   ScheduleData *CurrentLoadStore = PrevLoadStore;
5092   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
5093     ScheduleData *SD = ScheduleDataMap[I];
5094     if (!SD) {
5095       SD = allocateScheduleDataChunks();
5096       ScheduleDataMap[I] = SD;
5097       SD->Inst = I;
5098     }
5099     assert(!isInSchedulingRegion(SD) &&
5100            "new ScheduleData already in scheduling region");
5101     SD->init(SchedulingRegionID, I);
5102 
5103     if (I->mayReadOrWriteMemory() &&
5104         (!isa<IntrinsicInst>(I) ||
5105          cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect)) {
5106       // Update the linked list of memory accessing instructions.
5107       if (CurrentLoadStore) {
5108         CurrentLoadStore->NextLoadStore = SD;
5109       } else {
5110         FirstLoadStoreInRegion = SD;
5111       }
5112       CurrentLoadStore = SD;
5113     }
5114   }
5115   if (NextLoadStore) {
5116     if (CurrentLoadStore)
5117       CurrentLoadStore->NextLoadStore = NextLoadStore;
5118   } else {
5119     LastLoadStoreInRegion = CurrentLoadStore;
5120   }
5121 }
5122 
5123 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
5124                                                      bool InsertInReadyList,
5125                                                      BoUpSLP *SLP) {
5126   assert(SD->isSchedulingEntity());
5127 
5128   SmallVector<ScheduleData *, 10> WorkList;
5129   WorkList.push_back(SD);
5130 
5131   while (!WorkList.empty()) {
5132     ScheduleData *SD = WorkList.back();
5133     WorkList.pop_back();
5134 
5135     ScheduleData *BundleMember = SD;
5136     while (BundleMember) {
5137       assert(isInSchedulingRegion(BundleMember));
5138       if (!BundleMember->hasValidDependencies()) {
5139 
5140         LLVM_DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember
5141                           << "\n");
5142         BundleMember->Dependencies = 0;
5143         BundleMember->resetUnscheduledDeps();
5144 
5145         // Handle def-use chain dependencies.
5146         if (BundleMember->OpValue != BundleMember->Inst) {
5147           ScheduleData *UseSD = getScheduleData(BundleMember->Inst);
5148           if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
5149             BundleMember->Dependencies++;
5150             ScheduleData *DestBundle = UseSD->FirstInBundle;
5151             if (!DestBundle->IsScheduled)
5152               BundleMember->incrementUnscheduledDeps(1);
5153             if (!DestBundle->hasValidDependencies())
5154               WorkList.push_back(DestBundle);
5155           }
5156         } else {
5157           for (User *U : BundleMember->Inst->users()) {
5158             if (isa<Instruction>(U)) {
5159               ScheduleData *UseSD = getScheduleData(U);
5160               if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
5161                 BundleMember->Dependencies++;
5162                 ScheduleData *DestBundle = UseSD->FirstInBundle;
5163                 if (!DestBundle->IsScheduled)
5164                   BundleMember->incrementUnscheduledDeps(1);
5165                 if (!DestBundle->hasValidDependencies())
5166                   WorkList.push_back(DestBundle);
5167               }
5168             } else {
5169               // I'm not sure if this can ever happen. But we need to be safe.
5170               // This lets the instruction/bundle never be scheduled and
5171               // eventually disable vectorization.
5172               BundleMember->Dependencies++;
5173               BundleMember->incrementUnscheduledDeps(1);
5174             }
5175           }
5176         }
5177 
5178         // Handle the memory dependencies.
5179         ScheduleData *DepDest = BundleMember->NextLoadStore;
5180         if (DepDest) {
5181           Instruction *SrcInst = BundleMember->Inst;
5182           MemoryLocation SrcLoc = getLocation(SrcInst, SLP->AA);
5183           bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
5184           unsigned numAliased = 0;
5185           unsigned DistToSrc = 1;
5186 
5187           while (DepDest) {
5188             assert(isInSchedulingRegion(DepDest));
5189 
5190             // We have two limits to reduce the complexity:
5191             // 1) AliasedCheckLimit: It's a small limit to reduce calls to
5192             //    SLP->isAliased (which is the expensive part in this loop).
5193             // 2) MaxMemDepDistance: It's for very large blocks and it aborts
5194             //    the whole loop (even if the loop is fast, it's quadratic).
5195             //    It's important for the loop break condition (see below) to
5196             //    check this limit even between two read-only instructions.
5197             if (DistToSrc >= MaxMemDepDistance ||
5198                     ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
5199                      (numAliased >= AliasedCheckLimit ||
5200                       SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
5201 
5202               // We increment the counter only if the locations are aliased
5203               // (instead of counting all alias checks). This gives a better
5204               // balance between reduced runtime and accurate dependencies.
5205               numAliased++;
5206 
5207               DepDest->MemoryDependencies.push_back(BundleMember);
5208               BundleMember->Dependencies++;
5209               ScheduleData *DestBundle = DepDest->FirstInBundle;
5210               if (!DestBundle->IsScheduled) {
5211                 BundleMember->incrementUnscheduledDeps(1);
5212               }
5213               if (!DestBundle->hasValidDependencies()) {
5214                 WorkList.push_back(DestBundle);
5215               }
5216             }
5217             DepDest = DepDest->NextLoadStore;
5218 
5219             // Example, explaining the loop break condition: Let's assume our
5220             // starting instruction is i0 and MaxMemDepDistance = 3.
5221             //
5222             //                      +--------v--v--v
5223             //             i0,i1,i2,i3,i4,i5,i6,i7,i8
5224             //             +--------^--^--^
5225             //
5226             // MaxMemDepDistance let us stop alias-checking at i3 and we add
5227             // dependencies from i0 to i3,i4,.. (even if they are not aliased).
5228             // Previously we already added dependencies from i3 to i6,i7,i8
5229             // (because of MaxMemDepDistance). As we added a dependency from
5230             // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
5231             // and we can abort this loop at i6.
5232             if (DistToSrc >= 2 * MaxMemDepDistance)
5233               break;
5234             DistToSrc++;
5235           }
5236         }
5237       }
5238       BundleMember = BundleMember->NextInBundle;
5239     }
5240     if (InsertInReadyList && SD->isReady()) {
5241       ReadyInsts.push_back(SD);
5242       LLVM_DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst
5243                         << "\n");
5244     }
5245   }
5246 }
5247 
5248 void BoUpSLP::BlockScheduling::resetSchedule() {
5249   assert(ScheduleStart &&
5250          "tried to reset schedule on block which has not been scheduled");
5251   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
5252     doForAllOpcodes(I, [&](ScheduleData *SD) {
5253       assert(isInSchedulingRegion(SD) &&
5254              "ScheduleData not in scheduling region");
5255       SD->IsScheduled = false;
5256       SD->resetUnscheduledDeps();
5257     });
5258   }
5259   ReadyInsts.clear();
5260 }
5261 
5262 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
5263   if (!BS->ScheduleStart)
5264     return;
5265 
5266   LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
5267 
5268   BS->resetSchedule();
5269 
5270   // For the real scheduling we use a more sophisticated ready-list: it is
5271   // sorted by the original instruction location. This lets the final schedule
5272   // be as  close as possible to the original instruction order.
5273   struct ScheduleDataCompare {
5274     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
5275       return SD2->SchedulingPriority < SD1->SchedulingPriority;
5276     }
5277   };
5278   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
5279 
5280   // Ensure that all dependency data is updated and fill the ready-list with
5281   // initial instructions.
5282   int Idx = 0;
5283   int NumToSchedule = 0;
5284   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
5285        I = I->getNextNode()) {
5286     BS->doForAllOpcodes(I, [this, &Idx, &NumToSchedule, BS](ScheduleData *SD) {
5287       assert(SD->isPartOfBundle() ==
5288                  (getTreeEntry(SD->Inst) != nullptr) &&
5289              "scheduler and vectorizer bundle mismatch");
5290       SD->FirstInBundle->SchedulingPriority = Idx++;
5291       if (SD->isSchedulingEntity()) {
5292         BS->calculateDependencies(SD, false, this);
5293         NumToSchedule++;
5294       }
5295     });
5296   }
5297   BS->initialFillReadyList(ReadyInsts);
5298 
5299   Instruction *LastScheduledInst = BS->ScheduleEnd;
5300 
5301   // Do the "real" scheduling.
5302   while (!ReadyInsts.empty()) {
5303     ScheduleData *picked = *ReadyInsts.begin();
5304     ReadyInsts.erase(ReadyInsts.begin());
5305 
5306     // Move the scheduled instruction(s) to their dedicated places, if not
5307     // there yet.
5308     ScheduleData *BundleMember = picked;
5309     while (BundleMember) {
5310       Instruction *pickedInst = BundleMember->Inst;
5311       if (LastScheduledInst->getNextNode() != pickedInst) {
5312         BS->BB->getInstList().remove(pickedInst);
5313         BS->BB->getInstList().insert(LastScheduledInst->getIterator(),
5314                                      pickedInst);
5315       }
5316       LastScheduledInst = pickedInst;
5317       BundleMember = BundleMember->NextInBundle;
5318     }
5319 
5320     BS->schedule(picked, ReadyInsts);
5321     NumToSchedule--;
5322   }
5323   assert(NumToSchedule == 0 && "could not schedule all instructions");
5324 
5325   // Avoid duplicate scheduling of the block.
5326   BS->ScheduleStart = nullptr;
5327 }
5328 
5329 unsigned BoUpSLP::getVectorElementSize(Value *V) {
5330   // If V is a store, just return the width of the stored value without
5331   // traversing the expression tree. This is the common case.
5332   if (auto *Store = dyn_cast<StoreInst>(V))
5333     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
5334 
5335   auto E = InstrElementSize.find(V);
5336   if (E != InstrElementSize.end())
5337     return E->second;
5338 
5339   // If V is not a store, we can traverse the expression tree to find loads
5340   // that feed it. The type of the loaded value may indicate a more suitable
5341   // width than V's type. We want to base the vector element size on the width
5342   // of memory operations where possible.
5343   SmallVector<Instruction *, 16> Worklist;
5344   SmallPtrSet<Instruction *, 16> Visited;
5345   if (auto *I = dyn_cast<Instruction>(V)) {
5346     Worklist.push_back(I);
5347     Visited.insert(I);
5348   }
5349 
5350   // Traverse the expression tree in bottom-up order looking for loads. If we
5351   // encounter an instruction we don't yet handle, we give up.
5352   auto MaxWidth = 0u;
5353   auto FoundUnknownInst = false;
5354   while (!Worklist.empty() && !FoundUnknownInst) {
5355     auto *I = Worklist.pop_back_val();
5356 
5357     // We should only be looking at scalar instructions here. If the current
5358     // instruction has a vector type, give up.
5359     auto *Ty = I->getType();
5360     if (isa<VectorType>(Ty))
5361       FoundUnknownInst = true;
5362 
5363     // If the current instruction is a load, update MaxWidth to reflect the
5364     // width of the loaded value.
5365     else if (isa<LoadInst>(I))
5366       MaxWidth = std::max<unsigned>(MaxWidth, DL->getTypeSizeInBits(Ty));
5367 
5368     // Otherwise, we need to visit the operands of the instruction. We only
5369     // handle the interesting cases from buildTree here. If an operand is an
5370     // instruction we haven't yet visited, we add it to the worklist.
5371     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
5372              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I)) {
5373       for (Use &U : I->operands())
5374         if (auto *J = dyn_cast<Instruction>(U.get()))
5375           if (Visited.insert(J).second)
5376             Worklist.push_back(J);
5377     }
5378 
5379     // If we don't yet handle the instruction, give up.
5380     else
5381       FoundUnknownInst = true;
5382   }
5383 
5384   int Width = MaxWidth;
5385   // If we didn't encounter a memory access in the expression tree, or if we
5386   // gave up for some reason, just return the width of V. Otherwise, return the
5387   // maximum width we found.
5388   if (!MaxWidth || FoundUnknownInst)
5389     Width = DL->getTypeSizeInBits(V->getType());
5390 
5391   for (Instruction *I : Visited)
5392     InstrElementSize[I] = Width;
5393 
5394   return Width;
5395 }
5396 
5397 // Determine if a value V in a vectorizable expression Expr can be demoted to a
5398 // smaller type with a truncation. We collect the values that will be demoted
5399 // in ToDemote and additional roots that require investigating in Roots.
5400 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
5401                                   SmallVectorImpl<Value *> &ToDemote,
5402                                   SmallVectorImpl<Value *> &Roots) {
5403   // We can always demote constants.
5404   if (isa<Constant>(V)) {
5405     ToDemote.push_back(V);
5406     return true;
5407   }
5408 
5409   // If the value is not an instruction in the expression with only one use, it
5410   // cannot be demoted.
5411   auto *I = dyn_cast<Instruction>(V);
5412   if (!I || !I->hasOneUse() || !Expr.count(I))
5413     return false;
5414 
5415   switch (I->getOpcode()) {
5416 
5417   // We can always demote truncations and extensions. Since truncations can
5418   // seed additional demotion, we save the truncated value.
5419   case Instruction::Trunc:
5420     Roots.push_back(I->getOperand(0));
5421     break;
5422   case Instruction::ZExt:
5423   case Instruction::SExt:
5424     break;
5425 
5426   // We can demote certain binary operations if we can demote both of their
5427   // operands.
5428   case Instruction::Add:
5429   case Instruction::Sub:
5430   case Instruction::Mul:
5431   case Instruction::And:
5432   case Instruction::Or:
5433   case Instruction::Xor:
5434     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
5435         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
5436       return false;
5437     break;
5438 
5439   // We can demote selects if we can demote their true and false values.
5440   case Instruction::Select: {
5441     SelectInst *SI = cast<SelectInst>(I);
5442     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
5443         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
5444       return false;
5445     break;
5446   }
5447 
5448   // We can demote phis if we can demote all their incoming operands. Note that
5449   // we don't need to worry about cycles since we ensure single use above.
5450   case Instruction::PHI: {
5451     PHINode *PN = cast<PHINode>(I);
5452     for (Value *IncValue : PN->incoming_values())
5453       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
5454         return false;
5455     break;
5456   }
5457 
5458   // Otherwise, conservatively give up.
5459   default:
5460     return false;
5461   }
5462 
5463   // Record the value that we can demote.
5464   ToDemote.push_back(V);
5465   return true;
5466 }
5467 
5468 void BoUpSLP::computeMinimumValueSizes() {
5469   // If there are no external uses, the expression tree must be rooted by a
5470   // store. We can't demote in-memory values, so there is nothing to do here.
5471   if (ExternalUses.empty())
5472     return;
5473 
5474   // We only attempt to truncate integer expressions.
5475   auto &TreeRoot = VectorizableTree[0]->Scalars;
5476   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
5477   if (!TreeRootIT)
5478     return;
5479 
5480   // If the expression is not rooted by a store, these roots should have
5481   // external uses. We will rely on InstCombine to rewrite the expression in
5482   // the narrower type. However, InstCombine only rewrites single-use values.
5483   // This means that if a tree entry other than a root is used externally, it
5484   // must have multiple uses and InstCombine will not rewrite it. The code
5485   // below ensures that only the roots are used externally.
5486   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
5487   for (auto &EU : ExternalUses)
5488     if (!Expr.erase(EU.Scalar))
5489       return;
5490   if (!Expr.empty())
5491     return;
5492 
5493   // Collect the scalar values of the vectorizable expression. We will use this
5494   // context to determine which values can be demoted. If we see a truncation,
5495   // we mark it as seeding another demotion.
5496   for (auto &EntryPtr : VectorizableTree)
5497     Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
5498 
5499   // Ensure the roots of the vectorizable tree don't form a cycle. They must
5500   // have a single external user that is not in the vectorizable tree.
5501   for (auto *Root : TreeRoot)
5502     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
5503       return;
5504 
5505   // Conservatively determine if we can actually truncate the roots of the
5506   // expression. Collect the values that can be demoted in ToDemote and
5507   // additional roots that require investigating in Roots.
5508   SmallVector<Value *, 32> ToDemote;
5509   SmallVector<Value *, 4> Roots;
5510   for (auto *Root : TreeRoot)
5511     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
5512       return;
5513 
5514   // The maximum bit width required to represent all the values that can be
5515   // demoted without loss of precision. It would be safe to truncate the roots
5516   // of the expression to this width.
5517   auto MaxBitWidth = 8u;
5518 
5519   // We first check if all the bits of the roots are demanded. If they're not,
5520   // we can truncate the roots to this narrower type.
5521   for (auto *Root : TreeRoot) {
5522     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
5523     MaxBitWidth = std::max<unsigned>(
5524         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
5525   }
5526 
5527   // True if the roots can be zero-extended back to their original type, rather
5528   // than sign-extended. We know that if the leading bits are not demanded, we
5529   // can safely zero-extend. So we initialize IsKnownPositive to True.
5530   bool IsKnownPositive = true;
5531 
5532   // If all the bits of the roots are demanded, we can try a little harder to
5533   // compute a narrower type. This can happen, for example, if the roots are
5534   // getelementptr indices. InstCombine promotes these indices to the pointer
5535   // width. Thus, all their bits are technically demanded even though the
5536   // address computation might be vectorized in a smaller type.
5537   //
5538   // We start by looking at each entry that can be demoted. We compute the
5539   // maximum bit width required to store the scalar by using ValueTracking to
5540   // compute the number of high-order bits we can truncate.
5541   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
5542       llvm::all_of(TreeRoot, [](Value *R) {
5543         assert(R->hasOneUse() && "Root should have only one use!");
5544         return isa<GetElementPtrInst>(R->user_back());
5545       })) {
5546     MaxBitWidth = 8u;
5547 
5548     // Determine if the sign bit of all the roots is known to be zero. If not,
5549     // IsKnownPositive is set to False.
5550     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
5551       KnownBits Known = computeKnownBits(R, *DL);
5552       return Known.isNonNegative();
5553     });
5554 
5555     // Determine the maximum number of bits required to store the scalar
5556     // values.
5557     for (auto *Scalar : ToDemote) {
5558       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
5559       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
5560       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
5561     }
5562 
5563     // If we can't prove that the sign bit is zero, we must add one to the
5564     // maximum bit width to account for the unknown sign bit. This preserves
5565     // the existing sign bit so we can safely sign-extend the root back to the
5566     // original type. Otherwise, if we know the sign bit is zero, we will
5567     // zero-extend the root instead.
5568     //
5569     // FIXME: This is somewhat suboptimal, as there will be cases where adding
5570     //        one to the maximum bit width will yield a larger-than-necessary
5571     //        type. In general, we need to add an extra bit only if we can't
5572     //        prove that the upper bit of the original type is equal to the
5573     //        upper bit of the proposed smaller type. If these two bits are the
5574     //        same (either zero or one) we know that sign-extending from the
5575     //        smaller type will result in the same value. Here, since we can't
5576     //        yet prove this, we are just making the proposed smaller type
5577     //        larger to ensure correctness.
5578     if (!IsKnownPositive)
5579       ++MaxBitWidth;
5580   }
5581 
5582   // Round MaxBitWidth up to the next power-of-two.
5583   if (!isPowerOf2_64(MaxBitWidth))
5584     MaxBitWidth = NextPowerOf2(MaxBitWidth);
5585 
5586   // If the maximum bit width we compute is less than the with of the roots'
5587   // type, we can proceed with the narrowing. Otherwise, do nothing.
5588   if (MaxBitWidth >= TreeRootIT->getBitWidth())
5589     return;
5590 
5591   // If we can truncate the root, we must collect additional values that might
5592   // be demoted as a result. That is, those seeded by truncations we will
5593   // modify.
5594   while (!Roots.empty())
5595     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
5596 
5597   // Finally, map the values we can demote to the maximum bit with we computed.
5598   for (auto *Scalar : ToDemote)
5599     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
5600 }
5601 
5602 namespace {
5603 
5604 /// The SLPVectorizer Pass.
5605 struct SLPVectorizer : public FunctionPass {
5606   SLPVectorizerPass Impl;
5607 
5608   /// Pass identification, replacement for typeid
5609   static char ID;
5610 
5611   explicit SLPVectorizer() : FunctionPass(ID) {
5612     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
5613   }
5614 
5615   bool doInitialization(Module &M) override {
5616     return false;
5617   }
5618 
5619   bool runOnFunction(Function &F) override {
5620     if (skipFunction(F))
5621       return false;
5622 
5623     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
5624     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
5625     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
5626     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
5627     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
5628     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
5629     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
5630     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
5631     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
5632     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
5633 
5634     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
5635   }
5636 
5637   void getAnalysisUsage(AnalysisUsage &AU) const override {
5638     FunctionPass::getAnalysisUsage(AU);
5639     AU.addRequired<AssumptionCacheTracker>();
5640     AU.addRequired<ScalarEvolutionWrapperPass>();
5641     AU.addRequired<AAResultsWrapperPass>();
5642     AU.addRequired<TargetTransformInfoWrapperPass>();
5643     AU.addRequired<LoopInfoWrapperPass>();
5644     AU.addRequired<DominatorTreeWrapperPass>();
5645     AU.addRequired<DemandedBitsWrapperPass>();
5646     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
5647     AU.addRequired<InjectTLIMappingsLegacy>();
5648     AU.addPreserved<LoopInfoWrapperPass>();
5649     AU.addPreserved<DominatorTreeWrapperPass>();
5650     AU.addPreserved<AAResultsWrapperPass>();
5651     AU.addPreserved<GlobalsAAWrapperPass>();
5652     AU.setPreservesCFG();
5653   }
5654 };
5655 
5656 } // end anonymous namespace
5657 
5658 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
5659   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
5660   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
5661   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
5662   auto *AA = &AM.getResult<AAManager>(F);
5663   auto *LI = &AM.getResult<LoopAnalysis>(F);
5664   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
5665   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
5666   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
5667   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
5668 
5669   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
5670   if (!Changed)
5671     return PreservedAnalyses::all();
5672 
5673   PreservedAnalyses PA;
5674   PA.preserveSet<CFGAnalyses>();
5675   PA.preserve<AAManager>();
5676   PA.preserve<GlobalsAA>();
5677   return PA;
5678 }
5679 
5680 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
5681                                 TargetTransformInfo *TTI_,
5682                                 TargetLibraryInfo *TLI_, AliasAnalysis *AA_,
5683                                 LoopInfo *LI_, DominatorTree *DT_,
5684                                 AssumptionCache *AC_, DemandedBits *DB_,
5685                                 OptimizationRemarkEmitter *ORE_) {
5686   if (!RunSLPVectorization)
5687     return false;
5688   SE = SE_;
5689   TTI = TTI_;
5690   TLI = TLI_;
5691   AA = AA_;
5692   LI = LI_;
5693   DT = DT_;
5694   AC = AC_;
5695   DB = DB_;
5696   DL = &F.getParent()->getDataLayout();
5697 
5698   Stores.clear();
5699   GEPs.clear();
5700   bool Changed = false;
5701 
5702   // If the target claims to have no vector registers don't attempt
5703   // vectorization.
5704   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true)))
5705     return false;
5706 
5707   // Don't vectorize when the attribute NoImplicitFloat is used.
5708   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
5709     return false;
5710 
5711   LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
5712 
5713   // Use the bottom up slp vectorizer to construct chains that start with
5714   // store instructions.
5715   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
5716 
5717   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
5718   // delete instructions.
5719 
5720   // Scan the blocks in the function in post order.
5721   for (auto BB : post_order(&F.getEntryBlock())) {
5722     collectSeedInstructions(BB);
5723 
5724     // Vectorize trees that end at stores.
5725     if (!Stores.empty()) {
5726       LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
5727                         << " underlying objects.\n");
5728       Changed |= vectorizeStoreChains(R);
5729     }
5730 
5731     // Vectorize trees that end at reductions.
5732     Changed |= vectorizeChainsInBlock(BB, R);
5733 
5734     // Vectorize the index computations of getelementptr instructions. This
5735     // is primarily intended to catch gather-like idioms ending at
5736     // non-consecutive loads.
5737     if (!GEPs.empty()) {
5738       LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
5739                         << " underlying objects.\n");
5740       Changed |= vectorizeGEPIndices(BB, R);
5741     }
5742   }
5743 
5744   if (Changed) {
5745     R.optimizeGatherSequence();
5746     LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
5747   }
5748   return Changed;
5749 }
5750 
5751 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
5752                                             unsigned Idx) {
5753   LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()
5754                     << "\n");
5755   const unsigned Sz = R.getVectorElementSize(Chain[0]);
5756   const unsigned MinVF = R.getMinVecRegSize() / Sz;
5757   unsigned VF = Chain.size();
5758 
5759   if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
5760     return false;
5761 
5762   LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx
5763                     << "\n");
5764 
5765   R.buildTree(Chain);
5766   Optional<ArrayRef<unsigned>> Order = R.bestOrder();
5767   // TODO: Handle orders of size less than number of elements in the vector.
5768   if (Order && Order->size() == Chain.size()) {
5769     // TODO: reorder tree nodes without tree rebuilding.
5770     SmallVector<Value *, 4> ReorderedOps(Chain.rbegin(), Chain.rend());
5771     llvm::transform(*Order, ReorderedOps.begin(),
5772                     [Chain](const unsigned Idx) { return Chain[Idx]; });
5773     R.buildTree(ReorderedOps);
5774   }
5775   if (R.isTreeTinyAndNotFullyVectorizable())
5776     return false;
5777   if (R.isLoadCombineCandidate())
5778     return false;
5779 
5780   R.computeMinimumValueSizes();
5781 
5782   int Cost = R.getTreeCost();
5783 
5784   LLVM_DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
5785   if (Cost < -SLPCostThreshold) {
5786     LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
5787 
5788     using namespace ore;
5789 
5790     R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
5791                                         cast<StoreInst>(Chain[0]))
5792                      << "Stores SLP vectorized with cost " << NV("Cost", Cost)
5793                      << " and with tree size "
5794                      << NV("TreeSize", R.getTreeSize()));
5795 
5796     R.vectorizeTree();
5797     return true;
5798   }
5799 
5800   return false;
5801 }
5802 
5803 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
5804                                         BoUpSLP &R) {
5805   // We may run into multiple chains that merge into a single chain. We mark the
5806   // stores that we vectorized so that we don't visit the same store twice.
5807   BoUpSLP::ValueSet VectorizedStores;
5808   bool Changed = false;
5809 
5810   int E = Stores.size();
5811   SmallBitVector Tails(E, false);
5812   SmallVector<int, 16> ConsecutiveChain(E, E + 1);
5813   int MaxIter = MaxStoreLookup.getValue();
5814   int IterCnt;
5815   auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
5816                                   &ConsecutiveChain](int K, int Idx) {
5817     if (IterCnt >= MaxIter)
5818       return true;
5819     ++IterCnt;
5820     if (!isConsecutiveAccess(Stores[K], Stores[Idx], *DL, *SE))
5821       return false;
5822 
5823     Tails.set(Idx);
5824     ConsecutiveChain[K] = Idx;
5825     return true;
5826   };
5827   // Do a quadratic search on all of the given stores in reverse order and find
5828   // all of the pairs of stores that follow each other.
5829   for (int Idx = E - 1; Idx >= 0; --Idx) {
5830     // If a store has multiple consecutive store candidates, search according
5831     // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
5832     // This is because usually pairing with immediate succeeding or preceding
5833     // candidate create the best chance to find slp vectorization opportunity.
5834     const int MaxLookDepth = std::max(E - Idx, Idx + 1);
5835     IterCnt = 0;
5836     for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
5837       if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
5838           (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
5839         break;
5840   }
5841 
5842   // For stores that start but don't end a link in the chain:
5843   for (int Cnt = E; Cnt > 0; --Cnt) {
5844     int I = Cnt - 1;
5845     if (ConsecutiveChain[I] == E + 1 || Tails.test(I))
5846       continue;
5847     // We found a store instr that starts a chain. Now follow the chain and try
5848     // to vectorize it.
5849     BoUpSLP::ValueList Operands;
5850     // Collect the chain into a list.
5851     while (I != E + 1 && !VectorizedStores.count(Stores[I])) {
5852       Operands.push_back(Stores[I]);
5853       // Move to the next value in the chain.
5854       I = ConsecutiveChain[I];
5855     }
5856 
5857     // If a vector register can't hold 1 element, we are done.
5858     unsigned MaxVecRegSize = R.getMaxVecRegSize();
5859     unsigned EltSize = R.getVectorElementSize(Stores[0]);
5860     if (MaxVecRegSize % EltSize != 0)
5861       continue;
5862 
5863     unsigned MaxElts = MaxVecRegSize / EltSize;
5864     // FIXME: Is division-by-2 the correct step? Should we assert that the
5865     // register size is a power-of-2?
5866     unsigned StartIdx = 0;
5867     for (unsigned Size = llvm::PowerOf2Ceil(MaxElts); Size >= 2; Size /= 2) {
5868       for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
5869         ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size);
5870         if (!VectorizedStores.count(Slice.front()) &&
5871             !VectorizedStores.count(Slice.back()) &&
5872             vectorizeStoreChain(Slice, R, Cnt)) {
5873           // Mark the vectorized stores so that we don't vectorize them again.
5874           VectorizedStores.insert(Slice.begin(), Slice.end());
5875           Changed = true;
5876           // If we vectorized initial block, no need to try to vectorize it
5877           // again.
5878           if (Cnt == StartIdx)
5879             StartIdx += Size;
5880           Cnt += Size;
5881           continue;
5882         }
5883         ++Cnt;
5884       }
5885       // Check if the whole array was vectorized already - exit.
5886       if (StartIdx >= Operands.size())
5887         break;
5888     }
5889   }
5890 
5891   return Changed;
5892 }
5893 
5894 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
5895   // Initialize the collections. We will make a single pass over the block.
5896   Stores.clear();
5897   GEPs.clear();
5898 
5899   // Visit the store and getelementptr instructions in BB and organize them in
5900   // Stores and GEPs according to the underlying objects of their pointer
5901   // operands.
5902   for (Instruction &I : *BB) {
5903     // Ignore store instructions that are volatile or have a pointer operand
5904     // that doesn't point to a scalar type.
5905     if (auto *SI = dyn_cast<StoreInst>(&I)) {
5906       if (!SI->isSimple())
5907         continue;
5908       if (!isValidElementType(SI->getValueOperand()->getType()))
5909         continue;
5910       Stores[GetUnderlyingObject(SI->getPointerOperand(), *DL)].push_back(SI);
5911     }
5912 
5913     // Ignore getelementptr instructions that have more than one index, a
5914     // constant index, or a pointer operand that doesn't point to a scalar
5915     // type.
5916     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
5917       auto Idx = GEP->idx_begin()->get();
5918       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
5919         continue;
5920       if (!isValidElementType(Idx->getType()))
5921         continue;
5922       if (GEP->getType()->isVectorTy())
5923         continue;
5924       GEPs[GEP->getPointerOperand()].push_back(GEP);
5925     }
5926   }
5927 }
5928 
5929 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
5930   if (!A || !B)
5931     return false;
5932   Value *VL[] = {A, B};
5933   return tryToVectorizeList(VL, R, /*AllowReorder=*/true);
5934 }
5935 
5936 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
5937                                            bool AllowReorder,
5938                                            ArrayRef<Value *> InsertUses) {
5939   if (VL.size() < 2)
5940     return false;
5941 
5942   LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
5943                     << VL.size() << ".\n");
5944 
5945   // Check that all of the parts are instructions of the same type,
5946   // we permit an alternate opcode via InstructionsState.
5947   InstructionsState S = getSameOpcode(VL);
5948   if (!S.getOpcode())
5949     return false;
5950 
5951   Instruction *I0 = cast<Instruction>(S.OpValue);
5952   // Make sure invalid types (including vector type) are rejected before
5953   // determining vectorization factor for scalar instructions.
5954   for (Value *V : VL) {
5955     Type *Ty = V->getType();
5956     if (!isValidElementType(Ty)) {
5957       // NOTE: the following will give user internal llvm type name, which may
5958       // not be useful.
5959       R.getORE()->emit([&]() {
5960         std::string type_str;
5961         llvm::raw_string_ostream rso(type_str);
5962         Ty->print(rso);
5963         return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
5964                << "Cannot SLP vectorize list: type "
5965                << rso.str() + " is unsupported by vectorizer";
5966       });
5967       return false;
5968     }
5969   }
5970 
5971   unsigned Sz = R.getVectorElementSize(I0);
5972   unsigned MinVF = std::max(2U, R.getMinVecRegSize() / Sz);
5973   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
5974   if (MaxVF < 2) {
5975     R.getORE()->emit([&]() {
5976       return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
5977              << "Cannot SLP vectorize list: vectorization factor "
5978              << "less than 2 is not supported";
5979     });
5980     return false;
5981   }
5982 
5983   bool Changed = false;
5984   bool CandidateFound = false;
5985   int MinCost = SLPCostThreshold;
5986 
5987   bool CompensateUseCost =
5988       !InsertUses.empty() && llvm::all_of(InsertUses, [](const Value *V) {
5989         return V && isa<InsertElementInst>(V);
5990       });
5991   assert((!CompensateUseCost || InsertUses.size() == VL.size()) &&
5992          "Each scalar expected to have an associated InsertElement user.");
5993 
5994   unsigned NextInst = 0, MaxInst = VL.size();
5995   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
5996     // No actual vectorization should happen, if number of parts is the same as
5997     // provided vectorization factor (i.e. the scalar type is used for vector
5998     // code during codegen).
5999     auto *VecTy = FixedVectorType::get(VL[0]->getType(), VF);
6000     if (TTI->getNumberOfParts(VecTy) == VF)
6001       continue;
6002     for (unsigned I = NextInst; I < MaxInst; ++I) {
6003       unsigned OpsWidth = 0;
6004 
6005       if (I + VF > MaxInst)
6006         OpsWidth = MaxInst - I;
6007       else
6008         OpsWidth = VF;
6009 
6010       if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
6011         break;
6012 
6013       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
6014       // Check that a previous iteration of this loop did not delete the Value.
6015       if (llvm::any_of(Ops, [&R](Value *V) {
6016             auto *I = dyn_cast<Instruction>(V);
6017             return I && R.isDeleted(I);
6018           }))
6019         continue;
6020 
6021       LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
6022                         << "\n");
6023 
6024       R.buildTree(Ops);
6025       Optional<ArrayRef<unsigned>> Order = R.bestOrder();
6026       // TODO: check if we can allow reordering for more cases.
6027       if (AllowReorder && Order) {
6028         // TODO: reorder tree nodes without tree rebuilding.
6029         // Conceptually, there is nothing actually preventing us from trying to
6030         // reorder a larger list. In fact, we do exactly this when vectorizing
6031         // reductions. However, at this point, we only expect to get here when
6032         // there are exactly two operations.
6033         assert(Ops.size() == 2);
6034         Value *ReorderedOps[] = {Ops[1], Ops[0]};
6035         R.buildTree(ReorderedOps, None);
6036       }
6037       if (R.isTreeTinyAndNotFullyVectorizable())
6038         continue;
6039 
6040       R.computeMinimumValueSizes();
6041       int Cost = R.getTreeCost();
6042       CandidateFound = true;
6043       if (CompensateUseCost) {
6044         // TODO: Use TTI's getScalarizationOverhead for sequence of inserts
6045         // rather than sum of single inserts as the latter may overestimate
6046         // cost. This work should imply improving cost estimation for extracts
6047         // that added in for external (for vectorization tree) users,i.e. that
6048         // part should also switch to same interface.
6049         // For example, the following case is projected code after SLP:
6050         //  %4 = extractelement <4 x i64> %3, i32 0
6051         //  %v0 = insertelement <4 x i64> undef, i64 %4, i32 0
6052         //  %5 = extractelement <4 x i64> %3, i32 1
6053         //  %v1 = insertelement <4 x i64> %v0, i64 %5, i32 1
6054         //  %6 = extractelement <4 x i64> %3, i32 2
6055         //  %v2 = insertelement <4 x i64> %v1, i64 %6, i32 2
6056         //  %7 = extractelement <4 x i64> %3, i32 3
6057         //  %v3 = insertelement <4 x i64> %v2, i64 %7, i32 3
6058         //
6059         // Extracts here added by SLP in order to feed users (the inserts) of
6060         // original scalars and contribute to "ExtractCost" at cost evaluation.
6061         // The inserts in turn form sequence to build an aggregate that
6062         // detected by findBuildAggregate routine.
6063         // SLP makes an assumption that such sequence will be optimized away
6064         // later (instcombine) so it tries to compensate ExctractCost with
6065         // cost of insert sequence.
6066         // Current per element cost calculation approach is not quite accurate
6067         // and tends to create bias toward favoring vectorization.
6068         // Switching to the TTI interface might help a bit.
6069         // Alternative solution could be pattern-match to detect a no-op or
6070         // shuffle.
6071         unsigned UserCost = 0;
6072         for (unsigned Lane = 0; Lane < OpsWidth; Lane++) {
6073           auto *IE = cast<InsertElementInst>(InsertUses[I + Lane]);
6074           if (auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2)))
6075             UserCost += TTI->getVectorInstrCost(
6076                 Instruction::InsertElement, IE->getType(), CI->getZExtValue());
6077         }
6078         LLVM_DEBUG(dbgs() << "SLP: Compensate cost of users by: " << UserCost
6079                           << ".\n");
6080         Cost -= UserCost;
6081       }
6082 
6083       MinCost = std::min(MinCost, Cost);
6084 
6085       if (Cost < -SLPCostThreshold) {
6086         LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
6087         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
6088                                                     cast<Instruction>(Ops[0]))
6089                                  << "SLP vectorized with cost " << ore::NV("Cost", Cost)
6090                                  << " and with tree size "
6091                                  << ore::NV("TreeSize", R.getTreeSize()));
6092 
6093         R.vectorizeTree();
6094         // Move to the next bundle.
6095         I += VF - 1;
6096         NextInst = I + 1;
6097         Changed = true;
6098       }
6099     }
6100   }
6101 
6102   if (!Changed && CandidateFound) {
6103     R.getORE()->emit([&]() {
6104       return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
6105              << "List vectorization was possible but not beneficial with cost "
6106              << ore::NV("Cost", MinCost) << " >= "
6107              << ore::NV("Treshold", -SLPCostThreshold);
6108     });
6109   } else if (!Changed) {
6110     R.getORE()->emit([&]() {
6111       return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
6112              << "Cannot SLP vectorize list: vectorization was impossible"
6113              << " with available vectorization factors";
6114     });
6115   }
6116   return Changed;
6117 }
6118 
6119 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
6120   if (!I)
6121     return false;
6122 
6123   if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I))
6124     return false;
6125 
6126   Value *P = I->getParent();
6127 
6128   // Vectorize in current basic block only.
6129   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
6130   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
6131   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
6132     return false;
6133 
6134   // Try to vectorize V.
6135   if (tryToVectorizePair(Op0, Op1, R))
6136     return true;
6137 
6138   auto *A = dyn_cast<BinaryOperator>(Op0);
6139   auto *B = dyn_cast<BinaryOperator>(Op1);
6140   // Try to skip B.
6141   if (B && B->hasOneUse()) {
6142     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
6143     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
6144     if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
6145       return true;
6146     if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
6147       return true;
6148   }
6149 
6150   // Try to skip A.
6151   if (A && A->hasOneUse()) {
6152     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
6153     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
6154     if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
6155       return true;
6156     if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
6157       return true;
6158   }
6159   return false;
6160 }
6161 
6162 /// Generate a shuffle mask to be used in a reduction tree.
6163 ///
6164 /// \param VecLen The length of the vector to be reduced.
6165 /// \param NumEltsToRdx The number of elements that should be reduced in the
6166 ///        vector.
6167 /// \param IsPairwise Whether the reduction is a pairwise or splitting
6168 ///        reduction. A pairwise reduction will generate a mask of
6169 ///        <0,2,...> or <1,3,..> while a splitting reduction will generate
6170 ///        <2,3, undef,undef> for a vector of 4 and NumElts = 2.
6171 /// \param IsLeft True will generate a mask of even elements, odd otherwise.
6172 static SmallVector<int, 32> createRdxShuffleMask(unsigned VecLen,
6173                                                  unsigned NumEltsToRdx,
6174                                                  bool IsPairwise, bool IsLeft) {
6175   assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask");
6176 
6177   SmallVector<int, 32> ShuffleMask(VecLen, -1);
6178 
6179   if (IsPairwise)
6180     // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
6181     for (unsigned i = 0; i != NumEltsToRdx; ++i)
6182       ShuffleMask[i] = 2 * i + !IsLeft;
6183   else
6184     // Move the upper half of the vector to the lower half.
6185     for (unsigned i = 0; i != NumEltsToRdx; ++i)
6186       ShuffleMask[i] = NumEltsToRdx + i;
6187 
6188   return ShuffleMask;
6189 }
6190 
6191 namespace {
6192 
6193 /// Model horizontal reductions.
6194 ///
6195 /// A horizontal reduction is a tree of reduction operations (currently add and
6196 /// fadd) that has operations that can be put into a vector as its leaf.
6197 /// For example, this tree:
6198 ///
6199 /// mul mul mul mul
6200 ///  \  /    \  /
6201 ///   +       +
6202 ///    \     /
6203 ///       +
6204 /// This tree has "mul" as its reduced values and "+" as its reduction
6205 /// operations. A reduction might be feeding into a store or a binary operation
6206 /// feeding a phi.
6207 ///    ...
6208 ///    \  /
6209 ///     +
6210 ///     |
6211 ///  phi +=
6212 ///
6213 ///  Or:
6214 ///    ...
6215 ///    \  /
6216 ///     +
6217 ///     |
6218 ///   *p =
6219 ///
6220 class HorizontalReduction {
6221   using ReductionOpsType = SmallVector<Value *, 16>;
6222   using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
6223   ReductionOpsListType  ReductionOps;
6224   SmallVector<Value *, 32> ReducedVals;
6225   // Use map vector to make stable output.
6226   MapVector<Instruction *, Value *> ExtraArgs;
6227 
6228   /// Kind of the reduction data.
6229   enum ReductionKind {
6230     RK_None,       /// Not a reduction.
6231     RK_Arithmetic, /// Binary reduction data.
6232     RK_Min,        /// Minimum reduction data.
6233     RK_UMin,       /// Unsigned minimum reduction data.
6234     RK_Max,        /// Maximum reduction data.
6235     RK_UMax,       /// Unsigned maximum reduction data.
6236   };
6237 
6238   /// Contains info about operation, like its opcode, left and right operands.
6239   class OperationData {
6240     /// Opcode of the instruction.
6241     unsigned Opcode = 0;
6242 
6243     /// Left operand of the reduction operation.
6244     Value *LHS = nullptr;
6245 
6246     /// Right operand of the reduction operation.
6247     Value *RHS = nullptr;
6248 
6249     /// Kind of the reduction operation.
6250     ReductionKind Kind = RK_None;
6251 
6252     /// True if float point min/max reduction has no NaNs.
6253     bool NoNaN = false;
6254 
6255     /// Checks if the reduction operation can be vectorized.
6256     bool isVectorizable() const {
6257       return LHS && RHS &&
6258              // We currently only support add/mul/logical && min/max reductions.
6259              ((Kind == RK_Arithmetic &&
6260                (Opcode == Instruction::Add || Opcode == Instruction::FAdd ||
6261                 Opcode == Instruction::Mul || Opcode == Instruction::FMul ||
6262                 Opcode == Instruction::And || Opcode == Instruction::Or ||
6263                 Opcode == Instruction::Xor)) ||
6264               ((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
6265                (Kind == RK_Min || Kind == RK_Max)) ||
6266               (Opcode == Instruction::ICmp &&
6267                (Kind == RK_UMin || Kind == RK_UMax)));
6268     }
6269 
6270     /// Creates reduction operation with the current opcode.
6271     Value *createOp(IRBuilder<> &Builder, const Twine &Name) const {
6272       assert(isVectorizable() &&
6273              "Expected add|fadd or min/max reduction operation.");
6274       Value *Cmp = nullptr;
6275       switch (Kind) {
6276       case RK_Arithmetic:
6277         return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, LHS, RHS,
6278                                    Name);
6279       case RK_Min:
6280         Cmp = Opcode == Instruction::ICmp ? Builder.CreateICmpSLT(LHS, RHS)
6281                                           : Builder.CreateFCmpOLT(LHS, RHS);
6282         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
6283       case RK_Max:
6284         Cmp = Opcode == Instruction::ICmp ? Builder.CreateICmpSGT(LHS, RHS)
6285                                           : Builder.CreateFCmpOGT(LHS, RHS);
6286         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
6287       case RK_UMin:
6288         assert(Opcode == Instruction::ICmp && "Expected integer types.");
6289         Cmp = Builder.CreateICmpULT(LHS, RHS);
6290         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
6291       case RK_UMax:
6292         assert(Opcode == Instruction::ICmp && "Expected integer types.");
6293         Cmp = Builder.CreateICmpUGT(LHS, RHS);
6294         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
6295       case RK_None:
6296         break;
6297       }
6298       llvm_unreachable("Unknown reduction operation.");
6299     }
6300 
6301   public:
6302     explicit OperationData() = default;
6303 
6304     /// Construction for reduced values. They are identified by opcode only and
6305     /// don't have associated LHS/RHS values.
6306     explicit OperationData(Value *V) {
6307       if (auto *I = dyn_cast<Instruction>(V))
6308         Opcode = I->getOpcode();
6309     }
6310 
6311     /// Constructor for reduction operations with opcode and its left and
6312     /// right operands.
6313     OperationData(unsigned Opcode, Value *LHS, Value *RHS, ReductionKind Kind,
6314                   bool NoNaN = false)
6315         : Opcode(Opcode), LHS(LHS), RHS(RHS), Kind(Kind), NoNaN(NoNaN) {
6316       assert(Kind != RK_None && "One of the reduction operations is expected.");
6317     }
6318 
6319     explicit operator bool() const { return Opcode; }
6320 
6321     /// Return true if this operation is any kind of minimum or maximum.
6322     bool isMinMax() const {
6323       switch (Kind) {
6324       case RK_Arithmetic:
6325         return false;
6326       case RK_Min:
6327       case RK_Max:
6328       case RK_UMin:
6329       case RK_UMax:
6330         return true;
6331       case RK_None:
6332         break;
6333       }
6334       llvm_unreachable("Reduction kind is not set");
6335     }
6336 
6337     /// Get the index of the first operand.
6338     unsigned getFirstOperandIndex() const {
6339       assert(!!*this && "The opcode is not set.");
6340       // We allow calling this before 'Kind' is set, so handle that specially.
6341       if (Kind == RK_None)
6342         return 0;
6343       return isMinMax() ? 1 : 0;
6344     }
6345 
6346     /// Total number of operands in the reduction operation.
6347     unsigned getNumberOfOperands() const {
6348       assert(Kind != RK_None && !!*this && LHS && RHS &&
6349              "Expected reduction operation.");
6350       return isMinMax() ? 3 : 2;
6351     }
6352 
6353     /// Checks if the operation has the same parent as \p P.
6354     bool hasSameParent(Instruction *I, Value *P, bool IsRedOp) const {
6355       assert(Kind != RK_None && !!*this && LHS && RHS &&
6356              "Expected reduction operation.");
6357       if (!IsRedOp)
6358         return I->getParent() == P;
6359       if (isMinMax()) {
6360         // SelectInst must be used twice while the condition op must have single
6361         // use only.
6362         auto *Cmp = cast<Instruction>(cast<SelectInst>(I)->getCondition());
6363         return I->getParent() == P && Cmp && Cmp->getParent() == P;
6364       }
6365       // Arithmetic reduction operation must be used once only.
6366       return I->getParent() == P;
6367     }
6368 
6369     /// Expected number of uses for reduction operations/reduced values.
6370     bool hasRequiredNumberOfUses(Instruction *I, bool IsReductionOp) const {
6371       assert(Kind != RK_None && !!*this && LHS && RHS &&
6372              "Expected reduction operation.");
6373       if (isMinMax())
6374         return I->hasNUses(2) &&
6375                (!IsReductionOp ||
6376                 cast<SelectInst>(I)->getCondition()->hasOneUse());
6377       return I->hasOneUse();
6378     }
6379 
6380     /// Initializes the list of reduction operations.
6381     void initReductionOps(ReductionOpsListType &ReductionOps) {
6382       assert(Kind != RK_None && !!*this && LHS && RHS &&
6383              "Expected reduction operation.");
6384       if (isMinMax())
6385         ReductionOps.assign(2, ReductionOpsType());
6386       else
6387         ReductionOps.assign(1, ReductionOpsType());
6388     }
6389 
6390     /// Add all reduction operations for the reduction instruction \p I.
6391     void addReductionOps(Instruction *I, ReductionOpsListType &ReductionOps) {
6392       assert(Kind != RK_None && !!*this && LHS && RHS &&
6393              "Expected reduction operation.");
6394       if (isMinMax()) {
6395         ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
6396         ReductionOps[1].emplace_back(I);
6397       } else {
6398         ReductionOps[0].emplace_back(I);
6399       }
6400     }
6401 
6402     /// Checks if instruction is associative and can be vectorized.
6403     bool isAssociative(Instruction *I) const {
6404       assert(Kind != RK_None && *this && LHS && RHS &&
6405              "Expected reduction operation.");
6406       switch (Kind) {
6407       case RK_Arithmetic:
6408         return I->isAssociative();
6409       case RK_Min:
6410       case RK_Max:
6411         return Opcode == Instruction::ICmp ||
6412                cast<Instruction>(I->getOperand(0))->isFast();
6413       case RK_UMin:
6414       case RK_UMax:
6415         assert(Opcode == Instruction::ICmp &&
6416                "Only integer compare operation is expected.");
6417         return true;
6418       case RK_None:
6419         break;
6420       }
6421       llvm_unreachable("Reduction kind is not set");
6422     }
6423 
6424     /// Checks if the reduction operation can be vectorized.
6425     bool isVectorizable(Instruction *I) const {
6426       return isVectorizable() && isAssociative(I);
6427     }
6428 
6429     /// Checks if two operation data are both a reduction op or both a reduced
6430     /// value.
6431     bool operator==(const OperationData &OD) const {
6432       assert(((Kind != OD.Kind) || ((!LHS == !OD.LHS) && (!RHS == !OD.RHS))) &&
6433              "One of the comparing operations is incorrect.");
6434       return this == &OD || (Kind == OD.Kind && Opcode == OD.Opcode);
6435     }
6436     bool operator!=(const OperationData &OD) const { return !(*this == OD); }
6437     void clear() {
6438       Opcode = 0;
6439       LHS = nullptr;
6440       RHS = nullptr;
6441       Kind = RK_None;
6442       NoNaN = false;
6443     }
6444 
6445     /// Get the opcode of the reduction operation.
6446     unsigned getOpcode() const {
6447       assert(isVectorizable() && "Expected vectorizable operation.");
6448       return Opcode;
6449     }
6450 
6451     /// Get kind of reduction data.
6452     ReductionKind getKind() const { return Kind; }
6453     Value *getLHS() const { return LHS; }
6454     Value *getRHS() const { return RHS; }
6455     Type *getConditionType() const {
6456       return isMinMax() ? CmpInst::makeCmpResultType(LHS->getType()) : nullptr;
6457     }
6458 
6459     /// Creates reduction operation with the current opcode with the IR flags
6460     /// from \p ReductionOps.
6461     Value *createOp(IRBuilder<> &Builder, const Twine &Name,
6462                     const ReductionOpsListType &ReductionOps) const {
6463       assert(isVectorizable() &&
6464              "Expected add|fadd or min/max reduction operation.");
6465       auto *Op = createOp(Builder, Name);
6466       switch (Kind) {
6467       case RK_Arithmetic:
6468         propagateIRFlags(Op, ReductionOps[0]);
6469         return Op;
6470       case RK_Min:
6471       case RK_Max:
6472       case RK_UMin:
6473       case RK_UMax:
6474         if (auto *SI = dyn_cast<SelectInst>(Op))
6475           propagateIRFlags(SI->getCondition(), ReductionOps[0]);
6476         propagateIRFlags(Op, ReductionOps[1]);
6477         return Op;
6478       case RK_None:
6479         break;
6480       }
6481       llvm_unreachable("Unknown reduction operation.");
6482     }
6483     /// Creates reduction operation with the current opcode with the IR flags
6484     /// from \p I.
6485     Value *createOp(IRBuilder<> &Builder, const Twine &Name,
6486                     Instruction *I) const {
6487       assert(isVectorizable() &&
6488              "Expected add|fadd or min/max reduction operation.");
6489       auto *Op = createOp(Builder, Name);
6490       switch (Kind) {
6491       case RK_Arithmetic:
6492         propagateIRFlags(Op, I);
6493         return Op;
6494       case RK_Min:
6495       case RK_Max:
6496       case RK_UMin:
6497       case RK_UMax:
6498         if (auto *SI = dyn_cast<SelectInst>(Op)) {
6499           propagateIRFlags(SI->getCondition(),
6500                            cast<SelectInst>(I)->getCondition());
6501         }
6502         propagateIRFlags(Op, I);
6503         return Op;
6504       case RK_None:
6505         break;
6506       }
6507       llvm_unreachable("Unknown reduction operation.");
6508     }
6509 
6510     TargetTransformInfo::ReductionFlags getFlags() const {
6511       TargetTransformInfo::ReductionFlags Flags;
6512       Flags.NoNaN = NoNaN;
6513       switch (Kind) {
6514       case RK_Arithmetic:
6515         break;
6516       case RK_Min:
6517         Flags.IsSigned = Opcode == Instruction::ICmp;
6518         Flags.IsMaxOp = false;
6519         break;
6520       case RK_Max:
6521         Flags.IsSigned = Opcode == Instruction::ICmp;
6522         Flags.IsMaxOp = true;
6523         break;
6524       case RK_UMin:
6525         Flags.IsSigned = false;
6526         Flags.IsMaxOp = false;
6527         break;
6528       case RK_UMax:
6529         Flags.IsSigned = false;
6530         Flags.IsMaxOp = true;
6531         break;
6532       case RK_None:
6533         llvm_unreachable("Reduction kind is not set");
6534       }
6535       return Flags;
6536     }
6537   };
6538 
6539   WeakTrackingVH ReductionRoot;
6540 
6541   /// The operation data of the reduction operation.
6542   OperationData ReductionData;
6543 
6544   /// The operation data of the values we perform a reduction on.
6545   OperationData ReducedValueData;
6546 
6547   /// Should we model this reduction as a pairwise reduction tree or a tree that
6548   /// splits the vector in halves and adds those halves.
6549   bool IsPairwiseReduction = false;
6550 
6551   /// Checks if the ParentStackElem.first should be marked as a reduction
6552   /// operation with an extra argument or as extra argument itself.
6553   void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem,
6554                     Value *ExtraArg) {
6555     if (ExtraArgs.count(ParentStackElem.first)) {
6556       ExtraArgs[ParentStackElem.first] = nullptr;
6557       // We ran into something like:
6558       // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg.
6559       // The whole ParentStackElem.first should be considered as an extra value
6560       // in this case.
6561       // Do not perform analysis of remaining operands of ParentStackElem.first
6562       // instruction, this whole instruction is an extra argument.
6563       ParentStackElem.second = ParentStackElem.first->getNumOperands();
6564     } else {
6565       // We ran into something like:
6566       // ParentStackElem.first += ... + ExtraArg + ...
6567       ExtraArgs[ParentStackElem.first] = ExtraArg;
6568     }
6569   }
6570 
6571   static OperationData getOperationData(Value *V) {
6572     if (!V)
6573       return OperationData();
6574 
6575     Value *LHS;
6576     Value *RHS;
6577     if (m_BinOp(m_Value(LHS), m_Value(RHS)).match(V)) {
6578       return OperationData(cast<BinaryOperator>(V)->getOpcode(), LHS, RHS,
6579                            RK_Arithmetic);
6580     }
6581     if (auto *Select = dyn_cast<SelectInst>(V)) {
6582       // Look for a min/max pattern.
6583       if (m_UMin(m_Value(LHS), m_Value(RHS)).match(Select)) {
6584         return OperationData(Instruction::ICmp, LHS, RHS, RK_UMin);
6585       } else if (m_SMin(m_Value(LHS), m_Value(RHS)).match(Select)) {
6586         return OperationData(Instruction::ICmp, LHS, RHS, RK_Min);
6587       } else if (m_OrdFMin(m_Value(LHS), m_Value(RHS)).match(Select) ||
6588                  m_UnordFMin(m_Value(LHS), m_Value(RHS)).match(Select)) {
6589         return OperationData(
6590             Instruction::FCmp, LHS, RHS, RK_Min,
6591             cast<Instruction>(Select->getCondition())->hasNoNaNs());
6592       } else if (m_UMax(m_Value(LHS), m_Value(RHS)).match(Select)) {
6593         return OperationData(Instruction::ICmp, LHS, RHS, RK_UMax);
6594       } else if (m_SMax(m_Value(LHS), m_Value(RHS)).match(Select)) {
6595         return OperationData(Instruction::ICmp, LHS, RHS, RK_Max);
6596       } else if (m_OrdFMax(m_Value(LHS), m_Value(RHS)).match(Select) ||
6597                  m_UnordFMax(m_Value(LHS), m_Value(RHS)).match(Select)) {
6598         return OperationData(
6599             Instruction::FCmp, LHS, RHS, RK_Max,
6600             cast<Instruction>(Select->getCondition())->hasNoNaNs());
6601       } else {
6602         // Try harder: look for min/max pattern based on instructions producing
6603         // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
6604         // During the intermediate stages of SLP, it's very common to have
6605         // pattern like this (since optimizeGatherSequence is run only once
6606         // at the end):
6607         // %1 = extractelement <2 x i32> %a, i32 0
6608         // %2 = extractelement <2 x i32> %a, i32 1
6609         // %cond = icmp sgt i32 %1, %2
6610         // %3 = extractelement <2 x i32> %a, i32 0
6611         // %4 = extractelement <2 x i32> %a, i32 1
6612         // %select = select i1 %cond, i32 %3, i32 %4
6613         CmpInst::Predicate Pred;
6614         Instruction *L1;
6615         Instruction *L2;
6616 
6617         LHS = Select->getTrueValue();
6618         RHS = Select->getFalseValue();
6619         Value *Cond = Select->getCondition();
6620 
6621         // TODO: Support inverse predicates.
6622         if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
6623           if (!isa<ExtractElementInst>(RHS) ||
6624               !L2->isIdenticalTo(cast<Instruction>(RHS)))
6625             return OperationData(V);
6626         } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
6627           if (!isa<ExtractElementInst>(LHS) ||
6628               !L1->isIdenticalTo(cast<Instruction>(LHS)))
6629             return OperationData(V);
6630         } else {
6631           if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
6632             return OperationData(V);
6633           if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
6634               !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
6635               !L2->isIdenticalTo(cast<Instruction>(RHS)))
6636             return OperationData(V);
6637         }
6638         switch (Pred) {
6639         default:
6640           return OperationData(V);
6641 
6642         case CmpInst::ICMP_ULT:
6643         case CmpInst::ICMP_ULE:
6644           return OperationData(Instruction::ICmp, LHS, RHS, RK_UMin);
6645 
6646         case CmpInst::ICMP_SLT:
6647         case CmpInst::ICMP_SLE:
6648           return OperationData(Instruction::ICmp, LHS, RHS, RK_Min);
6649 
6650         case CmpInst::FCMP_OLT:
6651         case CmpInst::FCMP_OLE:
6652         case CmpInst::FCMP_ULT:
6653         case CmpInst::FCMP_ULE:
6654           return OperationData(Instruction::FCmp, LHS, RHS, RK_Min,
6655                                cast<Instruction>(Cond)->hasNoNaNs());
6656 
6657         case CmpInst::ICMP_UGT:
6658         case CmpInst::ICMP_UGE:
6659           return OperationData(Instruction::ICmp, LHS, RHS, RK_UMax);
6660 
6661         case CmpInst::ICMP_SGT:
6662         case CmpInst::ICMP_SGE:
6663           return OperationData(Instruction::ICmp, LHS, RHS, RK_Max);
6664 
6665         case CmpInst::FCMP_OGT:
6666         case CmpInst::FCMP_OGE:
6667         case CmpInst::FCMP_UGT:
6668         case CmpInst::FCMP_UGE:
6669           return OperationData(Instruction::FCmp, LHS, RHS, RK_Max,
6670                                cast<Instruction>(Cond)->hasNoNaNs());
6671         }
6672       }
6673     }
6674     return OperationData(V);
6675   }
6676 
6677 public:
6678   HorizontalReduction() = default;
6679 
6680   /// Try to find a reduction tree.
6681   bool matchAssociativeReduction(PHINode *Phi, Instruction *B) {
6682     assert((!Phi || is_contained(Phi->operands(), B)) &&
6683            "Thi phi needs to use the binary operator");
6684 
6685     ReductionData = getOperationData(B);
6686 
6687     // We could have a initial reductions that is not an add.
6688     //  r *= v1 + v2 + v3 + v4
6689     // In such a case start looking for a tree rooted in the first '+'.
6690     if (Phi) {
6691       if (ReductionData.getLHS() == Phi) {
6692         Phi = nullptr;
6693         B = dyn_cast<Instruction>(ReductionData.getRHS());
6694         ReductionData = getOperationData(B);
6695       } else if (ReductionData.getRHS() == Phi) {
6696         Phi = nullptr;
6697         B = dyn_cast<Instruction>(ReductionData.getLHS());
6698         ReductionData = getOperationData(B);
6699       }
6700     }
6701 
6702     if (!ReductionData.isVectorizable(B))
6703       return false;
6704 
6705     Type *Ty = B->getType();
6706     if (!isValidElementType(Ty))
6707       return false;
6708     if (!Ty->isIntOrIntVectorTy() && !Ty->isFPOrFPVectorTy())
6709       return false;
6710 
6711     ReducedValueData.clear();
6712     ReductionRoot = B;
6713 
6714     // Post order traverse the reduction tree starting at B. We only handle true
6715     // trees containing only binary operators.
6716     SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
6717     Stack.push_back(std::make_pair(B, ReductionData.getFirstOperandIndex()));
6718     ReductionData.initReductionOps(ReductionOps);
6719     while (!Stack.empty()) {
6720       Instruction *TreeN = Stack.back().first;
6721       unsigned EdgeToVist = Stack.back().second++;
6722       OperationData OpData = getOperationData(TreeN);
6723       bool IsReducedValue = OpData != ReductionData;
6724 
6725       // Postorder vist.
6726       if (IsReducedValue || EdgeToVist == OpData.getNumberOfOperands()) {
6727         if (IsReducedValue)
6728           ReducedVals.push_back(TreeN);
6729         else {
6730           auto I = ExtraArgs.find(TreeN);
6731           if (I != ExtraArgs.end() && !I->second) {
6732             // Check if TreeN is an extra argument of its parent operation.
6733             if (Stack.size() <= 1) {
6734               // TreeN can't be an extra argument as it is a root reduction
6735               // operation.
6736               return false;
6737             }
6738             // Yes, TreeN is an extra argument, do not add it to a list of
6739             // reduction operations.
6740             // Stack[Stack.size() - 2] always points to the parent operation.
6741             markExtraArg(Stack[Stack.size() - 2], TreeN);
6742             ExtraArgs.erase(TreeN);
6743           } else
6744             ReductionData.addReductionOps(TreeN, ReductionOps);
6745         }
6746         // Retract.
6747         Stack.pop_back();
6748         continue;
6749       }
6750 
6751       // Visit left or right.
6752       Value *NextV = TreeN->getOperand(EdgeToVist);
6753       if (NextV != Phi) {
6754         auto *I = dyn_cast<Instruction>(NextV);
6755         OpData = getOperationData(I);
6756         // Continue analysis if the next operand is a reduction operation or
6757         // (possibly) a reduced value. If the reduced value opcode is not set,
6758         // the first met operation != reduction operation is considered as the
6759         // reduced value class.
6760         if (I && (!ReducedValueData || OpData == ReducedValueData ||
6761                   OpData == ReductionData)) {
6762           const bool IsReductionOperation = OpData == ReductionData;
6763           // Only handle trees in the current basic block.
6764           if (!ReductionData.hasSameParent(I, B->getParent(),
6765                                            IsReductionOperation)) {
6766             // I is an extra argument for TreeN (its parent operation).
6767             markExtraArg(Stack.back(), I);
6768             continue;
6769           }
6770 
6771           // Each tree node needs to have minimal number of users except for the
6772           // ultimate reduction.
6773           if (!ReductionData.hasRequiredNumberOfUses(I,
6774                                                      OpData == ReductionData) &&
6775               I != B) {
6776             // I is an extra argument for TreeN (its parent operation).
6777             markExtraArg(Stack.back(), I);
6778             continue;
6779           }
6780 
6781           if (IsReductionOperation) {
6782             // We need to be able to reassociate the reduction operations.
6783             if (!OpData.isAssociative(I)) {
6784               // I is an extra argument for TreeN (its parent operation).
6785               markExtraArg(Stack.back(), I);
6786               continue;
6787             }
6788           } else if (ReducedValueData &&
6789                      ReducedValueData != OpData) {
6790             // Make sure that the opcodes of the operations that we are going to
6791             // reduce match.
6792             // I is an extra argument for TreeN (its parent operation).
6793             markExtraArg(Stack.back(), I);
6794             continue;
6795           } else if (!ReducedValueData)
6796             ReducedValueData = OpData;
6797 
6798           Stack.push_back(std::make_pair(I, OpData.getFirstOperandIndex()));
6799           continue;
6800         }
6801       }
6802       // NextV is an extra argument for TreeN (its parent operation).
6803       markExtraArg(Stack.back(), NextV);
6804     }
6805     return true;
6806   }
6807 
6808   /// Attempt to vectorize the tree found by
6809   /// matchAssociativeReduction.
6810   bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
6811     if (ReducedVals.empty())
6812       return false;
6813 
6814     // If there is a sufficient number of reduction values, reduce
6815     // to a nearby power-of-2. Can safely generate oversized
6816     // vectors and rely on the backend to split them to legal sizes.
6817     unsigned NumReducedVals = ReducedVals.size();
6818     if (NumReducedVals < 4)
6819       return false;
6820 
6821     unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
6822 
6823     Value *VectorizedTree = nullptr;
6824 
6825     // FIXME: Fast-math-flags should be set based on the instructions in the
6826     //        reduction (not all of 'fast' are required).
6827     IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
6828     FastMathFlags Unsafe;
6829     Unsafe.setFast();
6830     Builder.setFastMathFlags(Unsafe);
6831     unsigned i = 0;
6832 
6833     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
6834     // The same extra argument may be used several time, so log each attempt
6835     // to use it.
6836     for (auto &Pair : ExtraArgs) {
6837       assert(Pair.first && "DebugLoc must be set.");
6838       ExternallyUsedValues[Pair.second].push_back(Pair.first);
6839     }
6840 
6841     // The compare instruction of a min/max is the insertion point for new
6842     // instructions and may be replaced with a new compare instruction.
6843     auto getCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
6844       assert(isa<SelectInst>(RdxRootInst) &&
6845              "Expected min/max reduction to have select root instruction");
6846       Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
6847       assert(isa<Instruction>(ScalarCond) &&
6848              "Expected min/max reduction to have compare condition");
6849       return cast<Instruction>(ScalarCond);
6850     };
6851 
6852     // The reduction root is used as the insertion point for new instructions,
6853     // so set it as externally used to prevent it from being deleted.
6854     ExternallyUsedValues[ReductionRoot];
6855     SmallVector<Value *, 16> IgnoreList;
6856     for (auto &V : ReductionOps)
6857       IgnoreList.append(V.begin(), V.end());
6858     while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) {
6859       auto VL = makeArrayRef(&ReducedVals[i], ReduxWidth);
6860       V.buildTree(VL, ExternallyUsedValues, IgnoreList);
6861       Optional<ArrayRef<unsigned>> Order = V.bestOrder();
6862       // TODO: Handle orders of size less than number of elements in the vector.
6863       if (Order && Order->size() == VL.size()) {
6864         // TODO: reorder tree nodes without tree rebuilding.
6865         SmallVector<Value *, 4> ReorderedOps(VL.size());
6866         llvm::transform(*Order, ReorderedOps.begin(),
6867                         [VL](const unsigned Idx) { return VL[Idx]; });
6868         V.buildTree(ReorderedOps, ExternallyUsedValues, IgnoreList);
6869       }
6870       if (V.isTreeTinyAndNotFullyVectorizable())
6871         break;
6872       if (V.isLoadCombineReductionCandidate(ReductionData.getOpcode()))
6873         break;
6874 
6875       V.computeMinimumValueSizes();
6876 
6877       // Estimate cost.
6878       int TreeCost = V.getTreeCost();
6879       int ReductionCost = getReductionCost(TTI, ReducedVals[i], ReduxWidth);
6880       int Cost = TreeCost + ReductionCost;
6881       if (Cost >= -SLPCostThreshold) {
6882           V.getORE()->emit([&]() {
6883               return OptimizationRemarkMissed(
6884                          SV_NAME, "HorSLPNotBeneficial", cast<Instruction>(VL[0]))
6885                      << "Vectorizing horizontal reduction is possible"
6886                      << "but not beneficial with cost "
6887                      << ore::NV("Cost", Cost) << " and threshold "
6888                      << ore::NV("Threshold", -SLPCostThreshold);
6889           });
6890           break;
6891       }
6892 
6893       LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
6894                         << Cost << ". (HorRdx)\n");
6895       V.getORE()->emit([&]() {
6896           return OptimizationRemark(
6897                      SV_NAME, "VectorizedHorizontalReduction", cast<Instruction>(VL[0]))
6898           << "Vectorized horizontal reduction with cost "
6899           << ore::NV("Cost", Cost) << " and with tree size "
6900           << ore::NV("TreeSize", V.getTreeSize());
6901       });
6902 
6903       // Vectorize a tree.
6904       DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
6905       Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues);
6906 
6907       // Emit a reduction. For min/max, the root is a select, but the insertion
6908       // point is the compare condition of that select.
6909       Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
6910       if (ReductionData.isMinMax())
6911         Builder.SetInsertPoint(getCmpForMinMaxReduction(RdxRootInst));
6912       else
6913         Builder.SetInsertPoint(RdxRootInst);
6914 
6915       Value *ReducedSubTree =
6916           emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
6917       if (VectorizedTree) {
6918         Builder.SetCurrentDebugLocation(Loc);
6919         OperationData VectReductionData(ReductionData.getOpcode(),
6920                                         VectorizedTree, ReducedSubTree,
6921                                         ReductionData.getKind());
6922         VectorizedTree =
6923             VectReductionData.createOp(Builder, "op.rdx", ReductionOps);
6924       } else
6925         VectorizedTree = ReducedSubTree;
6926       i += ReduxWidth;
6927       ReduxWidth = PowerOf2Floor(NumReducedVals - i);
6928     }
6929 
6930     if (VectorizedTree) {
6931       // Finish the reduction.
6932       for (; i < NumReducedVals; ++i) {
6933         auto *I = cast<Instruction>(ReducedVals[i]);
6934         Builder.SetCurrentDebugLocation(I->getDebugLoc());
6935         OperationData VectReductionData(ReductionData.getOpcode(),
6936                                         VectorizedTree, I,
6937                                         ReductionData.getKind());
6938         VectorizedTree = VectReductionData.createOp(Builder, "", ReductionOps);
6939       }
6940       for (auto &Pair : ExternallyUsedValues) {
6941         // Add each externally used value to the final reduction.
6942         for (auto *I : Pair.second) {
6943           Builder.SetCurrentDebugLocation(I->getDebugLoc());
6944           OperationData VectReductionData(ReductionData.getOpcode(),
6945                                           VectorizedTree, Pair.first,
6946                                           ReductionData.getKind());
6947           VectorizedTree = VectReductionData.createOp(Builder, "op.extra", I);
6948         }
6949       }
6950 
6951       // Update users. For a min/max reduction that ends with a compare and
6952       // select, we also have to RAUW for the compare instruction feeding the
6953       // reduction root. That's because the original compare may have extra uses
6954       // besides the final select of the reduction.
6955       if (ReductionData.isMinMax()) {
6956         if (auto *VecSelect = dyn_cast<SelectInst>(VectorizedTree)) {
6957           Instruction *ScalarCmp =
6958               getCmpForMinMaxReduction(cast<Instruction>(ReductionRoot));
6959           ScalarCmp->replaceAllUsesWith(VecSelect->getCondition());
6960         }
6961       }
6962       ReductionRoot->replaceAllUsesWith(VectorizedTree);
6963 
6964       // Mark all scalar reduction ops for deletion, they are replaced by the
6965       // vector reductions.
6966       V.eraseInstructions(IgnoreList);
6967     }
6968     return VectorizedTree != nullptr;
6969   }
6970 
6971   unsigned numReductionValues() const {
6972     return ReducedVals.size();
6973   }
6974 
6975 private:
6976   /// Calculate the cost of a reduction.
6977   int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal,
6978                        unsigned ReduxWidth) {
6979     Type *ScalarTy = FirstReducedVal->getType();
6980     VectorType *VecTy = VectorType::get(ScalarTy, ReduxWidth);
6981 
6982     int PairwiseRdxCost;
6983     int SplittingRdxCost;
6984     switch (ReductionData.getKind()) {
6985     case RK_Arithmetic:
6986       PairwiseRdxCost =
6987           TTI->getArithmeticReductionCost(ReductionData.getOpcode(), VecTy,
6988                                           /*IsPairwiseForm=*/true);
6989       SplittingRdxCost =
6990           TTI->getArithmeticReductionCost(ReductionData.getOpcode(), VecTy,
6991                                           /*IsPairwiseForm=*/false);
6992       break;
6993     case RK_Min:
6994     case RK_Max:
6995     case RK_UMin:
6996     case RK_UMax: {
6997       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VecTy));
6998       bool IsUnsigned = ReductionData.getKind() == RK_UMin ||
6999                         ReductionData.getKind() == RK_UMax;
7000       PairwiseRdxCost =
7001           TTI->getMinMaxReductionCost(VecTy, VecCondTy,
7002                                       /*IsPairwiseForm=*/true, IsUnsigned);
7003       SplittingRdxCost =
7004           TTI->getMinMaxReductionCost(VecTy, VecCondTy,
7005                                       /*IsPairwiseForm=*/false, IsUnsigned);
7006       break;
7007     }
7008     case RK_None:
7009       llvm_unreachable("Expected arithmetic or min/max reduction operation");
7010     }
7011 
7012     IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
7013     int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
7014 
7015     int ScalarReduxCost = 0;
7016     switch (ReductionData.getKind()) {
7017     case RK_Arithmetic:
7018       ScalarReduxCost =
7019           TTI->getArithmeticInstrCost(ReductionData.getOpcode(), ScalarTy);
7020       break;
7021     case RK_Min:
7022     case RK_Max:
7023     case RK_UMin:
7024     case RK_UMax:
7025       ScalarReduxCost =
7026           TTI->getCmpSelInstrCost(ReductionData.getOpcode(), ScalarTy) +
7027           TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
7028                                   CmpInst::makeCmpResultType(ScalarTy));
7029       break;
7030     case RK_None:
7031       llvm_unreachable("Expected arithmetic or min/max reduction operation");
7032     }
7033     ScalarReduxCost *= (ReduxWidth - 1);
7034 
7035     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost
7036                       << " for reduction that starts with " << *FirstReducedVal
7037                       << " (It is a "
7038                       << (IsPairwiseReduction ? "pairwise" : "splitting")
7039                       << " reduction)\n");
7040 
7041     return VecReduxCost - ScalarReduxCost;
7042   }
7043 
7044   /// Emit a horizontal reduction of the vectorized value.
7045   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
7046                        unsigned ReduxWidth, const TargetTransformInfo *TTI) {
7047     assert(VectorizedValue && "Need to have a vectorized tree node");
7048     assert(isPowerOf2_32(ReduxWidth) &&
7049            "We only handle power-of-two reductions for now");
7050 
7051     if (!IsPairwiseReduction) {
7052       // FIXME: The builder should use an FMF guard. It should not be hard-coded
7053       //        to 'fast'.
7054       assert(Builder.getFastMathFlags().isFast() && "Expected 'fast' FMF");
7055       return createSimpleTargetReduction(
7056           Builder, TTI, ReductionData.getOpcode(), VectorizedValue,
7057           ReductionData.getFlags(), ReductionOps.back());
7058     }
7059 
7060     Value *TmpVec = VectorizedValue;
7061     for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
7062       auto LeftMask = createRdxShuffleMask(ReduxWidth, i, true, true);
7063       auto RightMask = createRdxShuffleMask(ReduxWidth, i, true, false);
7064 
7065       Value *LeftShuf = Builder.CreateShuffleVector(
7066           TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l");
7067       Value *RightShuf = Builder.CreateShuffleVector(
7068           TmpVec, UndefValue::get(TmpVec->getType()), (RightMask),
7069           "rdx.shuf.r");
7070       OperationData VectReductionData(ReductionData.getOpcode(), LeftShuf,
7071                                       RightShuf, ReductionData.getKind());
7072       TmpVec = VectReductionData.createOp(Builder, "op.rdx", ReductionOps);
7073     }
7074 
7075     // The result is in the first element of the vector.
7076     return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
7077   }
7078 };
7079 
7080 } // end anonymous namespace
7081 
7082 /// Recognize construction of vectors like
7083 ///  %ra = insertelement <4 x float> undef, float %s0, i32 0
7084 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
7085 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
7086 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
7087 ///  starting from the last insertelement or insertvalue instruction.
7088 ///
7089 /// Also recognize aggregates like {<2 x float>, <2 x float>},
7090 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
7091 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
7092 ///
7093 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
7094 ///
7095 /// \return true if it matches.
7096 static bool findBuildAggregate(Value *LastInsertInst, TargetTransformInfo *TTI,
7097                                SmallVectorImpl<Value *> &BuildVectorOpds,
7098                                SmallVectorImpl<Value *> &InsertElts) {
7099   assert((isa<InsertElementInst>(LastInsertInst) ||
7100           isa<InsertValueInst>(LastInsertInst)) &&
7101          "Expected insertelement or insertvalue instruction!");
7102   do {
7103     Value *InsertedOperand;
7104     auto *IE = dyn_cast<InsertElementInst>(LastInsertInst);
7105     if (IE) {
7106       InsertedOperand = IE->getOperand(1);
7107       LastInsertInst = IE->getOperand(0);
7108     } else {
7109       auto *IV = cast<InsertValueInst>(LastInsertInst);
7110       InsertedOperand = IV->getInsertedValueOperand();
7111       LastInsertInst = IV->getAggregateOperand();
7112     }
7113     if (isa<InsertElementInst>(InsertedOperand) ||
7114         isa<InsertValueInst>(InsertedOperand)) {
7115       SmallVector<Value *, 8> TmpBuildVectorOpds;
7116       SmallVector<Value *, 8> TmpInsertElts;
7117       if (!findBuildAggregate(InsertedOperand, TTI, TmpBuildVectorOpds,
7118                               TmpInsertElts))
7119         return false;
7120       BuildVectorOpds.append(TmpBuildVectorOpds.rbegin(),
7121                              TmpBuildVectorOpds.rend());
7122       InsertElts.append(TmpInsertElts.rbegin(), TmpInsertElts.rend());
7123     } else {
7124       BuildVectorOpds.push_back(InsertedOperand);
7125       InsertElts.push_back(IE);
7126     }
7127     if (isa<UndefValue>(LastInsertInst))
7128       break;
7129     if ((!isa<InsertValueInst>(LastInsertInst) &&
7130          !isa<InsertElementInst>(LastInsertInst)) ||
7131         !LastInsertInst->hasOneUse())
7132       return false;
7133   } while (true);
7134   std::reverse(BuildVectorOpds.begin(), BuildVectorOpds.end());
7135   std::reverse(InsertElts.begin(), InsertElts.end());
7136   return true;
7137 }
7138 
7139 static bool PhiTypeSorterFunc(Value *V, Value *V2) {
7140   return V->getType() < V2->getType();
7141 }
7142 
7143 /// Try and get a reduction value from a phi node.
7144 ///
7145 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
7146 /// if they come from either \p ParentBB or a containing loop latch.
7147 ///
7148 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
7149 /// if not possible.
7150 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
7151                                 BasicBlock *ParentBB, LoopInfo *LI) {
7152   // There are situations where the reduction value is not dominated by the
7153   // reduction phi. Vectorizing such cases has been reported to cause
7154   // miscompiles. See PR25787.
7155   auto DominatedReduxValue = [&](Value *R) {
7156     return isa<Instruction>(R) &&
7157            DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
7158   };
7159 
7160   Value *Rdx = nullptr;
7161 
7162   // Return the incoming value if it comes from the same BB as the phi node.
7163   if (P->getIncomingBlock(0) == ParentBB) {
7164     Rdx = P->getIncomingValue(0);
7165   } else if (P->getIncomingBlock(1) == ParentBB) {
7166     Rdx = P->getIncomingValue(1);
7167   }
7168 
7169   if (Rdx && DominatedReduxValue(Rdx))
7170     return Rdx;
7171 
7172   // Otherwise, check whether we have a loop latch to look at.
7173   Loop *BBL = LI->getLoopFor(ParentBB);
7174   if (!BBL)
7175     return nullptr;
7176   BasicBlock *BBLatch = BBL->getLoopLatch();
7177   if (!BBLatch)
7178     return nullptr;
7179 
7180   // There is a loop latch, return the incoming value if it comes from
7181   // that. This reduction pattern occasionally turns up.
7182   if (P->getIncomingBlock(0) == BBLatch) {
7183     Rdx = P->getIncomingValue(0);
7184   } else if (P->getIncomingBlock(1) == BBLatch) {
7185     Rdx = P->getIncomingValue(1);
7186   }
7187 
7188   if (Rdx && DominatedReduxValue(Rdx))
7189     return Rdx;
7190 
7191   return nullptr;
7192 }
7193 
7194 /// Attempt to reduce a horizontal reduction.
7195 /// If it is legal to match a horizontal reduction feeding the phi node \a P
7196 /// with reduction operators \a Root (or one of its operands) in a basic block
7197 /// \a BB, then check if it can be done. If horizontal reduction is not found
7198 /// and root instruction is a binary operation, vectorization of the operands is
7199 /// attempted.
7200 /// \returns true if a horizontal reduction was matched and reduced or operands
7201 /// of one of the binary instruction were vectorized.
7202 /// \returns false if a horizontal reduction was not matched (or not possible)
7203 /// or no vectorization of any binary operation feeding \a Root instruction was
7204 /// performed.
7205 static bool tryToVectorizeHorReductionOrInstOperands(
7206     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
7207     TargetTransformInfo *TTI,
7208     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
7209   if (!ShouldVectorizeHor)
7210     return false;
7211 
7212   if (!Root)
7213     return false;
7214 
7215   if (Root->getParent() != BB || isa<PHINode>(Root))
7216     return false;
7217   // Start analysis starting from Root instruction. If horizontal reduction is
7218   // found, try to vectorize it. If it is not a horizontal reduction or
7219   // vectorization is not possible or not effective, and currently analyzed
7220   // instruction is a binary operation, try to vectorize the operands, using
7221   // pre-order DFS traversal order. If the operands were not vectorized, repeat
7222   // the same procedure considering each operand as a possible root of the
7223   // horizontal reduction.
7224   // Interrupt the process if the Root instruction itself was vectorized or all
7225   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
7226   SmallVector<std::pair<Instruction *, unsigned>, 8> Stack(1, {Root, 0});
7227   SmallPtrSet<Value *, 8> VisitedInstrs;
7228   bool Res = false;
7229   while (!Stack.empty()) {
7230     Instruction *Inst;
7231     unsigned Level;
7232     std::tie(Inst, Level) = Stack.pop_back_val();
7233     auto *BI = dyn_cast<BinaryOperator>(Inst);
7234     auto *SI = dyn_cast<SelectInst>(Inst);
7235     if (BI || SI) {
7236       HorizontalReduction HorRdx;
7237       if (HorRdx.matchAssociativeReduction(P, Inst)) {
7238         if (HorRdx.tryToReduce(R, TTI)) {
7239           Res = true;
7240           // Set P to nullptr to avoid re-analysis of phi node in
7241           // matchAssociativeReduction function unless this is the root node.
7242           P = nullptr;
7243           continue;
7244         }
7245       }
7246       if (P && BI) {
7247         Inst = dyn_cast<Instruction>(BI->getOperand(0));
7248         if (Inst == P)
7249           Inst = dyn_cast<Instruction>(BI->getOperand(1));
7250         if (!Inst) {
7251           // Set P to nullptr to avoid re-analysis of phi node in
7252           // matchAssociativeReduction function unless this is the root node.
7253           P = nullptr;
7254           continue;
7255         }
7256       }
7257     }
7258     // Set P to nullptr to avoid re-analysis of phi node in
7259     // matchAssociativeReduction function unless this is the root node.
7260     P = nullptr;
7261     if (Vectorize(Inst, R)) {
7262       Res = true;
7263       continue;
7264     }
7265 
7266     // Try to vectorize operands.
7267     // Continue analysis for the instruction from the same basic block only to
7268     // save compile time.
7269     if (++Level < RecursionMaxDepth)
7270       for (auto *Op : Inst->operand_values())
7271         if (VisitedInstrs.insert(Op).second)
7272           if (auto *I = dyn_cast<Instruction>(Op))
7273             if (!isa<PHINode>(I) && !R.isDeleted(I) && I->getParent() == BB)
7274               Stack.emplace_back(I, Level);
7275   }
7276   return Res;
7277 }
7278 
7279 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
7280                                                  BasicBlock *BB, BoUpSLP &R,
7281                                                  TargetTransformInfo *TTI) {
7282   if (!V)
7283     return false;
7284   auto *I = dyn_cast<Instruction>(V);
7285   if (!I)
7286     return false;
7287 
7288   if (!isa<BinaryOperator>(I))
7289     P = nullptr;
7290   // Try to match and vectorize a horizontal reduction.
7291   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
7292     return tryToVectorize(I, R);
7293   };
7294   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI,
7295                                                   ExtraVectorization);
7296 }
7297 
7298 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
7299                                                  BasicBlock *BB, BoUpSLP &R) {
7300   const DataLayout &DL = BB->getModule()->getDataLayout();
7301   if (!R.canMapToVector(IVI->getType(), DL))
7302     return false;
7303 
7304   SmallVector<Value *, 16> BuildVectorOpds;
7305   SmallVector<Value *, 16> BuildVectorInsts;
7306   if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts) ||
7307       BuildVectorOpds.size() < 2)
7308     return false;
7309 
7310   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
7311   // Aggregate value is unlikely to be processed in vector register, we need to
7312   // extract scalars into scalar registers, so NeedExtraction is set true.
7313   return tryToVectorizeList(BuildVectorOpds, R, /*AllowReorder=*/false,
7314                             BuildVectorInsts);
7315 }
7316 
7317 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
7318                                                    BasicBlock *BB, BoUpSLP &R) {
7319   SmallVector<Value *, 16> BuildVectorInsts;
7320   SmallVector<Value *, 16> BuildVectorOpds;
7321   if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
7322       BuildVectorOpds.size() < 2 ||
7323       (llvm::all_of(BuildVectorOpds,
7324                     [](Value *V) { return isa<ExtractElementInst>(V); }) &&
7325        isShuffle(BuildVectorOpds)))
7326     return false;
7327 
7328   // Vectorize starting with the build vector operands ignoring the BuildVector
7329   // instructions for the purpose of scheduling and user extraction.
7330   return tryToVectorizeList(BuildVectorOpds, R, /*AllowReorder=*/false,
7331                             BuildVectorInsts);
7332 }
7333 
7334 bool SLPVectorizerPass::vectorizeCmpInst(CmpInst *CI, BasicBlock *BB,
7335                                          BoUpSLP &R) {
7336   if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R))
7337     return true;
7338 
7339   bool OpsChanged = false;
7340   for (int Idx = 0; Idx < 2; ++Idx) {
7341     OpsChanged |=
7342         vectorizeRootInstruction(nullptr, CI->getOperand(Idx), BB, R, TTI);
7343   }
7344   return OpsChanged;
7345 }
7346 
7347 bool SLPVectorizerPass::vectorizeSimpleInstructions(
7348     SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R) {
7349   bool OpsChanged = false;
7350   for (auto *I : reverse(Instructions)) {
7351     if (R.isDeleted(I))
7352       continue;
7353     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I))
7354       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
7355     else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I))
7356       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
7357     else if (auto *CI = dyn_cast<CmpInst>(I))
7358       OpsChanged |= vectorizeCmpInst(CI, BB, R);
7359   }
7360   Instructions.clear();
7361   return OpsChanged;
7362 }
7363 
7364 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
7365   bool Changed = false;
7366   SmallVector<Value *, 4> Incoming;
7367   SmallPtrSet<Value *, 16> VisitedInstrs;
7368 
7369   bool HaveVectorizedPhiNodes = true;
7370   while (HaveVectorizedPhiNodes) {
7371     HaveVectorizedPhiNodes = false;
7372 
7373     // Collect the incoming values from the PHIs.
7374     Incoming.clear();
7375     for (Instruction &I : *BB) {
7376       PHINode *P = dyn_cast<PHINode>(&I);
7377       if (!P)
7378         break;
7379 
7380       if (!VisitedInstrs.count(P) && !R.isDeleted(P))
7381         Incoming.push_back(P);
7382     }
7383 
7384     // Sort by type.
7385     llvm::stable_sort(Incoming, PhiTypeSorterFunc);
7386 
7387     // Try to vectorize elements base on their type.
7388     for (SmallVector<Value *, 4>::iterator IncIt = Incoming.begin(),
7389                                            E = Incoming.end();
7390          IncIt != E;) {
7391 
7392       // Look for the next elements with the same type.
7393       SmallVector<Value *, 4>::iterator SameTypeIt = IncIt;
7394       while (SameTypeIt != E &&
7395              (*SameTypeIt)->getType() == (*IncIt)->getType()) {
7396         VisitedInstrs.insert(*SameTypeIt);
7397         ++SameTypeIt;
7398       }
7399 
7400       // Try to vectorize them.
7401       unsigned NumElts = (SameTypeIt - IncIt);
7402       LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at PHIs ("
7403                         << NumElts << ")\n");
7404       // The order in which the phi nodes appear in the program does not matter.
7405       // So allow tryToVectorizeList to reorder them if it is beneficial. This
7406       // is done when there are exactly two elements since tryToVectorizeList
7407       // asserts that there are only two values when AllowReorder is true.
7408       bool AllowReorder = NumElts == 2;
7409       if (NumElts > 1 &&
7410           tryToVectorizeList(makeArrayRef(IncIt, NumElts), R, AllowReorder)) {
7411         // Success start over because instructions might have been changed.
7412         HaveVectorizedPhiNodes = true;
7413         Changed = true;
7414         break;
7415       }
7416 
7417       // Start over at the next instruction of a different type (or the end).
7418       IncIt = SameTypeIt;
7419     }
7420   }
7421 
7422   VisitedInstrs.clear();
7423 
7424   SmallVector<Instruction *, 8> PostProcessInstructions;
7425   SmallDenseSet<Instruction *, 4> KeyNodes;
7426   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
7427     // Skip instructions marked for the deletion.
7428     if (R.isDeleted(&*it))
7429       continue;
7430     // We may go through BB multiple times so skip the one we have checked.
7431     if (!VisitedInstrs.insert(&*it).second) {
7432       if (it->use_empty() && KeyNodes.count(&*it) > 0 &&
7433           vectorizeSimpleInstructions(PostProcessInstructions, BB, R)) {
7434         // We would like to start over since some instructions are deleted
7435         // and the iterator may become invalid value.
7436         Changed = true;
7437         it = BB->begin();
7438         e = BB->end();
7439       }
7440       continue;
7441     }
7442 
7443     if (isa<DbgInfoIntrinsic>(it))
7444       continue;
7445 
7446     // Try to vectorize reductions that use PHINodes.
7447     if (PHINode *P = dyn_cast<PHINode>(it)) {
7448       // Check that the PHI is a reduction PHI.
7449       if (P->getNumIncomingValues() != 2)
7450         return Changed;
7451 
7452       // Try to match and vectorize a horizontal reduction.
7453       if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
7454                                    TTI)) {
7455         Changed = true;
7456         it = BB->begin();
7457         e = BB->end();
7458         continue;
7459       }
7460       continue;
7461     }
7462 
7463     // Ran into an instruction without users, like terminator, or function call
7464     // with ignored return value, store. Ignore unused instructions (basing on
7465     // instruction type, except for CallInst and InvokeInst).
7466     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
7467                             isa<InvokeInst>(it))) {
7468       KeyNodes.insert(&*it);
7469       bool OpsChanged = false;
7470       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
7471         for (auto *V : it->operand_values()) {
7472           // Try to match and vectorize a horizontal reduction.
7473           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
7474         }
7475       }
7476       // Start vectorization of post-process list of instructions from the
7477       // top-tree instructions to try to vectorize as many instructions as
7478       // possible.
7479       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R);
7480       if (OpsChanged) {
7481         // We would like to start over since some instructions are deleted
7482         // and the iterator may become invalid value.
7483         Changed = true;
7484         it = BB->begin();
7485         e = BB->end();
7486         continue;
7487       }
7488     }
7489 
7490     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
7491         isa<InsertValueInst>(it))
7492       PostProcessInstructions.push_back(&*it);
7493   }
7494 
7495   return Changed;
7496 }
7497 
7498 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
7499   auto Changed = false;
7500   for (auto &Entry : GEPs) {
7501     // If the getelementptr list has fewer than two elements, there's nothing
7502     // to do.
7503     if (Entry.second.size() < 2)
7504       continue;
7505 
7506     LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
7507                       << Entry.second.size() << ".\n");
7508 
7509     // Process the GEP list in chunks suitable for the target's supported
7510     // vector size. If a vector register can't hold 1 element, we are done.
7511     unsigned MaxVecRegSize = R.getMaxVecRegSize();
7512     unsigned EltSize = R.getVectorElementSize(Entry.second[0]);
7513     if (MaxVecRegSize < EltSize)
7514       continue;
7515 
7516     unsigned MaxElts = MaxVecRegSize / EltSize;
7517     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
7518       auto Len = std::min<unsigned>(BE - BI, MaxElts);
7519       auto GEPList = makeArrayRef(&Entry.second[BI], Len);
7520 
7521       // Initialize a set a candidate getelementptrs. Note that we use a
7522       // SetVector here to preserve program order. If the index computations
7523       // are vectorizable and begin with loads, we want to minimize the chance
7524       // of having to reorder them later.
7525       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
7526 
7527       // Some of the candidates may have already been vectorized after we
7528       // initially collected them. If so, they are marked as deleted, so remove
7529       // them from the set of candidates.
7530       Candidates.remove_if(
7531           [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
7532 
7533       // Remove from the set of candidates all pairs of getelementptrs with
7534       // constant differences. Such getelementptrs are likely not good
7535       // candidates for vectorization in a bottom-up phase since one can be
7536       // computed from the other. We also ensure all candidate getelementptr
7537       // indices are unique.
7538       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
7539         auto *GEPI = GEPList[I];
7540         if (!Candidates.count(GEPI))
7541           continue;
7542         auto *SCEVI = SE->getSCEV(GEPList[I]);
7543         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
7544           auto *GEPJ = GEPList[J];
7545           auto *SCEVJ = SE->getSCEV(GEPList[J]);
7546           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
7547             Candidates.remove(GEPI);
7548             Candidates.remove(GEPJ);
7549           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
7550             Candidates.remove(GEPJ);
7551           }
7552         }
7553       }
7554 
7555       // We break out of the above computation as soon as we know there are
7556       // fewer than two candidates remaining.
7557       if (Candidates.size() < 2)
7558         continue;
7559 
7560       // Add the single, non-constant index of each candidate to the bundle. We
7561       // ensured the indices met these constraints when we originally collected
7562       // the getelementptrs.
7563       SmallVector<Value *, 16> Bundle(Candidates.size());
7564       auto BundleIndex = 0u;
7565       for (auto *V : Candidates) {
7566         auto *GEP = cast<GetElementPtrInst>(V);
7567         auto *GEPIdx = GEP->idx_begin()->get();
7568         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
7569         Bundle[BundleIndex++] = GEPIdx;
7570       }
7571 
7572       // Try and vectorize the indices. We are currently only interested in
7573       // gather-like cases of the form:
7574       //
7575       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
7576       //
7577       // where the loads of "a", the loads of "b", and the subtractions can be
7578       // performed in parallel. It's likely that detecting this pattern in a
7579       // bottom-up phase will be simpler and less costly than building a
7580       // full-blown top-down phase beginning at the consecutive loads.
7581       Changed |= tryToVectorizeList(Bundle, R);
7582     }
7583   }
7584   return Changed;
7585 }
7586 
7587 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
7588   bool Changed = false;
7589   // Attempt to sort and vectorize each of the store-groups.
7590   for (StoreListMap::iterator it = Stores.begin(), e = Stores.end(); it != e;
7591        ++it) {
7592     if (it->second.size() < 2)
7593       continue;
7594 
7595     LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
7596                       << it->second.size() << ".\n");
7597 
7598     Changed |= vectorizeStores(it->second, R);
7599   }
7600   return Changed;
7601 }
7602 
7603 char SLPVectorizer::ID = 0;
7604 
7605 static const char lv_name[] = "SLP Vectorizer";
7606 
7607 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
7608 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
7609 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
7610 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
7611 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
7612 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
7613 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
7614 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
7615 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
7616 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
7617 
7618 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
7619