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/DenseMap.h"
21 #include "llvm/ADT/DenseSet.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/ADT/PostOrderIterator.h"
24 #include "llvm/ADT/PriorityQueue.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SetOperations.h"
27 #include "llvm/ADT/SetVector.h"
28 #include "llvm/ADT/SmallBitVector.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/iterator.h"
34 #include "llvm/ADT/iterator_range.h"
35 #include "llvm/Analysis/AliasAnalysis.h"
36 #include "llvm/Analysis/AssumptionCache.h"
37 #include "llvm/Analysis/CodeMetrics.h"
38 #include "llvm/Analysis/DemandedBits.h"
39 #include "llvm/Analysis/GlobalsModRef.h"
40 #include "llvm/Analysis/IVDescriptors.h"
41 #include "llvm/Analysis/LoopAccessAnalysis.h"
42 #include "llvm/Analysis/LoopInfo.h"
43 #include "llvm/Analysis/MemoryLocation.h"
44 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
45 #include "llvm/Analysis/ScalarEvolution.h"
46 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
47 #include "llvm/Analysis/TargetLibraryInfo.h"
48 #include "llvm/Analysis/TargetTransformInfo.h"
49 #include "llvm/Analysis/ValueTracking.h"
50 #include "llvm/Analysis/VectorUtils.h"
51 #include "llvm/IR/Attributes.h"
52 #include "llvm/IR/BasicBlock.h"
53 #include "llvm/IR/Constant.h"
54 #include "llvm/IR/Constants.h"
55 #include "llvm/IR/DataLayout.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/Operator.h"
67 #include "llvm/IR/PatternMatch.h"
68 #include "llvm/IR/Type.h"
69 #include "llvm/IR/Use.h"
70 #include "llvm/IR/User.h"
71 #include "llvm/IR/Value.h"
72 #include "llvm/IR/ValueHandle.h"
73 #ifdef EXPENSIVE_CHECKS
74 #include "llvm/IR/Verifier.h"
75 #endif
76 #include "llvm/Pass.h"
77 #include "llvm/Support/Casting.h"
78 #include "llvm/Support/CommandLine.h"
79 #include "llvm/Support/Compiler.h"
80 #include "llvm/Support/DOTGraphTraits.h"
81 #include "llvm/Support/Debug.h"
82 #include "llvm/Support/ErrorHandling.h"
83 #include "llvm/Support/GraphWriter.h"
84 #include "llvm/Support/InstructionCost.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/Local.h"
90 #include "llvm/Transforms/Utils/LoopUtils.h"
91 #include "llvm/Transforms/Vectorize.h"
92 #include <algorithm>
93 #include <cassert>
94 #include <cstdint>
95 #include <iterator>
96 #include <memory>
97 #include <set>
98 #include <string>
99 #include <tuple>
100 #include <utility>
101 #include <vector>
102 
103 using namespace llvm;
104 using namespace llvm::PatternMatch;
105 using namespace slpvectorizer;
106 
107 #define SV_NAME "slp-vectorizer"
108 #define DEBUG_TYPE "SLP"
109 
110 STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
111 
112 cl::opt<bool> RunSLPVectorization("vectorize-slp", cl::init(true), cl::Hidden,
113                                   cl::desc("Run the SLP vectorization passes"));
114 
115 static cl::opt<int>
116     SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
117                      cl::desc("Only vectorize if you gain more than this "
118                               "number "));
119 
120 static cl::opt<bool>
121 ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden,
122                    cl::desc("Attempt to vectorize horizontal reductions"));
123 
124 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
125     "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
126     cl::desc(
127         "Attempt to vectorize horizontal reductions feeding into a store"));
128 
129 static cl::opt<int>
130 MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden,
131     cl::desc("Attempt to vectorize for this register size in bits"));
132 
133 static cl::opt<unsigned>
134 MaxVFOption("slp-max-vf", cl::init(0), cl::Hidden,
135     cl::desc("Maximum SLP vectorization factor (0=unlimited)"));
136 
137 static cl::opt<int>
138 MaxStoreLookup("slp-max-store-lookup", cl::init(32), cl::Hidden,
139     cl::desc("Maximum depth of the lookup for consecutive stores."));
140 
141 /// Limits the size of scheduling regions in a block.
142 /// It avoid long compile times for _very_ large blocks where vector
143 /// instructions are spread over a wide range.
144 /// This limit is way higher than needed by real-world functions.
145 static cl::opt<int>
146 ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden,
147     cl::desc("Limit the size of the SLP scheduling region per block"));
148 
149 static cl::opt<int> MinVectorRegSizeOption(
150     "slp-min-reg-size", cl::init(128), cl::Hidden,
151     cl::desc("Attempt to vectorize for this register size in bits"));
152 
153 static cl::opt<unsigned> RecursionMaxDepth(
154     "slp-recursion-max-depth", cl::init(12), cl::Hidden,
155     cl::desc("Limit the recursion depth when building a vectorizable tree"));
156 
157 static cl::opt<unsigned> MinTreeSize(
158     "slp-min-tree-size", cl::init(3), cl::Hidden,
159     cl::desc("Only vectorize small trees if they are fully vectorizable"));
160 
161 // The maximum depth that the look-ahead score heuristic will explore.
162 // The higher this value, the higher the compilation time overhead.
163 static cl::opt<int> LookAheadMaxDepth(
164     "slp-max-look-ahead-depth", cl::init(2), cl::Hidden,
165     cl::desc("The maximum look-ahead depth for operand reordering scores"));
166 
167 // The maximum depth that the look-ahead score heuristic will explore
168 // when it probing among candidates for vectorization tree roots.
169 // The higher this value, the higher the compilation time overhead but unlike
170 // similar limit for operands ordering this is less frequently used, hence
171 // impact of higher value is less noticeable.
172 static cl::opt<int> RootLookAheadMaxDepth(
173     "slp-max-root-look-ahead-depth", cl::init(2), cl::Hidden,
174     cl::desc("The maximum look-ahead depth for searching best rooting option"));
175 
176 static cl::opt<bool>
177     ViewSLPTree("view-slp-tree", cl::Hidden,
178                 cl::desc("Display the SLP trees with Graphviz"));
179 
180 // Limit the number of alias checks. The limit is chosen so that
181 // it has no negative effect on the llvm benchmarks.
182 static const unsigned AliasedCheckLimit = 10;
183 
184 // Another limit for the alias checks: The maximum distance between load/store
185 // instructions where alias checks are done.
186 // This limit is useful for very large basic blocks.
187 static const unsigned MaxMemDepDistance = 160;
188 
189 /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
190 /// regions to be handled.
191 static const int MinScheduleRegionSize = 16;
192 
193 /// Predicate for the element types that the SLP vectorizer supports.
194 ///
195 /// The most important thing to filter here are types which are invalid in LLVM
196 /// vectors. We also filter target specific types which have absolutely no
197 /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
198 /// avoids spending time checking the cost model and realizing that they will
199 /// be inevitably scalarized.
200 static bool isValidElementType(Type *Ty) {
201   return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() &&
202          !Ty->isPPC_FP128Ty();
203 }
204 
205 /// \returns True if the value is a constant (but not globals/constant
206 /// expressions).
207 static bool isConstant(Value *V) {
208   return isa<Constant>(V) && !isa<ConstantExpr>(V) && !isa<GlobalValue>(V);
209 }
210 
211 /// Checks if \p V is one of vector-like instructions, i.e. undef,
212 /// insertelement/extractelement with constant indices for fixed vector type or
213 /// extractvalue instruction.
214 static bool isVectorLikeInstWithConstOps(Value *V) {
215   if (!isa<InsertElementInst, ExtractElementInst>(V) &&
216       !isa<ExtractValueInst, UndefValue>(V))
217     return false;
218   auto *I = dyn_cast<Instruction>(V);
219   if (!I || isa<ExtractValueInst>(I))
220     return true;
221   if (!isa<FixedVectorType>(I->getOperand(0)->getType()))
222     return false;
223   if (isa<ExtractElementInst>(I))
224     return isConstant(I->getOperand(1));
225   assert(isa<InsertElementInst>(V) && "Expected only insertelement.");
226   return isConstant(I->getOperand(2));
227 }
228 
229 /// \returns true if all of the instructions in \p VL are in the same block or
230 /// false otherwise.
231 static bool allSameBlock(ArrayRef<Value *> VL) {
232   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
233   if (!I0)
234     return false;
235   if (all_of(VL, isVectorLikeInstWithConstOps))
236     return true;
237 
238   BasicBlock *BB = I0->getParent();
239   for (int I = 1, E = VL.size(); I < E; I++) {
240     auto *II = dyn_cast<Instruction>(VL[I]);
241     if (!II)
242       return false;
243 
244     if (BB != II->getParent())
245       return false;
246   }
247   return true;
248 }
249 
250 /// \returns True if all of the values in \p VL are constants (but not
251 /// globals/constant expressions).
252 static bool allConstant(ArrayRef<Value *> VL) {
253   // Constant expressions and globals can't be vectorized like normal integer/FP
254   // constants.
255   return all_of(VL, isConstant);
256 }
257 
258 /// \returns True if all of the values in \p VL are identical or some of them
259 /// are UndefValue.
260 static bool isSplat(ArrayRef<Value *> VL) {
261   Value *FirstNonUndef = nullptr;
262   for (Value *V : VL) {
263     if (isa<UndefValue>(V))
264       continue;
265     if (!FirstNonUndef) {
266       FirstNonUndef = V;
267       continue;
268     }
269     if (V != FirstNonUndef)
270       return false;
271   }
272   return FirstNonUndef != nullptr;
273 }
274 
275 /// \returns True if \p I is commutative, handles CmpInst and BinaryOperator.
276 static bool isCommutative(Instruction *I) {
277   if (auto *Cmp = dyn_cast<CmpInst>(I))
278     return Cmp->isCommutative();
279   if (auto *BO = dyn_cast<BinaryOperator>(I))
280     return BO->isCommutative();
281   // TODO: This should check for generic Instruction::isCommutative(), but
282   //       we need to confirm that the caller code correctly handles Intrinsics
283   //       for example (does not have 2 operands).
284   return false;
285 }
286 
287 /// Checks if the given value is actually an undefined constant vector.
288 static bool isUndefVector(const Value *V) {
289   if (isa<UndefValue>(V))
290     return true;
291   auto *C = dyn_cast<Constant>(V);
292   if (!C)
293     return false;
294   if (!C->containsUndefOrPoisonElement())
295     return false;
296   auto *VecTy = dyn_cast<FixedVectorType>(C->getType());
297   if (!VecTy)
298     return false;
299   for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
300     if (Constant *Elem = C->getAggregateElement(I))
301       if (!isa<UndefValue>(Elem))
302         return false;
303   }
304   return true;
305 }
306 
307 /// Checks if the vector of instructions can be represented as a shuffle, like:
308 /// %x0 = extractelement <4 x i8> %x, i32 0
309 /// %x3 = extractelement <4 x i8> %x, i32 3
310 /// %y1 = extractelement <4 x i8> %y, i32 1
311 /// %y2 = extractelement <4 x i8> %y, i32 2
312 /// %x0x0 = mul i8 %x0, %x0
313 /// %x3x3 = mul i8 %x3, %x3
314 /// %y1y1 = mul i8 %y1, %y1
315 /// %y2y2 = mul i8 %y2, %y2
316 /// %ins1 = insertelement <4 x i8> poison, i8 %x0x0, i32 0
317 /// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1
318 /// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2
319 /// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3
320 /// ret <4 x i8> %ins4
321 /// can be transformed into:
322 /// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5,
323 ///                                                         i32 6>
324 /// %2 = mul <4 x i8> %1, %1
325 /// ret <4 x i8> %2
326 /// We convert this initially to something like:
327 /// %x0 = extractelement <4 x i8> %x, i32 0
328 /// %x3 = extractelement <4 x i8> %x, i32 3
329 /// %y1 = extractelement <4 x i8> %y, i32 1
330 /// %y2 = extractelement <4 x i8> %y, i32 2
331 /// %1 = insertelement <4 x i8> poison, i8 %x0, i32 0
332 /// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1
333 /// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2
334 /// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3
335 /// %5 = mul <4 x i8> %4, %4
336 /// %6 = extractelement <4 x i8> %5, i32 0
337 /// %ins1 = insertelement <4 x i8> poison, i8 %6, i32 0
338 /// %7 = extractelement <4 x i8> %5, i32 1
339 /// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1
340 /// %8 = extractelement <4 x i8> %5, i32 2
341 /// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2
342 /// %9 = extractelement <4 x i8> %5, i32 3
343 /// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3
344 /// ret <4 x i8> %ins4
345 /// InstCombiner transforms this into a shuffle and vector mul
346 /// Mask will return the Shuffle Mask equivalent to the extracted elements.
347 /// TODO: Can we split off and reuse the shuffle mask detection from
348 /// TargetTransformInfo::getInstructionThroughput?
349 static Optional<TargetTransformInfo::ShuffleKind>
350 isFixedVectorShuffle(ArrayRef<Value *> VL, SmallVectorImpl<int> &Mask) {
351   const auto *It =
352       find_if(VL, [](Value *V) { return isa<ExtractElementInst>(V); });
353   if (It == VL.end())
354     return None;
355   auto *EI0 = cast<ExtractElementInst>(*It);
356   if (isa<ScalableVectorType>(EI0->getVectorOperandType()))
357     return None;
358   unsigned Size =
359       cast<FixedVectorType>(EI0->getVectorOperandType())->getNumElements();
360   Value *Vec1 = nullptr;
361   Value *Vec2 = nullptr;
362   enum ShuffleMode { Unknown, Select, Permute };
363   ShuffleMode CommonShuffleMode = Unknown;
364   Mask.assign(VL.size(), UndefMaskElem);
365   for (unsigned I = 0, E = VL.size(); I < E; ++I) {
366     // Undef can be represented as an undef element in a vector.
367     if (isa<UndefValue>(VL[I]))
368       continue;
369     auto *EI = cast<ExtractElementInst>(VL[I]);
370     if (isa<ScalableVectorType>(EI->getVectorOperandType()))
371       return None;
372     auto *Vec = EI->getVectorOperand();
373     // We can extractelement from undef or poison vector.
374     if (isUndefVector(Vec))
375       continue;
376     // All vector operands must have the same number of vector elements.
377     if (cast<FixedVectorType>(Vec->getType())->getNumElements() != Size)
378       return None;
379     if (isa<UndefValue>(EI->getIndexOperand()))
380       continue;
381     auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand());
382     if (!Idx)
383       return None;
384     // Undefined behavior if Idx is negative or >= Size.
385     if (Idx->getValue().uge(Size))
386       continue;
387     unsigned IntIdx = Idx->getValue().getZExtValue();
388     Mask[I] = IntIdx;
389     // For correct shuffling we have to have at most 2 different vector operands
390     // in all extractelement instructions.
391     if (!Vec1 || Vec1 == Vec) {
392       Vec1 = Vec;
393     } else if (!Vec2 || Vec2 == Vec) {
394       Vec2 = Vec;
395       Mask[I] += Size;
396     } else {
397       return None;
398     }
399     if (CommonShuffleMode == Permute)
400       continue;
401     // If the extract index is not the same as the operation number, it is a
402     // permutation.
403     if (IntIdx != I) {
404       CommonShuffleMode = Permute;
405       continue;
406     }
407     CommonShuffleMode = Select;
408   }
409   // If we're not crossing lanes in different vectors, consider it as blending.
410   if (CommonShuffleMode == Select && Vec2)
411     return TargetTransformInfo::SK_Select;
412   // If Vec2 was never used, we have a permutation of a single vector, otherwise
413   // we have permutation of 2 vectors.
414   return Vec2 ? TargetTransformInfo::SK_PermuteTwoSrc
415               : TargetTransformInfo::SK_PermuteSingleSrc;
416 }
417 
418 namespace {
419 
420 /// Main data required for vectorization of instructions.
421 struct InstructionsState {
422   /// The very first instruction in the list with the main opcode.
423   Value *OpValue = nullptr;
424 
425   /// The main/alternate instruction.
426   Instruction *MainOp = nullptr;
427   Instruction *AltOp = nullptr;
428 
429   /// The main/alternate opcodes for the list of instructions.
430   unsigned getOpcode() const {
431     return MainOp ? MainOp->getOpcode() : 0;
432   }
433 
434   unsigned getAltOpcode() const {
435     return AltOp ? AltOp->getOpcode() : 0;
436   }
437 
438   /// Some of the instructions in the list have alternate opcodes.
439   bool isAltShuffle() const { return AltOp != MainOp; }
440 
441   bool isOpcodeOrAlt(Instruction *I) const {
442     unsigned CheckedOpcode = I->getOpcode();
443     return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode;
444   }
445 
446   InstructionsState() = delete;
447   InstructionsState(Value *OpValue, Instruction *MainOp, Instruction *AltOp)
448       : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {}
449 };
450 
451 } // end anonymous namespace
452 
453 /// Chooses the correct key for scheduling data. If \p Op has the same (or
454 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p
455 /// OpValue.
456 static Value *isOneOf(const InstructionsState &S, Value *Op) {
457   auto *I = dyn_cast<Instruction>(Op);
458   if (I && S.isOpcodeOrAlt(I))
459     return Op;
460   return S.OpValue;
461 }
462 
463 /// \returns true if \p Opcode is allowed as part of of the main/alternate
464 /// instruction for SLP vectorization.
465 ///
466 /// Example of unsupported opcode is SDIV that can potentially cause UB if the
467 /// "shuffled out" lane would result in division by zero.
468 static bool isValidForAlternation(unsigned Opcode) {
469   if (Instruction::isIntDivRem(Opcode))
470     return false;
471 
472   return true;
473 }
474 
475 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
476                                        unsigned BaseIndex = 0);
477 
478 /// Checks if the provided operands of 2 cmp instructions are compatible, i.e.
479 /// compatible instructions or constants, or just some other regular values.
480 static bool areCompatibleCmpOps(Value *BaseOp0, Value *BaseOp1, Value *Op0,
481                                 Value *Op1) {
482   return (isConstant(BaseOp0) && isConstant(Op0)) ||
483          (isConstant(BaseOp1) && isConstant(Op1)) ||
484          (!isa<Instruction>(BaseOp0) && !isa<Instruction>(Op0) &&
485           !isa<Instruction>(BaseOp1) && !isa<Instruction>(Op1)) ||
486          getSameOpcode({BaseOp0, Op0}).getOpcode() ||
487          getSameOpcode({BaseOp1, Op1}).getOpcode();
488 }
489 
490 /// \returns analysis of the Instructions in \p VL described in
491 /// InstructionsState, the Opcode that we suppose the whole list
492 /// could be vectorized even if its structure is diverse.
493 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
494                                        unsigned BaseIndex) {
495   // Make sure these are all Instructions.
496   if (llvm::any_of(VL, [](Value *V) { return !isa<Instruction>(V); }))
497     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
498 
499   bool IsCastOp = isa<CastInst>(VL[BaseIndex]);
500   bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]);
501   bool IsCmpOp = isa<CmpInst>(VL[BaseIndex]);
502   CmpInst::Predicate BasePred =
503       IsCmpOp ? cast<CmpInst>(VL[BaseIndex])->getPredicate()
504               : CmpInst::BAD_ICMP_PREDICATE;
505   unsigned Opcode = cast<Instruction>(VL[BaseIndex])->getOpcode();
506   unsigned AltOpcode = Opcode;
507   unsigned AltIndex = BaseIndex;
508 
509   // Check for one alternate opcode from another BinaryOperator.
510   // TODO - generalize to support all operators (types, calls etc.).
511   for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) {
512     unsigned InstOpcode = cast<Instruction>(VL[Cnt])->getOpcode();
513     if (IsBinOp && isa<BinaryOperator>(VL[Cnt])) {
514       if (InstOpcode == Opcode || InstOpcode == AltOpcode)
515         continue;
516       if (Opcode == AltOpcode && isValidForAlternation(InstOpcode) &&
517           isValidForAlternation(Opcode)) {
518         AltOpcode = InstOpcode;
519         AltIndex = Cnt;
520         continue;
521       }
522     } else if (IsCastOp && isa<CastInst>(VL[Cnt])) {
523       Type *Ty0 = cast<Instruction>(VL[BaseIndex])->getOperand(0)->getType();
524       Type *Ty1 = cast<Instruction>(VL[Cnt])->getOperand(0)->getType();
525       if (Ty0 == Ty1) {
526         if (InstOpcode == Opcode || InstOpcode == AltOpcode)
527           continue;
528         if (Opcode == AltOpcode) {
529           assert(isValidForAlternation(Opcode) &&
530                  isValidForAlternation(InstOpcode) &&
531                  "Cast isn't safe for alternation, logic needs to be updated!");
532           AltOpcode = InstOpcode;
533           AltIndex = Cnt;
534           continue;
535         }
536       }
537     } else if (IsCmpOp && isa<CmpInst>(VL[Cnt])) {
538       auto *BaseInst = cast<Instruction>(VL[BaseIndex]);
539       auto *Inst = cast<Instruction>(VL[Cnt]);
540       Type *Ty0 = BaseInst->getOperand(0)->getType();
541       Type *Ty1 = Inst->getOperand(0)->getType();
542       if (Ty0 == Ty1) {
543         Value *BaseOp0 = BaseInst->getOperand(0);
544         Value *BaseOp1 = BaseInst->getOperand(1);
545         Value *Op0 = Inst->getOperand(0);
546         Value *Op1 = Inst->getOperand(1);
547         CmpInst::Predicate CurrentPred =
548             cast<CmpInst>(VL[Cnt])->getPredicate();
549         CmpInst::Predicate SwappedCurrentPred =
550             CmpInst::getSwappedPredicate(CurrentPred);
551         // Check for compatible operands. If the corresponding operands are not
552         // compatible - need to perform alternate vectorization.
553         if (InstOpcode == Opcode) {
554           if (BasePred == CurrentPred &&
555               areCompatibleCmpOps(BaseOp0, BaseOp1, Op0, Op1))
556             continue;
557           if (BasePred == SwappedCurrentPred &&
558               areCompatibleCmpOps(BaseOp0, BaseOp1, Op1, Op0))
559             continue;
560           if (E == 2 &&
561               (BasePred == CurrentPred || BasePred == SwappedCurrentPred))
562             continue;
563           auto *AltInst = cast<CmpInst>(VL[AltIndex]);
564           CmpInst::Predicate AltPred = AltInst->getPredicate();
565           Value *AltOp0 = AltInst->getOperand(0);
566           Value *AltOp1 = AltInst->getOperand(1);
567           // Check if operands are compatible with alternate operands.
568           if (AltPred == CurrentPred &&
569               areCompatibleCmpOps(AltOp0, AltOp1, Op0, Op1))
570             continue;
571           if (AltPred == SwappedCurrentPred &&
572               areCompatibleCmpOps(AltOp0, AltOp1, Op1, Op0))
573             continue;
574         }
575         if (BaseIndex == AltIndex && BasePred != CurrentPred) {
576           assert(isValidForAlternation(Opcode) &&
577                  isValidForAlternation(InstOpcode) &&
578                  "Cast isn't safe for alternation, logic needs to be updated!");
579           AltIndex = Cnt;
580           continue;
581         }
582         auto *AltInst = cast<CmpInst>(VL[AltIndex]);
583         CmpInst::Predicate AltPred = AltInst->getPredicate();
584         if (BasePred == CurrentPred || BasePred == SwappedCurrentPred ||
585             AltPred == CurrentPred || AltPred == SwappedCurrentPred)
586           continue;
587       }
588     } else if (InstOpcode == Opcode || InstOpcode == AltOpcode)
589       continue;
590     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
591   }
592 
593   return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]),
594                            cast<Instruction>(VL[AltIndex]));
595 }
596 
597 /// \returns true if all of the values in \p VL have the same type or false
598 /// otherwise.
599 static bool allSameType(ArrayRef<Value *> VL) {
600   Type *Ty = VL[0]->getType();
601   for (int i = 1, e = VL.size(); i < e; i++)
602     if (VL[i]->getType() != Ty)
603       return false;
604 
605   return true;
606 }
607 
608 /// \returns True if Extract{Value,Element} instruction extracts element Idx.
609 static Optional<unsigned> getExtractIndex(Instruction *E) {
610   unsigned Opcode = E->getOpcode();
611   assert((Opcode == Instruction::ExtractElement ||
612           Opcode == Instruction::ExtractValue) &&
613          "Expected extractelement or extractvalue instruction.");
614   if (Opcode == Instruction::ExtractElement) {
615     auto *CI = dyn_cast<ConstantInt>(E->getOperand(1));
616     if (!CI)
617       return None;
618     return CI->getZExtValue();
619   }
620   ExtractValueInst *EI = cast<ExtractValueInst>(E);
621   if (EI->getNumIndices() != 1)
622     return None;
623   return *EI->idx_begin();
624 }
625 
626 /// \returns True if in-tree use also needs extract. This refers to
627 /// possible scalar operand in vectorized instruction.
628 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
629                                     TargetLibraryInfo *TLI) {
630   unsigned Opcode = UserInst->getOpcode();
631   switch (Opcode) {
632   case Instruction::Load: {
633     LoadInst *LI = cast<LoadInst>(UserInst);
634     return (LI->getPointerOperand() == Scalar);
635   }
636   case Instruction::Store: {
637     StoreInst *SI = cast<StoreInst>(UserInst);
638     return (SI->getPointerOperand() == Scalar);
639   }
640   case Instruction::Call: {
641     CallInst *CI = cast<CallInst>(UserInst);
642     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
643     for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
644       if (isVectorIntrinsicWithScalarOpAtArg(ID, i))
645         return (CI->getArgOperand(i) == Scalar);
646     }
647     LLVM_FALLTHROUGH;
648   }
649   default:
650     return false;
651   }
652 }
653 
654 /// \returns the AA location that is being access by the instruction.
655 static MemoryLocation getLocation(Instruction *I) {
656   if (StoreInst *SI = dyn_cast<StoreInst>(I))
657     return MemoryLocation::get(SI);
658   if (LoadInst *LI = dyn_cast<LoadInst>(I))
659     return MemoryLocation::get(LI);
660   return MemoryLocation();
661 }
662 
663 /// \returns True if the instruction is not a volatile or atomic load/store.
664 static bool isSimple(Instruction *I) {
665   if (LoadInst *LI = dyn_cast<LoadInst>(I))
666     return LI->isSimple();
667   if (StoreInst *SI = dyn_cast<StoreInst>(I))
668     return SI->isSimple();
669   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
670     return !MI->isVolatile();
671   return true;
672 }
673 
674 /// Shuffles \p Mask in accordance with the given \p SubMask.
675 static void addMask(SmallVectorImpl<int> &Mask, ArrayRef<int> SubMask) {
676   if (SubMask.empty())
677     return;
678   if (Mask.empty()) {
679     Mask.append(SubMask.begin(), SubMask.end());
680     return;
681   }
682   SmallVector<int> NewMask(SubMask.size(), UndefMaskElem);
683   int TermValue = std::min(Mask.size(), SubMask.size());
684   for (int I = 0, E = SubMask.size(); I < E; ++I) {
685     if (SubMask[I] >= TermValue || SubMask[I] == UndefMaskElem ||
686         Mask[SubMask[I]] >= TermValue)
687       continue;
688     NewMask[I] = Mask[SubMask[I]];
689   }
690   Mask.swap(NewMask);
691 }
692 
693 /// Order may have elements assigned special value (size) which is out of
694 /// bounds. Such indices only appear on places which correspond to undef values
695 /// (see canReuseExtract for details) and used in order to avoid undef values
696 /// have effect on operands ordering.
697 /// The first loop below simply finds all unused indices and then the next loop
698 /// nest assigns these indices for undef values positions.
699 /// As an example below Order has two undef positions and they have assigned
700 /// values 3 and 7 respectively:
701 /// before:  6 9 5 4 9 2 1 0
702 /// after:   6 3 5 4 7 2 1 0
703 static void fixupOrderingIndices(SmallVectorImpl<unsigned> &Order) {
704   const unsigned Sz = Order.size();
705   SmallBitVector UnusedIndices(Sz, /*t=*/true);
706   SmallBitVector MaskedIndices(Sz);
707   for (unsigned I = 0; I < Sz; ++I) {
708     if (Order[I] < Sz)
709       UnusedIndices.reset(Order[I]);
710     else
711       MaskedIndices.set(I);
712   }
713   if (MaskedIndices.none())
714     return;
715   assert(UnusedIndices.count() == MaskedIndices.count() &&
716          "Non-synced masked/available indices.");
717   int Idx = UnusedIndices.find_first();
718   int MIdx = MaskedIndices.find_first();
719   while (MIdx >= 0) {
720     assert(Idx >= 0 && "Indices must be synced.");
721     Order[MIdx] = Idx;
722     Idx = UnusedIndices.find_next(Idx);
723     MIdx = MaskedIndices.find_next(MIdx);
724   }
725 }
726 
727 namespace llvm {
728 
729 static void inversePermutation(ArrayRef<unsigned> Indices,
730                                SmallVectorImpl<int> &Mask) {
731   Mask.clear();
732   const unsigned E = Indices.size();
733   Mask.resize(E, UndefMaskElem);
734   for (unsigned I = 0; I < E; ++I)
735     Mask[Indices[I]] = I;
736 }
737 
738 /// \returns inserting index of InsertElement or InsertValue instruction,
739 /// using Offset as base offset for index.
740 static Optional<unsigned> getInsertIndex(Value *InsertInst,
741                                          unsigned Offset = 0) {
742   int Index = Offset;
743   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst)) {
744     if (auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2))) {
745       auto *VT = cast<FixedVectorType>(IE->getType());
746       if (CI->getValue().uge(VT->getNumElements()))
747         return None;
748       Index *= VT->getNumElements();
749       Index += CI->getZExtValue();
750       return Index;
751     }
752     return None;
753   }
754 
755   auto *IV = cast<InsertValueInst>(InsertInst);
756   Type *CurrentType = IV->getType();
757   for (unsigned I : IV->indices()) {
758     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
759       Index *= ST->getNumElements();
760       CurrentType = ST->getElementType(I);
761     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
762       Index *= AT->getNumElements();
763       CurrentType = AT->getElementType();
764     } else {
765       return None;
766     }
767     Index += I;
768   }
769   return Index;
770 }
771 
772 /// Reorders the list of scalars in accordance with the given \p Mask.
773 static void reorderScalars(SmallVectorImpl<Value *> &Scalars,
774                            ArrayRef<int> Mask) {
775   assert(!Mask.empty() && "Expected non-empty mask.");
776   SmallVector<Value *> Prev(Scalars.size(),
777                             UndefValue::get(Scalars.front()->getType()));
778   Prev.swap(Scalars);
779   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
780     if (Mask[I] != UndefMaskElem)
781       Scalars[Mask[I]] = Prev[I];
782 }
783 
784 /// Checks if the provided value does not require scheduling. It does not
785 /// require scheduling if this is not an instruction or it is an instruction
786 /// that does not read/write memory and all operands are either not instructions
787 /// or phi nodes or instructions from different blocks.
788 static bool areAllOperandsNonInsts(Value *V) {
789   auto *I = dyn_cast<Instruction>(V);
790   if (!I)
791     return true;
792   return !mayHaveNonDefUseDependency(*I) &&
793     all_of(I->operands(), [I](Value *V) {
794       auto *IO = dyn_cast<Instruction>(V);
795       if (!IO)
796         return true;
797       return isa<PHINode>(IO) || IO->getParent() != I->getParent();
798     });
799 }
800 
801 /// Checks if the provided value does not require scheduling. It does not
802 /// require scheduling if this is not an instruction or it is an instruction
803 /// that does not read/write memory and all users are phi nodes or instructions
804 /// from the different blocks.
805 static bool isUsedOutsideBlock(Value *V) {
806   auto *I = dyn_cast<Instruction>(V);
807   if (!I)
808     return true;
809   // Limits the number of uses to save compile time.
810   constexpr int UsesLimit = 8;
811   return !I->mayReadOrWriteMemory() && !I->hasNUsesOrMore(UsesLimit) &&
812          all_of(I->users(), [I](User *U) {
813            auto *IU = dyn_cast<Instruction>(U);
814            if (!IU)
815              return true;
816            return IU->getParent() != I->getParent() || isa<PHINode>(IU);
817          });
818 }
819 
820 /// Checks if the specified value does not require scheduling. It does not
821 /// require scheduling if all operands and all users do not need to be scheduled
822 /// in the current basic block.
823 static bool doesNotNeedToBeScheduled(Value *V) {
824   return areAllOperandsNonInsts(V) && isUsedOutsideBlock(V);
825 }
826 
827 /// Checks if the specified array of instructions does not require scheduling.
828 /// It is so if all either instructions have operands that do not require
829 /// scheduling or their users do not require scheduling since they are phis or
830 /// in other basic blocks.
831 static bool doesNotNeedToSchedule(ArrayRef<Value *> VL) {
832   return !VL.empty() &&
833          (all_of(VL, isUsedOutsideBlock) || all_of(VL, areAllOperandsNonInsts));
834 }
835 
836 namespace slpvectorizer {
837 
838 /// Bottom Up SLP Vectorizer.
839 class BoUpSLP {
840   struct TreeEntry;
841   struct ScheduleData;
842 
843 public:
844   using ValueList = SmallVector<Value *, 8>;
845   using InstrList = SmallVector<Instruction *, 16>;
846   using ValueSet = SmallPtrSet<Value *, 16>;
847   using StoreList = SmallVector<StoreInst *, 8>;
848   using ExtraValueToDebugLocsMap =
849       MapVector<Value *, SmallVector<Instruction *, 2>>;
850   using OrdersType = SmallVector<unsigned, 4>;
851 
852   BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
853           TargetLibraryInfo *TLi, AAResults *Aa, LoopInfo *Li,
854           DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB,
855           const DataLayout *DL, OptimizationRemarkEmitter *ORE)
856       : BatchAA(*Aa), F(Func), SE(Se), TTI(Tti), TLI(TLi), LI(Li),
857         DT(Dt), AC(AC), DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) {
858     CodeMetrics::collectEphemeralValues(F, AC, EphValues);
859     // Use the vector register size specified by the target unless overridden
860     // by a command-line option.
861     // TODO: It would be better to limit the vectorization factor based on
862     //       data type rather than just register size. For example, x86 AVX has
863     //       256-bit registers, but it does not support integer operations
864     //       at that width (that requires AVX2).
865     if (MaxVectorRegSizeOption.getNumOccurrences())
866       MaxVecRegSize = MaxVectorRegSizeOption;
867     else
868       MaxVecRegSize =
869           TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
870               .getFixedSize();
871 
872     if (MinVectorRegSizeOption.getNumOccurrences())
873       MinVecRegSize = MinVectorRegSizeOption;
874     else
875       MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
876   }
877 
878   /// Vectorize the tree that starts with the elements in \p VL.
879   /// Returns the vectorized root.
880   Value *vectorizeTree();
881 
882   /// Vectorize the tree but with the list of externally used values \p
883   /// ExternallyUsedValues. Values in this MapVector can be replaced but the
884   /// generated extractvalue instructions.
885   Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues);
886 
887   /// \returns the cost incurred by unwanted spills and fills, caused by
888   /// holding live values over call sites.
889   InstructionCost getSpillCost() const;
890 
891   /// \returns the vectorization cost of the subtree that starts at \p VL.
892   /// A negative number means that this is profitable.
893   InstructionCost getTreeCost(ArrayRef<Value *> VectorizedVals = None);
894 
895   /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
896   /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
897   void buildTree(ArrayRef<Value *> Roots,
898                  ArrayRef<Value *> UserIgnoreLst = None);
899 
900   /// Builds external uses of the vectorized scalars, i.e. the list of
901   /// vectorized scalars to be extracted, their lanes and their scalar users. \p
902   /// ExternallyUsedValues contains additional list of external uses to handle
903   /// vectorization of reductions.
904   void
905   buildExternalUses(const ExtraValueToDebugLocsMap &ExternallyUsedValues = {});
906 
907   /// Clear the internal data structures that are created by 'buildTree'.
908   void deleteTree() {
909     VectorizableTree.clear();
910     ScalarToTreeEntry.clear();
911     MustGather.clear();
912     ExternalUses.clear();
913     for (auto &Iter : BlocksSchedules) {
914       BlockScheduling *BS = Iter.second.get();
915       BS->clear();
916     }
917     MinBWs.clear();
918     InstrElementSize.clear();
919   }
920 
921   unsigned getTreeSize() const { return VectorizableTree.size(); }
922 
923   /// Perform LICM and CSE on the newly generated gather sequences.
924   void optimizeGatherSequence();
925 
926   /// Checks if the specified gather tree entry \p TE can be represented as a
927   /// shuffled vector entry + (possibly) permutation with other gathers. It
928   /// implements the checks only for possibly ordered scalars (Loads,
929   /// ExtractElement, ExtractValue), which can be part of the graph.
930   Optional<OrdersType> findReusedOrderedScalars(const TreeEntry &TE);
931 
932   /// Sort loads into increasing pointers offsets to allow greater clustering.
933   Optional<OrdersType> findPartiallyOrderedLoads(const TreeEntry &TE);
934 
935   /// Gets reordering data for the given tree entry. If the entry is vectorized
936   /// - just return ReorderIndices, otherwise check if the scalars can be
937   /// reordered and return the most optimal order.
938   /// \param TopToBottom If true, include the order of vectorized stores and
939   /// insertelement nodes, otherwise skip them.
940   Optional<OrdersType> getReorderingData(const TreeEntry &TE, bool TopToBottom);
941 
942   /// Reorders the current graph to the most profitable order starting from the
943   /// root node to the leaf nodes. The best order is chosen only from the nodes
944   /// of the same size (vectorization factor). Smaller nodes are considered
945   /// parts of subgraph with smaller VF and they are reordered independently. We
946   /// can make it because we still need to extend smaller nodes to the wider VF
947   /// and we can merge reordering shuffles with the widening shuffles.
948   void reorderTopToBottom();
949 
950   /// Reorders the current graph to the most profitable order starting from
951   /// leaves to the root. It allows to rotate small subgraphs and reduce the
952   /// number of reshuffles if the leaf nodes use the same order. In this case we
953   /// can merge the orders and just shuffle user node instead of shuffling its
954   /// operands. Plus, even the leaf nodes have different orders, it allows to
955   /// sink reordering in the graph closer to the root node and merge it later
956   /// during analysis.
957   void reorderBottomToTop(bool IgnoreReorder = false);
958 
959   /// \return The vector element size in bits to use when vectorizing the
960   /// expression tree ending at \p V. If V is a store, the size is the width of
961   /// the stored value. Otherwise, the size is the width of the largest loaded
962   /// value reaching V. This method is used by the vectorizer to calculate
963   /// vectorization factors.
964   unsigned getVectorElementSize(Value *V);
965 
966   /// Compute the minimum type sizes required to represent the entries in a
967   /// vectorizable tree.
968   void computeMinimumValueSizes();
969 
970   // \returns maximum vector register size as set by TTI or overridden by cl::opt.
971   unsigned getMaxVecRegSize() const {
972     return MaxVecRegSize;
973   }
974 
975   // \returns minimum vector register size as set by cl::opt.
976   unsigned getMinVecRegSize() const {
977     return MinVecRegSize;
978   }
979 
980   unsigned getMinVF(unsigned Sz) const {
981     return std::max(2U, getMinVecRegSize() / Sz);
982   }
983 
984   unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const {
985     unsigned MaxVF = MaxVFOption.getNumOccurrences() ?
986       MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode);
987     return MaxVF ? MaxVF : UINT_MAX;
988   }
989 
990   /// Check if homogeneous aggregate is isomorphic to some VectorType.
991   /// Accepts homogeneous multidimensional aggregate of scalars/vectors like
992   /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> },
993   /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on.
994   ///
995   /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
996   unsigned canMapToVector(Type *T, const DataLayout &DL) const;
997 
998   /// \returns True if the VectorizableTree is both tiny and not fully
999   /// vectorizable. We do not vectorize such trees.
1000   bool isTreeTinyAndNotFullyVectorizable(bool ForReduction = false) const;
1001 
1002   /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values
1003   /// can be load combined in the backend. Load combining may not be allowed in
1004   /// the IR optimizer, so we do not want to alter the pattern. For example,
1005   /// partially transforming a scalar bswap() pattern into vector code is
1006   /// effectively impossible for the backend to undo.
1007   /// TODO: If load combining is allowed in the IR optimizer, this analysis
1008   ///       may not be necessary.
1009   bool isLoadCombineReductionCandidate(RecurKind RdxKind) const;
1010 
1011   /// Assume that a vector of stores of bitwise-or/shifted/zexted loaded values
1012   /// can be load combined in the backend. Load combining may not be allowed in
1013   /// the IR optimizer, so we do not want to alter the pattern. For example,
1014   /// partially transforming a scalar bswap() pattern into vector code is
1015   /// effectively impossible for the backend to undo.
1016   /// TODO: If load combining is allowed in the IR optimizer, this analysis
1017   ///       may not be necessary.
1018   bool isLoadCombineCandidate() const;
1019 
1020   OptimizationRemarkEmitter *getORE() { return ORE; }
1021 
1022   /// This structure holds any data we need about the edges being traversed
1023   /// during buildTree_rec(). We keep track of:
1024   /// (i) the user TreeEntry index, and
1025   /// (ii) the index of the edge.
1026   struct EdgeInfo {
1027     EdgeInfo() = default;
1028     EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx)
1029         : UserTE(UserTE), EdgeIdx(EdgeIdx) {}
1030     /// The user TreeEntry.
1031     TreeEntry *UserTE = nullptr;
1032     /// The operand index of the use.
1033     unsigned EdgeIdx = UINT_MAX;
1034 #ifndef NDEBUG
1035     friend inline raw_ostream &operator<<(raw_ostream &OS,
1036                                           const BoUpSLP::EdgeInfo &EI) {
1037       EI.dump(OS);
1038       return OS;
1039     }
1040     /// Debug print.
1041     void dump(raw_ostream &OS) const {
1042       OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null")
1043          << " EdgeIdx:" << EdgeIdx << "}";
1044     }
1045     LLVM_DUMP_METHOD void dump() const { dump(dbgs()); }
1046 #endif
1047   };
1048 
1049   /// A helper class used for scoring candidates for two consecutive lanes.
1050   class LookAheadHeuristics {
1051     const DataLayout &DL;
1052     ScalarEvolution &SE;
1053     const BoUpSLP &R;
1054     int NumLanes; // Total number of lanes (aka vectorization factor).
1055     int MaxLevel; // The maximum recursion depth for accumulating score.
1056 
1057   public:
1058     LookAheadHeuristics(const DataLayout &DL, ScalarEvolution &SE,
1059                         const BoUpSLP &R, int NumLanes, int MaxLevel)
1060         : DL(DL), SE(SE), R(R), NumLanes(NumLanes), MaxLevel(MaxLevel) {}
1061 
1062     // The hard-coded scores listed here are not very important, though it shall
1063     // be higher for better matches to improve the resulting cost. When
1064     // computing the scores of matching one sub-tree with another, we are
1065     // basically counting the number of values that are matching. So even if all
1066     // scores are set to 1, we would still get a decent matching result.
1067     // However, sometimes we have to break ties. For example we may have to
1068     // choose between matching loads vs matching opcodes. This is what these
1069     // scores are helping us with: they provide the order of preference. Also,
1070     // this is important if the scalar is externally used or used in another
1071     // tree entry node in the different lane.
1072 
1073     /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]).
1074     static const int ScoreConsecutiveLoads = 4;
1075     /// The same load multiple times. This should have a better score than
1076     /// `ScoreSplat` because it in x86 for a 2-lane vector we can represent it
1077     /// with `movddup (%reg), xmm0` which has a throughput of 0.5 versus 0.5 for
1078     /// a vector load and 1.0 for a broadcast.
1079     static const int ScoreSplatLoads = 3;
1080     /// Loads from reversed memory addresses, e.g. load(A[i+1]), load(A[i]).
1081     static const int ScoreReversedLoads = 3;
1082     /// ExtractElementInst from same vector and consecutive indexes.
1083     static const int ScoreConsecutiveExtracts = 4;
1084     /// ExtractElementInst from same vector and reversed indices.
1085     static const int ScoreReversedExtracts = 3;
1086     /// Constants.
1087     static const int ScoreConstants = 2;
1088     /// Instructions with the same opcode.
1089     static const int ScoreSameOpcode = 2;
1090     /// Instructions with alt opcodes (e.g, add + sub).
1091     static const int ScoreAltOpcodes = 1;
1092     /// Identical instructions (a.k.a. splat or broadcast).
1093     static const int ScoreSplat = 1;
1094     /// Matching with an undef is preferable to failing.
1095     static const int ScoreUndef = 1;
1096     /// Score for failing to find a decent match.
1097     static const int ScoreFail = 0;
1098     /// Score if all users are vectorized.
1099     static const int ScoreAllUserVectorized = 1;
1100 
1101     /// \returns the score of placing \p V1 and \p V2 in consecutive lanes.
1102     /// \p U1 and \p U2 are the users of \p V1 and \p V2.
1103     /// Also, checks if \p V1 and \p V2 are compatible with instructions in \p
1104     /// MainAltOps.
1105     int getShallowScore(Value *V1, Value *V2, Instruction *U1, Instruction *U2,
1106                         ArrayRef<Value *> MainAltOps) const {
1107       if (V1 == V2) {
1108         if (isa<LoadInst>(V1)) {
1109           // Retruns true if the users of V1 and V2 won't need to be extracted.
1110           auto AllUsersAreInternal = [U1, U2, this](Value *V1, Value *V2) {
1111             // Bail out if we have too many uses to save compilation time.
1112             static constexpr unsigned Limit = 8;
1113             if (V1->hasNUsesOrMore(Limit) || V2->hasNUsesOrMore(Limit))
1114               return false;
1115 
1116             auto AllUsersVectorized = [U1, U2, this](Value *V) {
1117               return llvm::all_of(V->users(), [U1, U2, this](Value *U) {
1118                 return U == U1 || U == U2 || R.getTreeEntry(U) != nullptr;
1119               });
1120             };
1121             return AllUsersVectorized(V1) && AllUsersVectorized(V2);
1122           };
1123           // A broadcast of a load can be cheaper on some targets.
1124           if (R.TTI->isLegalBroadcastLoad(V1->getType(),
1125                                           ElementCount::getFixed(NumLanes)) &&
1126               ((int)V1->getNumUses() == NumLanes ||
1127                AllUsersAreInternal(V1, V2)))
1128             return LookAheadHeuristics::ScoreSplatLoads;
1129         }
1130         return LookAheadHeuristics::ScoreSplat;
1131       }
1132 
1133       auto *LI1 = dyn_cast<LoadInst>(V1);
1134       auto *LI2 = dyn_cast<LoadInst>(V2);
1135       if (LI1 && LI2) {
1136         if (LI1->getParent() != LI2->getParent())
1137           return LookAheadHeuristics::ScoreFail;
1138 
1139         Optional<int> Dist = getPointersDiff(
1140             LI1->getType(), LI1->getPointerOperand(), LI2->getType(),
1141             LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true);
1142         if (!Dist || *Dist == 0)
1143           return LookAheadHeuristics::ScoreFail;
1144         // The distance is too large - still may be profitable to use masked
1145         // loads/gathers.
1146         if (std::abs(*Dist) > NumLanes / 2)
1147           return LookAheadHeuristics::ScoreAltOpcodes;
1148         // This still will detect consecutive loads, but we might have "holes"
1149         // in some cases. It is ok for non-power-2 vectorization and may produce
1150         // better results. It should not affect current vectorization.
1151         return (*Dist > 0) ? LookAheadHeuristics::ScoreConsecutiveLoads
1152                            : LookAheadHeuristics::ScoreReversedLoads;
1153       }
1154 
1155       auto *C1 = dyn_cast<Constant>(V1);
1156       auto *C2 = dyn_cast<Constant>(V2);
1157       if (C1 && C2)
1158         return LookAheadHeuristics::ScoreConstants;
1159 
1160       // Extracts from consecutive indexes of the same vector better score as
1161       // the extracts could be optimized away.
1162       Value *EV1;
1163       ConstantInt *Ex1Idx;
1164       if (match(V1, m_ExtractElt(m_Value(EV1), m_ConstantInt(Ex1Idx)))) {
1165         // Undefs are always profitable for extractelements.
1166         if (isa<UndefValue>(V2))
1167           return LookAheadHeuristics::ScoreConsecutiveExtracts;
1168         Value *EV2 = nullptr;
1169         ConstantInt *Ex2Idx = nullptr;
1170         if (match(V2,
1171                   m_ExtractElt(m_Value(EV2), m_CombineOr(m_ConstantInt(Ex2Idx),
1172                                                          m_Undef())))) {
1173           // Undefs are always profitable for extractelements.
1174           if (!Ex2Idx)
1175             return LookAheadHeuristics::ScoreConsecutiveExtracts;
1176           if (isUndefVector(EV2) && EV2->getType() == EV1->getType())
1177             return LookAheadHeuristics::ScoreConsecutiveExtracts;
1178           if (EV2 == EV1) {
1179             int Idx1 = Ex1Idx->getZExtValue();
1180             int Idx2 = Ex2Idx->getZExtValue();
1181             int Dist = Idx2 - Idx1;
1182             // The distance is too large - still may be profitable to use
1183             // shuffles.
1184             if (std::abs(Dist) == 0)
1185               return LookAheadHeuristics::ScoreSplat;
1186             if (std::abs(Dist) > NumLanes / 2)
1187               return LookAheadHeuristics::ScoreSameOpcode;
1188             return (Dist > 0) ? LookAheadHeuristics::ScoreConsecutiveExtracts
1189                               : LookAheadHeuristics::ScoreReversedExtracts;
1190           }
1191           return LookAheadHeuristics::ScoreAltOpcodes;
1192         }
1193         return LookAheadHeuristics::ScoreFail;
1194       }
1195 
1196       auto *I1 = dyn_cast<Instruction>(V1);
1197       auto *I2 = dyn_cast<Instruction>(V2);
1198       if (I1 && I2) {
1199         if (I1->getParent() != I2->getParent())
1200           return LookAheadHeuristics::ScoreFail;
1201         SmallVector<Value *, 4> Ops(MainAltOps.begin(), MainAltOps.end());
1202         Ops.push_back(I1);
1203         Ops.push_back(I2);
1204         InstructionsState S = getSameOpcode(Ops);
1205         // Note: Only consider instructions with <= 2 operands to avoid
1206         // complexity explosion.
1207         if (S.getOpcode() &&
1208             (S.MainOp->getNumOperands() <= 2 || !MainAltOps.empty() ||
1209              !S.isAltShuffle()) &&
1210             all_of(Ops, [&S](Value *V) {
1211               return cast<Instruction>(V)->getNumOperands() ==
1212                      S.MainOp->getNumOperands();
1213             }))
1214           return S.isAltShuffle() ? LookAheadHeuristics::ScoreAltOpcodes
1215                                   : LookAheadHeuristics::ScoreSameOpcode;
1216       }
1217 
1218       if (isa<UndefValue>(V2))
1219         return LookAheadHeuristics::ScoreUndef;
1220 
1221       return LookAheadHeuristics::ScoreFail;
1222     }
1223 
1224     /// Go through the operands of \p LHS and \p RHS recursively until
1225     /// MaxLevel, and return the cummulative score. \p U1 and \p U2 are
1226     /// the users of \p LHS and \p RHS (that is \p LHS and \p RHS are operands
1227     /// of \p U1 and \p U2), except at the beginning of the recursion where
1228     /// these are set to nullptr.
1229     ///
1230     /// For example:
1231     /// \verbatim
1232     ///  A[0]  B[0]  A[1]  B[1]  C[0] D[0]  B[1] A[1]
1233     ///     \ /         \ /         \ /        \ /
1234     ///      +           +           +          +
1235     ///     G1          G2          G3         G4
1236     /// \endverbatim
1237     /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at
1238     /// each level recursively, accumulating the score. It starts from matching
1239     /// the additions at level 0, then moves on to the loads (level 1). The
1240     /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and
1241     /// {B[0],B[1]} match with LookAheadHeuristics::ScoreConsecutiveLoads, while
1242     /// {A[0],C[0]} has a score of LookAheadHeuristics::ScoreFail.
1243     /// Please note that the order of the operands does not matter, as we
1244     /// evaluate the score of all profitable combinations of operands. In
1245     /// other words the score of G1 and G4 is the same as G1 and G2. This
1246     /// heuristic is based on ideas described in:
1247     ///   Look-ahead SLP: Auto-vectorization in the presence of commutative
1248     ///   operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha,
1249     ///   Luís F. W. Góes
1250     int getScoreAtLevelRec(Value *LHS, Value *RHS, Instruction *U1,
1251                            Instruction *U2, int CurrLevel,
1252                            ArrayRef<Value *> MainAltOps) const {
1253 
1254       // Get the shallow score of V1 and V2.
1255       int ShallowScoreAtThisLevel =
1256           getShallowScore(LHS, RHS, U1, U2, MainAltOps);
1257 
1258       // If reached MaxLevel,
1259       //  or if V1 and V2 are not instructions,
1260       //  or if they are SPLAT,
1261       //  or if they are not consecutive,
1262       //  or if profitable to vectorize loads or extractelements, early return
1263       //  the current cost.
1264       auto *I1 = dyn_cast<Instruction>(LHS);
1265       auto *I2 = dyn_cast<Instruction>(RHS);
1266       if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 ||
1267           ShallowScoreAtThisLevel == LookAheadHeuristics::ScoreFail ||
1268           (((isa<LoadInst>(I1) && isa<LoadInst>(I2)) ||
1269             (I1->getNumOperands() > 2 && I2->getNumOperands() > 2) ||
1270             (isa<ExtractElementInst>(I1) && isa<ExtractElementInst>(I2))) &&
1271            ShallowScoreAtThisLevel))
1272         return ShallowScoreAtThisLevel;
1273       assert(I1 && I2 && "Should have early exited.");
1274 
1275       // Contains the I2 operand indexes that got matched with I1 operands.
1276       SmallSet<unsigned, 4> Op2Used;
1277 
1278       // Recursion towards the operands of I1 and I2. We are trying all possible
1279       // operand pairs, and keeping track of the best score.
1280       for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands();
1281            OpIdx1 != NumOperands1; ++OpIdx1) {
1282         // Try to pair op1I with the best operand of I2.
1283         int MaxTmpScore = 0;
1284         unsigned MaxOpIdx2 = 0;
1285         bool FoundBest = false;
1286         // If I2 is commutative try all combinations.
1287         unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1;
1288         unsigned ToIdx = isCommutative(I2)
1289                              ? I2->getNumOperands()
1290                              : std::min(I2->getNumOperands(), OpIdx1 + 1);
1291         assert(FromIdx <= ToIdx && "Bad index");
1292         for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) {
1293           // Skip operands already paired with OpIdx1.
1294           if (Op2Used.count(OpIdx2))
1295             continue;
1296           // Recursively calculate the cost at each level
1297           int TmpScore =
1298               getScoreAtLevelRec(I1->getOperand(OpIdx1), I2->getOperand(OpIdx2),
1299                                  I1, I2, CurrLevel + 1, None);
1300           // Look for the best score.
1301           if (TmpScore > LookAheadHeuristics::ScoreFail &&
1302               TmpScore > MaxTmpScore) {
1303             MaxTmpScore = TmpScore;
1304             MaxOpIdx2 = OpIdx2;
1305             FoundBest = true;
1306           }
1307         }
1308         if (FoundBest) {
1309           // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it.
1310           Op2Used.insert(MaxOpIdx2);
1311           ShallowScoreAtThisLevel += MaxTmpScore;
1312         }
1313       }
1314       return ShallowScoreAtThisLevel;
1315     }
1316   };
1317   /// A helper data structure to hold the operands of a vector of instructions.
1318   /// This supports a fixed vector length for all operand vectors.
1319   class VLOperands {
1320     /// For each operand we need (i) the value, and (ii) the opcode that it
1321     /// would be attached to if the expression was in a left-linearized form.
1322     /// This is required to avoid illegal operand reordering.
1323     /// For example:
1324     /// \verbatim
1325     ///                         0 Op1
1326     ///                         |/
1327     /// Op1 Op2   Linearized    + Op2
1328     ///   \ /     ---------->   |/
1329     ///    -                    -
1330     ///
1331     /// Op1 - Op2            (0 + Op1) - Op2
1332     /// \endverbatim
1333     ///
1334     /// Value Op1 is attached to a '+' operation, and Op2 to a '-'.
1335     ///
1336     /// Another way to think of this is to track all the operations across the
1337     /// path from the operand all the way to the root of the tree and to
1338     /// calculate the operation that corresponds to this path. For example, the
1339     /// path from Op2 to the root crosses the RHS of the '-', therefore the
1340     /// corresponding operation is a '-' (which matches the one in the
1341     /// linearized tree, as shown above).
1342     ///
1343     /// For lack of a better term, we refer to this operation as Accumulated
1344     /// Path Operation (APO).
1345     struct OperandData {
1346       OperandData() = default;
1347       OperandData(Value *V, bool APO, bool IsUsed)
1348           : V(V), APO(APO), IsUsed(IsUsed) {}
1349       /// The operand value.
1350       Value *V = nullptr;
1351       /// TreeEntries only allow a single opcode, or an alternate sequence of
1352       /// them (e.g, +, -). Therefore, we can safely use a boolean value for the
1353       /// APO. It is set to 'true' if 'V' is attached to an inverse operation
1354       /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise
1355       /// (e.g., Add/Mul)
1356       bool APO = false;
1357       /// Helper data for the reordering function.
1358       bool IsUsed = false;
1359     };
1360 
1361     /// During operand reordering, we are trying to select the operand at lane
1362     /// that matches best with the operand at the neighboring lane. Our
1363     /// selection is based on the type of value we are looking for. For example,
1364     /// if the neighboring lane has a load, we need to look for a load that is
1365     /// accessing a consecutive address. These strategies are summarized in the
1366     /// 'ReorderingMode' enumerator.
1367     enum class ReorderingMode {
1368       Load,     ///< Matching loads to consecutive memory addresses
1369       Opcode,   ///< Matching instructions based on opcode (same or alternate)
1370       Constant, ///< Matching constants
1371       Splat,    ///< Matching the same instruction multiple times (broadcast)
1372       Failed,   ///< We failed to create a vectorizable group
1373     };
1374 
1375     using OperandDataVec = SmallVector<OperandData, 2>;
1376 
1377     /// A vector of operand vectors.
1378     SmallVector<OperandDataVec, 4> OpsVec;
1379 
1380     const DataLayout &DL;
1381     ScalarEvolution &SE;
1382     const BoUpSLP &R;
1383 
1384     /// \returns the operand data at \p OpIdx and \p Lane.
1385     OperandData &getData(unsigned OpIdx, unsigned Lane) {
1386       return OpsVec[OpIdx][Lane];
1387     }
1388 
1389     /// \returns the operand data at \p OpIdx and \p Lane. Const version.
1390     const OperandData &getData(unsigned OpIdx, unsigned Lane) const {
1391       return OpsVec[OpIdx][Lane];
1392     }
1393 
1394     /// Clears the used flag for all entries.
1395     void clearUsed() {
1396       for (unsigned OpIdx = 0, NumOperands = getNumOperands();
1397            OpIdx != NumOperands; ++OpIdx)
1398         for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
1399              ++Lane)
1400           OpsVec[OpIdx][Lane].IsUsed = false;
1401     }
1402 
1403     /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2.
1404     void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) {
1405       std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]);
1406     }
1407 
1408     /// \param Lane lane of the operands under analysis.
1409     /// \param OpIdx operand index in \p Lane lane we're looking the best
1410     /// candidate for.
1411     /// \param Idx operand index of the current candidate value.
1412     /// \returns The additional score due to possible broadcasting of the
1413     /// elements in the lane. It is more profitable to have power-of-2 unique
1414     /// elements in the lane, it will be vectorized with higher probability
1415     /// after removing duplicates. Currently the SLP vectorizer supports only
1416     /// vectorization of the power-of-2 number of unique scalars.
1417     int getSplatScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1418       Value *IdxLaneV = getData(Idx, Lane).V;
1419       if (!isa<Instruction>(IdxLaneV) || IdxLaneV == getData(OpIdx, Lane).V)
1420         return 0;
1421       SmallPtrSet<Value *, 4> Uniques;
1422       for (unsigned Ln = 0, E = getNumLanes(); Ln < E; ++Ln) {
1423         if (Ln == Lane)
1424           continue;
1425         Value *OpIdxLnV = getData(OpIdx, Ln).V;
1426         if (!isa<Instruction>(OpIdxLnV))
1427           return 0;
1428         Uniques.insert(OpIdxLnV);
1429       }
1430       int UniquesCount = Uniques.size();
1431       int UniquesCntWithIdxLaneV =
1432           Uniques.contains(IdxLaneV) ? UniquesCount : UniquesCount + 1;
1433       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1434       int UniquesCntWithOpIdxLaneV =
1435           Uniques.contains(OpIdxLaneV) ? UniquesCount : UniquesCount + 1;
1436       if (UniquesCntWithIdxLaneV == UniquesCntWithOpIdxLaneV)
1437         return 0;
1438       return (PowerOf2Ceil(UniquesCntWithOpIdxLaneV) -
1439               UniquesCntWithOpIdxLaneV) -
1440              (PowerOf2Ceil(UniquesCntWithIdxLaneV) - UniquesCntWithIdxLaneV);
1441     }
1442 
1443     /// \param Lane lane of the operands under analysis.
1444     /// \param OpIdx operand index in \p Lane lane we're looking the best
1445     /// candidate for.
1446     /// \param Idx operand index of the current candidate value.
1447     /// \returns The additional score for the scalar which users are all
1448     /// vectorized.
1449     int getExternalUseScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1450       Value *IdxLaneV = getData(Idx, Lane).V;
1451       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1452       // Do not care about number of uses for vector-like instructions
1453       // (extractelement/extractvalue with constant indices), they are extracts
1454       // themselves and already externally used. Vectorization of such
1455       // instructions does not add extra extractelement instruction, just may
1456       // remove it.
1457       if (isVectorLikeInstWithConstOps(IdxLaneV) &&
1458           isVectorLikeInstWithConstOps(OpIdxLaneV))
1459         return LookAheadHeuristics::ScoreAllUserVectorized;
1460       auto *IdxLaneI = dyn_cast<Instruction>(IdxLaneV);
1461       if (!IdxLaneI || !isa<Instruction>(OpIdxLaneV))
1462         return 0;
1463       return R.areAllUsersVectorized(IdxLaneI, None)
1464                  ? LookAheadHeuristics::ScoreAllUserVectorized
1465                  : 0;
1466     }
1467 
1468     /// Score scaling factor for fully compatible instructions but with
1469     /// different number of external uses. Allows better selection of the
1470     /// instructions with less external uses.
1471     static const int ScoreScaleFactor = 10;
1472 
1473     /// \Returns the look-ahead score, which tells us how much the sub-trees
1474     /// rooted at \p LHS and \p RHS match, the more they match the higher the
1475     /// score. This helps break ties in an informed way when we cannot decide on
1476     /// the order of the operands by just considering the immediate
1477     /// predecessors.
1478     int getLookAheadScore(Value *LHS, Value *RHS, ArrayRef<Value *> MainAltOps,
1479                           int Lane, unsigned OpIdx, unsigned Idx,
1480                           bool &IsUsed) {
1481       LookAheadHeuristics LookAhead(DL, SE, R, getNumLanes(),
1482                                     LookAheadMaxDepth);
1483       // Keep track of the instruction stack as we recurse into the operands
1484       // during the look-ahead score exploration.
1485       int Score =
1486           LookAhead.getScoreAtLevelRec(LHS, RHS, /*U1=*/nullptr, /*U2=*/nullptr,
1487                                        /*CurrLevel=*/1, MainAltOps);
1488       if (Score) {
1489         int SplatScore = getSplatScore(Lane, OpIdx, Idx);
1490         if (Score <= -SplatScore) {
1491           // Set the minimum score for splat-like sequence to avoid setting
1492           // failed state.
1493           Score = 1;
1494         } else {
1495           Score += SplatScore;
1496           // Scale score to see the difference between different operands
1497           // and similar operands but all vectorized/not all vectorized
1498           // uses. It does not affect actual selection of the best
1499           // compatible operand in general, just allows to select the
1500           // operand with all vectorized uses.
1501           Score *= ScoreScaleFactor;
1502           Score += getExternalUseScore(Lane, OpIdx, Idx);
1503           IsUsed = true;
1504         }
1505       }
1506       return Score;
1507     }
1508 
1509     /// Best defined scores per lanes between the passes. Used to choose the
1510     /// best operand (with the highest score) between the passes.
1511     /// The key - {Operand Index, Lane}.
1512     /// The value - the best score between the passes for the lane and the
1513     /// operand.
1514     SmallDenseMap<std::pair<unsigned, unsigned>, unsigned, 8>
1515         BestScoresPerLanes;
1516 
1517     // Search all operands in Ops[*][Lane] for the one that matches best
1518     // Ops[OpIdx][LastLane] and return its opreand index.
1519     // If no good match can be found, return None.
1520     Optional<unsigned> getBestOperand(unsigned OpIdx, int Lane, int LastLane,
1521                                       ArrayRef<ReorderingMode> ReorderingModes,
1522                                       ArrayRef<Value *> MainAltOps) {
1523       unsigned NumOperands = getNumOperands();
1524 
1525       // The operand of the previous lane at OpIdx.
1526       Value *OpLastLane = getData(OpIdx, LastLane).V;
1527 
1528       // Our strategy mode for OpIdx.
1529       ReorderingMode RMode = ReorderingModes[OpIdx];
1530       if (RMode == ReorderingMode::Failed)
1531         return None;
1532 
1533       // The linearized opcode of the operand at OpIdx, Lane.
1534       bool OpIdxAPO = getData(OpIdx, Lane).APO;
1535 
1536       // The best operand index and its score.
1537       // Sometimes we have more than one option (e.g., Opcode and Undefs), so we
1538       // are using the score to differentiate between the two.
1539       struct BestOpData {
1540         Optional<unsigned> Idx = None;
1541         unsigned Score = 0;
1542       } BestOp;
1543       BestOp.Score =
1544           BestScoresPerLanes.try_emplace(std::make_pair(OpIdx, Lane), 0)
1545               .first->second;
1546 
1547       // Track if the operand must be marked as used. If the operand is set to
1548       // Score 1 explicitly (because of non power-of-2 unique scalars, we may
1549       // want to reestimate the operands again on the following iterations).
1550       bool IsUsed =
1551           RMode == ReorderingMode::Splat || RMode == ReorderingMode::Constant;
1552       // Iterate through all unused operands and look for the best.
1553       for (unsigned Idx = 0; Idx != NumOperands; ++Idx) {
1554         // Get the operand at Idx and Lane.
1555         OperandData &OpData = getData(Idx, Lane);
1556         Value *Op = OpData.V;
1557         bool OpAPO = OpData.APO;
1558 
1559         // Skip already selected operands.
1560         if (OpData.IsUsed)
1561           continue;
1562 
1563         // Skip if we are trying to move the operand to a position with a
1564         // different opcode in the linearized tree form. This would break the
1565         // semantics.
1566         if (OpAPO != OpIdxAPO)
1567           continue;
1568 
1569         // Look for an operand that matches the current mode.
1570         switch (RMode) {
1571         case ReorderingMode::Load:
1572         case ReorderingMode::Constant:
1573         case ReorderingMode::Opcode: {
1574           bool LeftToRight = Lane > LastLane;
1575           Value *OpLeft = (LeftToRight) ? OpLastLane : Op;
1576           Value *OpRight = (LeftToRight) ? Op : OpLastLane;
1577           int Score = getLookAheadScore(OpLeft, OpRight, MainAltOps, Lane,
1578                                         OpIdx, Idx, IsUsed);
1579           if (Score > static_cast<int>(BestOp.Score)) {
1580             BestOp.Idx = Idx;
1581             BestOp.Score = Score;
1582             BestScoresPerLanes[std::make_pair(OpIdx, Lane)] = Score;
1583           }
1584           break;
1585         }
1586         case ReorderingMode::Splat:
1587           if (Op == OpLastLane)
1588             BestOp.Idx = Idx;
1589           break;
1590         case ReorderingMode::Failed:
1591           llvm_unreachable("Not expected Failed reordering mode.");
1592         }
1593       }
1594 
1595       if (BestOp.Idx) {
1596         getData(BestOp.Idx.getValue(), Lane).IsUsed = IsUsed;
1597         return BestOp.Idx;
1598       }
1599       // If we could not find a good match return None.
1600       return None;
1601     }
1602 
1603     /// Helper for reorderOperandVecs.
1604     /// \returns the lane that we should start reordering from. This is the one
1605     /// which has the least number of operands that can freely move about or
1606     /// less profitable because it already has the most optimal set of operands.
1607     unsigned getBestLaneToStartReordering() const {
1608       unsigned Min = UINT_MAX;
1609       unsigned SameOpNumber = 0;
1610       // std::pair<unsigned, unsigned> is used to implement a simple voting
1611       // algorithm and choose the lane with the least number of operands that
1612       // can freely move about or less profitable because it already has the
1613       // most optimal set of operands. The first unsigned is a counter for
1614       // voting, the second unsigned is the counter of lanes with instructions
1615       // with same/alternate opcodes and same parent basic block.
1616       MapVector<unsigned, std::pair<unsigned, unsigned>> HashMap;
1617       // Try to be closer to the original results, if we have multiple lanes
1618       // with same cost. If 2 lanes have the same cost, use the one with the
1619       // lowest index.
1620       for (int I = getNumLanes(); I > 0; --I) {
1621         unsigned Lane = I - 1;
1622         OperandsOrderData NumFreeOpsHash =
1623             getMaxNumOperandsThatCanBeReordered(Lane);
1624         // Compare the number of operands that can move and choose the one with
1625         // the least number.
1626         if (NumFreeOpsHash.NumOfAPOs < Min) {
1627           Min = NumFreeOpsHash.NumOfAPOs;
1628           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1629           HashMap.clear();
1630           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1631         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1632                    NumFreeOpsHash.NumOpsWithSameOpcodeParent < SameOpNumber) {
1633           // Select the most optimal lane in terms of number of operands that
1634           // should be moved around.
1635           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1636           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1637         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1638                    NumFreeOpsHash.NumOpsWithSameOpcodeParent == SameOpNumber) {
1639           auto It = HashMap.find(NumFreeOpsHash.Hash);
1640           if (It == HashMap.end())
1641             HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1642           else
1643             ++It->second.first;
1644         }
1645       }
1646       // Select the lane with the minimum counter.
1647       unsigned BestLane = 0;
1648       unsigned CntMin = UINT_MAX;
1649       for (const auto &Data : reverse(HashMap)) {
1650         if (Data.second.first < CntMin) {
1651           CntMin = Data.second.first;
1652           BestLane = Data.second.second;
1653         }
1654       }
1655       return BestLane;
1656     }
1657 
1658     /// Data structure that helps to reorder operands.
1659     struct OperandsOrderData {
1660       /// The best number of operands with the same APOs, which can be
1661       /// reordered.
1662       unsigned NumOfAPOs = UINT_MAX;
1663       /// Number of operands with the same/alternate instruction opcode and
1664       /// parent.
1665       unsigned NumOpsWithSameOpcodeParent = 0;
1666       /// Hash for the actual operands ordering.
1667       /// Used to count operands, actually their position id and opcode
1668       /// value. It is used in the voting mechanism to find the lane with the
1669       /// least number of operands that can freely move about or less profitable
1670       /// because it already has the most optimal set of operands. Can be
1671       /// replaced with SmallVector<unsigned> instead but hash code is faster
1672       /// and requires less memory.
1673       unsigned Hash = 0;
1674     };
1675     /// \returns the maximum number of operands that are allowed to be reordered
1676     /// for \p Lane and the number of compatible instructions(with the same
1677     /// parent/opcode). This is used as a heuristic for selecting the first lane
1678     /// to start operand reordering.
1679     OperandsOrderData getMaxNumOperandsThatCanBeReordered(unsigned Lane) const {
1680       unsigned CntTrue = 0;
1681       unsigned NumOperands = getNumOperands();
1682       // Operands with the same APO can be reordered. We therefore need to count
1683       // how many of them we have for each APO, like this: Cnt[APO] = x.
1684       // Since we only have two APOs, namely true and false, we can avoid using
1685       // a map. Instead we can simply count the number of operands that
1686       // correspond to one of them (in this case the 'true' APO), and calculate
1687       // the other by subtracting it from the total number of operands.
1688       // Operands with the same instruction opcode and parent are more
1689       // profitable since we don't need to move them in many cases, with a high
1690       // probability such lane already can be vectorized effectively.
1691       bool AllUndefs = true;
1692       unsigned NumOpsWithSameOpcodeParent = 0;
1693       Instruction *OpcodeI = nullptr;
1694       BasicBlock *Parent = nullptr;
1695       unsigned Hash = 0;
1696       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1697         const OperandData &OpData = getData(OpIdx, Lane);
1698         if (OpData.APO)
1699           ++CntTrue;
1700         // Use Boyer-Moore majority voting for finding the majority opcode and
1701         // the number of times it occurs.
1702         if (auto *I = dyn_cast<Instruction>(OpData.V)) {
1703           if (!OpcodeI || !getSameOpcode({OpcodeI, I}).getOpcode() ||
1704               I->getParent() != Parent) {
1705             if (NumOpsWithSameOpcodeParent == 0) {
1706               NumOpsWithSameOpcodeParent = 1;
1707               OpcodeI = I;
1708               Parent = I->getParent();
1709             } else {
1710               --NumOpsWithSameOpcodeParent;
1711             }
1712           } else {
1713             ++NumOpsWithSameOpcodeParent;
1714           }
1715         }
1716         Hash = hash_combine(
1717             Hash, hash_value((OpIdx + 1) * (OpData.V->getValueID() + 1)));
1718         AllUndefs = AllUndefs && isa<UndefValue>(OpData.V);
1719       }
1720       if (AllUndefs)
1721         return {};
1722       OperandsOrderData Data;
1723       Data.NumOfAPOs = std::max(CntTrue, NumOperands - CntTrue);
1724       Data.NumOpsWithSameOpcodeParent = NumOpsWithSameOpcodeParent;
1725       Data.Hash = Hash;
1726       return Data;
1727     }
1728 
1729     /// Go through the instructions in VL and append their operands.
1730     void appendOperandsOfVL(ArrayRef<Value *> VL) {
1731       assert(!VL.empty() && "Bad VL");
1732       assert((empty() || VL.size() == getNumLanes()) &&
1733              "Expected same number of lanes");
1734       assert(isa<Instruction>(VL[0]) && "Expected instruction");
1735       unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands();
1736       OpsVec.resize(NumOperands);
1737       unsigned NumLanes = VL.size();
1738       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1739         OpsVec[OpIdx].resize(NumLanes);
1740         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1741           assert(isa<Instruction>(VL[Lane]) && "Expected instruction");
1742           // Our tree has just 3 nodes: the root and two operands.
1743           // It is therefore trivial to get the APO. We only need to check the
1744           // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or
1745           // RHS operand. The LHS operand of both add and sub is never attached
1746           // to an inversese operation in the linearized form, therefore its APO
1747           // is false. The RHS is true only if VL[Lane] is an inverse operation.
1748 
1749           // Since operand reordering is performed on groups of commutative
1750           // operations or alternating sequences (e.g., +, -), we can safely
1751           // tell the inverse operations by checking commutativity.
1752           bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane]));
1753           bool APO = (OpIdx == 0) ? false : IsInverseOperation;
1754           OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx),
1755                                  APO, false};
1756         }
1757       }
1758     }
1759 
1760     /// \returns the number of operands.
1761     unsigned getNumOperands() const { return OpsVec.size(); }
1762 
1763     /// \returns the number of lanes.
1764     unsigned getNumLanes() const { return OpsVec[0].size(); }
1765 
1766     /// \returns the operand value at \p OpIdx and \p Lane.
1767     Value *getValue(unsigned OpIdx, unsigned Lane) const {
1768       return getData(OpIdx, Lane).V;
1769     }
1770 
1771     /// \returns true if the data structure is empty.
1772     bool empty() const { return OpsVec.empty(); }
1773 
1774     /// Clears the data.
1775     void clear() { OpsVec.clear(); }
1776 
1777     /// \Returns true if there are enough operands identical to \p Op to fill
1778     /// the whole vector.
1779     /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow.
1780     bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) {
1781       bool OpAPO = getData(OpIdx, Lane).APO;
1782       for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) {
1783         if (Ln == Lane)
1784           continue;
1785         // This is set to true if we found a candidate for broadcast at Lane.
1786         bool FoundCandidate = false;
1787         for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) {
1788           OperandData &Data = getData(OpI, Ln);
1789           if (Data.APO != OpAPO || Data.IsUsed)
1790             continue;
1791           if (Data.V == Op) {
1792             FoundCandidate = true;
1793             Data.IsUsed = true;
1794             break;
1795           }
1796         }
1797         if (!FoundCandidate)
1798           return false;
1799       }
1800       return true;
1801     }
1802 
1803   public:
1804     /// Initialize with all the operands of the instruction vector \p RootVL.
1805     VLOperands(ArrayRef<Value *> RootVL, const DataLayout &DL,
1806                ScalarEvolution &SE, const BoUpSLP &R)
1807         : DL(DL), SE(SE), R(R) {
1808       // Append all the operands of RootVL.
1809       appendOperandsOfVL(RootVL);
1810     }
1811 
1812     /// \Returns a value vector with the operands across all lanes for the
1813     /// opearnd at \p OpIdx.
1814     ValueList getVL(unsigned OpIdx) const {
1815       ValueList OpVL(OpsVec[OpIdx].size());
1816       assert(OpsVec[OpIdx].size() == getNumLanes() &&
1817              "Expected same num of lanes across all operands");
1818       for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane)
1819         OpVL[Lane] = OpsVec[OpIdx][Lane].V;
1820       return OpVL;
1821     }
1822 
1823     // Performs operand reordering for 2 or more operands.
1824     // The original operands are in OrigOps[OpIdx][Lane].
1825     // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'.
1826     void reorder() {
1827       unsigned NumOperands = getNumOperands();
1828       unsigned NumLanes = getNumLanes();
1829       // Each operand has its own mode. We are using this mode to help us select
1830       // the instructions for each lane, so that they match best with the ones
1831       // we have selected so far.
1832       SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands);
1833 
1834       // This is a greedy single-pass algorithm. We are going over each lane
1835       // once and deciding on the best order right away with no back-tracking.
1836       // However, in order to increase its effectiveness, we start with the lane
1837       // that has operands that can move the least. For example, given the
1838       // following lanes:
1839       //  Lane 0 : A[0] = B[0] + C[0]   // Visited 3rd
1840       //  Lane 1 : A[1] = C[1] - B[1]   // Visited 1st
1841       //  Lane 2 : A[2] = B[2] + C[2]   // Visited 2nd
1842       //  Lane 3 : A[3] = C[3] - B[3]   // Visited 4th
1843       // we will start at Lane 1, since the operands of the subtraction cannot
1844       // be reordered. Then we will visit the rest of the lanes in a circular
1845       // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3.
1846 
1847       // Find the first lane that we will start our search from.
1848       unsigned FirstLane = getBestLaneToStartReordering();
1849 
1850       // Initialize the modes.
1851       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1852         Value *OpLane0 = getValue(OpIdx, FirstLane);
1853         // Keep track if we have instructions with all the same opcode on one
1854         // side.
1855         if (isa<LoadInst>(OpLane0))
1856           ReorderingModes[OpIdx] = ReorderingMode::Load;
1857         else if (isa<Instruction>(OpLane0)) {
1858           // Check if OpLane0 should be broadcast.
1859           if (shouldBroadcast(OpLane0, OpIdx, FirstLane))
1860             ReorderingModes[OpIdx] = ReorderingMode::Splat;
1861           else
1862             ReorderingModes[OpIdx] = ReorderingMode::Opcode;
1863         }
1864         else if (isa<Constant>(OpLane0))
1865           ReorderingModes[OpIdx] = ReorderingMode::Constant;
1866         else if (isa<Argument>(OpLane0))
1867           // Our best hope is a Splat. It may save some cost in some cases.
1868           ReorderingModes[OpIdx] = ReorderingMode::Splat;
1869         else
1870           // NOTE: This should be unreachable.
1871           ReorderingModes[OpIdx] = ReorderingMode::Failed;
1872       }
1873 
1874       // Check that we don't have same operands. No need to reorder if operands
1875       // are just perfect diamond or shuffled diamond match. Do not do it only
1876       // for possible broadcasts or non-power of 2 number of scalars (just for
1877       // now).
1878       auto &&SkipReordering = [this]() {
1879         SmallPtrSet<Value *, 4> UniqueValues;
1880         ArrayRef<OperandData> Op0 = OpsVec.front();
1881         for (const OperandData &Data : Op0)
1882           UniqueValues.insert(Data.V);
1883         for (ArrayRef<OperandData> Op : drop_begin(OpsVec, 1)) {
1884           if (any_of(Op, [&UniqueValues](const OperandData &Data) {
1885                 return !UniqueValues.contains(Data.V);
1886               }))
1887             return false;
1888         }
1889         // TODO: Check if we can remove a check for non-power-2 number of
1890         // scalars after full support of non-power-2 vectorization.
1891         return UniqueValues.size() != 2 && isPowerOf2_32(UniqueValues.size());
1892       };
1893 
1894       // If the initial strategy fails for any of the operand indexes, then we
1895       // perform reordering again in a second pass. This helps avoid assigning
1896       // high priority to the failed strategy, and should improve reordering for
1897       // the non-failed operand indexes.
1898       for (int Pass = 0; Pass != 2; ++Pass) {
1899         // Check if no need to reorder operands since they're are perfect or
1900         // shuffled diamond match.
1901         // Need to to do it to avoid extra external use cost counting for
1902         // shuffled matches, which may cause regressions.
1903         if (SkipReordering())
1904           break;
1905         // Skip the second pass if the first pass did not fail.
1906         bool StrategyFailed = false;
1907         // Mark all operand data as free to use.
1908         clearUsed();
1909         // We keep the original operand order for the FirstLane, so reorder the
1910         // rest of the lanes. We are visiting the nodes in a circular fashion,
1911         // using FirstLane as the center point and increasing the radius
1912         // distance.
1913         SmallVector<SmallVector<Value *, 2>> MainAltOps(NumOperands);
1914         for (unsigned I = 0; I < NumOperands; ++I)
1915           MainAltOps[I].push_back(getData(I, FirstLane).V);
1916 
1917         for (unsigned Distance = 1; Distance != NumLanes; ++Distance) {
1918           // Visit the lane on the right and then the lane on the left.
1919           for (int Direction : {+1, -1}) {
1920             int Lane = FirstLane + Direction * Distance;
1921             if (Lane < 0 || Lane >= (int)NumLanes)
1922               continue;
1923             int LastLane = Lane - Direction;
1924             assert(LastLane >= 0 && LastLane < (int)NumLanes &&
1925                    "Out of bounds");
1926             // Look for a good match for each operand.
1927             for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1928               // Search for the operand that matches SortedOps[OpIdx][Lane-1].
1929               Optional<unsigned> BestIdx = getBestOperand(
1930                   OpIdx, Lane, LastLane, ReorderingModes, MainAltOps[OpIdx]);
1931               // By not selecting a value, we allow the operands that follow to
1932               // select a better matching value. We will get a non-null value in
1933               // the next run of getBestOperand().
1934               if (BestIdx) {
1935                 // Swap the current operand with the one returned by
1936                 // getBestOperand().
1937                 swap(OpIdx, BestIdx.getValue(), Lane);
1938               } else {
1939                 // We failed to find a best operand, set mode to 'Failed'.
1940                 ReorderingModes[OpIdx] = ReorderingMode::Failed;
1941                 // Enable the second pass.
1942                 StrategyFailed = true;
1943               }
1944               // Try to get the alternate opcode and follow it during analysis.
1945               if (MainAltOps[OpIdx].size() != 2) {
1946                 OperandData &AltOp = getData(OpIdx, Lane);
1947                 InstructionsState OpS =
1948                     getSameOpcode({MainAltOps[OpIdx].front(), AltOp.V});
1949                 if (OpS.getOpcode() && OpS.isAltShuffle())
1950                   MainAltOps[OpIdx].push_back(AltOp.V);
1951               }
1952             }
1953           }
1954         }
1955         // Skip second pass if the strategy did not fail.
1956         if (!StrategyFailed)
1957           break;
1958       }
1959     }
1960 
1961 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1962     LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) {
1963       switch (RMode) {
1964       case ReorderingMode::Load:
1965         return "Load";
1966       case ReorderingMode::Opcode:
1967         return "Opcode";
1968       case ReorderingMode::Constant:
1969         return "Constant";
1970       case ReorderingMode::Splat:
1971         return "Splat";
1972       case ReorderingMode::Failed:
1973         return "Failed";
1974       }
1975       llvm_unreachable("Unimplemented Reordering Type");
1976     }
1977 
1978     LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode,
1979                                                    raw_ostream &OS) {
1980       return OS << getModeStr(RMode);
1981     }
1982 
1983     /// Debug print.
1984     LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) {
1985       printMode(RMode, dbgs());
1986     }
1987 
1988     friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) {
1989       return printMode(RMode, OS);
1990     }
1991 
1992     LLVM_DUMP_METHOD raw_ostream &print(raw_ostream &OS) const {
1993       const unsigned Indent = 2;
1994       unsigned Cnt = 0;
1995       for (const OperandDataVec &OpDataVec : OpsVec) {
1996         OS << "Operand " << Cnt++ << "\n";
1997         for (const OperandData &OpData : OpDataVec) {
1998           OS.indent(Indent) << "{";
1999           if (Value *V = OpData.V)
2000             OS << *V;
2001           else
2002             OS << "null";
2003           OS << ", APO:" << OpData.APO << "}\n";
2004         }
2005         OS << "\n";
2006       }
2007       return OS;
2008     }
2009 
2010     /// Debug print.
2011     LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
2012 #endif
2013   };
2014 
2015   /// Evaluate each pair in \p Candidates and return index into \p Candidates
2016   /// for a pair which have highest score deemed to have best chance to form
2017   /// root of profitable tree to vectorize. Return None if no candidate scored
2018   /// above the LookAheadHeuristics::ScoreFail.
2019   Optional<int>
2020   findBestRootPair(ArrayRef<std::pair<Value *, Value *>> Candidates) {
2021     LookAheadHeuristics LookAhead(*DL, *SE, *this, /*NumLanes=*/2,
2022                                   RootLookAheadMaxDepth);
2023     int BestScore = LookAheadHeuristics::ScoreFail;
2024     Optional<int> Index = None;
2025     for (int I : seq<int>(0, Candidates.size())) {
2026       int Score = LookAhead.getScoreAtLevelRec(Candidates[I].first,
2027                                                Candidates[I].second,
2028                                                /*U1=*/nullptr, /*U2=*/nullptr,
2029                                                /*Level=*/1, None);
2030       if (Score > BestScore) {
2031         BestScore = Score;
2032         Index = I;
2033       }
2034     }
2035     return Index;
2036   }
2037 
2038   /// Checks if the instruction is marked for deletion.
2039   bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); }
2040 
2041   /// Removes an instruction from its block and eventually deletes it.
2042   /// It's like Instruction::eraseFromParent() except that the actual deletion
2043   /// is delayed until BoUpSLP is destructed.
2044   void eraseInstruction(Instruction *I) {
2045     DeletedInstructions.insert(I);
2046   }
2047 
2048   /// Checks if the instruction was already analyzed for being possible
2049   /// reduction root.
2050   bool isAnalizedReductionRoot(Instruction *I) const {
2051     return AnalizedReductionsRoots.count(I);
2052   }
2053   /// Register given instruction as already analyzed for being possible
2054   /// reduction root.
2055   void analyzedReductionRoot(Instruction *I) {
2056     AnalizedReductionsRoots.insert(I);
2057   }
2058   /// Checks if the provided list of reduced values was checked already for
2059   /// vectorization.
2060   bool areAnalyzedReductionVals(ArrayRef<Value *> VL) {
2061     return AnalyzedReductionVals.contains(hash_value(VL));
2062   }
2063   /// Adds the list of reduced values to list of already checked values for the
2064   /// vectorization.
2065   void analyzedReductionVals(ArrayRef<Value *> VL) {
2066     AnalyzedReductionVals.insert(hash_value(VL));
2067   }
2068   /// Clear the list of the analyzed reduction root instructions.
2069   void clearReductionData() {
2070     AnalizedReductionsRoots.clear();
2071     AnalyzedReductionVals.clear();
2072   }
2073   /// Checks if the given value is gathered in one of the nodes.
2074   bool isGathered(Value *V) const {
2075     return MustGather.contains(V);
2076   }
2077 
2078   ~BoUpSLP();
2079 
2080 private:
2081   /// Check if the operands on the edges \p Edges of the \p UserTE allows
2082   /// reordering (i.e. the operands can be reordered because they have only one
2083   /// user and reordarable).
2084   /// \param ReorderableGathers List of all gather nodes that require reordering
2085   /// (e.g., gather of extractlements or partially vectorizable loads).
2086   /// \param GatherOps List of gather operand nodes for \p UserTE that require
2087   /// reordering, subset of \p NonVectorized.
2088   bool
2089   canReorderOperands(TreeEntry *UserTE,
2090                      SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
2091                      ArrayRef<TreeEntry *> ReorderableGathers,
2092                      SmallVectorImpl<TreeEntry *> &GatherOps);
2093 
2094   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
2095   /// if any. If it is not vectorized (gather node), returns nullptr.
2096   TreeEntry *getVectorizedOperand(TreeEntry *UserTE, unsigned OpIdx) {
2097     ArrayRef<Value *> VL = UserTE->getOperand(OpIdx);
2098     TreeEntry *TE = nullptr;
2099     const auto *It = find_if(VL, [this, &TE](Value *V) {
2100       TE = getTreeEntry(V);
2101       return TE;
2102     });
2103     if (It != VL.end() && TE->isSame(VL))
2104       return TE;
2105     return nullptr;
2106   }
2107 
2108   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
2109   /// if any. If it is not vectorized (gather node), returns nullptr.
2110   const TreeEntry *getVectorizedOperand(const TreeEntry *UserTE,
2111                                         unsigned OpIdx) const {
2112     return const_cast<BoUpSLP *>(this)->getVectorizedOperand(
2113         const_cast<TreeEntry *>(UserTE), OpIdx);
2114   }
2115 
2116   /// Checks if all users of \p I are the part of the vectorization tree.
2117   bool areAllUsersVectorized(Instruction *I,
2118                              ArrayRef<Value *> VectorizedVals) const;
2119 
2120   /// \returns the cost of the vectorizable entry.
2121   InstructionCost getEntryCost(const TreeEntry *E,
2122                                ArrayRef<Value *> VectorizedVals);
2123 
2124   /// This is the recursive part of buildTree.
2125   void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth,
2126                      const EdgeInfo &EI);
2127 
2128   /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
2129   /// be vectorized to use the original vector (or aggregate "bitcast" to a
2130   /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
2131   /// returns false, setting \p CurrentOrder to either an empty vector or a
2132   /// non-identity permutation that allows to reuse extract instructions.
2133   bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
2134                        SmallVectorImpl<unsigned> &CurrentOrder) const;
2135 
2136   /// Vectorize a single entry in the tree.
2137   Value *vectorizeTree(TreeEntry *E);
2138 
2139   /// Vectorize a single entry in the tree, starting in \p VL.
2140   Value *vectorizeTree(ArrayRef<Value *> VL);
2141 
2142   /// Create a new vector from a list of scalar values.  Produces a sequence
2143   /// which exploits values reused across lanes, and arranges the inserts
2144   /// for ease of later optimization.
2145   Value *createBuildVector(ArrayRef<Value *> VL);
2146 
2147   /// \returns the scalarization cost for this type. Scalarization in this
2148   /// context means the creation of vectors from a group of scalars. If \p
2149   /// NeedToShuffle is true, need to add a cost of reshuffling some of the
2150   /// vector elements.
2151   InstructionCost getGatherCost(FixedVectorType *Ty,
2152                                 const APInt &ShuffledIndices,
2153                                 bool NeedToShuffle) const;
2154 
2155   /// Checks if the gathered \p VL can be represented as shuffle(s) of previous
2156   /// tree entries.
2157   /// \returns ShuffleKind, if gathered values can be represented as shuffles of
2158   /// previous tree entries. \p Mask is filled with the shuffle mask.
2159   Optional<TargetTransformInfo::ShuffleKind>
2160   isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
2161                         SmallVectorImpl<const TreeEntry *> &Entries);
2162 
2163   /// \returns the scalarization cost for this list of values. Assuming that
2164   /// this subtree gets vectorized, we may need to extract the values from the
2165   /// roots. This method calculates the cost of extracting the values.
2166   InstructionCost getGatherCost(ArrayRef<Value *> VL) const;
2167 
2168   /// Set the Builder insert point to one after the last instruction in
2169   /// the bundle
2170   void setInsertPointAfterBundle(const TreeEntry *E);
2171 
2172   /// \returns a vector from a collection of scalars in \p VL.
2173   Value *gather(ArrayRef<Value *> VL);
2174 
2175   /// \returns whether the VectorizableTree is fully vectorizable and will
2176   /// be beneficial even the tree height is tiny.
2177   bool isFullyVectorizableTinyTree(bool ForReduction) const;
2178 
2179   /// Reorder commutative or alt operands to get better probability of
2180   /// generating vectorized code.
2181   static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
2182                                              SmallVectorImpl<Value *> &Left,
2183                                              SmallVectorImpl<Value *> &Right,
2184                                              const DataLayout &DL,
2185                                              ScalarEvolution &SE,
2186                                              const BoUpSLP &R);
2187   struct TreeEntry {
2188     using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>;
2189     TreeEntry(VecTreeTy &Container) : Container(Container) {}
2190 
2191     /// \returns true if the scalars in VL are equal to this entry.
2192     bool isSame(ArrayRef<Value *> VL) const {
2193       auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) {
2194         if (Mask.size() != VL.size() && VL.size() == Scalars.size())
2195           return std::equal(VL.begin(), VL.end(), Scalars.begin());
2196         return VL.size() == Mask.size() &&
2197                std::equal(VL.begin(), VL.end(), Mask.begin(),
2198                           [Scalars](Value *V, int Idx) {
2199                             return (isa<UndefValue>(V) &&
2200                                     Idx == UndefMaskElem) ||
2201                                    (Idx != UndefMaskElem && V == Scalars[Idx]);
2202                           });
2203       };
2204       if (!ReorderIndices.empty()) {
2205         // TODO: implement matching if the nodes are just reordered, still can
2206         // treat the vector as the same if the list of scalars matches VL
2207         // directly, without reordering.
2208         SmallVector<int> Mask;
2209         inversePermutation(ReorderIndices, Mask);
2210         if (VL.size() == Scalars.size())
2211           return IsSame(Scalars, Mask);
2212         if (VL.size() == ReuseShuffleIndices.size()) {
2213           ::addMask(Mask, ReuseShuffleIndices);
2214           return IsSame(Scalars, Mask);
2215         }
2216         return false;
2217       }
2218       return IsSame(Scalars, ReuseShuffleIndices);
2219     }
2220 
2221     /// \returns true if current entry has same operands as \p TE.
2222     bool hasEqualOperands(const TreeEntry &TE) const {
2223       if (TE.getNumOperands() != getNumOperands())
2224         return false;
2225       SmallBitVector Used(getNumOperands());
2226       for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
2227         unsigned PrevCount = Used.count();
2228         for (unsigned K = 0; K < E; ++K) {
2229           if (Used.test(K))
2230             continue;
2231           if (getOperand(K) == TE.getOperand(I)) {
2232             Used.set(K);
2233             break;
2234           }
2235         }
2236         // Check if we actually found the matching operand.
2237         if (PrevCount == Used.count())
2238           return false;
2239       }
2240       return true;
2241     }
2242 
2243     /// \return Final vectorization factor for the node. Defined by the total
2244     /// number of vectorized scalars, including those, used several times in the
2245     /// entry and counted in the \a ReuseShuffleIndices, if any.
2246     unsigned getVectorFactor() const {
2247       if (!ReuseShuffleIndices.empty())
2248         return ReuseShuffleIndices.size();
2249       return Scalars.size();
2250     };
2251 
2252     /// A vector of scalars.
2253     ValueList Scalars;
2254 
2255     /// The Scalars are vectorized into this value. It is initialized to Null.
2256     Value *VectorizedValue = nullptr;
2257 
2258     /// Do we need to gather this sequence or vectorize it
2259     /// (either with vector instruction or with scatter/gather
2260     /// intrinsics for store/load)?
2261     enum EntryState { Vectorize, ScatterVectorize, NeedToGather };
2262     EntryState State;
2263 
2264     /// Does this sequence require some shuffling?
2265     SmallVector<int, 4> ReuseShuffleIndices;
2266 
2267     /// Does this entry require reordering?
2268     SmallVector<unsigned, 4> ReorderIndices;
2269 
2270     /// Points back to the VectorizableTree.
2271     ///
2272     /// Only used for Graphviz right now.  Unfortunately GraphTrait::NodeRef has
2273     /// to be a pointer and needs to be able to initialize the child iterator.
2274     /// Thus we need a reference back to the container to translate the indices
2275     /// to entries.
2276     VecTreeTy &Container;
2277 
2278     /// The TreeEntry index containing the user of this entry.  We can actually
2279     /// have multiple users so the data structure is not truly a tree.
2280     SmallVector<EdgeInfo, 1> UserTreeIndices;
2281 
2282     /// The index of this treeEntry in VectorizableTree.
2283     int Idx = -1;
2284 
2285   private:
2286     /// The operands of each instruction in each lane Operands[op_index][lane].
2287     /// Note: This helps avoid the replication of the code that performs the
2288     /// reordering of operands during buildTree_rec() and vectorizeTree().
2289     SmallVector<ValueList, 2> Operands;
2290 
2291     /// The main/alternate instruction.
2292     Instruction *MainOp = nullptr;
2293     Instruction *AltOp = nullptr;
2294 
2295   public:
2296     /// Set this bundle's \p OpIdx'th operand to \p OpVL.
2297     void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) {
2298       if (Operands.size() < OpIdx + 1)
2299         Operands.resize(OpIdx + 1);
2300       assert(Operands[OpIdx].empty() && "Already resized?");
2301       assert(OpVL.size() <= Scalars.size() &&
2302              "Number of operands is greater than the number of scalars.");
2303       Operands[OpIdx].resize(OpVL.size());
2304       copy(OpVL, Operands[OpIdx].begin());
2305     }
2306 
2307     /// Set the operands of this bundle in their original order.
2308     void setOperandsInOrder() {
2309       assert(Operands.empty() && "Already initialized?");
2310       auto *I0 = cast<Instruction>(Scalars[0]);
2311       Operands.resize(I0->getNumOperands());
2312       unsigned NumLanes = Scalars.size();
2313       for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands();
2314            OpIdx != NumOperands; ++OpIdx) {
2315         Operands[OpIdx].resize(NumLanes);
2316         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
2317           auto *I = cast<Instruction>(Scalars[Lane]);
2318           assert(I->getNumOperands() == NumOperands &&
2319                  "Expected same number of operands");
2320           Operands[OpIdx][Lane] = I->getOperand(OpIdx);
2321         }
2322       }
2323     }
2324 
2325     /// Reorders operands of the node to the given mask \p Mask.
2326     void reorderOperands(ArrayRef<int> Mask) {
2327       for (ValueList &Operand : Operands)
2328         reorderScalars(Operand, Mask);
2329     }
2330 
2331     /// \returns the \p OpIdx operand of this TreeEntry.
2332     ValueList &getOperand(unsigned OpIdx) {
2333       assert(OpIdx < Operands.size() && "Off bounds");
2334       return Operands[OpIdx];
2335     }
2336 
2337     /// \returns the \p OpIdx operand of this TreeEntry.
2338     ArrayRef<Value *> getOperand(unsigned OpIdx) const {
2339       assert(OpIdx < Operands.size() && "Off bounds");
2340       return Operands[OpIdx];
2341     }
2342 
2343     /// \returns the number of operands.
2344     unsigned getNumOperands() const { return Operands.size(); }
2345 
2346     /// \return the single \p OpIdx operand.
2347     Value *getSingleOperand(unsigned OpIdx) const {
2348       assert(OpIdx < Operands.size() && "Off bounds");
2349       assert(!Operands[OpIdx].empty() && "No operand available");
2350       return Operands[OpIdx][0];
2351     }
2352 
2353     /// Some of the instructions in the list have alternate opcodes.
2354     bool isAltShuffle() const { return MainOp != AltOp; }
2355 
2356     bool isOpcodeOrAlt(Instruction *I) const {
2357       unsigned CheckedOpcode = I->getOpcode();
2358       return (getOpcode() == CheckedOpcode ||
2359               getAltOpcode() == CheckedOpcode);
2360     }
2361 
2362     /// Chooses the correct key for scheduling data. If \p Op has the same (or
2363     /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is
2364     /// \p OpValue.
2365     Value *isOneOf(Value *Op) const {
2366       auto *I = dyn_cast<Instruction>(Op);
2367       if (I && isOpcodeOrAlt(I))
2368         return Op;
2369       return MainOp;
2370     }
2371 
2372     void setOperations(const InstructionsState &S) {
2373       MainOp = S.MainOp;
2374       AltOp = S.AltOp;
2375     }
2376 
2377     Instruction *getMainOp() const {
2378       return MainOp;
2379     }
2380 
2381     Instruction *getAltOp() const {
2382       return AltOp;
2383     }
2384 
2385     /// The main/alternate opcodes for the list of instructions.
2386     unsigned getOpcode() const {
2387       return MainOp ? MainOp->getOpcode() : 0;
2388     }
2389 
2390     unsigned getAltOpcode() const {
2391       return AltOp ? AltOp->getOpcode() : 0;
2392     }
2393 
2394     /// When ReuseReorderShuffleIndices is empty it just returns position of \p
2395     /// V within vector of Scalars. Otherwise, try to remap on its reuse index.
2396     int findLaneForValue(Value *V) const {
2397       unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V));
2398       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2399       if (!ReorderIndices.empty())
2400         FoundLane = ReorderIndices[FoundLane];
2401       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2402       if (!ReuseShuffleIndices.empty()) {
2403         FoundLane = std::distance(ReuseShuffleIndices.begin(),
2404                                   find(ReuseShuffleIndices, FoundLane));
2405       }
2406       return FoundLane;
2407     }
2408 
2409 #ifndef NDEBUG
2410     /// Debug printer.
2411     LLVM_DUMP_METHOD void dump() const {
2412       dbgs() << Idx << ".\n";
2413       for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) {
2414         dbgs() << "Operand " << OpI << ":\n";
2415         for (const Value *V : Operands[OpI])
2416           dbgs().indent(2) << *V << "\n";
2417       }
2418       dbgs() << "Scalars: \n";
2419       for (Value *V : Scalars)
2420         dbgs().indent(2) << *V << "\n";
2421       dbgs() << "State: ";
2422       switch (State) {
2423       case Vectorize:
2424         dbgs() << "Vectorize\n";
2425         break;
2426       case ScatterVectorize:
2427         dbgs() << "ScatterVectorize\n";
2428         break;
2429       case NeedToGather:
2430         dbgs() << "NeedToGather\n";
2431         break;
2432       }
2433       dbgs() << "MainOp: ";
2434       if (MainOp)
2435         dbgs() << *MainOp << "\n";
2436       else
2437         dbgs() << "NULL\n";
2438       dbgs() << "AltOp: ";
2439       if (AltOp)
2440         dbgs() << *AltOp << "\n";
2441       else
2442         dbgs() << "NULL\n";
2443       dbgs() << "VectorizedValue: ";
2444       if (VectorizedValue)
2445         dbgs() << *VectorizedValue << "\n";
2446       else
2447         dbgs() << "NULL\n";
2448       dbgs() << "ReuseShuffleIndices: ";
2449       if (ReuseShuffleIndices.empty())
2450         dbgs() << "Empty";
2451       else
2452         for (int ReuseIdx : ReuseShuffleIndices)
2453           dbgs() << ReuseIdx << ", ";
2454       dbgs() << "\n";
2455       dbgs() << "ReorderIndices: ";
2456       for (unsigned ReorderIdx : ReorderIndices)
2457         dbgs() << ReorderIdx << ", ";
2458       dbgs() << "\n";
2459       dbgs() << "UserTreeIndices: ";
2460       for (const auto &EInfo : UserTreeIndices)
2461         dbgs() << EInfo << ", ";
2462       dbgs() << "\n";
2463     }
2464 #endif
2465   };
2466 
2467 #ifndef NDEBUG
2468   void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost,
2469                      InstructionCost VecCost,
2470                      InstructionCost ScalarCost) const {
2471     dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump();
2472     dbgs() << "SLP: Costs:\n";
2473     dbgs() << "SLP:     ReuseShuffleCost = " << ReuseShuffleCost << "\n";
2474     dbgs() << "SLP:     VectorCost = " << VecCost << "\n";
2475     dbgs() << "SLP:     ScalarCost = " << ScalarCost << "\n";
2476     dbgs() << "SLP:     ReuseShuffleCost + VecCost - ScalarCost = " <<
2477                ReuseShuffleCost + VecCost - ScalarCost << "\n";
2478   }
2479 #endif
2480 
2481   /// Create a new VectorizableTree entry.
2482   TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle,
2483                           const InstructionsState &S,
2484                           const EdgeInfo &UserTreeIdx,
2485                           ArrayRef<int> ReuseShuffleIndices = None,
2486                           ArrayRef<unsigned> ReorderIndices = None) {
2487     TreeEntry::EntryState EntryState =
2488         Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather;
2489     return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx,
2490                         ReuseShuffleIndices, ReorderIndices);
2491   }
2492 
2493   TreeEntry *newTreeEntry(ArrayRef<Value *> VL,
2494                           TreeEntry::EntryState EntryState,
2495                           Optional<ScheduleData *> Bundle,
2496                           const InstructionsState &S,
2497                           const EdgeInfo &UserTreeIdx,
2498                           ArrayRef<int> ReuseShuffleIndices = None,
2499                           ArrayRef<unsigned> ReorderIndices = None) {
2500     assert(((!Bundle && EntryState == TreeEntry::NeedToGather) ||
2501             (Bundle && EntryState != TreeEntry::NeedToGather)) &&
2502            "Need to vectorize gather entry?");
2503     VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree));
2504     TreeEntry *Last = VectorizableTree.back().get();
2505     Last->Idx = VectorizableTree.size() - 1;
2506     Last->State = EntryState;
2507     Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
2508                                      ReuseShuffleIndices.end());
2509     if (ReorderIndices.empty()) {
2510       Last->Scalars.assign(VL.begin(), VL.end());
2511       Last->setOperations(S);
2512     } else {
2513       // Reorder scalars and build final mask.
2514       Last->Scalars.assign(VL.size(), nullptr);
2515       transform(ReorderIndices, Last->Scalars.begin(),
2516                 [VL](unsigned Idx) -> Value * {
2517                   if (Idx >= VL.size())
2518                     return UndefValue::get(VL.front()->getType());
2519                   return VL[Idx];
2520                 });
2521       InstructionsState S = getSameOpcode(Last->Scalars);
2522       Last->setOperations(S);
2523       Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end());
2524     }
2525     if (Last->State != TreeEntry::NeedToGather) {
2526       for (Value *V : VL) {
2527         assert(!getTreeEntry(V) && "Scalar already in tree!");
2528         ScalarToTreeEntry[V] = Last;
2529       }
2530       // Update the scheduler bundle to point to this TreeEntry.
2531       ScheduleData *BundleMember = Bundle.getValue();
2532       assert((BundleMember || isa<PHINode>(S.MainOp) ||
2533               isVectorLikeInstWithConstOps(S.MainOp) ||
2534               doesNotNeedToSchedule(VL)) &&
2535              "Bundle and VL out of sync");
2536       if (BundleMember) {
2537         for (Value *V : VL) {
2538           if (doesNotNeedToBeScheduled(V))
2539             continue;
2540           assert(BundleMember && "Unexpected end of bundle.");
2541           BundleMember->TE = Last;
2542           BundleMember = BundleMember->NextInBundle;
2543         }
2544       }
2545       assert(!BundleMember && "Bundle and VL out of sync");
2546     } else {
2547       MustGather.insert(VL.begin(), VL.end());
2548     }
2549 
2550     if (UserTreeIdx.UserTE)
2551       Last->UserTreeIndices.push_back(UserTreeIdx);
2552 
2553     return Last;
2554   }
2555 
2556   /// -- Vectorization State --
2557   /// Holds all of the tree entries.
2558   TreeEntry::VecTreeTy VectorizableTree;
2559 
2560 #ifndef NDEBUG
2561   /// Debug printer.
2562   LLVM_DUMP_METHOD void dumpVectorizableTree() const {
2563     for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) {
2564       VectorizableTree[Id]->dump();
2565       dbgs() << "\n";
2566     }
2567   }
2568 #endif
2569 
2570   TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); }
2571 
2572   const TreeEntry *getTreeEntry(Value *V) const {
2573     return ScalarToTreeEntry.lookup(V);
2574   }
2575 
2576   /// Maps a specific scalar to its tree entry.
2577   SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry;
2578 
2579   /// Maps a value to the proposed vectorizable size.
2580   SmallDenseMap<Value *, unsigned> InstrElementSize;
2581 
2582   /// A list of scalars that we found that we need to keep as scalars.
2583   ValueSet MustGather;
2584 
2585   /// This POD struct describes one external user in the vectorized tree.
2586   struct ExternalUser {
2587     ExternalUser(Value *S, llvm::User *U, int L)
2588         : Scalar(S), User(U), Lane(L) {}
2589 
2590     // Which scalar in our function.
2591     Value *Scalar;
2592 
2593     // Which user that uses the scalar.
2594     llvm::User *User;
2595 
2596     // Which lane does the scalar belong to.
2597     int Lane;
2598   };
2599   using UserList = SmallVector<ExternalUser, 16>;
2600 
2601   /// Checks if two instructions may access the same memory.
2602   ///
2603   /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
2604   /// is invariant in the calling loop.
2605   bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
2606                  Instruction *Inst2) {
2607     // First check if the result is already in the cache.
2608     AliasCacheKey key = std::make_pair(Inst1, Inst2);
2609     Optional<bool> &result = AliasCache[key];
2610     if (result.hasValue()) {
2611       return result.getValue();
2612     }
2613     bool aliased = true;
2614     if (Loc1.Ptr && isSimple(Inst1))
2615       aliased = isModOrRefSet(BatchAA.getModRefInfo(Inst2, Loc1));
2616     // Store the result in the cache.
2617     result = aliased;
2618     return aliased;
2619   }
2620 
2621   using AliasCacheKey = std::pair<Instruction *, Instruction *>;
2622 
2623   /// Cache for alias results.
2624   /// TODO: consider moving this to the AliasAnalysis itself.
2625   DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
2626 
2627   // Cache for pointerMayBeCaptured calls inside AA.  This is preserved
2628   // globally through SLP because we don't perform any action which
2629   // invalidates capture results.
2630   BatchAAResults BatchAA;
2631 
2632   /// Temporary store for deleted instructions. Instructions will be deleted
2633   /// eventually when the BoUpSLP is destructed.  The deferral is required to
2634   /// ensure that there are no incorrect collisions in the AliasCache, which
2635   /// can happen if a new instruction is allocated at the same address as a
2636   /// previously deleted instruction.
2637   DenseSet<Instruction *> DeletedInstructions;
2638 
2639   /// Set of the instruction, being analyzed already for reductions.
2640   SmallPtrSet<Instruction *, 16> AnalizedReductionsRoots;
2641 
2642   /// Set of hashes for the list of reduction values already being analyzed.
2643   DenseSet<size_t> AnalyzedReductionVals;
2644 
2645   /// A list of values that need to extracted out of the tree.
2646   /// This list holds pairs of (Internal Scalar : External User). External User
2647   /// can be nullptr, it means that this Internal Scalar will be used later,
2648   /// after vectorization.
2649   UserList ExternalUses;
2650 
2651   /// Values used only by @llvm.assume calls.
2652   SmallPtrSet<const Value *, 32> EphValues;
2653 
2654   /// Holds all of the instructions that we gathered.
2655   SetVector<Instruction *> GatherShuffleSeq;
2656 
2657   /// A list of blocks that we are going to CSE.
2658   SetVector<BasicBlock *> CSEBlocks;
2659 
2660   /// Contains all scheduling relevant data for an instruction.
2661   /// A ScheduleData either represents a single instruction or a member of an
2662   /// instruction bundle (= a group of instructions which is combined into a
2663   /// vector instruction).
2664   struct ScheduleData {
2665     // The initial value for the dependency counters. It means that the
2666     // dependencies are not calculated yet.
2667     enum { InvalidDeps = -1 };
2668 
2669     ScheduleData() = default;
2670 
2671     void init(int BlockSchedulingRegionID, Value *OpVal) {
2672       FirstInBundle = this;
2673       NextInBundle = nullptr;
2674       NextLoadStore = nullptr;
2675       IsScheduled = false;
2676       SchedulingRegionID = BlockSchedulingRegionID;
2677       clearDependencies();
2678       OpValue = OpVal;
2679       TE = nullptr;
2680     }
2681 
2682     /// Verify basic self consistency properties
2683     void verify() {
2684       if (hasValidDependencies()) {
2685         assert(UnscheduledDeps <= Dependencies && "invariant");
2686       } else {
2687         assert(UnscheduledDeps == Dependencies && "invariant");
2688       }
2689 
2690       if (IsScheduled) {
2691         assert(isSchedulingEntity() &&
2692                 "unexpected scheduled state");
2693         for (const ScheduleData *BundleMember = this; BundleMember;
2694              BundleMember = BundleMember->NextInBundle) {
2695           assert(BundleMember->hasValidDependencies() &&
2696                  BundleMember->UnscheduledDeps == 0 &&
2697                  "unexpected scheduled state");
2698           assert((BundleMember == this || !BundleMember->IsScheduled) &&
2699                  "only bundle is marked scheduled");
2700         }
2701       }
2702 
2703       assert(Inst->getParent() == FirstInBundle->Inst->getParent() &&
2704              "all bundle members must be in same basic block");
2705     }
2706 
2707     /// Returns true if the dependency information has been calculated.
2708     /// Note that depenendency validity can vary between instructions within
2709     /// a single bundle.
2710     bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
2711 
2712     /// Returns true for single instructions and for bundle representatives
2713     /// (= the head of a bundle).
2714     bool isSchedulingEntity() const { return FirstInBundle == this; }
2715 
2716     /// Returns true if it represents an instruction bundle and not only a
2717     /// single instruction.
2718     bool isPartOfBundle() const {
2719       return NextInBundle != nullptr || FirstInBundle != this || TE;
2720     }
2721 
2722     /// Returns true if it is ready for scheduling, i.e. it has no more
2723     /// unscheduled depending instructions/bundles.
2724     bool isReady() const {
2725       assert(isSchedulingEntity() &&
2726              "can't consider non-scheduling entity for ready list");
2727       return unscheduledDepsInBundle() == 0 && !IsScheduled;
2728     }
2729 
2730     /// Modifies the number of unscheduled dependencies for this instruction,
2731     /// and returns the number of remaining dependencies for the containing
2732     /// bundle.
2733     int incrementUnscheduledDeps(int Incr) {
2734       assert(hasValidDependencies() &&
2735              "increment of unscheduled deps would be meaningless");
2736       UnscheduledDeps += Incr;
2737       return FirstInBundle->unscheduledDepsInBundle();
2738     }
2739 
2740     /// Sets the number of unscheduled dependencies to the number of
2741     /// dependencies.
2742     void resetUnscheduledDeps() {
2743       UnscheduledDeps = Dependencies;
2744     }
2745 
2746     /// Clears all dependency information.
2747     void clearDependencies() {
2748       Dependencies = InvalidDeps;
2749       resetUnscheduledDeps();
2750       MemoryDependencies.clear();
2751       ControlDependencies.clear();
2752     }
2753 
2754     int unscheduledDepsInBundle() const {
2755       assert(isSchedulingEntity() && "only meaningful on the bundle");
2756       int Sum = 0;
2757       for (const ScheduleData *BundleMember = this; BundleMember;
2758            BundleMember = BundleMember->NextInBundle) {
2759         if (BundleMember->UnscheduledDeps == InvalidDeps)
2760           return InvalidDeps;
2761         Sum += BundleMember->UnscheduledDeps;
2762       }
2763       return Sum;
2764     }
2765 
2766     void dump(raw_ostream &os) const {
2767       if (!isSchedulingEntity()) {
2768         os << "/ " << *Inst;
2769       } else if (NextInBundle) {
2770         os << '[' << *Inst;
2771         ScheduleData *SD = NextInBundle;
2772         while (SD) {
2773           os << ';' << *SD->Inst;
2774           SD = SD->NextInBundle;
2775         }
2776         os << ']';
2777       } else {
2778         os << *Inst;
2779       }
2780     }
2781 
2782     Instruction *Inst = nullptr;
2783 
2784     /// Opcode of the current instruction in the schedule data.
2785     Value *OpValue = nullptr;
2786 
2787     /// The TreeEntry that this instruction corresponds to.
2788     TreeEntry *TE = nullptr;
2789 
2790     /// Points to the head in an instruction bundle (and always to this for
2791     /// single instructions).
2792     ScheduleData *FirstInBundle = nullptr;
2793 
2794     /// Single linked list of all instructions in a bundle. Null if it is a
2795     /// single instruction.
2796     ScheduleData *NextInBundle = nullptr;
2797 
2798     /// Single linked list of all memory instructions (e.g. load, store, call)
2799     /// in the block - until the end of the scheduling region.
2800     ScheduleData *NextLoadStore = nullptr;
2801 
2802     /// The dependent memory instructions.
2803     /// This list is derived on demand in calculateDependencies().
2804     SmallVector<ScheduleData *, 4> MemoryDependencies;
2805 
2806     /// List of instructions which this instruction could be control dependent
2807     /// on.  Allowing such nodes to be scheduled below this one could introduce
2808     /// a runtime fault which didn't exist in the original program.
2809     /// ex: this is a load or udiv following a readonly call which inf loops
2810     SmallVector<ScheduleData *, 4> ControlDependencies;
2811 
2812     /// This ScheduleData is in the current scheduling region if this matches
2813     /// the current SchedulingRegionID of BlockScheduling.
2814     int SchedulingRegionID = 0;
2815 
2816     /// Used for getting a "good" final ordering of instructions.
2817     int SchedulingPriority = 0;
2818 
2819     /// The number of dependencies. Constitutes of the number of users of the
2820     /// instruction plus the number of dependent memory instructions (if any).
2821     /// This value is calculated on demand.
2822     /// If InvalidDeps, the number of dependencies is not calculated yet.
2823     int Dependencies = InvalidDeps;
2824 
2825     /// The number of dependencies minus the number of dependencies of scheduled
2826     /// instructions. As soon as this is zero, the instruction/bundle gets ready
2827     /// for scheduling.
2828     /// Note that this is negative as long as Dependencies is not calculated.
2829     int UnscheduledDeps = InvalidDeps;
2830 
2831     /// True if this instruction is scheduled (or considered as scheduled in the
2832     /// dry-run).
2833     bool IsScheduled = false;
2834   };
2835 
2836 #ifndef NDEBUG
2837   friend inline raw_ostream &operator<<(raw_ostream &os,
2838                                         const BoUpSLP::ScheduleData &SD) {
2839     SD.dump(os);
2840     return os;
2841   }
2842 #endif
2843 
2844   friend struct GraphTraits<BoUpSLP *>;
2845   friend struct DOTGraphTraits<BoUpSLP *>;
2846 
2847   /// Contains all scheduling data for a basic block.
2848   /// It does not schedules instructions, which are not memory read/write
2849   /// instructions and their operands are either constants, or arguments, or
2850   /// phis, or instructions from others blocks, or their users are phis or from
2851   /// the other blocks. The resulting vector instructions can be placed at the
2852   /// beginning of the basic block without scheduling (if operands does not need
2853   /// to be scheduled) or at the end of the block (if users are outside of the
2854   /// block). It allows to save some compile time and memory used by the
2855   /// compiler.
2856   /// ScheduleData is assigned for each instruction in between the boundaries of
2857   /// the tree entry, even for those, which are not part of the graph. It is
2858   /// required to correctly follow the dependencies between the instructions and
2859   /// their correct scheduling. The ScheduleData is not allocated for the
2860   /// instructions, which do not require scheduling, like phis, nodes with
2861   /// extractelements/insertelements only or nodes with instructions, with
2862   /// uses/operands outside of the block.
2863   struct BlockScheduling {
2864     BlockScheduling(BasicBlock *BB)
2865         : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
2866 
2867     void clear() {
2868       ReadyInsts.clear();
2869       ScheduleStart = nullptr;
2870       ScheduleEnd = nullptr;
2871       FirstLoadStoreInRegion = nullptr;
2872       LastLoadStoreInRegion = nullptr;
2873       RegionHasStackSave = false;
2874 
2875       // Reduce the maximum schedule region size by the size of the
2876       // previous scheduling run.
2877       ScheduleRegionSizeLimit -= ScheduleRegionSize;
2878       if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
2879         ScheduleRegionSizeLimit = MinScheduleRegionSize;
2880       ScheduleRegionSize = 0;
2881 
2882       // Make a new scheduling region, i.e. all existing ScheduleData is not
2883       // in the new region yet.
2884       ++SchedulingRegionID;
2885     }
2886 
2887     ScheduleData *getScheduleData(Instruction *I) {
2888       if (BB != I->getParent())
2889         // Avoid lookup if can't possibly be in map.
2890         return nullptr;
2891       ScheduleData *SD = ScheduleDataMap.lookup(I);
2892       if (SD && isInSchedulingRegion(SD))
2893         return SD;
2894       return nullptr;
2895     }
2896 
2897     ScheduleData *getScheduleData(Value *V) {
2898       if (auto *I = dyn_cast<Instruction>(V))
2899         return getScheduleData(I);
2900       return nullptr;
2901     }
2902 
2903     ScheduleData *getScheduleData(Value *V, Value *Key) {
2904       if (V == Key)
2905         return getScheduleData(V);
2906       auto I = ExtraScheduleDataMap.find(V);
2907       if (I != ExtraScheduleDataMap.end()) {
2908         ScheduleData *SD = I->second.lookup(Key);
2909         if (SD && isInSchedulingRegion(SD))
2910           return SD;
2911       }
2912       return nullptr;
2913     }
2914 
2915     bool isInSchedulingRegion(ScheduleData *SD) const {
2916       return SD->SchedulingRegionID == SchedulingRegionID;
2917     }
2918 
2919     /// Marks an instruction as scheduled and puts all dependent ready
2920     /// instructions into the ready-list.
2921     template <typename ReadyListType>
2922     void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
2923       SD->IsScheduled = true;
2924       LLVM_DEBUG(dbgs() << "SLP:   schedule " << *SD << "\n");
2925 
2926       for (ScheduleData *BundleMember = SD; BundleMember;
2927            BundleMember = BundleMember->NextInBundle) {
2928         if (BundleMember->Inst != BundleMember->OpValue)
2929           continue;
2930 
2931         // Handle the def-use chain dependencies.
2932 
2933         // Decrement the unscheduled counter and insert to ready list if ready.
2934         auto &&DecrUnsched = [this, &ReadyList](Instruction *I) {
2935           doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
2936             if (OpDef && OpDef->hasValidDependencies() &&
2937                 OpDef->incrementUnscheduledDeps(-1) == 0) {
2938               // There are no more unscheduled dependencies after
2939               // decrementing, so we can put the dependent instruction
2940               // into the ready list.
2941               ScheduleData *DepBundle = OpDef->FirstInBundle;
2942               assert(!DepBundle->IsScheduled &&
2943                      "already scheduled bundle gets ready");
2944               ReadyList.insert(DepBundle);
2945               LLVM_DEBUG(dbgs()
2946                          << "SLP:    gets ready (def): " << *DepBundle << "\n");
2947             }
2948           });
2949         };
2950 
2951         // If BundleMember is a vector bundle, its operands may have been
2952         // reordered during buildTree(). We therefore need to get its operands
2953         // through the TreeEntry.
2954         if (TreeEntry *TE = BundleMember->TE) {
2955           // Need to search for the lane since the tree entry can be reordered.
2956           int Lane = std::distance(TE->Scalars.begin(),
2957                                    find(TE->Scalars, BundleMember->Inst));
2958           assert(Lane >= 0 && "Lane not set");
2959 
2960           // Since vectorization tree is being built recursively this assertion
2961           // ensures that the tree entry has all operands set before reaching
2962           // this code. Couple of exceptions known at the moment are extracts
2963           // where their second (immediate) operand is not added. Since
2964           // immediates do not affect scheduler behavior this is considered
2965           // okay.
2966           auto *In = BundleMember->Inst;
2967           assert(In &&
2968                  (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) ||
2969                   In->getNumOperands() == TE->getNumOperands()) &&
2970                  "Missed TreeEntry operands?");
2971           (void)In; // fake use to avoid build failure when assertions disabled
2972 
2973           for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands();
2974                OpIdx != NumOperands; ++OpIdx)
2975             if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane]))
2976               DecrUnsched(I);
2977         } else {
2978           // If BundleMember is a stand-alone instruction, no operand reordering
2979           // has taken place, so we directly access its operands.
2980           for (Use &U : BundleMember->Inst->operands())
2981             if (auto *I = dyn_cast<Instruction>(U.get()))
2982               DecrUnsched(I);
2983         }
2984         // Handle the memory dependencies.
2985         for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
2986           if (MemoryDepSD->hasValidDependencies() &&
2987               MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
2988             // There are no more unscheduled dependencies after decrementing,
2989             // so we can put the dependent instruction into the ready list.
2990             ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
2991             assert(!DepBundle->IsScheduled &&
2992                    "already scheduled bundle gets ready");
2993             ReadyList.insert(DepBundle);
2994             LLVM_DEBUG(dbgs()
2995                        << "SLP:    gets ready (mem): " << *DepBundle << "\n");
2996           }
2997         }
2998         // Handle the control dependencies.
2999         for (ScheduleData *DepSD : BundleMember->ControlDependencies) {
3000           if (DepSD->incrementUnscheduledDeps(-1) == 0) {
3001             // There are no more unscheduled dependencies after decrementing,
3002             // so we can put the dependent instruction into the ready list.
3003             ScheduleData *DepBundle = DepSD->FirstInBundle;
3004             assert(!DepBundle->IsScheduled &&
3005                    "already scheduled bundle gets ready");
3006             ReadyList.insert(DepBundle);
3007             LLVM_DEBUG(dbgs()
3008                        << "SLP:    gets ready (ctl): " << *DepBundle << "\n");
3009           }
3010         }
3011 
3012       }
3013     }
3014 
3015     /// Verify basic self consistency properties of the data structure.
3016     void verify() {
3017       if (!ScheduleStart)
3018         return;
3019 
3020       assert(ScheduleStart->getParent() == ScheduleEnd->getParent() &&
3021              ScheduleStart->comesBefore(ScheduleEnd) &&
3022              "Not a valid scheduling region?");
3023 
3024       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
3025         auto *SD = getScheduleData(I);
3026         if (!SD)
3027           continue;
3028         assert(isInSchedulingRegion(SD) &&
3029                "primary schedule data not in window?");
3030         assert(isInSchedulingRegion(SD->FirstInBundle) &&
3031                "entire bundle in window!");
3032         (void)SD;
3033         doForAllOpcodes(I, [](ScheduleData *SD) { SD->verify(); });
3034       }
3035 
3036       for (auto *SD : ReadyInsts) {
3037         assert(SD->isSchedulingEntity() && SD->isReady() &&
3038                "item in ready list not ready?");
3039         (void)SD;
3040       }
3041     }
3042 
3043     void doForAllOpcodes(Value *V,
3044                          function_ref<void(ScheduleData *SD)> Action) {
3045       if (ScheduleData *SD = getScheduleData(V))
3046         Action(SD);
3047       auto I = ExtraScheduleDataMap.find(V);
3048       if (I != ExtraScheduleDataMap.end())
3049         for (auto &P : I->second)
3050           if (isInSchedulingRegion(P.second))
3051             Action(P.second);
3052     }
3053 
3054     /// Put all instructions into the ReadyList which are ready for scheduling.
3055     template <typename ReadyListType>
3056     void initialFillReadyList(ReadyListType &ReadyList) {
3057       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
3058         doForAllOpcodes(I, [&](ScheduleData *SD) {
3059           if (SD->isSchedulingEntity() && SD->hasValidDependencies() &&
3060               SD->isReady()) {
3061             ReadyList.insert(SD);
3062             LLVM_DEBUG(dbgs()
3063                        << "SLP:    initially in ready list: " << *SD << "\n");
3064           }
3065         });
3066       }
3067     }
3068 
3069     /// Build a bundle from the ScheduleData nodes corresponding to the
3070     /// scalar instruction for each lane.
3071     ScheduleData *buildBundle(ArrayRef<Value *> VL);
3072 
3073     /// Checks if a bundle of instructions can be scheduled, i.e. has no
3074     /// cyclic dependencies. This is only a dry-run, no instructions are
3075     /// actually moved at this stage.
3076     /// \returns the scheduling bundle. The returned Optional value is non-None
3077     /// if \p VL is allowed to be scheduled.
3078     Optional<ScheduleData *>
3079     tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
3080                       const InstructionsState &S);
3081 
3082     /// Un-bundles a group of instructions.
3083     void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
3084 
3085     /// Allocates schedule data chunk.
3086     ScheduleData *allocateScheduleDataChunks();
3087 
3088     /// Extends the scheduling region so that V is inside the region.
3089     /// \returns true if the region size is within the limit.
3090     bool extendSchedulingRegion(Value *V, const InstructionsState &S);
3091 
3092     /// Initialize the ScheduleData structures for new instructions in the
3093     /// scheduling region.
3094     void initScheduleData(Instruction *FromI, Instruction *ToI,
3095                           ScheduleData *PrevLoadStore,
3096                           ScheduleData *NextLoadStore);
3097 
3098     /// Updates the dependency information of a bundle and of all instructions/
3099     /// bundles which depend on the original bundle.
3100     void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
3101                                BoUpSLP *SLP);
3102 
3103     /// Sets all instruction in the scheduling region to un-scheduled.
3104     void resetSchedule();
3105 
3106     BasicBlock *BB;
3107 
3108     /// Simple memory allocation for ScheduleData.
3109     std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
3110 
3111     /// The size of a ScheduleData array in ScheduleDataChunks.
3112     int ChunkSize;
3113 
3114     /// The allocator position in the current chunk, which is the last entry
3115     /// of ScheduleDataChunks.
3116     int ChunkPos;
3117 
3118     /// Attaches ScheduleData to Instruction.
3119     /// Note that the mapping survives during all vectorization iterations, i.e.
3120     /// ScheduleData structures are recycled.
3121     DenseMap<Instruction *, ScheduleData *> ScheduleDataMap;
3122 
3123     /// Attaches ScheduleData to Instruction with the leading key.
3124     DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
3125         ExtraScheduleDataMap;
3126 
3127     /// The ready-list for scheduling (only used for the dry-run).
3128     SetVector<ScheduleData *> ReadyInsts;
3129 
3130     /// The first instruction of the scheduling region.
3131     Instruction *ScheduleStart = nullptr;
3132 
3133     /// The first instruction _after_ the scheduling region.
3134     Instruction *ScheduleEnd = nullptr;
3135 
3136     /// The first memory accessing instruction in the scheduling region
3137     /// (can be null).
3138     ScheduleData *FirstLoadStoreInRegion = nullptr;
3139 
3140     /// The last memory accessing instruction in the scheduling region
3141     /// (can be null).
3142     ScheduleData *LastLoadStoreInRegion = nullptr;
3143 
3144     /// Is there an llvm.stacksave or llvm.stackrestore in the scheduling
3145     /// region?  Used to optimize the dependence calculation for the
3146     /// common case where there isn't.
3147     bool RegionHasStackSave = false;
3148 
3149     /// The current size of the scheduling region.
3150     int ScheduleRegionSize = 0;
3151 
3152     /// The maximum size allowed for the scheduling region.
3153     int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
3154 
3155     /// The ID of the scheduling region. For a new vectorization iteration this
3156     /// is incremented which "removes" all ScheduleData from the region.
3157     /// Make sure that the initial SchedulingRegionID is greater than the
3158     /// initial SchedulingRegionID in ScheduleData (which is 0).
3159     int SchedulingRegionID = 1;
3160   };
3161 
3162   /// Attaches the BlockScheduling structures to basic blocks.
3163   MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
3164 
3165   /// Performs the "real" scheduling. Done before vectorization is actually
3166   /// performed in a basic block.
3167   void scheduleBlock(BlockScheduling *BS);
3168 
3169   /// List of users to ignore during scheduling and that don't need extracting.
3170   ArrayRef<Value *> UserIgnoreList;
3171 
3172   /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
3173   /// sorted SmallVectors of unsigned.
3174   struct OrdersTypeDenseMapInfo {
3175     static OrdersType getEmptyKey() {
3176       OrdersType V;
3177       V.push_back(~1U);
3178       return V;
3179     }
3180 
3181     static OrdersType getTombstoneKey() {
3182       OrdersType V;
3183       V.push_back(~2U);
3184       return V;
3185     }
3186 
3187     static unsigned getHashValue(const OrdersType &V) {
3188       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
3189     }
3190 
3191     static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
3192       return LHS == RHS;
3193     }
3194   };
3195 
3196   // Analysis and block reference.
3197   Function *F;
3198   ScalarEvolution *SE;
3199   TargetTransformInfo *TTI;
3200   TargetLibraryInfo *TLI;
3201   LoopInfo *LI;
3202   DominatorTree *DT;
3203   AssumptionCache *AC;
3204   DemandedBits *DB;
3205   const DataLayout *DL;
3206   OptimizationRemarkEmitter *ORE;
3207 
3208   unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
3209   unsigned MinVecRegSize; // Set by cl::opt (default: 128).
3210 
3211   /// Instruction builder to construct the vectorized tree.
3212   IRBuilder<> Builder;
3213 
3214   /// A map of scalar integer values to the smallest bit width with which they
3215   /// can legally be represented. The values map to (width, signed) pairs,
3216   /// where "width" indicates the minimum bit width and "signed" is True if the
3217   /// value must be signed-extended, rather than zero-extended, back to its
3218   /// original width.
3219   MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
3220 };
3221 
3222 } // end namespace slpvectorizer
3223 
3224 template <> struct GraphTraits<BoUpSLP *> {
3225   using TreeEntry = BoUpSLP::TreeEntry;
3226 
3227   /// NodeRef has to be a pointer per the GraphWriter.
3228   using NodeRef = TreeEntry *;
3229 
3230   using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy;
3231 
3232   /// Add the VectorizableTree to the index iterator to be able to return
3233   /// TreeEntry pointers.
3234   struct ChildIteratorType
3235       : public iterator_adaptor_base<
3236             ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
3237     ContainerTy &VectorizableTree;
3238 
3239     ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W,
3240                       ContainerTy &VT)
3241         : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
3242 
3243     NodeRef operator*() { return I->UserTE; }
3244   };
3245 
3246   static NodeRef getEntryNode(BoUpSLP &R) {
3247     return R.VectorizableTree[0].get();
3248   }
3249 
3250   static ChildIteratorType child_begin(NodeRef N) {
3251     return {N->UserTreeIndices.begin(), N->Container};
3252   }
3253 
3254   static ChildIteratorType child_end(NodeRef N) {
3255     return {N->UserTreeIndices.end(), N->Container};
3256   }
3257 
3258   /// For the node iterator we just need to turn the TreeEntry iterator into a
3259   /// TreeEntry* iterator so that it dereferences to NodeRef.
3260   class nodes_iterator {
3261     using ItTy = ContainerTy::iterator;
3262     ItTy It;
3263 
3264   public:
3265     nodes_iterator(const ItTy &It2) : It(It2) {}
3266     NodeRef operator*() { return It->get(); }
3267     nodes_iterator operator++() {
3268       ++It;
3269       return *this;
3270     }
3271     bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
3272   };
3273 
3274   static nodes_iterator nodes_begin(BoUpSLP *R) {
3275     return nodes_iterator(R->VectorizableTree.begin());
3276   }
3277 
3278   static nodes_iterator nodes_end(BoUpSLP *R) {
3279     return nodes_iterator(R->VectorizableTree.end());
3280   }
3281 
3282   static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
3283 };
3284 
3285 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
3286   using TreeEntry = BoUpSLP::TreeEntry;
3287 
3288   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
3289 
3290   std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
3291     std::string Str;
3292     raw_string_ostream OS(Str);
3293     if (isSplat(Entry->Scalars))
3294       OS << "<splat> ";
3295     for (auto V : Entry->Scalars) {
3296       OS << *V;
3297       if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) {
3298             return EU.Scalar == V;
3299           }))
3300         OS << " <extract>";
3301       OS << "\n";
3302     }
3303     return Str;
3304   }
3305 
3306   static std::string getNodeAttributes(const TreeEntry *Entry,
3307                                        const BoUpSLP *) {
3308     if (Entry->State == TreeEntry::NeedToGather)
3309       return "color=red";
3310     return "";
3311   }
3312 };
3313 
3314 } // end namespace llvm
3315 
3316 BoUpSLP::~BoUpSLP() {
3317   SmallVector<WeakTrackingVH> DeadInsts;
3318   for (auto *I : DeletedInstructions) {
3319     for (Use &U : I->operands()) {
3320       auto *Op = dyn_cast<Instruction>(U.get());
3321       if (Op && !DeletedInstructions.count(Op) && Op->hasOneUser() &&
3322           wouldInstructionBeTriviallyDead(Op, TLI))
3323         DeadInsts.emplace_back(Op);
3324     }
3325     I->dropAllReferences();
3326   }
3327   for (auto *I : DeletedInstructions) {
3328     assert(I->use_empty() &&
3329            "trying to erase instruction with users.");
3330     I->eraseFromParent();
3331   }
3332 
3333   // Cleanup any dead scalar code feeding the vectorized instructions
3334   RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI);
3335 
3336 #ifdef EXPENSIVE_CHECKS
3337   // If we could guarantee that this call is not extremely slow, we could
3338   // remove the ifdef limitation (see PR47712).
3339   assert(!verifyFunction(*F, &dbgs()));
3340 #endif
3341 }
3342 
3343 /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses
3344 /// contains original mask for the scalars reused in the node. Procedure
3345 /// transform this mask in accordance with the given \p Mask.
3346 static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) {
3347   assert(!Mask.empty() && Reuses.size() == Mask.size() &&
3348          "Expected non-empty mask.");
3349   SmallVector<int> Prev(Reuses.begin(), Reuses.end());
3350   Prev.swap(Reuses);
3351   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
3352     if (Mask[I] != UndefMaskElem)
3353       Reuses[Mask[I]] = Prev[I];
3354 }
3355 
3356 /// Reorders the given \p Order according to the given \p Mask. \p Order - is
3357 /// the original order of the scalars. Procedure transforms the provided order
3358 /// in accordance with the given \p Mask. If the resulting \p Order is just an
3359 /// identity order, \p Order is cleared.
3360 static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) {
3361   assert(!Mask.empty() && "Expected non-empty mask.");
3362   SmallVector<int> MaskOrder;
3363   if (Order.empty()) {
3364     MaskOrder.resize(Mask.size());
3365     std::iota(MaskOrder.begin(), MaskOrder.end(), 0);
3366   } else {
3367     inversePermutation(Order, MaskOrder);
3368   }
3369   reorderReuses(MaskOrder, Mask);
3370   if (ShuffleVectorInst::isIdentityMask(MaskOrder)) {
3371     Order.clear();
3372     return;
3373   }
3374   Order.assign(Mask.size(), Mask.size());
3375   for (unsigned I = 0, E = Mask.size(); I < E; ++I)
3376     if (MaskOrder[I] != UndefMaskElem)
3377       Order[MaskOrder[I]] = I;
3378   fixupOrderingIndices(Order);
3379 }
3380 
3381 Optional<BoUpSLP::OrdersType>
3382 BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) {
3383   assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
3384   unsigned NumScalars = TE.Scalars.size();
3385   OrdersType CurrentOrder(NumScalars, NumScalars);
3386   SmallVector<int> Positions;
3387   SmallBitVector UsedPositions(NumScalars);
3388   const TreeEntry *STE = nullptr;
3389   // Try to find all gathered scalars that are gets vectorized in other
3390   // vectorize node. Here we can have only one single tree vector node to
3391   // correctly identify order of the gathered scalars.
3392   for (unsigned I = 0; I < NumScalars; ++I) {
3393     Value *V = TE.Scalars[I];
3394     if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V))
3395       continue;
3396     if (const auto *LocalSTE = getTreeEntry(V)) {
3397       if (!STE)
3398         STE = LocalSTE;
3399       else if (STE != LocalSTE)
3400         // Take the order only from the single vector node.
3401         return None;
3402       unsigned Lane =
3403           std::distance(STE->Scalars.begin(), find(STE->Scalars, V));
3404       if (Lane >= NumScalars)
3405         return None;
3406       if (CurrentOrder[Lane] != NumScalars) {
3407         if (Lane != I)
3408           continue;
3409         UsedPositions.reset(CurrentOrder[Lane]);
3410       }
3411       // The partial identity (where only some elements of the gather node are
3412       // in the identity order) is good.
3413       CurrentOrder[Lane] = I;
3414       UsedPositions.set(I);
3415     }
3416   }
3417   // Need to keep the order if we have a vector entry and at least 2 scalars or
3418   // the vectorized entry has just 2 scalars.
3419   if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) {
3420     auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) {
3421       for (unsigned I = 0; I < NumScalars; ++I)
3422         if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars)
3423           return false;
3424       return true;
3425     };
3426     if (IsIdentityOrder(CurrentOrder)) {
3427       CurrentOrder.clear();
3428       return CurrentOrder;
3429     }
3430     auto *It = CurrentOrder.begin();
3431     for (unsigned I = 0; I < NumScalars;) {
3432       if (UsedPositions.test(I)) {
3433         ++I;
3434         continue;
3435       }
3436       if (*It == NumScalars) {
3437         *It = I;
3438         ++I;
3439       }
3440       ++It;
3441     }
3442     return CurrentOrder;
3443   }
3444   return None;
3445 }
3446 
3447 bool clusterSortPtrAccesses(ArrayRef<Value *> VL, Type *ElemTy,
3448                             const DataLayout &DL, ScalarEvolution &SE,
3449                             SmallVectorImpl<unsigned> &SortedIndices) {
3450   assert(llvm::all_of(
3451              VL, [](const Value *V) { return V->getType()->isPointerTy(); }) &&
3452          "Expected list of pointer operands.");
3453   // Map from bases to a vector of (Ptr, Offset, OrigIdx), which we insert each
3454   // Ptr into, sort and return the sorted indices with values next to one
3455   // another.
3456   MapVector<Value *, SmallVector<std::tuple<Value *, int, unsigned>>> Bases;
3457   Bases[VL[0]].push_back(std::make_tuple(VL[0], 0U, 0U));
3458 
3459   unsigned Cnt = 1;
3460   for (Value *Ptr : VL.drop_front()) {
3461     bool Found = any_of(Bases, [&](auto &Base) {
3462       Optional<int> Diff =
3463           getPointersDiff(ElemTy, Base.first, ElemTy, Ptr, DL, SE,
3464                           /*StrictCheck=*/true);
3465       if (!Diff)
3466         return false;
3467 
3468       Base.second.emplace_back(Ptr, *Diff, Cnt++);
3469       return true;
3470     });
3471 
3472     if (!Found) {
3473       // If we haven't found enough to usefully cluster, return early.
3474       if (Bases.size() > VL.size() / 2 - 1)
3475         return false;
3476 
3477       // Not found already - add a new Base
3478       Bases[Ptr].emplace_back(Ptr, 0, Cnt++);
3479     }
3480   }
3481 
3482   // For each of the bases sort the pointers by Offset and check if any of the
3483   // base become consecutively allocated.
3484   bool AnyConsecutive = false;
3485   for (auto &Base : Bases) {
3486     auto &Vec = Base.second;
3487     if (Vec.size() > 1) {
3488       llvm::stable_sort(Vec, [](const std::tuple<Value *, int, unsigned> &X,
3489                                 const std::tuple<Value *, int, unsigned> &Y) {
3490         return std::get<1>(X) < std::get<1>(Y);
3491       });
3492       int InitialOffset = std::get<1>(Vec[0]);
3493       AnyConsecutive |= all_of(enumerate(Vec), [InitialOffset](auto &P) {
3494         return std::get<1>(P.value()) == int(P.index()) + InitialOffset;
3495       });
3496     }
3497   }
3498 
3499   // Fill SortedIndices array only if it looks worth-while to sort the ptrs.
3500   SortedIndices.clear();
3501   if (!AnyConsecutive)
3502     return false;
3503 
3504   for (auto &Base : Bases) {
3505     for (auto &T : Base.second)
3506       SortedIndices.push_back(std::get<2>(T));
3507   }
3508 
3509   assert(SortedIndices.size() == VL.size() &&
3510          "Expected SortedIndices to be the size of VL");
3511   return true;
3512 }
3513 
3514 Optional<BoUpSLP::OrdersType>
3515 BoUpSLP::findPartiallyOrderedLoads(const BoUpSLP::TreeEntry &TE) {
3516   assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
3517   Type *ScalarTy = TE.Scalars[0]->getType();
3518 
3519   SmallVector<Value *> Ptrs;
3520   Ptrs.reserve(TE.Scalars.size());
3521   for (Value *V : TE.Scalars) {
3522     auto *L = dyn_cast<LoadInst>(V);
3523     if (!L || !L->isSimple())
3524       return None;
3525     Ptrs.push_back(L->getPointerOperand());
3526   }
3527 
3528   BoUpSLP::OrdersType Order;
3529   if (clusterSortPtrAccesses(Ptrs, ScalarTy, *DL, *SE, Order))
3530     return Order;
3531   return None;
3532 }
3533 
3534 Optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE,
3535                                                          bool TopToBottom) {
3536   // No need to reorder if need to shuffle reuses, still need to shuffle the
3537   // node.
3538   if (!TE.ReuseShuffleIndices.empty())
3539     return None;
3540   if (TE.State == TreeEntry::Vectorize &&
3541       (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) ||
3542        (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) &&
3543       !TE.isAltShuffle())
3544     return TE.ReorderIndices;
3545   if (TE.State == TreeEntry::NeedToGather) {
3546     // TODO: add analysis of other gather nodes with extractelement
3547     // instructions and other values/instructions, not only undefs.
3548     if (((TE.getOpcode() == Instruction::ExtractElement &&
3549           !TE.isAltShuffle()) ||
3550          (all_of(TE.Scalars,
3551                  [](Value *V) {
3552                    return isa<UndefValue, ExtractElementInst>(V);
3553                  }) &&
3554           any_of(TE.Scalars,
3555                  [](Value *V) { return isa<ExtractElementInst>(V); }))) &&
3556         all_of(TE.Scalars,
3557                [](Value *V) {
3558                  auto *EE = dyn_cast<ExtractElementInst>(V);
3559                  return !EE || isa<FixedVectorType>(EE->getVectorOperandType());
3560                }) &&
3561         allSameType(TE.Scalars)) {
3562       // Check that gather of extractelements can be represented as
3563       // just a shuffle of a single vector.
3564       OrdersType CurrentOrder;
3565       bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder);
3566       if (Reuse || !CurrentOrder.empty()) {
3567         if (!CurrentOrder.empty())
3568           fixupOrderingIndices(CurrentOrder);
3569         return CurrentOrder;
3570       }
3571     }
3572     if (Optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE))
3573       return CurrentOrder;
3574     if (TE.Scalars.size() >= 4)
3575       if (Optional<OrdersType> Order = findPartiallyOrderedLoads(TE))
3576         return Order;
3577   }
3578   return None;
3579 }
3580 
3581 void BoUpSLP::reorderTopToBottom() {
3582   // Maps VF to the graph nodes.
3583   DenseMap<unsigned, SetVector<TreeEntry *>> VFToOrderedEntries;
3584   // ExtractElement gather nodes which can be vectorized and need to handle
3585   // their ordering.
3586   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3587   // Find all reorderable nodes with the given VF.
3588   // Currently the are vectorized stores,loads,extracts + some gathering of
3589   // extracts.
3590   for_each(VectorizableTree, [this, &VFToOrderedEntries, &GathersToOrders](
3591                                  const std::unique_ptr<TreeEntry> &TE) {
3592     if (Optional<OrdersType> CurrentOrder =
3593             getReorderingData(*TE, /*TopToBottom=*/true)) {
3594       // Do not include ordering for nodes used in the alt opcode vectorization,
3595       // better to reorder them during bottom-to-top stage. If follow the order
3596       // here, it causes reordering of the whole graph though actually it is
3597       // profitable just to reorder the subgraph that starts from the alternate
3598       // opcode vectorization node. Such nodes already end-up with the shuffle
3599       // instruction and it is just enough to change this shuffle rather than
3600       // rotate the scalars for the whole graph.
3601       unsigned Cnt = 0;
3602       const TreeEntry *UserTE = TE.get();
3603       while (UserTE && Cnt < RecursionMaxDepth) {
3604         if (UserTE->UserTreeIndices.size() != 1)
3605           break;
3606         if (all_of(UserTE->UserTreeIndices, [](const EdgeInfo &EI) {
3607               return EI.UserTE->State == TreeEntry::Vectorize &&
3608                      EI.UserTE->isAltShuffle() && EI.UserTE->Idx != 0;
3609             }))
3610           return;
3611         if (UserTE->UserTreeIndices.empty())
3612           UserTE = nullptr;
3613         else
3614           UserTE = UserTE->UserTreeIndices.back().UserTE;
3615         ++Cnt;
3616       }
3617       VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
3618       if (TE->State != TreeEntry::Vectorize)
3619         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3620     }
3621   });
3622 
3623   // Reorder the graph nodes according to their vectorization factor.
3624   for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1;
3625        VF /= 2) {
3626     auto It = VFToOrderedEntries.find(VF);
3627     if (It == VFToOrderedEntries.end())
3628       continue;
3629     // Try to find the most profitable order. We just are looking for the most
3630     // used order and reorder scalar elements in the nodes according to this
3631     // mostly used order.
3632     ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef();
3633     // All operands are reordered and used only in this node - propagate the
3634     // most used order to the user node.
3635     MapVector<OrdersType, unsigned,
3636               DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3637         OrdersUses;
3638     SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3639     for (const TreeEntry *OpTE : OrderedEntries) {
3640       // No need to reorder this nodes, still need to extend and to use shuffle,
3641       // just need to merge reordering shuffle and the reuse shuffle.
3642       if (!OpTE->ReuseShuffleIndices.empty())
3643         continue;
3644       // Count number of orders uses.
3645       const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3646         if (OpTE->State == TreeEntry::NeedToGather)
3647           return GathersToOrders.find(OpTE)->second;
3648         return OpTE->ReorderIndices;
3649       }();
3650       // Stores actually store the mask, not the order, need to invert.
3651       if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3652           OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3653         SmallVector<int> Mask;
3654         inversePermutation(Order, Mask);
3655         unsigned E = Order.size();
3656         OrdersType CurrentOrder(E, E);
3657         transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3658           return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3659         });
3660         fixupOrderingIndices(CurrentOrder);
3661         ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
3662       } else {
3663         ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
3664       }
3665     }
3666     // Set order of the user node.
3667     if (OrdersUses.empty())
3668       continue;
3669     // Choose the most used order.
3670     ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3671     unsigned Cnt = OrdersUses.front().second;
3672     for (const auto &Pair : drop_begin(OrdersUses)) {
3673       if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3674         BestOrder = Pair.first;
3675         Cnt = Pair.second;
3676       }
3677     }
3678     // Set order of the user node.
3679     if (BestOrder.empty())
3680       continue;
3681     SmallVector<int> Mask;
3682     inversePermutation(BestOrder, Mask);
3683     SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3684     unsigned E = BestOrder.size();
3685     transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3686       return I < E ? static_cast<int>(I) : UndefMaskElem;
3687     });
3688     // Do an actual reordering, if profitable.
3689     for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
3690       // Just do the reordering for the nodes with the given VF.
3691       if (TE->Scalars.size() != VF) {
3692         if (TE->ReuseShuffleIndices.size() == VF) {
3693           // Need to reorder the reuses masks of the operands with smaller VF to
3694           // be able to find the match between the graph nodes and scalar
3695           // operands of the given node during vectorization/cost estimation.
3696           assert(all_of(TE->UserTreeIndices,
3697                         [VF, &TE](const EdgeInfo &EI) {
3698                           return EI.UserTE->Scalars.size() == VF ||
3699                                  EI.UserTE->Scalars.size() ==
3700                                      TE->Scalars.size();
3701                         }) &&
3702                  "All users must be of VF size.");
3703           // Update ordering of the operands with the smaller VF than the given
3704           // one.
3705           reorderReuses(TE->ReuseShuffleIndices, Mask);
3706         }
3707         continue;
3708       }
3709       if (TE->State == TreeEntry::Vectorize &&
3710           isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst,
3711               InsertElementInst>(TE->getMainOp()) &&
3712           !TE->isAltShuffle()) {
3713         // Build correct orders for extract{element,value}, loads and
3714         // stores.
3715         reorderOrder(TE->ReorderIndices, Mask);
3716         if (isa<InsertElementInst, StoreInst>(TE->getMainOp()))
3717           TE->reorderOperands(Mask);
3718       } else {
3719         // Reorder the node and its operands.
3720         TE->reorderOperands(Mask);
3721         assert(TE->ReorderIndices.empty() &&
3722                "Expected empty reorder sequence.");
3723         reorderScalars(TE->Scalars, Mask);
3724       }
3725       if (!TE->ReuseShuffleIndices.empty()) {
3726         // Apply reversed order to keep the original ordering of the reused
3727         // elements to avoid extra reorder indices shuffling.
3728         OrdersType CurrentOrder;
3729         reorderOrder(CurrentOrder, MaskOrder);
3730         SmallVector<int> NewReuses;
3731         inversePermutation(CurrentOrder, NewReuses);
3732         addMask(NewReuses, TE->ReuseShuffleIndices);
3733         TE->ReuseShuffleIndices.swap(NewReuses);
3734       }
3735     }
3736   }
3737 }
3738 
3739 bool BoUpSLP::canReorderOperands(
3740     TreeEntry *UserTE, SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
3741     ArrayRef<TreeEntry *> ReorderableGathers,
3742     SmallVectorImpl<TreeEntry *> &GatherOps) {
3743   for (unsigned I = 0, E = UserTE->getNumOperands(); I < E; ++I) {
3744     if (any_of(Edges, [I](const std::pair<unsigned, TreeEntry *> &OpData) {
3745           return OpData.first == I &&
3746                  OpData.second->State == TreeEntry::Vectorize;
3747         }))
3748       continue;
3749     if (TreeEntry *TE = getVectorizedOperand(UserTE, I)) {
3750       // Do not reorder if operand node is used by many user nodes.
3751       if (any_of(TE->UserTreeIndices,
3752                  [UserTE](const EdgeInfo &EI) { return EI.UserTE != UserTE; }))
3753         return false;
3754       // Add the node to the list of the ordered nodes with the identity
3755       // order.
3756       Edges.emplace_back(I, TE);
3757       continue;
3758     }
3759     ArrayRef<Value *> VL = UserTE->getOperand(I);
3760     TreeEntry *Gather = nullptr;
3761     if (count_if(ReorderableGathers, [VL, &Gather](TreeEntry *TE) {
3762           assert(TE->State != TreeEntry::Vectorize &&
3763                  "Only non-vectorized nodes are expected.");
3764           if (TE->isSame(VL)) {
3765             Gather = TE;
3766             return true;
3767           }
3768           return false;
3769         }) > 1)
3770       return false;
3771     if (Gather)
3772       GatherOps.push_back(Gather);
3773   }
3774   return true;
3775 }
3776 
3777 void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) {
3778   SetVector<TreeEntry *> OrderedEntries;
3779   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3780   // Find all reorderable leaf nodes with the given VF.
3781   // Currently the are vectorized loads,extracts without alternate operands +
3782   // some gathering of extracts.
3783   SmallVector<TreeEntry *> NonVectorized;
3784   for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders,
3785                               &NonVectorized](
3786                                  const std::unique_ptr<TreeEntry> &TE) {
3787     if (TE->State != TreeEntry::Vectorize)
3788       NonVectorized.push_back(TE.get());
3789     if (Optional<OrdersType> CurrentOrder =
3790             getReorderingData(*TE, /*TopToBottom=*/false)) {
3791       OrderedEntries.insert(TE.get());
3792       if (TE->State != TreeEntry::Vectorize)
3793         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3794     }
3795   });
3796 
3797   // 1. Propagate order to the graph nodes, which use only reordered nodes.
3798   // I.e., if the node has operands, that are reordered, try to make at least
3799   // one operand order in the natural order and reorder others + reorder the
3800   // user node itself.
3801   SmallPtrSet<const TreeEntry *, 4> Visited;
3802   while (!OrderedEntries.empty()) {
3803     // 1. Filter out only reordered nodes.
3804     // 2. If the entry has multiple uses - skip it and jump to the next node.
3805     MapVector<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users;
3806     SmallVector<TreeEntry *> Filtered;
3807     for (TreeEntry *TE : OrderedEntries) {
3808       if (!(TE->State == TreeEntry::Vectorize ||
3809             (TE->State == TreeEntry::NeedToGather &&
3810              GathersToOrders.count(TE))) ||
3811           TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3812           !all_of(drop_begin(TE->UserTreeIndices),
3813                   [TE](const EdgeInfo &EI) {
3814                     return EI.UserTE == TE->UserTreeIndices.front().UserTE;
3815                   }) ||
3816           !Visited.insert(TE).second) {
3817         Filtered.push_back(TE);
3818         continue;
3819       }
3820       // Build a map between user nodes and their operands order to speedup
3821       // search. The graph currently does not provide this dependency directly.
3822       for (EdgeInfo &EI : TE->UserTreeIndices) {
3823         TreeEntry *UserTE = EI.UserTE;
3824         auto It = Users.find(UserTE);
3825         if (It == Users.end())
3826           It = Users.insert({UserTE, {}}).first;
3827         It->second.emplace_back(EI.EdgeIdx, TE);
3828       }
3829     }
3830     // Erase filtered entries.
3831     for_each(Filtered,
3832              [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); });
3833     for (auto &Data : Users) {
3834       // Check that operands are used only in the User node.
3835       SmallVector<TreeEntry *> GatherOps;
3836       if (!canReorderOperands(Data.first, Data.second, NonVectorized,
3837                               GatherOps)) {
3838         for_each(Data.second,
3839                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3840                    OrderedEntries.remove(Op.second);
3841                  });
3842         continue;
3843       }
3844       // All operands are reordered and used only in this node - propagate the
3845       // most used order to the user node.
3846       MapVector<OrdersType, unsigned,
3847                 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3848           OrdersUses;
3849       // Do the analysis for each tree entry only once, otherwise the order of
3850       // the same node my be considered several times, though might be not
3851       // profitable.
3852       SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3853       SmallPtrSet<const TreeEntry *, 4> VisitedUsers;
3854       for (const auto &Op : Data.second) {
3855         TreeEntry *OpTE = Op.second;
3856         if (!VisitedOps.insert(OpTE).second)
3857           continue;
3858         if (!OpTE->ReuseShuffleIndices.empty() ||
3859             (IgnoreReorder && OpTE == VectorizableTree.front().get()))
3860           continue;
3861         const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3862           if (OpTE->State == TreeEntry::NeedToGather)
3863             return GathersToOrders.find(OpTE)->second;
3864           return OpTE->ReorderIndices;
3865         }();
3866         unsigned NumOps = count_if(
3867             Data.second, [OpTE](const std::pair<unsigned, TreeEntry *> &P) {
3868               return P.second == OpTE;
3869             });
3870         // Stores actually store the mask, not the order, need to invert.
3871         if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3872             OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3873           SmallVector<int> Mask;
3874           inversePermutation(Order, Mask);
3875           unsigned E = Order.size();
3876           OrdersType CurrentOrder(E, E);
3877           transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3878             return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3879           });
3880           fixupOrderingIndices(CurrentOrder);
3881           OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second +=
3882               NumOps;
3883         } else {
3884           OrdersUses.insert(std::make_pair(Order, 0)).first->second += NumOps;
3885         }
3886         auto Res = OrdersUses.insert(std::make_pair(OrdersType(), 0));
3887         const auto &&AllowsReordering = [IgnoreReorder, &GathersToOrders](
3888                                             const TreeEntry *TE) {
3889           if (!TE->ReorderIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3890               (TE->State == TreeEntry::Vectorize && TE->isAltShuffle()) ||
3891               (IgnoreReorder && TE->Idx == 0))
3892             return true;
3893           if (TE->State == TreeEntry::NeedToGather) {
3894             auto It = GathersToOrders.find(TE);
3895             if (It != GathersToOrders.end())
3896               return !It->second.empty();
3897             return true;
3898           }
3899           return false;
3900         };
3901         for (const EdgeInfo &EI : OpTE->UserTreeIndices) {
3902           TreeEntry *UserTE = EI.UserTE;
3903           if (!VisitedUsers.insert(UserTE).second)
3904             continue;
3905           // May reorder user node if it requires reordering, has reused
3906           // scalars, is an alternate op vectorize node or its op nodes require
3907           // reordering.
3908           if (AllowsReordering(UserTE))
3909             continue;
3910           // Check if users allow reordering.
3911           // Currently look up just 1 level of operands to avoid increase of
3912           // the compile time.
3913           // Profitable to reorder if definitely more operands allow
3914           // reordering rather than those with natural order.
3915           ArrayRef<std::pair<unsigned, TreeEntry *>> Ops = Users[UserTE];
3916           if (static_cast<unsigned>(count_if(
3917                   Ops, [UserTE, &AllowsReordering](
3918                            const std::pair<unsigned, TreeEntry *> &Op) {
3919                     return AllowsReordering(Op.second) &&
3920                            all_of(Op.second->UserTreeIndices,
3921                                   [UserTE](const EdgeInfo &EI) {
3922                                     return EI.UserTE == UserTE;
3923                                   });
3924                   })) <= Ops.size() / 2)
3925             ++Res.first->second;
3926         }
3927       }
3928       // If no orders - skip current nodes and jump to the next one, if any.
3929       if (OrdersUses.empty()) {
3930         for_each(Data.second,
3931                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3932                    OrderedEntries.remove(Op.second);
3933                  });
3934         continue;
3935       }
3936       // Choose the best order.
3937       ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3938       unsigned Cnt = OrdersUses.front().second;
3939       for (const auto &Pair : drop_begin(OrdersUses)) {
3940         if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3941           BestOrder = Pair.first;
3942           Cnt = Pair.second;
3943         }
3944       }
3945       // Set order of the user node (reordering of operands and user nodes).
3946       if (BestOrder.empty()) {
3947         for_each(Data.second,
3948                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3949                    OrderedEntries.remove(Op.second);
3950                  });
3951         continue;
3952       }
3953       // Erase operands from OrderedEntries list and adjust their orders.
3954       VisitedOps.clear();
3955       SmallVector<int> Mask;
3956       inversePermutation(BestOrder, Mask);
3957       SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3958       unsigned E = BestOrder.size();
3959       transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3960         return I < E ? static_cast<int>(I) : UndefMaskElem;
3961       });
3962       for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) {
3963         TreeEntry *TE = Op.second;
3964         OrderedEntries.remove(TE);
3965         if (!VisitedOps.insert(TE).second)
3966           continue;
3967         if (TE->ReuseShuffleIndices.size() == BestOrder.size()) {
3968           // Just reorder reuses indices.
3969           reorderReuses(TE->ReuseShuffleIndices, Mask);
3970           continue;
3971         }
3972         // Gathers are processed separately.
3973         if (TE->State != TreeEntry::Vectorize)
3974           continue;
3975         assert((BestOrder.size() == TE->ReorderIndices.size() ||
3976                 TE->ReorderIndices.empty()) &&
3977                "Non-matching sizes of user/operand entries.");
3978         reorderOrder(TE->ReorderIndices, Mask);
3979       }
3980       // For gathers just need to reorder its scalars.
3981       for (TreeEntry *Gather : GatherOps) {
3982         assert(Gather->ReorderIndices.empty() &&
3983                "Unexpected reordering of gathers.");
3984         if (!Gather->ReuseShuffleIndices.empty()) {
3985           // Just reorder reuses indices.
3986           reorderReuses(Gather->ReuseShuffleIndices, Mask);
3987           continue;
3988         }
3989         reorderScalars(Gather->Scalars, Mask);
3990         OrderedEntries.remove(Gather);
3991       }
3992       // Reorder operands of the user node and set the ordering for the user
3993       // node itself.
3994       if (Data.first->State != TreeEntry::Vectorize ||
3995           !isa<ExtractElementInst, ExtractValueInst, LoadInst>(
3996               Data.first->getMainOp()) ||
3997           Data.first->isAltShuffle())
3998         Data.first->reorderOperands(Mask);
3999       if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) ||
4000           Data.first->isAltShuffle()) {
4001         reorderScalars(Data.first->Scalars, Mask);
4002         reorderOrder(Data.first->ReorderIndices, MaskOrder);
4003         if (Data.first->ReuseShuffleIndices.empty() &&
4004             !Data.first->ReorderIndices.empty() &&
4005             !Data.first->isAltShuffle()) {
4006           // Insert user node to the list to try to sink reordering deeper in
4007           // the graph.
4008           OrderedEntries.insert(Data.first);
4009         }
4010       } else {
4011         reorderOrder(Data.first->ReorderIndices, Mask);
4012       }
4013     }
4014   }
4015   // If the reordering is unnecessary, just remove the reorder.
4016   if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() &&
4017       VectorizableTree.front()->ReuseShuffleIndices.empty())
4018     VectorizableTree.front()->ReorderIndices.clear();
4019 }
4020 
4021 void BoUpSLP::buildExternalUses(
4022     const ExtraValueToDebugLocsMap &ExternallyUsedValues) {
4023   // Collect the values that we need to extract from the tree.
4024   for (auto &TEPtr : VectorizableTree) {
4025     TreeEntry *Entry = TEPtr.get();
4026 
4027     // No need to handle users of gathered values.
4028     if (Entry->State == TreeEntry::NeedToGather)
4029       continue;
4030 
4031     // For each lane:
4032     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
4033       Value *Scalar = Entry->Scalars[Lane];
4034       int FoundLane = Entry->findLaneForValue(Scalar);
4035 
4036       // Check if the scalar is externally used as an extra arg.
4037       auto ExtI = ExternallyUsedValues.find(Scalar);
4038       if (ExtI != ExternallyUsedValues.end()) {
4039         LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
4040                           << Lane << " from " << *Scalar << ".\n");
4041         ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
4042       }
4043       for (User *U : Scalar->users()) {
4044         LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
4045 
4046         Instruction *UserInst = dyn_cast<Instruction>(U);
4047         if (!UserInst)
4048           continue;
4049 
4050         if (isDeleted(UserInst))
4051           continue;
4052 
4053         // Skip in-tree scalars that become vectors
4054         if (TreeEntry *UseEntry = getTreeEntry(U)) {
4055           Value *UseScalar = UseEntry->Scalars[0];
4056           // Some in-tree scalars will remain as scalar in vectorized
4057           // instructions. If that is the case, the one in Lane 0 will
4058           // be used.
4059           if (UseScalar != U ||
4060               UseEntry->State == TreeEntry::ScatterVectorize ||
4061               !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
4062             LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
4063                               << ".\n");
4064             assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state");
4065             continue;
4066           }
4067         }
4068 
4069         // Ignore users in the user ignore list.
4070         if (is_contained(UserIgnoreList, UserInst))
4071           continue;
4072 
4073         LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
4074                           << Lane << " from " << *Scalar << ".\n");
4075         ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
4076       }
4077     }
4078   }
4079 }
4080 
4081 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
4082                         ArrayRef<Value *> UserIgnoreLst) {
4083   deleteTree();
4084   UserIgnoreList = UserIgnoreLst;
4085   if (!allSameType(Roots))
4086     return;
4087   buildTree_rec(Roots, 0, EdgeInfo());
4088 }
4089 
4090 namespace {
4091 /// Tracks the state we can represent the loads in the given sequence.
4092 enum class LoadsState { Gather, Vectorize, ScatterVectorize };
4093 } // anonymous namespace
4094 
4095 /// Checks if the given array of loads can be represented as a vectorized,
4096 /// scatter or just simple gather.
4097 static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0,
4098                                     const TargetTransformInfo &TTI,
4099                                     const DataLayout &DL, ScalarEvolution &SE,
4100                                     SmallVectorImpl<unsigned> &Order,
4101                                     SmallVectorImpl<Value *> &PointerOps) {
4102   // Check that a vectorized load would load the same memory as a scalar
4103   // load. For example, we don't want to vectorize loads that are smaller
4104   // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
4105   // treats loading/storing it as an i8 struct. If we vectorize loads/stores
4106   // from such a struct, we read/write packed bits disagreeing with the
4107   // unvectorized version.
4108   Type *ScalarTy = VL0->getType();
4109 
4110   if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy))
4111     return LoadsState::Gather;
4112 
4113   // Make sure all loads in the bundle are simple - we can't vectorize
4114   // atomic or volatile loads.
4115   PointerOps.clear();
4116   PointerOps.resize(VL.size());
4117   auto *POIter = PointerOps.begin();
4118   for (Value *V : VL) {
4119     auto *L = cast<LoadInst>(V);
4120     if (!L->isSimple())
4121       return LoadsState::Gather;
4122     *POIter = L->getPointerOperand();
4123     ++POIter;
4124   }
4125 
4126   Order.clear();
4127   // Check the order of pointer operands.
4128   if (llvm::sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order)) {
4129     Value *Ptr0;
4130     Value *PtrN;
4131     if (Order.empty()) {
4132       Ptr0 = PointerOps.front();
4133       PtrN = PointerOps.back();
4134     } else {
4135       Ptr0 = PointerOps[Order.front()];
4136       PtrN = PointerOps[Order.back()];
4137     }
4138     Optional<int> Diff =
4139         getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE);
4140     // Check that the sorted loads are consecutive.
4141     if (static_cast<unsigned>(*Diff) == VL.size() - 1)
4142       return LoadsState::Vectorize;
4143     Align CommonAlignment = cast<LoadInst>(VL0)->getAlign();
4144     for (Value *V : VL)
4145       CommonAlignment =
4146           commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
4147     if (TTI.isLegalMaskedGather(FixedVectorType::get(ScalarTy, VL.size()),
4148                                 CommonAlignment))
4149       return LoadsState::ScatterVectorize;
4150   }
4151 
4152   return LoadsState::Gather;
4153 }
4154 
4155 /// \return true if the specified list of values has only one instruction that
4156 /// requires scheduling, false otherwise.
4157 #ifndef NDEBUG
4158 static bool needToScheduleSingleInstruction(ArrayRef<Value *> VL) {
4159   Value *NeedsScheduling = nullptr;
4160   for (Value *V : VL) {
4161     if (doesNotNeedToBeScheduled(V))
4162       continue;
4163     if (!NeedsScheduling) {
4164       NeedsScheduling = V;
4165       continue;
4166     }
4167     return false;
4168   }
4169   return NeedsScheduling;
4170 }
4171 #endif
4172 
4173 /// Generates key/subkey pair for the given value to provide effective sorting
4174 /// of the values and better detection of the vectorizable values sequences. The
4175 /// keys/subkeys can be used for better sorting of the values themselves (keys)
4176 /// and in values subgroups (subkeys).
4177 static std::pair<size_t, size_t> generateKeySubkey(
4178     Value *V, const TargetLibraryInfo *TLI,
4179     function_ref<hash_code(size_t, LoadInst *)> LoadsSubkeyGenerator,
4180     bool AllowAlternate) {
4181   hash_code Key = hash_value(V->getValueID() + 2);
4182   hash_code SubKey = hash_value(0);
4183   // Sort the loads by the distance between the pointers.
4184   if (auto *LI = dyn_cast<LoadInst>(V)) {
4185     Key = hash_combine(hash_value(Instruction::Load), Key);
4186     if (LI->isSimple())
4187       SubKey = hash_value(LoadsSubkeyGenerator(Key, LI));
4188     else
4189       SubKey = hash_value(LI);
4190   } else if (isVectorLikeInstWithConstOps(V)) {
4191     // Sort extracts by the vector operands.
4192     if (isa<ExtractElementInst, UndefValue>(V))
4193       Key = hash_value(Value::UndefValueVal + 1);
4194     if (auto *EI = dyn_cast<ExtractElementInst>(V)) {
4195       if (!isUndefVector(EI->getVectorOperand()) &&
4196           !isa<UndefValue>(EI->getIndexOperand()))
4197         SubKey = hash_value(EI->getVectorOperand());
4198     }
4199   } else if (auto *I = dyn_cast<Instruction>(V)) {
4200     // Sort other instructions just by the opcodes except for CMPInst.
4201     // For CMP also sort by the predicate kind.
4202     if ((isa<BinaryOperator>(I) || isa<CastInst>(I)) &&
4203         isValidForAlternation(I->getOpcode())) {
4204       if (AllowAlternate)
4205         Key = hash_value(isa<BinaryOperator>(I) ? 1 : 0);
4206       else
4207         Key = hash_combine(hash_value(I->getOpcode()), Key);
4208       SubKey = hash_combine(
4209           hash_value(I->getOpcode()), hash_value(I->getType()),
4210           hash_value(isa<BinaryOperator>(I)
4211                          ? I->getType()
4212                          : cast<CastInst>(I)->getOperand(0)->getType()));
4213     } else if (auto *CI = dyn_cast<CmpInst>(I)) {
4214       CmpInst::Predicate Pred = CI->getPredicate();
4215       if (CI->isCommutative())
4216         Pred = std::min(Pred, CmpInst::getInversePredicate(Pred));
4217       CmpInst::Predicate SwapPred = CmpInst::getSwappedPredicate(Pred);
4218       SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(Pred),
4219                             hash_value(SwapPred),
4220                             hash_value(CI->getOperand(0)->getType()));
4221     } else if (auto *Call = dyn_cast<CallInst>(I)) {
4222       Intrinsic::ID ID = getVectorIntrinsicIDForCall(Call, TLI);
4223       if (isTriviallyVectorizable(ID))
4224         SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(ID));
4225       else if (!VFDatabase(*Call).getMappings(*Call).empty())
4226         SubKey = hash_combine(hash_value(I->getOpcode()),
4227                               hash_value(Call->getCalledFunction()));
4228       else
4229         SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(Call));
4230       for (const CallBase::BundleOpInfo &Op : Call->bundle_op_infos())
4231         SubKey = hash_combine(hash_value(Op.Begin), hash_value(Op.End),
4232                               hash_value(Op.Tag), SubKey);
4233     } else if (auto *Gep = dyn_cast<GetElementPtrInst>(I)) {
4234       if (Gep->getNumOperands() == 2 && isa<ConstantInt>(Gep->getOperand(1)))
4235         SubKey = hash_value(Gep->getPointerOperand());
4236       else
4237         SubKey = hash_value(Gep);
4238     } else if (BinaryOperator::isIntDivRem(I->getOpcode()) &&
4239                !isa<ConstantInt>(I->getOperand(1))) {
4240       // Do not try to vectorize instructions with potentially high cost.
4241       SubKey = hash_value(I);
4242     } else {
4243       SubKey = hash_value(I->getOpcode());
4244     }
4245     Key = hash_combine(hash_value(I->getParent()), Key);
4246   }
4247   return std::make_pair(Key, SubKey);
4248 }
4249 
4250 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
4251                             const EdgeInfo &UserTreeIdx) {
4252   assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
4253 
4254   SmallVector<int> ReuseShuffleIndicies;
4255   SmallVector<Value *> UniqueValues;
4256   auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues,
4257                                 &UserTreeIdx,
4258                                 this](const InstructionsState &S) {
4259     // Check that every instruction appears once in this bundle.
4260     DenseMap<Value *, unsigned> UniquePositions;
4261     for (Value *V : VL) {
4262       if (isConstant(V)) {
4263         ReuseShuffleIndicies.emplace_back(
4264             isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size());
4265         UniqueValues.emplace_back(V);
4266         continue;
4267       }
4268       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
4269       ReuseShuffleIndicies.emplace_back(Res.first->second);
4270       if (Res.second)
4271         UniqueValues.emplace_back(V);
4272     }
4273     size_t NumUniqueScalarValues = UniqueValues.size();
4274     if (NumUniqueScalarValues == VL.size()) {
4275       ReuseShuffleIndicies.clear();
4276     } else {
4277       LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
4278       if (NumUniqueScalarValues <= 1 ||
4279           (UniquePositions.size() == 1 && all_of(UniqueValues,
4280                                                  [](Value *V) {
4281                                                    return isa<UndefValue>(V) ||
4282                                                           !isConstant(V);
4283                                                  })) ||
4284           !llvm::isPowerOf2_32(NumUniqueScalarValues)) {
4285         LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
4286         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4287         return false;
4288       }
4289       VL = UniqueValues;
4290     }
4291     return true;
4292   };
4293 
4294   InstructionsState S = getSameOpcode(VL);
4295   if (Depth == RecursionMaxDepth) {
4296     LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
4297     if (TryToFindDuplicates(S))
4298       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4299                    ReuseShuffleIndicies);
4300     return;
4301   }
4302 
4303   // Don't handle scalable vectors
4304   if (S.getOpcode() == Instruction::ExtractElement &&
4305       isa<ScalableVectorType>(
4306           cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) {
4307     LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n");
4308     if (TryToFindDuplicates(S))
4309       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4310                    ReuseShuffleIndicies);
4311     return;
4312   }
4313 
4314   // Don't handle vectors.
4315   if (S.OpValue->getType()->isVectorTy() &&
4316       !isa<InsertElementInst>(S.OpValue)) {
4317     LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
4318     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4319     return;
4320   }
4321 
4322   if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
4323     if (SI->getValueOperand()->getType()->isVectorTy()) {
4324       LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
4325       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4326       return;
4327     }
4328 
4329   // If all of the operands are identical or constant we have a simple solution.
4330   // If we deal with insert/extract instructions, they all must have constant
4331   // indices, otherwise we should gather them, not try to vectorize.
4332   if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode() ||
4333       (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(S.MainOp) &&
4334        !all_of(VL, isVectorLikeInstWithConstOps))) {
4335     LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
4336     if (TryToFindDuplicates(S))
4337       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4338                    ReuseShuffleIndicies);
4339     return;
4340   }
4341 
4342   // We now know that this is a vector of instructions of the same type from
4343   // the same block.
4344 
4345   // Don't vectorize ephemeral values.
4346   for (Value *V : VL) {
4347     if (EphValues.count(V)) {
4348       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
4349                         << ") is ephemeral.\n");
4350       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4351       return;
4352     }
4353   }
4354 
4355   // Check if this is a duplicate of another entry.
4356   if (TreeEntry *E = getTreeEntry(S.OpValue)) {
4357     LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n");
4358     if (!E->isSame(VL)) {
4359       LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
4360       if (TryToFindDuplicates(S))
4361         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4362                      ReuseShuffleIndicies);
4363       return;
4364     }
4365     // Record the reuse of the tree node.  FIXME, currently this is only used to
4366     // properly draw the graph rather than for the actual vectorization.
4367     E->UserTreeIndices.push_back(UserTreeIdx);
4368     LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue
4369                       << ".\n");
4370     return;
4371   }
4372 
4373   // Check that none of the instructions in the bundle are already in the tree.
4374   for (Value *V : VL) {
4375     auto *I = dyn_cast<Instruction>(V);
4376     if (!I)
4377       continue;
4378     if (getTreeEntry(I)) {
4379       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
4380                         << ") is already in tree.\n");
4381       if (TryToFindDuplicates(S))
4382         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4383                      ReuseShuffleIndicies);
4384       return;
4385     }
4386   }
4387 
4388   // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
4389   for (Value *V : VL) {
4390     if (is_contained(UserIgnoreList, V)) {
4391       LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
4392       if (TryToFindDuplicates(S))
4393         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4394                      ReuseShuffleIndicies);
4395       return;
4396     }
4397   }
4398 
4399   // Check that all of the users of the scalars that we want to vectorize are
4400   // schedulable.
4401   auto *VL0 = cast<Instruction>(S.OpValue);
4402   BasicBlock *BB = VL0->getParent();
4403 
4404   if (!DT->isReachableFromEntry(BB)) {
4405     // Don't go into unreachable blocks. They may contain instructions with
4406     // dependency cycles which confuse the final scheduling.
4407     LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
4408     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4409     return;
4410   }
4411 
4412   // Check that every instruction appears once in this bundle.
4413   if (!TryToFindDuplicates(S))
4414     return;
4415 
4416   auto &BSRef = BlocksSchedules[BB];
4417   if (!BSRef)
4418     BSRef = std::make_unique<BlockScheduling>(BB);
4419 
4420   BlockScheduling &BS = *BSRef;
4421 
4422   Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S);
4423 #ifdef EXPENSIVE_CHECKS
4424   // Make sure we didn't break any internal invariants
4425   BS.verify();
4426 #endif
4427   if (!Bundle) {
4428     LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
4429     assert((!BS.getScheduleData(VL0) ||
4430             !BS.getScheduleData(VL0)->isPartOfBundle()) &&
4431            "tryScheduleBundle should cancelScheduling on failure");
4432     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4433                  ReuseShuffleIndicies);
4434     return;
4435   }
4436   LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
4437 
4438   unsigned ShuffleOrOp = S.isAltShuffle() ?
4439                 (unsigned) Instruction::ShuffleVector : S.getOpcode();
4440   switch (ShuffleOrOp) {
4441     case Instruction::PHI: {
4442       auto *PH = cast<PHINode>(VL0);
4443 
4444       // Check for terminator values (e.g. invoke).
4445       for (Value *V : VL)
4446         for (Value *Incoming : cast<PHINode>(V)->incoming_values()) {
4447           Instruction *Term = dyn_cast<Instruction>(Incoming);
4448           if (Term && Term->isTerminator()) {
4449             LLVM_DEBUG(dbgs()
4450                        << "SLP: Need to swizzle PHINodes (terminator use).\n");
4451             BS.cancelScheduling(VL, VL0);
4452             newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4453                          ReuseShuffleIndicies);
4454             return;
4455           }
4456         }
4457 
4458       TreeEntry *TE =
4459           newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies);
4460       LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
4461 
4462       // Keeps the reordered operands to avoid code duplication.
4463       SmallVector<ValueList, 2> OperandsVec;
4464       for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
4465         if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) {
4466           ValueList Operands(VL.size(), PoisonValue::get(PH->getType()));
4467           TE->setOperand(I, Operands);
4468           OperandsVec.push_back(Operands);
4469           continue;
4470         }
4471         ValueList Operands;
4472         // Prepare the operand vector.
4473         for (Value *V : VL)
4474           Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(
4475               PH->getIncomingBlock(I)));
4476         TE->setOperand(I, Operands);
4477         OperandsVec.push_back(Operands);
4478       }
4479       for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx)
4480         buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx});
4481       return;
4482     }
4483     case Instruction::ExtractValue:
4484     case Instruction::ExtractElement: {
4485       OrdersType CurrentOrder;
4486       bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
4487       if (Reuse) {
4488         LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
4489         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4490                      ReuseShuffleIndicies);
4491         // This is a special case, as it does not gather, but at the same time
4492         // we are not extending buildTree_rec() towards the operands.
4493         ValueList Op0;
4494         Op0.assign(VL.size(), VL0->getOperand(0));
4495         VectorizableTree.back()->setOperand(0, Op0);
4496         return;
4497       }
4498       if (!CurrentOrder.empty()) {
4499         LLVM_DEBUG({
4500           dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
4501                     "with order";
4502           for (unsigned Idx : CurrentOrder)
4503             dbgs() << " " << Idx;
4504           dbgs() << "\n";
4505         });
4506         fixupOrderingIndices(CurrentOrder);
4507         // Insert new order with initial value 0, if it does not exist,
4508         // otherwise return the iterator to the existing one.
4509         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4510                      ReuseShuffleIndicies, CurrentOrder);
4511         // This is a special case, as it does not gather, but at the same time
4512         // we are not extending buildTree_rec() towards the operands.
4513         ValueList Op0;
4514         Op0.assign(VL.size(), VL0->getOperand(0));
4515         VectorizableTree.back()->setOperand(0, Op0);
4516         return;
4517       }
4518       LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
4519       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4520                    ReuseShuffleIndicies);
4521       BS.cancelScheduling(VL, VL0);
4522       return;
4523     }
4524     case Instruction::InsertElement: {
4525       assert(ReuseShuffleIndicies.empty() && "All inserts should be unique");
4526 
4527       // Check that we have a buildvector and not a shuffle of 2 or more
4528       // different vectors.
4529       ValueSet SourceVectors;
4530       for (Value *V : VL) {
4531         SourceVectors.insert(cast<Instruction>(V)->getOperand(0));
4532         assert(getInsertIndex(V) != None && "Non-constant or undef index?");
4533       }
4534 
4535       if (count_if(VL, [&SourceVectors](Value *V) {
4536             return !SourceVectors.contains(V);
4537           }) >= 2) {
4538         // Found 2nd source vector - cancel.
4539         LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with "
4540                              "different source vectors.\n");
4541         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4542         BS.cancelScheduling(VL, VL0);
4543         return;
4544       }
4545 
4546       auto OrdCompare = [](const std::pair<int, int> &P1,
4547                            const std::pair<int, int> &P2) {
4548         return P1.first > P2.first;
4549       };
4550       PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>,
4551                     decltype(OrdCompare)>
4552           Indices(OrdCompare);
4553       for (int I = 0, E = VL.size(); I < E; ++I) {
4554         unsigned Idx = *getInsertIndex(VL[I]);
4555         Indices.emplace(Idx, I);
4556       }
4557       OrdersType CurrentOrder(VL.size(), VL.size());
4558       bool IsIdentity = true;
4559       for (int I = 0, E = VL.size(); I < E; ++I) {
4560         CurrentOrder[Indices.top().second] = I;
4561         IsIdentity &= Indices.top().second == I;
4562         Indices.pop();
4563       }
4564       if (IsIdentity)
4565         CurrentOrder.clear();
4566       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4567                                    None, CurrentOrder);
4568       LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n");
4569 
4570       constexpr int NumOps = 2;
4571       ValueList VectorOperands[NumOps];
4572       for (int I = 0; I < NumOps; ++I) {
4573         for (Value *V : VL)
4574           VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I));
4575 
4576         TE->setOperand(I, VectorOperands[I]);
4577       }
4578       buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1});
4579       return;
4580     }
4581     case Instruction::Load: {
4582       // Check that a vectorized load would load the same memory as a scalar
4583       // load. For example, we don't want to vectorize loads that are smaller
4584       // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
4585       // treats loading/storing it as an i8 struct. If we vectorize loads/stores
4586       // from such a struct, we read/write packed bits disagreeing with the
4587       // unvectorized version.
4588       SmallVector<Value *> PointerOps;
4589       OrdersType CurrentOrder;
4590       TreeEntry *TE = nullptr;
4591       switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, CurrentOrder,
4592                                 PointerOps)) {
4593       case LoadsState::Vectorize:
4594         if (CurrentOrder.empty()) {
4595           // Original loads are consecutive and does not require reordering.
4596           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4597                             ReuseShuffleIndicies);
4598           LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
4599         } else {
4600           fixupOrderingIndices(CurrentOrder);
4601           // Need to reorder.
4602           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4603                             ReuseShuffleIndicies, CurrentOrder);
4604           LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
4605         }
4606         TE->setOperandsInOrder();
4607         break;
4608       case LoadsState::ScatterVectorize:
4609         // Vectorizing non-consecutive loads with `llvm.masked.gather`.
4610         TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S,
4611                           UserTreeIdx, ReuseShuffleIndicies);
4612         TE->setOperandsInOrder();
4613         buildTree_rec(PointerOps, Depth + 1, {TE, 0});
4614         LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n");
4615         break;
4616       case LoadsState::Gather:
4617         BS.cancelScheduling(VL, VL0);
4618         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4619                      ReuseShuffleIndicies);
4620 #ifndef NDEBUG
4621         Type *ScalarTy = VL0->getType();
4622         if (DL->getTypeSizeInBits(ScalarTy) !=
4623             DL->getTypeAllocSizeInBits(ScalarTy))
4624           LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
4625         else if (any_of(VL, [](Value *V) {
4626                    return !cast<LoadInst>(V)->isSimple();
4627                  }))
4628           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
4629         else
4630           LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
4631 #endif // NDEBUG
4632         break;
4633       }
4634       return;
4635     }
4636     case Instruction::ZExt:
4637     case Instruction::SExt:
4638     case Instruction::FPToUI:
4639     case Instruction::FPToSI:
4640     case Instruction::FPExt:
4641     case Instruction::PtrToInt:
4642     case Instruction::IntToPtr:
4643     case Instruction::SIToFP:
4644     case Instruction::UIToFP:
4645     case Instruction::Trunc:
4646     case Instruction::FPTrunc:
4647     case Instruction::BitCast: {
4648       Type *SrcTy = VL0->getOperand(0)->getType();
4649       for (Value *V : VL) {
4650         Type *Ty = cast<Instruction>(V)->getOperand(0)->getType();
4651         if (Ty != SrcTy || !isValidElementType(Ty)) {
4652           BS.cancelScheduling(VL, VL0);
4653           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4654                        ReuseShuffleIndicies);
4655           LLVM_DEBUG(dbgs()
4656                      << "SLP: Gathering casts with different src types.\n");
4657           return;
4658         }
4659       }
4660       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4661                                    ReuseShuffleIndicies);
4662       LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
4663 
4664       TE->setOperandsInOrder();
4665       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4666         ValueList Operands;
4667         // Prepare the operand vector.
4668         for (Value *V : VL)
4669           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4670 
4671         buildTree_rec(Operands, Depth + 1, {TE, i});
4672       }
4673       return;
4674     }
4675     case Instruction::ICmp:
4676     case Instruction::FCmp: {
4677       // Check that all of the compares have the same predicate.
4678       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
4679       CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0);
4680       Type *ComparedTy = VL0->getOperand(0)->getType();
4681       for (Value *V : VL) {
4682         CmpInst *Cmp = cast<CmpInst>(V);
4683         if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) ||
4684             Cmp->getOperand(0)->getType() != ComparedTy) {
4685           BS.cancelScheduling(VL, VL0);
4686           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4687                        ReuseShuffleIndicies);
4688           LLVM_DEBUG(dbgs()
4689                      << "SLP: Gathering cmp with different predicate.\n");
4690           return;
4691         }
4692       }
4693 
4694       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4695                                    ReuseShuffleIndicies);
4696       LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
4697 
4698       ValueList Left, Right;
4699       if (cast<CmpInst>(VL0)->isCommutative()) {
4700         // Commutative predicate - collect + sort operands of the instructions
4701         // so that each side is more likely to have the same opcode.
4702         assert(P0 == SwapP0 && "Commutative Predicate mismatch");
4703         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4704       } else {
4705         // Collect operands - commute if it uses the swapped predicate.
4706         for (Value *V : VL) {
4707           auto *Cmp = cast<CmpInst>(V);
4708           Value *LHS = Cmp->getOperand(0);
4709           Value *RHS = Cmp->getOperand(1);
4710           if (Cmp->getPredicate() != P0)
4711             std::swap(LHS, RHS);
4712           Left.push_back(LHS);
4713           Right.push_back(RHS);
4714         }
4715       }
4716       TE->setOperand(0, Left);
4717       TE->setOperand(1, Right);
4718       buildTree_rec(Left, Depth + 1, {TE, 0});
4719       buildTree_rec(Right, Depth + 1, {TE, 1});
4720       return;
4721     }
4722     case Instruction::Select:
4723     case Instruction::FNeg:
4724     case Instruction::Add:
4725     case Instruction::FAdd:
4726     case Instruction::Sub:
4727     case Instruction::FSub:
4728     case Instruction::Mul:
4729     case Instruction::FMul:
4730     case Instruction::UDiv:
4731     case Instruction::SDiv:
4732     case Instruction::FDiv:
4733     case Instruction::URem:
4734     case Instruction::SRem:
4735     case Instruction::FRem:
4736     case Instruction::Shl:
4737     case Instruction::LShr:
4738     case Instruction::AShr:
4739     case Instruction::And:
4740     case Instruction::Or:
4741     case Instruction::Xor: {
4742       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4743                                    ReuseShuffleIndicies);
4744       LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n");
4745 
4746       // Sort operands of the instructions so that each side is more likely to
4747       // have the same opcode.
4748       if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
4749         ValueList Left, Right;
4750         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4751         TE->setOperand(0, Left);
4752         TE->setOperand(1, Right);
4753         buildTree_rec(Left, Depth + 1, {TE, 0});
4754         buildTree_rec(Right, Depth + 1, {TE, 1});
4755         return;
4756       }
4757 
4758       TE->setOperandsInOrder();
4759       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4760         ValueList Operands;
4761         // Prepare the operand vector.
4762         for (Value *V : VL)
4763           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4764 
4765         buildTree_rec(Operands, Depth + 1, {TE, i});
4766       }
4767       return;
4768     }
4769     case Instruction::GetElementPtr: {
4770       // We don't combine GEPs with complicated (nested) indexing.
4771       for (Value *V : VL) {
4772         if (cast<Instruction>(V)->getNumOperands() != 2) {
4773           LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
4774           BS.cancelScheduling(VL, VL0);
4775           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4776                        ReuseShuffleIndicies);
4777           return;
4778         }
4779       }
4780 
4781       // We can't combine several GEPs into one vector if they operate on
4782       // different types.
4783       Type *Ty0 = cast<GEPOperator>(VL0)->getSourceElementType();
4784       for (Value *V : VL) {
4785         Type *CurTy = cast<GEPOperator>(V)->getSourceElementType();
4786         if (Ty0 != CurTy) {
4787           LLVM_DEBUG(dbgs()
4788                      << "SLP: not-vectorizable GEP (different types).\n");
4789           BS.cancelScheduling(VL, VL0);
4790           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4791                        ReuseShuffleIndicies);
4792           return;
4793         }
4794       }
4795 
4796       // We don't combine GEPs with non-constant indexes.
4797       Type *Ty1 = VL0->getOperand(1)->getType();
4798       for (Value *V : VL) {
4799         auto Op = cast<Instruction>(V)->getOperand(1);
4800         if (!isa<ConstantInt>(Op) ||
4801             (Op->getType() != Ty1 &&
4802              Op->getType()->getScalarSizeInBits() >
4803                  DL->getIndexSizeInBits(
4804                      V->getType()->getPointerAddressSpace()))) {
4805           LLVM_DEBUG(dbgs()
4806                      << "SLP: not-vectorizable GEP (non-constant indexes).\n");
4807           BS.cancelScheduling(VL, VL0);
4808           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4809                        ReuseShuffleIndicies);
4810           return;
4811         }
4812       }
4813 
4814       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4815                                    ReuseShuffleIndicies);
4816       LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
4817       SmallVector<ValueList, 2> Operands(2);
4818       // Prepare the operand vector for pointer operands.
4819       for (Value *V : VL)
4820         Operands.front().push_back(
4821             cast<GetElementPtrInst>(V)->getPointerOperand());
4822       TE->setOperand(0, Operands.front());
4823       // Need to cast all indices to the same type before vectorization to
4824       // avoid crash.
4825       // Required to be able to find correct matches between different gather
4826       // nodes and reuse the vectorized values rather than trying to gather them
4827       // again.
4828       int IndexIdx = 1;
4829       Type *VL0Ty = VL0->getOperand(IndexIdx)->getType();
4830       Type *Ty = all_of(VL,
4831                         [VL0Ty, IndexIdx](Value *V) {
4832                           return VL0Ty == cast<GetElementPtrInst>(V)
4833                                               ->getOperand(IndexIdx)
4834                                               ->getType();
4835                         })
4836                      ? VL0Ty
4837                      : DL->getIndexType(cast<GetElementPtrInst>(VL0)
4838                                             ->getPointerOperandType()
4839                                             ->getScalarType());
4840       // Prepare the operand vector.
4841       for (Value *V : VL) {
4842         auto *Op = cast<Instruction>(V)->getOperand(IndexIdx);
4843         auto *CI = cast<ConstantInt>(Op);
4844         Operands.back().push_back(ConstantExpr::getIntegerCast(
4845             CI, Ty, CI->getValue().isSignBitSet()));
4846       }
4847       TE->setOperand(IndexIdx, Operands.back());
4848 
4849       for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I)
4850         buildTree_rec(Operands[I], Depth + 1, {TE, I});
4851       return;
4852     }
4853     case Instruction::Store: {
4854       // Check if the stores are consecutive or if we need to swizzle them.
4855       llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType();
4856       // Avoid types that are padded when being allocated as scalars, while
4857       // being packed together in a vector (such as i1).
4858       if (DL->getTypeSizeInBits(ScalarTy) !=
4859           DL->getTypeAllocSizeInBits(ScalarTy)) {
4860         BS.cancelScheduling(VL, VL0);
4861         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4862                      ReuseShuffleIndicies);
4863         LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n");
4864         return;
4865       }
4866       // Make sure all stores in the bundle are simple - we can't vectorize
4867       // atomic or volatile stores.
4868       SmallVector<Value *, 4> PointerOps(VL.size());
4869       ValueList Operands(VL.size());
4870       auto POIter = PointerOps.begin();
4871       auto OIter = Operands.begin();
4872       for (Value *V : VL) {
4873         auto *SI = cast<StoreInst>(V);
4874         if (!SI->isSimple()) {
4875           BS.cancelScheduling(VL, VL0);
4876           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4877                        ReuseShuffleIndicies);
4878           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n");
4879           return;
4880         }
4881         *POIter = SI->getPointerOperand();
4882         *OIter = SI->getValueOperand();
4883         ++POIter;
4884         ++OIter;
4885       }
4886 
4887       OrdersType CurrentOrder;
4888       // Check the order of pointer operands.
4889       if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) {
4890         Value *Ptr0;
4891         Value *PtrN;
4892         if (CurrentOrder.empty()) {
4893           Ptr0 = PointerOps.front();
4894           PtrN = PointerOps.back();
4895         } else {
4896           Ptr0 = PointerOps[CurrentOrder.front()];
4897           PtrN = PointerOps[CurrentOrder.back()];
4898         }
4899         Optional<int> Dist =
4900             getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE);
4901         // Check that the sorted pointer operands are consecutive.
4902         if (static_cast<unsigned>(*Dist) == VL.size() - 1) {
4903           if (CurrentOrder.empty()) {
4904             // Original stores are consecutive and does not require reordering.
4905             TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
4906                                          UserTreeIdx, ReuseShuffleIndicies);
4907             TE->setOperandsInOrder();
4908             buildTree_rec(Operands, Depth + 1, {TE, 0});
4909             LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
4910           } else {
4911             fixupOrderingIndices(CurrentOrder);
4912             TreeEntry *TE =
4913                 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4914                              ReuseShuffleIndicies, CurrentOrder);
4915             TE->setOperandsInOrder();
4916             buildTree_rec(Operands, Depth + 1, {TE, 0});
4917             LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n");
4918           }
4919           return;
4920         }
4921       }
4922 
4923       BS.cancelScheduling(VL, VL0);
4924       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4925                    ReuseShuffleIndicies);
4926       LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
4927       return;
4928     }
4929     case Instruction::Call: {
4930       // Check if the calls are all to the same vectorizable intrinsic or
4931       // library function.
4932       CallInst *CI = cast<CallInst>(VL0);
4933       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4934 
4935       VFShape Shape = VFShape::get(
4936           *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())),
4937           false /*HasGlobalPred*/);
4938       Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4939 
4940       if (!VecFunc && !isTriviallyVectorizable(ID)) {
4941         BS.cancelScheduling(VL, VL0);
4942         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4943                      ReuseShuffleIndicies);
4944         LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
4945         return;
4946       }
4947       Function *F = CI->getCalledFunction();
4948       unsigned NumArgs = CI->arg_size();
4949       SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr);
4950       for (unsigned j = 0; j != NumArgs; ++j)
4951         if (isVectorIntrinsicWithScalarOpAtArg(ID, j))
4952           ScalarArgs[j] = CI->getArgOperand(j);
4953       for (Value *V : VL) {
4954         CallInst *CI2 = dyn_cast<CallInst>(V);
4955         if (!CI2 || CI2->getCalledFunction() != F ||
4956             getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
4957             (VecFunc &&
4958              VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) ||
4959             !CI->hasIdenticalOperandBundleSchema(*CI2)) {
4960           BS.cancelScheduling(VL, VL0);
4961           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4962                        ReuseShuffleIndicies);
4963           LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V
4964                             << "\n");
4965           return;
4966         }
4967         // Some intrinsics have scalar arguments and should be same in order for
4968         // them to be vectorized.
4969         for (unsigned j = 0; j != NumArgs; ++j) {
4970           if (isVectorIntrinsicWithScalarOpAtArg(ID, j)) {
4971             Value *A1J = CI2->getArgOperand(j);
4972             if (ScalarArgs[j] != A1J) {
4973               BS.cancelScheduling(VL, VL0);
4974               newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4975                            ReuseShuffleIndicies);
4976               LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
4977                                 << " argument " << ScalarArgs[j] << "!=" << A1J
4978                                 << "\n");
4979               return;
4980             }
4981           }
4982         }
4983         // Verify that the bundle operands are identical between the two calls.
4984         if (CI->hasOperandBundles() &&
4985             !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
4986                         CI->op_begin() + CI->getBundleOperandsEndIndex(),
4987                         CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
4988           BS.cancelScheduling(VL, VL0);
4989           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4990                        ReuseShuffleIndicies);
4991           LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
4992                             << *CI << "!=" << *V << '\n');
4993           return;
4994         }
4995       }
4996 
4997       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4998                                    ReuseShuffleIndicies);
4999       TE->setOperandsInOrder();
5000       for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
5001         // For scalar operands no need to to create an entry since no need to
5002         // vectorize it.
5003         if (isVectorIntrinsicWithScalarOpAtArg(ID, i))
5004           continue;
5005         ValueList Operands;
5006         // Prepare the operand vector.
5007         for (Value *V : VL) {
5008           auto *CI2 = cast<CallInst>(V);
5009           Operands.push_back(CI2->getArgOperand(i));
5010         }
5011         buildTree_rec(Operands, Depth + 1, {TE, i});
5012       }
5013       return;
5014     }
5015     case Instruction::ShuffleVector: {
5016       // If this is not an alternate sequence of opcode like add-sub
5017       // then do not vectorize this instruction.
5018       if (!S.isAltShuffle()) {
5019         BS.cancelScheduling(VL, VL0);
5020         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5021                      ReuseShuffleIndicies);
5022         LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
5023         return;
5024       }
5025       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
5026                                    ReuseShuffleIndicies);
5027       LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
5028 
5029       // Reorder operands if reordering would enable vectorization.
5030       auto *CI = dyn_cast<CmpInst>(VL0);
5031       if (isa<BinaryOperator>(VL0) || CI) {
5032         ValueList Left, Right;
5033         if (!CI || all_of(VL, [](Value *V) {
5034               return cast<CmpInst>(V)->isCommutative();
5035             })) {
5036           reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
5037         } else {
5038           CmpInst::Predicate P0 = CI->getPredicate();
5039           CmpInst::Predicate AltP0 = cast<CmpInst>(S.AltOp)->getPredicate();
5040           assert(P0 != AltP0 &&
5041                  "Expected different main/alternate predicates.");
5042           CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
5043           Value *BaseOp0 = VL0->getOperand(0);
5044           Value *BaseOp1 = VL0->getOperand(1);
5045           // Collect operands - commute if it uses the swapped predicate or
5046           // alternate operation.
5047           for (Value *V : VL) {
5048             auto *Cmp = cast<CmpInst>(V);
5049             Value *LHS = Cmp->getOperand(0);
5050             Value *RHS = Cmp->getOperand(1);
5051             CmpInst::Predicate CurrentPred = Cmp->getPredicate();
5052             if (P0 == AltP0Swapped) {
5053               if (CI != Cmp && S.AltOp != Cmp &&
5054                   ((P0 == CurrentPred &&
5055                     !areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)) ||
5056                    (AltP0 == CurrentPred &&
5057                     areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS))))
5058                 std::swap(LHS, RHS);
5059             } else if (P0 != CurrentPred && AltP0 != CurrentPred) {
5060               std::swap(LHS, RHS);
5061             }
5062             Left.push_back(LHS);
5063             Right.push_back(RHS);
5064           }
5065         }
5066         TE->setOperand(0, Left);
5067         TE->setOperand(1, Right);
5068         buildTree_rec(Left, Depth + 1, {TE, 0});
5069         buildTree_rec(Right, Depth + 1, {TE, 1});
5070         return;
5071       }
5072 
5073       TE->setOperandsInOrder();
5074       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
5075         ValueList Operands;
5076         // Prepare the operand vector.
5077         for (Value *V : VL)
5078           Operands.push_back(cast<Instruction>(V)->getOperand(i));
5079 
5080         buildTree_rec(Operands, Depth + 1, {TE, i});
5081       }
5082       return;
5083     }
5084     default:
5085       BS.cancelScheduling(VL, VL0);
5086       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5087                    ReuseShuffleIndicies);
5088       LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
5089       return;
5090   }
5091 }
5092 
5093 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
5094   unsigned N = 1;
5095   Type *EltTy = T;
5096 
5097   while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) ||
5098          isa<VectorType>(EltTy)) {
5099     if (auto *ST = dyn_cast<StructType>(EltTy)) {
5100       // Check that struct is homogeneous.
5101       for (const auto *Ty : ST->elements())
5102         if (Ty != *ST->element_begin())
5103           return 0;
5104       N *= ST->getNumElements();
5105       EltTy = *ST->element_begin();
5106     } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) {
5107       N *= AT->getNumElements();
5108       EltTy = AT->getElementType();
5109     } else {
5110       auto *VT = cast<FixedVectorType>(EltTy);
5111       N *= VT->getNumElements();
5112       EltTy = VT->getElementType();
5113     }
5114   }
5115 
5116   if (!isValidElementType(EltTy))
5117     return 0;
5118   uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N));
5119   if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
5120     return 0;
5121   return N;
5122 }
5123 
5124 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
5125                               SmallVectorImpl<unsigned> &CurrentOrder) const {
5126   const auto *It = find_if(VL, [](Value *V) {
5127     return isa<ExtractElementInst, ExtractValueInst>(V);
5128   });
5129   assert(It != VL.end() && "Expected at least one extract instruction.");
5130   auto *E0 = cast<Instruction>(*It);
5131   assert(all_of(VL,
5132                 [](Value *V) {
5133                   return isa<UndefValue, ExtractElementInst, ExtractValueInst>(
5134                       V);
5135                 }) &&
5136          "Invalid opcode");
5137   // Check if all of the extracts come from the same vector and from the
5138   // correct offset.
5139   Value *Vec = E0->getOperand(0);
5140 
5141   CurrentOrder.clear();
5142 
5143   // We have to extract from a vector/aggregate with the same number of elements.
5144   unsigned NElts;
5145   if (E0->getOpcode() == Instruction::ExtractValue) {
5146     const DataLayout &DL = E0->getModule()->getDataLayout();
5147     NElts = canMapToVector(Vec->getType(), DL);
5148     if (!NElts)
5149       return false;
5150     // Check if load can be rewritten as load of vector.
5151     LoadInst *LI = dyn_cast<LoadInst>(Vec);
5152     if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
5153       return false;
5154   } else {
5155     NElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
5156   }
5157 
5158   if (NElts != VL.size())
5159     return false;
5160 
5161   // Check that all of the indices extract from the correct offset.
5162   bool ShouldKeepOrder = true;
5163   unsigned E = VL.size();
5164   // Assign to all items the initial value E + 1 so we can check if the extract
5165   // instruction index was used already.
5166   // Also, later we can check that all the indices are used and we have a
5167   // consecutive access in the extract instructions, by checking that no
5168   // element of CurrentOrder still has value E + 1.
5169   CurrentOrder.assign(E, E);
5170   unsigned I = 0;
5171   for (; I < E; ++I) {
5172     auto *Inst = dyn_cast<Instruction>(VL[I]);
5173     if (!Inst)
5174       continue;
5175     if (Inst->getOperand(0) != Vec)
5176       break;
5177     if (auto *EE = dyn_cast<ExtractElementInst>(Inst))
5178       if (isa<UndefValue>(EE->getIndexOperand()))
5179         continue;
5180     Optional<unsigned> Idx = getExtractIndex(Inst);
5181     if (!Idx)
5182       break;
5183     const unsigned ExtIdx = *Idx;
5184     if (ExtIdx != I) {
5185       if (ExtIdx >= E || CurrentOrder[ExtIdx] != E)
5186         break;
5187       ShouldKeepOrder = false;
5188       CurrentOrder[ExtIdx] = I;
5189     } else {
5190       if (CurrentOrder[I] != E)
5191         break;
5192       CurrentOrder[I] = I;
5193     }
5194   }
5195   if (I < E) {
5196     CurrentOrder.clear();
5197     return false;
5198   }
5199   if (ShouldKeepOrder)
5200     CurrentOrder.clear();
5201 
5202   return ShouldKeepOrder;
5203 }
5204 
5205 bool BoUpSLP::areAllUsersVectorized(Instruction *I,
5206                                     ArrayRef<Value *> VectorizedVals) const {
5207   return (I->hasOneUse() && is_contained(VectorizedVals, I)) ||
5208          all_of(I->users(), [this](User *U) {
5209            return ScalarToTreeEntry.count(U) > 0 ||
5210                   isVectorLikeInstWithConstOps(U) ||
5211                   (isa<ExtractElementInst>(U) && MustGather.contains(U));
5212          });
5213 }
5214 
5215 static std::pair<InstructionCost, InstructionCost>
5216 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy,
5217                    TargetTransformInfo *TTI, TargetLibraryInfo *TLI) {
5218   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5219 
5220   // Calculate the cost of the scalar and vector calls.
5221   SmallVector<Type *, 4> VecTys;
5222   for (Use &Arg : CI->args())
5223     VecTys.push_back(
5224         FixedVectorType::get(Arg->getType(), VecTy->getNumElements()));
5225   FastMathFlags FMF;
5226   if (auto *FPCI = dyn_cast<FPMathOperator>(CI))
5227     FMF = FPCI->getFastMathFlags();
5228   SmallVector<const Value *> Arguments(CI->args());
5229   IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF,
5230                                     dyn_cast<IntrinsicInst>(CI));
5231   auto IntrinsicCost =
5232     TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput);
5233 
5234   auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
5235                                      VecTy->getNumElements())),
5236                             false /*HasGlobalPred*/);
5237   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
5238   auto LibCost = IntrinsicCost;
5239   if (!CI->isNoBuiltin() && VecFunc) {
5240     // Calculate the cost of the vector library call.
5241     // If the corresponding vector call is cheaper, return its cost.
5242     LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys,
5243                                     TTI::TCK_RecipThroughput);
5244   }
5245   return {IntrinsicCost, LibCost};
5246 }
5247 
5248 /// Compute the cost of creating a vector of type \p VecTy containing the
5249 /// extracted values from \p VL.
5250 static InstructionCost
5251 computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy,
5252                    TargetTransformInfo::ShuffleKind ShuffleKind,
5253                    ArrayRef<int> Mask, TargetTransformInfo &TTI) {
5254   unsigned NumOfParts = TTI.getNumberOfParts(VecTy);
5255 
5256   if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts ||
5257       VecTy->getNumElements() < NumOfParts)
5258     return TTI.getShuffleCost(ShuffleKind, VecTy, Mask);
5259 
5260   bool AllConsecutive = true;
5261   unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts;
5262   unsigned Idx = -1;
5263   InstructionCost Cost = 0;
5264 
5265   // Process extracts in blocks of EltsPerVector to check if the source vector
5266   // operand can be re-used directly. If not, add the cost of creating a shuffle
5267   // to extract the values into a vector register.
5268   SmallVector<int> RegMask(EltsPerVector, UndefMaskElem);
5269   for (auto *V : VL) {
5270     ++Idx;
5271 
5272     // Need to exclude undefs from analysis.
5273     if (isa<UndefValue>(V) || Mask[Idx] == UndefMaskElem)
5274       continue;
5275 
5276     // Reached the start of a new vector registers.
5277     if (Idx % EltsPerVector == 0) {
5278       RegMask.assign(EltsPerVector, UndefMaskElem);
5279       AllConsecutive = true;
5280       continue;
5281     }
5282 
5283     // Check all extracts for a vector register on the target directly
5284     // extract values in order.
5285     unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V));
5286     if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != UndefMaskElem) {
5287       unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1]));
5288       AllConsecutive &= PrevIdx + 1 == CurrentIdx &&
5289                         CurrentIdx % EltsPerVector == Idx % EltsPerVector;
5290       RegMask[Idx % EltsPerVector] = CurrentIdx % EltsPerVector;
5291     }
5292 
5293     if (AllConsecutive)
5294       continue;
5295 
5296     // Skip all indices, except for the last index per vector block.
5297     if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size())
5298       continue;
5299 
5300     // If we have a series of extracts which are not consecutive and hence
5301     // cannot re-use the source vector register directly, compute the shuffle
5302     // cost to extract the vector with EltsPerVector elements.
5303     Cost += TTI.getShuffleCost(
5304         TargetTransformInfo::SK_PermuteSingleSrc,
5305         FixedVectorType::get(VecTy->getElementType(), EltsPerVector), RegMask);
5306   }
5307   return Cost;
5308 }
5309 
5310 /// Build shuffle mask for shuffle graph entries and lists of main and alternate
5311 /// operations operands.
5312 static void
5313 buildShuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices,
5314                       ArrayRef<int> ReusesIndices,
5315                       const function_ref<bool(Instruction *)> IsAltOp,
5316                       SmallVectorImpl<int> &Mask,
5317                       SmallVectorImpl<Value *> *OpScalars = nullptr,
5318                       SmallVectorImpl<Value *> *AltScalars = nullptr) {
5319   unsigned Sz = VL.size();
5320   Mask.assign(Sz, UndefMaskElem);
5321   SmallVector<int> OrderMask;
5322   if (!ReorderIndices.empty())
5323     inversePermutation(ReorderIndices, OrderMask);
5324   for (unsigned I = 0; I < Sz; ++I) {
5325     unsigned Idx = I;
5326     if (!ReorderIndices.empty())
5327       Idx = OrderMask[I];
5328     auto *OpInst = cast<Instruction>(VL[Idx]);
5329     if (IsAltOp(OpInst)) {
5330       Mask[I] = Sz + Idx;
5331       if (AltScalars)
5332         AltScalars->push_back(OpInst);
5333     } else {
5334       Mask[I] = Idx;
5335       if (OpScalars)
5336         OpScalars->push_back(OpInst);
5337     }
5338   }
5339   if (!ReusesIndices.empty()) {
5340     SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem);
5341     transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) {
5342       return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem;
5343     });
5344     Mask.swap(NewMask);
5345   }
5346 }
5347 
5348 /// Checks if the specified instruction \p I is an alternate operation for the
5349 /// given \p MainOp and \p AltOp instructions.
5350 static bool isAlternateInstruction(const Instruction *I,
5351                                    const Instruction *MainOp,
5352                                    const Instruction *AltOp) {
5353   if (auto *CI0 = dyn_cast<CmpInst>(MainOp)) {
5354     auto *AltCI0 = cast<CmpInst>(AltOp);
5355     auto *CI = cast<CmpInst>(I);
5356     CmpInst::Predicate P0 = CI0->getPredicate();
5357     CmpInst::Predicate AltP0 = AltCI0->getPredicate();
5358     assert(P0 != AltP0 && "Expected different main/alternate predicates.");
5359     CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
5360     CmpInst::Predicate CurrentPred = CI->getPredicate();
5361     if (P0 == AltP0Swapped)
5362       return I == AltCI0 ||
5363              (I != MainOp &&
5364               !areCompatibleCmpOps(CI0->getOperand(0), CI0->getOperand(1),
5365                                    CI->getOperand(0), CI->getOperand(1)));
5366     return AltP0 == CurrentPred || AltP0Swapped == CurrentPred;
5367   }
5368   return I->getOpcode() == AltOp->getOpcode();
5369 }
5370 
5371 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E,
5372                                       ArrayRef<Value *> VectorizedVals) {
5373   ArrayRef<Value*> VL = E->Scalars;
5374 
5375   Type *ScalarTy = VL[0]->getType();
5376   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
5377     ScalarTy = SI->getValueOperand()->getType();
5378   else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
5379     ScalarTy = CI->getOperand(0)->getType();
5380   else if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
5381     ScalarTy = IE->getOperand(1)->getType();
5382   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
5383   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
5384 
5385   // If we have computed a smaller type for the expression, update VecTy so
5386   // that the costs will be accurate.
5387   if (MinBWs.count(VL[0]))
5388     VecTy = FixedVectorType::get(
5389         IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
5390   unsigned EntryVF = E->getVectorFactor();
5391   auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF);
5392 
5393   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
5394   // FIXME: it tries to fix a problem with MSVC buildbots.
5395   TargetTransformInfo &TTIRef = *TTI;
5396   auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy,
5397                                VectorizedVals, E](InstructionCost &Cost) {
5398     DenseMap<Value *, int> ExtractVectorsTys;
5399     SmallPtrSet<Value *, 4> CheckedExtracts;
5400     for (auto *V : VL) {
5401       if (isa<UndefValue>(V))
5402         continue;
5403       // If all users of instruction are going to be vectorized and this
5404       // instruction itself is not going to be vectorized, consider this
5405       // instruction as dead and remove its cost from the final cost of the
5406       // vectorized tree.
5407       // Also, avoid adjusting the cost for extractelements with multiple uses
5408       // in different graph entries.
5409       const TreeEntry *VE = getTreeEntry(V);
5410       if (!CheckedExtracts.insert(V).second ||
5411           !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) ||
5412           (VE && VE != E))
5413         continue;
5414       auto *EE = cast<ExtractElementInst>(V);
5415       Optional<unsigned> EEIdx = getExtractIndex(EE);
5416       if (!EEIdx)
5417         continue;
5418       unsigned Idx = *EEIdx;
5419       if (TTIRef.getNumberOfParts(VecTy) !=
5420           TTIRef.getNumberOfParts(EE->getVectorOperandType())) {
5421         auto It =
5422             ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first;
5423         It->getSecond() = std::min<int>(It->second, Idx);
5424       }
5425       // Take credit for instruction that will become dead.
5426       if (EE->hasOneUse()) {
5427         Instruction *Ext = EE->user_back();
5428         if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5429             all_of(Ext->users(),
5430                    [](User *U) { return isa<GetElementPtrInst>(U); })) {
5431           // Use getExtractWithExtendCost() to calculate the cost of
5432           // extractelement/ext pair.
5433           Cost -=
5434               TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(),
5435                                               EE->getVectorOperandType(), Idx);
5436           // Add back the cost of s|zext which is subtracted separately.
5437           Cost += TTIRef.getCastInstrCost(
5438               Ext->getOpcode(), Ext->getType(), EE->getType(),
5439               TTI::getCastContextHint(Ext), CostKind, Ext);
5440           continue;
5441         }
5442       }
5443       Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement,
5444                                         EE->getVectorOperandType(), Idx);
5445     }
5446     // Add a cost for subvector extracts/inserts if required.
5447     for (const auto &Data : ExtractVectorsTys) {
5448       auto *EEVTy = cast<FixedVectorType>(Data.first->getType());
5449       unsigned NumElts = VecTy->getNumElements();
5450       if (Data.second % NumElts == 0)
5451         continue;
5452       if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) {
5453         unsigned Idx = (Data.second / NumElts) * NumElts;
5454         unsigned EENumElts = EEVTy->getNumElements();
5455         if (Idx + NumElts <= EENumElts) {
5456           Cost +=
5457               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5458                                     EEVTy, None, Idx, VecTy);
5459         } else {
5460           // Need to round up the subvector type vectorization factor to avoid a
5461           // crash in cost model functions. Make SubVT so that Idx + VF of SubVT
5462           // <= EENumElts.
5463           auto *SubVT =
5464               FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx);
5465           Cost +=
5466               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5467                                     EEVTy, None, Idx, SubVT);
5468         }
5469       } else {
5470         Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector,
5471                                       VecTy, None, 0, EEVTy);
5472       }
5473     }
5474   };
5475   if (E->State == TreeEntry::NeedToGather) {
5476     if (allConstant(VL))
5477       return 0;
5478     if (isa<InsertElementInst>(VL[0]))
5479       return InstructionCost::getInvalid();
5480     SmallVector<int> Mask;
5481     SmallVector<const TreeEntry *> Entries;
5482     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
5483         isGatherShuffledEntry(E, Mask, Entries);
5484     if (Shuffle.hasValue()) {
5485       InstructionCost GatherCost = 0;
5486       if (ShuffleVectorInst::isIdentityMask(Mask)) {
5487         // Perfect match in the graph, will reuse the previously vectorized
5488         // node. Cost is 0.
5489         LLVM_DEBUG(
5490             dbgs()
5491             << "SLP: perfect diamond match for gather bundle that starts with "
5492             << *VL.front() << ".\n");
5493         if (NeedToShuffleReuses)
5494           GatherCost =
5495               TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5496                                   FinalVecTy, E->ReuseShuffleIndices);
5497       } else {
5498         LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size()
5499                           << " entries for bundle that starts with "
5500                           << *VL.front() << ".\n");
5501         // Detected that instead of gather we can emit a shuffle of single/two
5502         // previously vectorized nodes. Add the cost of the permutation rather
5503         // than gather.
5504         ::addMask(Mask, E->ReuseShuffleIndices);
5505         GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask);
5506       }
5507       return GatherCost;
5508     }
5509     if ((E->getOpcode() == Instruction::ExtractElement ||
5510          all_of(E->Scalars,
5511                 [](Value *V) {
5512                   return isa<ExtractElementInst, UndefValue>(V);
5513                 })) &&
5514         allSameType(VL)) {
5515       // Check that gather of extractelements can be represented as just a
5516       // shuffle of a single/two vectors the scalars are extracted from.
5517       SmallVector<int> Mask;
5518       Optional<TargetTransformInfo::ShuffleKind> ShuffleKind =
5519           isFixedVectorShuffle(VL, Mask);
5520       if (ShuffleKind.hasValue()) {
5521         // Found the bunch of extractelement instructions that must be gathered
5522         // into a vector and can be represented as a permutation elements in a
5523         // single input vector or of 2 input vectors.
5524         InstructionCost Cost =
5525             computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI);
5526         AdjustExtractsCost(Cost);
5527         if (NeedToShuffleReuses)
5528           Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5529                                       FinalVecTy, E->ReuseShuffleIndices);
5530         return Cost;
5531       }
5532     }
5533     if (isSplat(VL)) {
5534       // Found the broadcasting of the single scalar, calculate the cost as the
5535       // broadcast.
5536       assert(VecTy == FinalVecTy &&
5537              "No reused scalars expected for broadcast.");
5538       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy,
5539                                  /*Mask=*/None, /*Index=*/0,
5540                                  /*SubTp=*/nullptr, /*Args=*/VL[0]);
5541     }
5542     InstructionCost ReuseShuffleCost = 0;
5543     if (NeedToShuffleReuses)
5544       ReuseShuffleCost = TTI->getShuffleCost(
5545           TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices);
5546     // Improve gather cost for gather of loads, if we can group some of the
5547     // loads into vector loads.
5548     if (VL.size() > 2 && E->getOpcode() == Instruction::Load &&
5549         !E->isAltShuffle()) {
5550       BoUpSLP::ValueSet VectorizedLoads;
5551       unsigned StartIdx = 0;
5552       unsigned VF = VL.size() / 2;
5553       unsigned VectorizedCnt = 0;
5554       unsigned ScatterVectorizeCnt = 0;
5555       const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType());
5556       for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) {
5557         for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End;
5558              Cnt += VF) {
5559           ArrayRef<Value *> Slice = VL.slice(Cnt, VF);
5560           if (!VectorizedLoads.count(Slice.front()) &&
5561               !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) {
5562             SmallVector<Value *> PointerOps;
5563             OrdersType CurrentOrder;
5564             LoadsState LS = canVectorizeLoads(Slice, Slice.front(), *TTI, *DL,
5565                                               *SE, CurrentOrder, PointerOps);
5566             switch (LS) {
5567             case LoadsState::Vectorize:
5568             case LoadsState::ScatterVectorize:
5569               // Mark the vectorized loads so that we don't vectorize them
5570               // again.
5571               if (LS == LoadsState::Vectorize)
5572                 ++VectorizedCnt;
5573               else
5574                 ++ScatterVectorizeCnt;
5575               VectorizedLoads.insert(Slice.begin(), Slice.end());
5576               // If we vectorized initial block, no need to try to vectorize it
5577               // again.
5578               if (Cnt == StartIdx)
5579                 StartIdx += VF;
5580               break;
5581             case LoadsState::Gather:
5582               break;
5583             }
5584           }
5585         }
5586         // Check if the whole array was vectorized already - exit.
5587         if (StartIdx >= VL.size())
5588           break;
5589         // Found vectorizable parts - exit.
5590         if (!VectorizedLoads.empty())
5591           break;
5592       }
5593       if (!VectorizedLoads.empty()) {
5594         InstructionCost GatherCost = 0;
5595         unsigned NumParts = TTI->getNumberOfParts(VecTy);
5596         bool NeedInsertSubvectorAnalysis =
5597             !NumParts || (VL.size() / VF) > NumParts;
5598         // Get the cost for gathered loads.
5599         for (unsigned I = 0, End = VL.size(); I < End; I += VF) {
5600           if (VectorizedLoads.contains(VL[I]))
5601             continue;
5602           GatherCost += getGatherCost(VL.slice(I, VF));
5603         }
5604         // The cost for vectorized loads.
5605         InstructionCost ScalarsCost = 0;
5606         for (Value *V : VectorizedLoads) {
5607           auto *LI = cast<LoadInst>(V);
5608           ScalarsCost += TTI->getMemoryOpCost(
5609               Instruction::Load, LI->getType(), LI->getAlign(),
5610               LI->getPointerAddressSpace(), CostKind, LI);
5611         }
5612         auto *LI = cast<LoadInst>(E->getMainOp());
5613         auto *LoadTy = FixedVectorType::get(LI->getType(), VF);
5614         Align Alignment = LI->getAlign();
5615         GatherCost +=
5616             VectorizedCnt *
5617             TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment,
5618                                  LI->getPointerAddressSpace(), CostKind, LI);
5619         GatherCost += ScatterVectorizeCnt *
5620                       TTI->getGatherScatterOpCost(
5621                           Instruction::Load, LoadTy, LI->getPointerOperand(),
5622                           /*VariableMask=*/false, Alignment, CostKind, LI);
5623         if (NeedInsertSubvectorAnalysis) {
5624           // Add the cost for the subvectors insert.
5625           for (int I = VF, E = VL.size(); I < E; I += VF)
5626             GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy,
5627                                               None, I, LoadTy);
5628         }
5629         return ReuseShuffleCost + GatherCost - ScalarsCost;
5630       }
5631     }
5632     return ReuseShuffleCost + getGatherCost(VL);
5633   }
5634   InstructionCost CommonCost = 0;
5635   SmallVector<int> Mask;
5636   if (!E->ReorderIndices.empty()) {
5637     SmallVector<int> NewMask;
5638     if (E->getOpcode() == Instruction::Store) {
5639       // For stores the order is actually a mask.
5640       NewMask.resize(E->ReorderIndices.size());
5641       copy(E->ReorderIndices, NewMask.begin());
5642     } else {
5643       inversePermutation(E->ReorderIndices, NewMask);
5644     }
5645     ::addMask(Mask, NewMask);
5646   }
5647   if (NeedToShuffleReuses)
5648     ::addMask(Mask, E->ReuseShuffleIndices);
5649   if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask))
5650     CommonCost =
5651         TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask);
5652   assert((E->State == TreeEntry::Vectorize ||
5653           E->State == TreeEntry::ScatterVectorize) &&
5654          "Unhandled state");
5655   assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
5656   Instruction *VL0 = E->getMainOp();
5657   unsigned ShuffleOrOp =
5658       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
5659   switch (ShuffleOrOp) {
5660     case Instruction::PHI:
5661       return 0;
5662 
5663     case Instruction::ExtractValue:
5664     case Instruction::ExtractElement: {
5665       // The common cost of removal ExtractElement/ExtractValue instructions +
5666       // the cost of shuffles, if required to resuffle the original vector.
5667       if (NeedToShuffleReuses) {
5668         unsigned Idx = 0;
5669         for (unsigned I : E->ReuseShuffleIndices) {
5670           if (ShuffleOrOp == Instruction::ExtractElement) {
5671             auto *EE = cast<ExtractElementInst>(VL[I]);
5672             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5673                                                   EE->getVectorOperandType(),
5674                                                   *getExtractIndex(EE));
5675           } else {
5676             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5677                                                   VecTy, Idx);
5678             ++Idx;
5679           }
5680         }
5681         Idx = EntryVF;
5682         for (Value *V : VL) {
5683           if (ShuffleOrOp == Instruction::ExtractElement) {
5684             auto *EE = cast<ExtractElementInst>(V);
5685             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5686                                                   EE->getVectorOperandType(),
5687                                                   *getExtractIndex(EE));
5688           } else {
5689             --Idx;
5690             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5691                                                   VecTy, Idx);
5692           }
5693         }
5694       }
5695       if (ShuffleOrOp == Instruction::ExtractValue) {
5696         for (unsigned I = 0, E = VL.size(); I < E; ++I) {
5697           auto *EI = cast<Instruction>(VL[I]);
5698           // Take credit for instruction that will become dead.
5699           if (EI->hasOneUse()) {
5700             Instruction *Ext = EI->user_back();
5701             if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5702                 all_of(Ext->users(),
5703                        [](User *U) { return isa<GetElementPtrInst>(U); })) {
5704               // Use getExtractWithExtendCost() to calculate the cost of
5705               // extractelement/ext pair.
5706               CommonCost -= TTI->getExtractWithExtendCost(
5707                   Ext->getOpcode(), Ext->getType(), VecTy, I);
5708               // Add back the cost of s|zext which is subtracted separately.
5709               CommonCost += TTI->getCastInstrCost(
5710                   Ext->getOpcode(), Ext->getType(), EI->getType(),
5711                   TTI::getCastContextHint(Ext), CostKind, Ext);
5712               continue;
5713             }
5714           }
5715           CommonCost -=
5716               TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I);
5717         }
5718       } else {
5719         AdjustExtractsCost(CommonCost);
5720       }
5721       return CommonCost;
5722     }
5723     case Instruction::InsertElement: {
5724       assert(E->ReuseShuffleIndices.empty() &&
5725              "Unique insertelements only are expected.");
5726       auto *SrcVecTy = cast<FixedVectorType>(VL0->getType());
5727 
5728       unsigned const NumElts = SrcVecTy->getNumElements();
5729       unsigned const NumScalars = VL.size();
5730       APInt DemandedElts = APInt::getZero(NumElts);
5731       // TODO: Add support for Instruction::InsertValue.
5732       SmallVector<int> Mask;
5733       if (!E->ReorderIndices.empty()) {
5734         inversePermutation(E->ReorderIndices, Mask);
5735         Mask.append(NumElts - NumScalars, UndefMaskElem);
5736       } else {
5737         Mask.assign(NumElts, UndefMaskElem);
5738         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
5739       }
5740       unsigned Offset = *getInsertIndex(VL0);
5741       bool IsIdentity = true;
5742       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
5743       Mask.swap(PrevMask);
5744       for (unsigned I = 0; I < NumScalars; ++I) {
5745         unsigned InsertIdx = *getInsertIndex(VL[PrevMask[I]]);
5746         DemandedElts.setBit(InsertIdx);
5747         IsIdentity &= InsertIdx - Offset == I;
5748         Mask[InsertIdx - Offset] = I;
5749       }
5750       assert(Offset < NumElts && "Failed to find vector index offset");
5751 
5752       InstructionCost Cost = 0;
5753       Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts,
5754                                             /*Insert*/ true, /*Extract*/ false);
5755 
5756       if (IsIdentity && NumElts != NumScalars && Offset % NumScalars != 0) {
5757         // FIXME: Replace with SK_InsertSubvector once it is properly supported.
5758         unsigned Sz = PowerOf2Ceil(Offset + NumScalars);
5759         Cost += TTI->getShuffleCost(
5760             TargetTransformInfo::SK_PermuteSingleSrc,
5761             FixedVectorType::get(SrcVecTy->getElementType(), Sz));
5762       } else if (!IsIdentity) {
5763         auto *FirstInsert =
5764             cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
5765               return !is_contained(E->Scalars,
5766                                    cast<Instruction>(V)->getOperand(0));
5767             }));
5768         if (isUndefVector(FirstInsert->getOperand(0))) {
5769           Cost += TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, SrcVecTy, Mask);
5770         } else {
5771           SmallVector<int> InsertMask(NumElts);
5772           std::iota(InsertMask.begin(), InsertMask.end(), 0);
5773           for (unsigned I = 0; I < NumElts; I++) {
5774             if (Mask[I] != UndefMaskElem)
5775               InsertMask[Offset + I] = NumElts + I;
5776           }
5777           Cost +=
5778               TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVecTy, InsertMask);
5779         }
5780       }
5781 
5782       return Cost;
5783     }
5784     case Instruction::ZExt:
5785     case Instruction::SExt:
5786     case Instruction::FPToUI:
5787     case Instruction::FPToSI:
5788     case Instruction::FPExt:
5789     case Instruction::PtrToInt:
5790     case Instruction::IntToPtr:
5791     case Instruction::SIToFP:
5792     case Instruction::UIToFP:
5793     case Instruction::Trunc:
5794     case Instruction::FPTrunc:
5795     case Instruction::BitCast: {
5796       Type *SrcTy = VL0->getOperand(0)->getType();
5797       InstructionCost ScalarEltCost =
5798           TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy,
5799                                 TTI::getCastContextHint(VL0), CostKind, VL0);
5800       if (NeedToShuffleReuses) {
5801         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5802       }
5803 
5804       // Calculate the cost of this instruction.
5805       InstructionCost ScalarCost = VL.size() * ScalarEltCost;
5806 
5807       auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size());
5808       InstructionCost VecCost = 0;
5809       // Check if the values are candidates to demote.
5810       if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
5811         VecCost = CommonCost + TTI->getCastInstrCost(
5812                                    E->getOpcode(), VecTy, SrcVecTy,
5813                                    TTI::getCastContextHint(VL0), CostKind, VL0);
5814       }
5815       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5816       return VecCost - ScalarCost;
5817     }
5818     case Instruction::FCmp:
5819     case Instruction::ICmp:
5820     case Instruction::Select: {
5821       // Calculate the cost of this instruction.
5822       InstructionCost ScalarEltCost =
5823           TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5824                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0);
5825       if (NeedToShuffleReuses) {
5826         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5827       }
5828       auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size());
5829       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5830 
5831       // Check if all entries in VL are either compares or selects with compares
5832       // as condition that have the same predicates.
5833       CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE;
5834       bool First = true;
5835       for (auto *V : VL) {
5836         CmpInst::Predicate CurrentPred;
5837         auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value());
5838         if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) &&
5839              !match(V, MatchCmp)) ||
5840             (!First && VecPred != CurrentPred)) {
5841           VecPred = CmpInst::BAD_ICMP_PREDICATE;
5842           break;
5843         }
5844         First = false;
5845         VecPred = CurrentPred;
5846       }
5847 
5848       InstructionCost VecCost = TTI->getCmpSelInstrCost(
5849           E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0);
5850       // Check if it is possible and profitable to use min/max for selects in
5851       // VL.
5852       //
5853       auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL);
5854       if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) {
5855         IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy,
5856                                           {VecTy, VecTy});
5857         InstructionCost IntrinsicCost =
5858             TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5859         // If the selects are the only uses of the compares, they will be dead
5860         // and we can adjust the cost by removing their cost.
5861         if (IntrinsicAndUse.second)
5862           IntrinsicCost -= TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy,
5863                                                    MaskTy, VecPred, CostKind);
5864         VecCost = std::min(VecCost, IntrinsicCost);
5865       }
5866       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5867       return CommonCost + VecCost - ScalarCost;
5868     }
5869     case Instruction::FNeg:
5870     case Instruction::Add:
5871     case Instruction::FAdd:
5872     case Instruction::Sub:
5873     case Instruction::FSub:
5874     case Instruction::Mul:
5875     case Instruction::FMul:
5876     case Instruction::UDiv:
5877     case Instruction::SDiv:
5878     case Instruction::FDiv:
5879     case Instruction::URem:
5880     case Instruction::SRem:
5881     case Instruction::FRem:
5882     case Instruction::Shl:
5883     case Instruction::LShr:
5884     case Instruction::AShr:
5885     case Instruction::And:
5886     case Instruction::Or:
5887     case Instruction::Xor: {
5888       // Certain instructions can be cheaper to vectorize if they have a
5889       // constant second vector operand.
5890       TargetTransformInfo::OperandValueKind Op1VK =
5891           TargetTransformInfo::OK_AnyValue;
5892       TargetTransformInfo::OperandValueKind Op2VK =
5893           TargetTransformInfo::OK_UniformConstantValue;
5894       TargetTransformInfo::OperandValueProperties Op1VP =
5895           TargetTransformInfo::OP_None;
5896       TargetTransformInfo::OperandValueProperties Op2VP =
5897           TargetTransformInfo::OP_PowerOf2;
5898 
5899       // If all operands are exactly the same ConstantInt then set the
5900       // operand kind to OK_UniformConstantValue.
5901       // If instead not all operands are constants, then set the operand kind
5902       // to OK_AnyValue. If all operands are constants but not the same,
5903       // then set the operand kind to OK_NonUniformConstantValue.
5904       ConstantInt *CInt0 = nullptr;
5905       for (unsigned i = 0, e = VL.size(); i < e; ++i) {
5906         const Instruction *I = cast<Instruction>(VL[i]);
5907         unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0;
5908         ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx));
5909         if (!CInt) {
5910           Op2VK = TargetTransformInfo::OK_AnyValue;
5911           Op2VP = TargetTransformInfo::OP_None;
5912           break;
5913         }
5914         if (Op2VP == TargetTransformInfo::OP_PowerOf2 &&
5915             !CInt->getValue().isPowerOf2())
5916           Op2VP = TargetTransformInfo::OP_None;
5917         if (i == 0) {
5918           CInt0 = CInt;
5919           continue;
5920         }
5921         if (CInt0 != CInt)
5922           Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5923       }
5924 
5925       SmallVector<const Value *, 4> Operands(VL0->operand_values());
5926       InstructionCost ScalarEltCost =
5927           TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK,
5928                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5929       if (NeedToShuffleReuses) {
5930         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5931       }
5932       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5933       InstructionCost VecCost =
5934           TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK,
5935                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5936       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5937       return CommonCost + VecCost - ScalarCost;
5938     }
5939     case Instruction::GetElementPtr: {
5940       TargetTransformInfo::OperandValueKind Op1VK =
5941           TargetTransformInfo::OK_AnyValue;
5942       TargetTransformInfo::OperandValueKind Op2VK =
5943           TargetTransformInfo::OK_UniformConstantValue;
5944 
5945       InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost(
5946           Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK);
5947       if (NeedToShuffleReuses) {
5948         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5949       }
5950       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5951       InstructionCost VecCost = TTI->getArithmeticInstrCost(
5952           Instruction::Add, VecTy, CostKind, Op1VK, Op2VK);
5953       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5954       return CommonCost + VecCost - ScalarCost;
5955     }
5956     case Instruction::Load: {
5957       // Cost of wide load - cost of scalar loads.
5958       Align Alignment = cast<LoadInst>(VL0)->getAlign();
5959       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5960           Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0);
5961       if (NeedToShuffleReuses) {
5962         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5963       }
5964       InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost;
5965       InstructionCost VecLdCost;
5966       if (E->State == TreeEntry::Vectorize) {
5967         VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0,
5968                                          CostKind, VL0);
5969       } else {
5970         assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState");
5971         Align CommonAlignment = Alignment;
5972         for (Value *V : VL)
5973           CommonAlignment =
5974               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
5975         VecLdCost = TTI->getGatherScatterOpCost(
5976             Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(),
5977             /*VariableMask=*/false, CommonAlignment, CostKind, VL0);
5978       }
5979       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost));
5980       return CommonCost + VecLdCost - ScalarLdCost;
5981     }
5982     case Instruction::Store: {
5983       // We know that we can merge the stores. Calculate the cost.
5984       bool IsReorder = !E->ReorderIndices.empty();
5985       auto *SI =
5986           cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0);
5987       Align Alignment = SI->getAlign();
5988       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5989           Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0);
5990       InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost;
5991       InstructionCost VecStCost = TTI->getMemoryOpCost(
5992           Instruction::Store, VecTy, Alignment, 0, CostKind, VL0);
5993       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost));
5994       return CommonCost + VecStCost - ScalarStCost;
5995     }
5996     case Instruction::Call: {
5997       CallInst *CI = cast<CallInst>(VL0);
5998       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5999 
6000       // Calculate the cost of the scalar and vector calls.
6001       IntrinsicCostAttributes CostAttrs(ID, *CI, 1);
6002       InstructionCost ScalarEltCost =
6003           TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
6004       if (NeedToShuffleReuses) {
6005         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
6006       }
6007       InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
6008 
6009       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
6010       InstructionCost VecCallCost =
6011           std::min(VecCallCosts.first, VecCallCosts.second);
6012 
6013       LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
6014                         << " (" << VecCallCost << "-" << ScalarCallCost << ")"
6015                         << " for " << *CI << "\n");
6016 
6017       return CommonCost + VecCallCost - ScalarCallCost;
6018     }
6019     case Instruction::ShuffleVector: {
6020       assert(E->isAltShuffle() &&
6021              ((Instruction::isBinaryOp(E->getOpcode()) &&
6022                Instruction::isBinaryOp(E->getAltOpcode())) ||
6023               (Instruction::isCast(E->getOpcode()) &&
6024                Instruction::isCast(E->getAltOpcode())) ||
6025               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
6026              "Invalid Shuffle Vector Operand");
6027       InstructionCost ScalarCost = 0;
6028       if (NeedToShuffleReuses) {
6029         for (unsigned Idx : E->ReuseShuffleIndices) {
6030           Instruction *I = cast<Instruction>(VL[Idx]);
6031           CommonCost -= TTI->getInstructionCost(I, CostKind);
6032         }
6033         for (Value *V : VL) {
6034           Instruction *I = cast<Instruction>(V);
6035           CommonCost += TTI->getInstructionCost(I, CostKind);
6036         }
6037       }
6038       for (Value *V : VL) {
6039         Instruction *I = cast<Instruction>(V);
6040         assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
6041         ScalarCost += TTI->getInstructionCost(I, CostKind);
6042       }
6043       // VecCost is equal to sum of the cost of creating 2 vectors
6044       // and the cost of creating shuffle.
6045       InstructionCost VecCost = 0;
6046       // Try to find the previous shuffle node with the same operands and same
6047       // main/alternate ops.
6048       auto &&TryFindNodeWithEqualOperands = [this, E]() {
6049         for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
6050           if (TE.get() == E)
6051             break;
6052           if (TE->isAltShuffle() &&
6053               ((TE->getOpcode() == E->getOpcode() &&
6054                 TE->getAltOpcode() == E->getAltOpcode()) ||
6055                (TE->getOpcode() == E->getAltOpcode() &&
6056                 TE->getAltOpcode() == E->getOpcode())) &&
6057               TE->hasEqualOperands(*E))
6058             return true;
6059         }
6060         return false;
6061       };
6062       if (TryFindNodeWithEqualOperands()) {
6063         LLVM_DEBUG({
6064           dbgs() << "SLP: diamond match for alternate node found.\n";
6065           E->dump();
6066         });
6067         // No need to add new vector costs here since we're going to reuse
6068         // same main/alternate vector ops, just do different shuffling.
6069       } else if (Instruction::isBinaryOp(E->getOpcode())) {
6070         VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind);
6071         VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy,
6072                                                CostKind);
6073       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
6074         VecCost = TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy,
6075                                           Builder.getInt1Ty(),
6076                                           CI0->getPredicate(), CostKind, VL0);
6077         VecCost += TTI->getCmpSelInstrCost(
6078             E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
6079             cast<CmpInst>(E->getAltOp())->getPredicate(), CostKind,
6080             E->getAltOp());
6081       } else {
6082         Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
6083         Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
6084         auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size());
6085         auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size());
6086         VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty,
6087                                         TTI::CastContextHint::None, CostKind);
6088         VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty,
6089                                          TTI::CastContextHint::None, CostKind);
6090       }
6091 
6092       if (E->ReuseShuffleIndices.empty()) {
6093         CommonCost =
6094             TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy);
6095       } else {
6096         SmallVector<int> Mask;
6097         buildShuffleEntryMask(
6098             E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
6099             [E](Instruction *I) {
6100               assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
6101               return I->getOpcode() == E->getAltOpcode();
6102             },
6103             Mask);
6104         CommonCost = TTI->getShuffleCost(TargetTransformInfo::SK_PermuteTwoSrc,
6105                                          FinalVecTy, Mask);
6106       }
6107       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
6108       return CommonCost + VecCost - ScalarCost;
6109     }
6110     default:
6111       llvm_unreachable("Unknown instruction");
6112   }
6113 }
6114 
6115 bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const {
6116   LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
6117                     << VectorizableTree.size() << " is fully vectorizable .\n");
6118 
6119   auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) {
6120     SmallVector<int> Mask;
6121     return TE->State == TreeEntry::NeedToGather &&
6122            !any_of(TE->Scalars,
6123                    [this](Value *V) { return EphValues.contains(V); }) &&
6124            (allConstant(TE->Scalars) || isSplat(TE->Scalars) ||
6125             TE->Scalars.size() < Limit ||
6126             ((TE->getOpcode() == Instruction::ExtractElement ||
6127               all_of(TE->Scalars,
6128                      [](Value *V) {
6129                        return isa<ExtractElementInst, UndefValue>(V);
6130                      })) &&
6131              isFixedVectorShuffle(TE->Scalars, Mask)) ||
6132             (TE->State == TreeEntry::NeedToGather &&
6133              TE->getOpcode() == Instruction::Load && !TE->isAltShuffle()));
6134   };
6135 
6136   // We only handle trees of heights 1 and 2.
6137   if (VectorizableTree.size() == 1 &&
6138       (VectorizableTree[0]->State == TreeEntry::Vectorize ||
6139        (ForReduction &&
6140         AreVectorizableGathers(VectorizableTree[0].get(),
6141                                VectorizableTree[0]->Scalars.size()) &&
6142         VectorizableTree[0]->getVectorFactor() > 2)))
6143     return true;
6144 
6145   if (VectorizableTree.size() != 2)
6146     return false;
6147 
6148   // Handle splat and all-constants stores. Also try to vectorize tiny trees
6149   // with the second gather nodes if they have less scalar operands rather than
6150   // the initial tree element (may be profitable to shuffle the second gather)
6151   // or they are extractelements, which form shuffle.
6152   SmallVector<int> Mask;
6153   if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
6154       AreVectorizableGathers(VectorizableTree[1].get(),
6155                              VectorizableTree[0]->Scalars.size()))
6156     return true;
6157 
6158   // Gathering cost would be too much for tiny trees.
6159   if (VectorizableTree[0]->State == TreeEntry::NeedToGather ||
6160       (VectorizableTree[1]->State == TreeEntry::NeedToGather &&
6161        VectorizableTree[0]->State != TreeEntry::ScatterVectorize))
6162     return false;
6163 
6164   return true;
6165 }
6166 
6167 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts,
6168                                        TargetTransformInfo *TTI,
6169                                        bool MustMatchOrInst) {
6170   // Look past the root to find a source value. Arbitrarily follow the
6171   // path through operand 0 of any 'or'. Also, peek through optional
6172   // shift-left-by-multiple-of-8-bits.
6173   Value *ZextLoad = Root;
6174   const APInt *ShAmtC;
6175   bool FoundOr = false;
6176   while (!isa<ConstantExpr>(ZextLoad) &&
6177          (match(ZextLoad, m_Or(m_Value(), m_Value())) ||
6178           (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) &&
6179            ShAmtC->urem(8) == 0))) {
6180     auto *BinOp = cast<BinaryOperator>(ZextLoad);
6181     ZextLoad = BinOp->getOperand(0);
6182     if (BinOp->getOpcode() == Instruction::Or)
6183       FoundOr = true;
6184   }
6185   // Check if the input is an extended load of the required or/shift expression.
6186   Value *Load;
6187   if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root ||
6188       !match(ZextLoad, m_ZExt(m_Value(Load))) || !isa<LoadInst>(Load))
6189     return false;
6190 
6191   // Require that the total load bit width is a legal integer type.
6192   // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
6193   // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
6194   Type *SrcTy = Load->getType();
6195   unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts;
6196   if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth)))
6197     return false;
6198 
6199   // Everything matched - assume that we can fold the whole sequence using
6200   // load combining.
6201   LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "
6202              << *(cast<Instruction>(Root)) << "\n");
6203 
6204   return true;
6205 }
6206 
6207 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const {
6208   if (RdxKind != RecurKind::Or)
6209     return false;
6210 
6211   unsigned NumElts = VectorizableTree[0]->Scalars.size();
6212   Value *FirstReduced = VectorizableTree[0]->Scalars[0];
6213   return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI,
6214                                     /* MatchOr */ false);
6215 }
6216 
6217 bool BoUpSLP::isLoadCombineCandidate() const {
6218   // Peek through a final sequence of stores and check if all operations are
6219   // likely to be load-combined.
6220   unsigned NumElts = VectorizableTree[0]->Scalars.size();
6221   for (Value *Scalar : VectorizableTree[0]->Scalars) {
6222     Value *X;
6223     if (!match(Scalar, m_Store(m_Value(X), m_Value())) ||
6224         !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true))
6225       return false;
6226   }
6227   return true;
6228 }
6229 
6230 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const {
6231   // No need to vectorize inserts of gathered values.
6232   if (VectorizableTree.size() == 2 &&
6233       isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) &&
6234       VectorizableTree[1]->State == TreeEntry::NeedToGather)
6235     return true;
6236 
6237   // We can vectorize the tree if its size is greater than or equal to the
6238   // minimum size specified by the MinTreeSize command line option.
6239   if (VectorizableTree.size() >= MinTreeSize)
6240     return false;
6241 
6242   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
6243   // can vectorize it if we can prove it fully vectorizable.
6244   if (isFullyVectorizableTinyTree(ForReduction))
6245     return false;
6246 
6247   assert(VectorizableTree.empty()
6248              ? ExternalUses.empty()
6249              : true && "We shouldn't have any external users");
6250 
6251   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
6252   // vectorizable.
6253   return true;
6254 }
6255 
6256 InstructionCost BoUpSLP::getSpillCost() const {
6257   // Walk from the bottom of the tree to the top, tracking which values are
6258   // live. When we see a call instruction that is not part of our tree,
6259   // query TTI to see if there is a cost to keeping values live over it
6260   // (for example, if spills and fills are required).
6261   unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
6262   InstructionCost Cost = 0;
6263 
6264   SmallPtrSet<Instruction*, 4> LiveValues;
6265   Instruction *PrevInst = nullptr;
6266 
6267   // The entries in VectorizableTree are not necessarily ordered by their
6268   // position in basic blocks. Collect them and order them by dominance so later
6269   // instructions are guaranteed to be visited first. For instructions in
6270   // different basic blocks, we only scan to the beginning of the block, so
6271   // their order does not matter, as long as all instructions in a basic block
6272   // are grouped together. Using dominance ensures a deterministic order.
6273   SmallVector<Instruction *, 16> OrderedScalars;
6274   for (const auto &TEPtr : VectorizableTree) {
6275     Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
6276     if (!Inst)
6277       continue;
6278     OrderedScalars.push_back(Inst);
6279   }
6280   llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) {
6281     auto *NodeA = DT->getNode(A->getParent());
6282     auto *NodeB = DT->getNode(B->getParent());
6283     assert(NodeA && "Should only process reachable instructions");
6284     assert(NodeB && "Should only process reachable instructions");
6285     assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
6286            "Different nodes should have different DFS numbers");
6287     if (NodeA != NodeB)
6288       return NodeA->getDFSNumIn() < NodeB->getDFSNumIn();
6289     return B->comesBefore(A);
6290   });
6291 
6292   for (Instruction *Inst : OrderedScalars) {
6293     if (!PrevInst) {
6294       PrevInst = Inst;
6295       continue;
6296     }
6297 
6298     // Update LiveValues.
6299     LiveValues.erase(PrevInst);
6300     for (auto &J : PrevInst->operands()) {
6301       if (isa<Instruction>(&*J) && getTreeEntry(&*J))
6302         LiveValues.insert(cast<Instruction>(&*J));
6303     }
6304 
6305     LLVM_DEBUG({
6306       dbgs() << "SLP: #LV: " << LiveValues.size();
6307       for (auto *X : LiveValues)
6308         dbgs() << " " << X->getName();
6309       dbgs() << ", Looking at ";
6310       Inst->dump();
6311     });
6312 
6313     // Now find the sequence of instructions between PrevInst and Inst.
6314     unsigned NumCalls = 0;
6315     BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
6316                                  PrevInstIt =
6317                                      PrevInst->getIterator().getReverse();
6318     while (InstIt != PrevInstIt) {
6319       if (PrevInstIt == PrevInst->getParent()->rend()) {
6320         PrevInstIt = Inst->getParent()->rbegin();
6321         continue;
6322       }
6323 
6324       // Debug information does not impact spill cost.
6325       if ((isa<CallInst>(&*PrevInstIt) &&
6326            !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
6327           &*PrevInstIt != PrevInst)
6328         NumCalls++;
6329 
6330       ++PrevInstIt;
6331     }
6332 
6333     if (NumCalls) {
6334       SmallVector<Type*, 4> V;
6335       for (auto *II : LiveValues) {
6336         auto *ScalarTy = II->getType();
6337         if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy))
6338           ScalarTy = VectorTy->getElementType();
6339         V.push_back(FixedVectorType::get(ScalarTy, BundleWidth));
6340       }
6341       Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
6342     }
6343 
6344     PrevInst = Inst;
6345   }
6346 
6347   return Cost;
6348 }
6349 
6350 /// Check if two insertelement instructions are from the same buildvector.
6351 static bool areTwoInsertFromSameBuildVector(InsertElementInst *VU,
6352                                             InsertElementInst *V) {
6353   // Instructions must be from the same basic blocks.
6354   if (VU->getParent() != V->getParent())
6355     return false;
6356   // Checks if 2 insertelements are from the same buildvector.
6357   if (VU->getType() != V->getType())
6358     return false;
6359   // Multiple used inserts are separate nodes.
6360   if (!VU->hasOneUse() && !V->hasOneUse())
6361     return false;
6362   auto *IE1 = VU;
6363   auto *IE2 = V;
6364   // Go through the vector operand of insertelement instructions trying to find
6365   // either VU as the original vector for IE2 or V as the original vector for
6366   // IE1.
6367   do {
6368     if (IE2 == VU || IE1 == V)
6369       return true;
6370     if (IE1) {
6371       if (IE1 != VU && !IE1->hasOneUse())
6372         IE1 = nullptr;
6373       else
6374         IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0));
6375     }
6376     if (IE2) {
6377       if (IE2 != V && !IE2->hasOneUse())
6378         IE2 = nullptr;
6379       else
6380         IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0));
6381     }
6382   } while (IE1 || IE2);
6383   return false;
6384 }
6385 
6386 /// Checks if the \p IE1 instructions is followed by \p IE2 instruction in the
6387 /// buildvector sequence.
6388 static bool isFirstInsertElement(const InsertElementInst *IE1,
6389                                  const InsertElementInst *IE2) {
6390   const auto *I1 = IE1;
6391   const auto *I2 = IE2;
6392   do {
6393     if (I2 == IE1)
6394       return true;
6395     if (I1 == IE2)
6396       return false;
6397     if (I1)
6398       I1 = dyn_cast<InsertElementInst>(I1->getOperand(0));
6399     if (I2)
6400       I2 = dyn_cast<InsertElementInst>(I2->getOperand(0));
6401   } while (I1 || I2);
6402   llvm_unreachable("Two different buildvectors not expected.");
6403 }
6404 
6405 /// Does the analysis of the provided shuffle masks and performs the requested
6406 /// actions on the vectors with the given shuffle masks. It tries to do it in
6407 /// several steps.
6408 /// 1. If the Base vector is not undef vector, resizing the very first mask to
6409 /// have common VF and perform action for 2 input vectors (including non-undef
6410 /// Base). Other shuffle masks are combined with the resulting after the 1 stage
6411 /// and processed as a shuffle of 2 elements.
6412 /// 2. If the Base is undef vector and have only 1 shuffle mask, perform the
6413 /// action only for 1 vector with the given mask, if it is not the identity
6414 /// mask.
6415 /// 3. If > 2 masks are used, perform the remaining shuffle actions for 2
6416 /// vectors, combing the masks properly between the steps.
6417 template <typename T>
6418 static T *performExtractsShuffleAction(
6419     MutableArrayRef<std::pair<T *, SmallVector<int>>> ShuffleMask, Value *Base,
6420     function_ref<unsigned(T *)> GetVF,
6421     function_ref<std::pair<T *, bool>(T *, ArrayRef<int>)> ResizeAction,
6422     function_ref<T *(ArrayRef<int>, ArrayRef<T *>)> Action) {
6423   assert(!ShuffleMask.empty() && "Empty list of shuffles for inserts.");
6424   SmallVector<int> Mask(ShuffleMask.begin()->second);
6425   auto VMIt = std::next(ShuffleMask.begin());
6426   T *Prev = nullptr;
6427   bool IsBaseNotUndef = !isUndefVector(Base);
6428   if (IsBaseNotUndef) {
6429     // Base is not undef, need to combine it with the next subvectors.
6430     std::pair<T *, bool> Res = ResizeAction(ShuffleMask.begin()->first, Mask);
6431     for (unsigned Idx = 0, VF = Mask.size(); Idx < VF; ++Idx) {
6432       if (Mask[Idx] == UndefMaskElem)
6433         Mask[Idx] = Idx;
6434       else
6435         Mask[Idx] = (Res.second ? Idx : Mask[Idx]) + VF;
6436     }
6437     Prev = Action(Mask, {nullptr, Res.first});
6438   } else if (ShuffleMask.size() == 1) {
6439     // Base is undef and only 1 vector is shuffled - perform the action only for
6440     // single vector, if the mask is not the identity mask.
6441     std::pair<T *, bool> Res = ResizeAction(ShuffleMask.begin()->first, Mask);
6442     if (Res.second)
6443       // Identity mask is found.
6444       Prev = Res.first;
6445     else
6446       Prev = Action(Mask, {ShuffleMask.begin()->first});
6447   } else {
6448     // Base is undef and at least 2 input vectors shuffled - perform 2 vectors
6449     // shuffles step by step, combining shuffle between the steps.
6450     unsigned Vec1VF = GetVF(ShuffleMask.begin()->first);
6451     unsigned Vec2VF = GetVF(VMIt->first);
6452     if (Vec1VF == Vec2VF) {
6453       // No need to resize the input vectors since they are of the same size, we
6454       // can shuffle them directly.
6455       ArrayRef<int> SecMask = VMIt->second;
6456       for (unsigned I = 0, VF = Mask.size(); I < VF; ++I) {
6457         if (SecMask[I] != UndefMaskElem) {
6458           assert(Mask[I] == UndefMaskElem && "Multiple uses of scalars.");
6459           Mask[I] = SecMask[I] + Vec1VF;
6460         }
6461       }
6462       Prev = Action(Mask, {ShuffleMask.begin()->first, VMIt->first});
6463     } else {
6464       // Vectors of different sizes - resize and reshuffle.
6465       std::pair<T *, bool> Res1 =
6466           ResizeAction(ShuffleMask.begin()->first, Mask);
6467       std::pair<T *, bool> Res2 = ResizeAction(VMIt->first, VMIt->second);
6468       ArrayRef<int> SecMask = VMIt->second;
6469       for (unsigned I = 0, VF = Mask.size(); I < VF; ++I) {
6470         if (Mask[I] != UndefMaskElem) {
6471           assert(SecMask[I] == UndefMaskElem && "Multiple uses of scalars.");
6472           if (Res1.second)
6473             Mask[I] = I;
6474         } else if (SecMask[I] != UndefMaskElem) {
6475           assert(Mask[I] == UndefMaskElem && "Multiple uses of scalars.");
6476           Mask[I] = (Res2.second ? I : SecMask[I]) + VF;
6477         }
6478       }
6479       Prev = Action(Mask, {Res1.first, Res2.first});
6480     }
6481     VMIt = std::next(VMIt);
6482   }
6483   // Perform requested actions for the remaining masks/vectors.
6484   for (auto E = ShuffleMask.end(); VMIt != E; ++VMIt) {
6485     // Shuffle other input vectors, if any.
6486     std::pair<T *, bool> Res = ResizeAction(VMIt->first, VMIt->second);
6487     ArrayRef<int> SecMask = VMIt->second;
6488     for (unsigned I = 0, VF = Mask.size(); I < VF; ++I) {
6489       if (SecMask[I] != UndefMaskElem) {
6490         assert((Mask[I] == UndefMaskElem || IsBaseNotUndef) &&
6491                "Multiple uses of scalars.");
6492         Mask[I] = (Res.second ? I : SecMask[I]) + VF;
6493       } else if (Mask[I] != UndefMaskElem) {
6494         Mask[I] = I;
6495       }
6496     }
6497     Prev = Action(Mask, {Prev, Res.first});
6498   }
6499   return Prev;
6500 }
6501 
6502 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) {
6503   InstructionCost Cost = 0;
6504   LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
6505                     << VectorizableTree.size() << ".\n");
6506 
6507   unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
6508 
6509   for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
6510     TreeEntry &TE = *VectorizableTree[I];
6511 
6512     InstructionCost C = getEntryCost(&TE, VectorizedVals);
6513     Cost += C;
6514     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6515                       << " for bundle that starts with " << *TE.Scalars[0]
6516                       << ".\n"
6517                       << "SLP: Current total cost = " << Cost << "\n");
6518   }
6519 
6520   SmallPtrSet<Value *, 16> ExtractCostCalculated;
6521   InstructionCost ExtractCost = 0;
6522   SmallVector<MapVector<const TreeEntry *, SmallVector<int>>> ShuffleMasks;
6523   SmallVector<std::pair<Value *, const TreeEntry *>> FirstUsers;
6524   SmallVector<APInt> DemandedElts;
6525   for (ExternalUser &EU : ExternalUses) {
6526     // We only add extract cost once for the same scalar.
6527     if (!isa_and_nonnull<InsertElementInst>(EU.User) &&
6528         !ExtractCostCalculated.insert(EU.Scalar).second)
6529       continue;
6530 
6531     // Uses by ephemeral values are free (because the ephemeral value will be
6532     // removed prior to code generation, and so the extraction will be
6533     // removed as well).
6534     if (EphValues.count(EU.User))
6535       continue;
6536 
6537     // No extract cost for vector "scalar"
6538     if (isa<FixedVectorType>(EU.Scalar->getType()))
6539       continue;
6540 
6541     // Already counted the cost for external uses when tried to adjust the cost
6542     // for extractelements, no need to add it again.
6543     if (isa<ExtractElementInst>(EU.Scalar))
6544       continue;
6545 
6546     // If found user is an insertelement, do not calculate extract cost but try
6547     // to detect it as a final shuffled/identity match.
6548     if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) {
6549       if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) {
6550         Optional<unsigned> InsertIdx = getInsertIndex(VU);
6551         if (InsertIdx) {
6552           const TreeEntry *ScalarTE = getTreeEntry(EU.Scalar);
6553           auto *It =
6554               find_if(FirstUsers,
6555                       [VU](const std::pair<Value *, const TreeEntry *> &Pair) {
6556                         return areTwoInsertFromSameBuildVector(
6557                             VU, cast<InsertElementInst>(Pair.first));
6558                       });
6559           int VecId = -1;
6560           if (It == FirstUsers.end()) {
6561             (void)ShuffleMasks.emplace_back();
6562             // Find the insertvector, vectorized in tree, if any.
6563             Value *Base = VU;
6564             while (auto *IEBase = dyn_cast<InsertElementInst>(Base)) {
6565               // Build the mask for the vectorized insertelement instructions.
6566               if (const TreeEntry *E = getTreeEntry(IEBase)) {
6567                 VU = IEBase;
6568                 do {
6569                   int Idx = E->findLaneForValue(Base);
6570                   SmallVectorImpl<int> &Mask = ShuffleMasks.back()[ScalarTE];
6571                   if (Mask.empty())
6572                     Mask.assign(FTy->getNumElements(), UndefMaskElem);
6573                   Mask[Idx] = Idx;
6574                   Base = cast<InsertElementInst>(Base)->getOperand(0);
6575                 } while (E == getTreeEntry(Base));
6576                 break;
6577               }
6578               Base = cast<InsertElementInst>(Base)->getOperand(0);
6579             }
6580             FirstUsers.emplace_back(VU, ScalarTE);
6581             DemandedElts.push_back(APInt::getZero(FTy->getNumElements()));
6582             VecId = FirstUsers.size() - 1;
6583           } else {
6584             if (isFirstInsertElement(VU, cast<InsertElementInst>(It->first)))
6585               It->first = VU;
6586             VecId = std::distance(FirstUsers.begin(), It);
6587           }
6588           int InIdx = *InsertIdx;
6589           SmallVectorImpl<int> &Mask = ShuffleMasks[VecId][ScalarTE];
6590           if (Mask.empty())
6591             Mask.assign(FTy->getNumElements(), UndefMaskElem);
6592           assert(Mask[InIdx] == UndefMaskElem &&
6593                  "InsertElementInstruction used already.");
6594           Mask[InIdx] = EU.Lane;
6595           DemandedElts[VecId].setBit(InIdx);
6596           continue;
6597         }
6598       }
6599     }
6600 
6601     // If we plan to rewrite the tree in a smaller type, we will need to sign
6602     // extend the extracted value back to the original type. Here, we account
6603     // for the extract and the added cost of the sign extend if needed.
6604     auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth);
6605     auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
6606     if (MinBWs.count(ScalarRoot)) {
6607       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
6608       auto Extend =
6609           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
6610       VecTy = FixedVectorType::get(MinTy, BundleWidth);
6611       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
6612                                                    VecTy, EU.Lane);
6613     } else {
6614       ExtractCost +=
6615           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
6616     }
6617   }
6618 
6619   InstructionCost SpillCost = getSpillCost();
6620   Cost += SpillCost + ExtractCost;
6621   auto &&ResizeToVF = [this, &Cost](const TreeEntry *TE, ArrayRef<int> Mask) {
6622     InstructionCost C = 0;
6623     unsigned VF = Mask.size();
6624     unsigned VecVF = TE->getVectorFactor();
6625     if (VF != VecVF &&
6626         (any_of(Mask, [VF](int Idx) { return Idx >= static_cast<int>(VF); }) ||
6627          (all_of(Mask,
6628                  [VF](int Idx) { return Idx < 2 * static_cast<int>(VF); }) &&
6629           !ShuffleVectorInst::isIdentityMask(Mask)))) {
6630       SmallVector<int> OrigMask(VecVF, UndefMaskElem);
6631       std::copy(Mask.begin(), std::next(Mask.begin(), std::min(VF, VecVF)),
6632                 OrigMask.begin());
6633       C = TTI->getShuffleCost(
6634           TTI::SK_PermuteSingleSrc,
6635           FixedVectorType::get(TE->getMainOp()->getType(), VecVF), OrigMask);
6636       LLVM_DEBUG(
6637           dbgs() << "SLP: Adding cost " << C
6638                  << " for final shuffle of insertelement external users.\n";
6639           TE->dump(); dbgs() << "SLP: Current total cost = " << Cost << "\n");
6640       Cost += C;
6641       return std::make_pair(TE, true);
6642     }
6643     return std::make_pair(TE, false);
6644   };
6645   // Calculate the cost of the reshuffled vectors, if any.
6646   for (int I = 0, E = FirstUsers.size(); I < E; ++I) {
6647     Value *Base = cast<Instruction>(FirstUsers[I].first)->getOperand(0);
6648     unsigned VF = ShuffleMasks[I].begin()->second.size();
6649     auto *FTy = FixedVectorType::get(
6650         cast<VectorType>(FirstUsers[I].first->getType())->getElementType(), VF);
6651     auto Vector = ShuffleMasks[I].takeVector();
6652     auto &&EstimateShufflesCost = [this, FTy,
6653                                    &Cost](ArrayRef<int> Mask,
6654                                           ArrayRef<const TreeEntry *> TEs) {
6655       assert((TEs.size() == 1 || TEs.size() == 2) &&
6656              "Expected exactly 1 or 2 tree entries.");
6657       if (TEs.size() == 1) {
6658         int Limit = 2 * Mask.size();
6659         if (!all_of(Mask, [Limit](int Idx) { return Idx < Limit; }) ||
6660             !ShuffleVectorInst::isIdentityMask(Mask)) {
6661           InstructionCost C =
6662               TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FTy, Mask);
6663           LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6664                             << " for final shuffle of insertelement "
6665                                "external users.\n";
6666                      TEs.front()->dump();
6667                      dbgs() << "SLP: Current total cost = " << Cost << "\n");
6668           Cost += C;
6669         }
6670       } else {
6671         InstructionCost C =
6672             TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, FTy, Mask);
6673         LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6674                           << " for final shuffle of vector node and external "
6675                              "insertelement users.\n";
6676                    if (TEs.front()) { TEs.front()->dump(); } TEs.back()->dump();
6677                    dbgs() << "SLP: Current total cost = " << Cost << "\n");
6678         Cost += C;
6679       }
6680       return TEs.back();
6681     };
6682     (void)performExtractsShuffleAction<const TreeEntry>(
6683         makeMutableArrayRef(Vector.data(), Vector.size()), Base,
6684         [](const TreeEntry *E) { return E->getVectorFactor(); }, ResizeToVF,
6685         EstimateShufflesCost);
6686     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6687         cast<FixedVectorType>(FirstUsers[I].first->getType()), DemandedElts[I],
6688         /*Insert*/ true, /*Extract*/ false);
6689     Cost -= InsertCost;
6690   }
6691 
6692 #ifndef NDEBUG
6693   SmallString<256> Str;
6694   {
6695     raw_svector_ostream OS(Str);
6696     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
6697        << "SLP: Extract Cost = " << ExtractCost << ".\n"
6698        << "SLP: Total Cost = " << Cost << ".\n";
6699   }
6700   LLVM_DEBUG(dbgs() << Str);
6701   if (ViewSLPTree)
6702     ViewGraph(this, "SLP" + F->getName(), false, Str);
6703 #endif
6704 
6705   return Cost;
6706 }
6707 
6708 Optional<TargetTransformInfo::ShuffleKind>
6709 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
6710                                SmallVectorImpl<const TreeEntry *> &Entries) {
6711   // TODO: currently checking only for Scalars in the tree entry, need to count
6712   // reused elements too for better cost estimation.
6713   Mask.assign(TE->Scalars.size(), UndefMaskElem);
6714   Entries.clear();
6715   // Build a lists of values to tree entries.
6716   DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs;
6717   for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) {
6718     if (EntryPtr.get() == TE)
6719       break;
6720     if (EntryPtr->State != TreeEntry::NeedToGather)
6721       continue;
6722     for (Value *V : EntryPtr->Scalars)
6723       ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get());
6724   }
6725   // Find all tree entries used by the gathered values. If no common entries
6726   // found - not a shuffle.
6727   // Here we build a set of tree nodes for each gathered value and trying to
6728   // find the intersection between these sets. If we have at least one common
6729   // tree node for each gathered value - we have just a permutation of the
6730   // single vector. If we have 2 different sets, we're in situation where we
6731   // have a permutation of 2 input vectors.
6732   SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs;
6733   DenseMap<Value *, int> UsedValuesEntry;
6734   for (Value *V : TE->Scalars) {
6735     if (isa<UndefValue>(V))
6736       continue;
6737     // Build a list of tree entries where V is used.
6738     SmallPtrSet<const TreeEntry *, 4> VToTEs;
6739     auto It = ValueToTEs.find(V);
6740     if (It != ValueToTEs.end())
6741       VToTEs = It->second;
6742     if (const TreeEntry *VTE = getTreeEntry(V))
6743       VToTEs.insert(VTE);
6744     if (VToTEs.empty())
6745       return None;
6746     if (UsedTEs.empty()) {
6747       // The first iteration, just insert the list of nodes to vector.
6748       UsedTEs.push_back(VToTEs);
6749     } else {
6750       // Need to check if there are any previously used tree nodes which use V.
6751       // If there are no such nodes, consider that we have another one input
6752       // vector.
6753       SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs);
6754       unsigned Idx = 0;
6755       for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) {
6756         // Do we have a non-empty intersection of previously listed tree entries
6757         // and tree entries using current V?
6758         set_intersect(VToTEs, Set);
6759         if (!VToTEs.empty()) {
6760           // Yes, write the new subset and continue analysis for the next
6761           // scalar.
6762           Set.swap(VToTEs);
6763           break;
6764         }
6765         VToTEs = SavedVToTEs;
6766         ++Idx;
6767       }
6768       // No non-empty intersection found - need to add a second set of possible
6769       // source vectors.
6770       if (Idx == UsedTEs.size()) {
6771         // If the number of input vectors is greater than 2 - not a permutation,
6772         // fallback to the regular gather.
6773         if (UsedTEs.size() == 2)
6774           return None;
6775         UsedTEs.push_back(SavedVToTEs);
6776         Idx = UsedTEs.size() - 1;
6777       }
6778       UsedValuesEntry.try_emplace(V, Idx);
6779     }
6780   }
6781 
6782   if (UsedTEs.empty()) {
6783     assert(all_of(TE->Scalars, UndefValue::classof) &&
6784            "Expected vector of undefs only.");
6785     return None;
6786   }
6787 
6788   unsigned VF = 0;
6789   if (UsedTEs.size() == 1) {
6790     // Try to find the perfect match in another gather node at first.
6791     auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) {
6792       return EntryPtr->isSame(TE->Scalars);
6793     });
6794     if (It != UsedTEs.front().end()) {
6795       Entries.push_back(*It);
6796       std::iota(Mask.begin(), Mask.end(), 0);
6797       return TargetTransformInfo::SK_PermuteSingleSrc;
6798     }
6799     // No perfect match, just shuffle, so choose the first tree node.
6800     Entries.push_back(*UsedTEs.front().begin());
6801   } else {
6802     // Try to find nodes with the same vector factor.
6803     assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries.");
6804     DenseMap<int, const TreeEntry *> VFToTE;
6805     for (const TreeEntry *TE : UsedTEs.front())
6806       VFToTE.try_emplace(TE->getVectorFactor(), TE);
6807     for (const TreeEntry *TE : UsedTEs.back()) {
6808       auto It = VFToTE.find(TE->getVectorFactor());
6809       if (It != VFToTE.end()) {
6810         VF = It->first;
6811         Entries.push_back(It->second);
6812         Entries.push_back(TE);
6813         break;
6814       }
6815     }
6816     // No 2 source vectors with the same vector factor - give up and do regular
6817     // gather.
6818     if (Entries.empty())
6819       return None;
6820   }
6821 
6822   // Build a shuffle mask for better cost estimation and vector emission.
6823   for (int I = 0, E = TE->Scalars.size(); I < E; ++I) {
6824     Value *V = TE->Scalars[I];
6825     if (isa<UndefValue>(V))
6826       continue;
6827     unsigned Idx = UsedValuesEntry.lookup(V);
6828     const TreeEntry *VTE = Entries[Idx];
6829     int FoundLane = VTE->findLaneForValue(V);
6830     Mask[I] = Idx * VF + FoundLane;
6831     // Extra check required by isSingleSourceMaskImpl function (called by
6832     // ShuffleVectorInst::isSingleSourceMask).
6833     if (Mask[I] >= 2 * E)
6834       return None;
6835   }
6836   switch (Entries.size()) {
6837   case 1:
6838     return TargetTransformInfo::SK_PermuteSingleSrc;
6839   case 2:
6840     return TargetTransformInfo::SK_PermuteTwoSrc;
6841   default:
6842     break;
6843   }
6844   return None;
6845 }
6846 
6847 InstructionCost BoUpSLP::getGatherCost(FixedVectorType *Ty,
6848                                        const APInt &ShuffledIndices,
6849                                        bool NeedToShuffle) const {
6850   InstructionCost Cost =
6851       TTI->getScalarizationOverhead(Ty, ~ShuffledIndices, /*Insert*/ true,
6852                                     /*Extract*/ false);
6853   if (NeedToShuffle)
6854     Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
6855   return Cost;
6856 }
6857 
6858 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
6859   // Find the type of the operands in VL.
6860   Type *ScalarTy = VL[0]->getType();
6861   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
6862     ScalarTy = SI->getValueOperand()->getType();
6863   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
6864   bool DuplicateNonConst = false;
6865   // Find the cost of inserting/extracting values from the vector.
6866   // Check if the same elements are inserted several times and count them as
6867   // shuffle candidates.
6868   APInt ShuffledElements = APInt::getZero(VL.size());
6869   DenseSet<Value *> UniqueElements;
6870   // Iterate in reverse order to consider insert elements with the high cost.
6871   for (unsigned I = VL.size(); I > 0; --I) {
6872     unsigned Idx = I - 1;
6873     // No need to shuffle duplicates for constants.
6874     if (isConstant(VL[Idx])) {
6875       ShuffledElements.setBit(Idx);
6876       continue;
6877     }
6878     if (!UniqueElements.insert(VL[Idx]).second) {
6879       DuplicateNonConst = true;
6880       ShuffledElements.setBit(Idx);
6881     }
6882   }
6883   return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst);
6884 }
6885 
6886 // Perform operand reordering on the instructions in VL and return the reordered
6887 // operands in Left and Right.
6888 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
6889                                              SmallVectorImpl<Value *> &Left,
6890                                              SmallVectorImpl<Value *> &Right,
6891                                              const DataLayout &DL,
6892                                              ScalarEvolution &SE,
6893                                              const BoUpSLP &R) {
6894   if (VL.empty())
6895     return;
6896   VLOperands Ops(VL, DL, SE, R);
6897   // Reorder the operands in place.
6898   Ops.reorder();
6899   Left = Ops.getVL(0);
6900   Right = Ops.getVL(1);
6901 }
6902 
6903 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) {
6904   // Get the basic block this bundle is in. All instructions in the bundle
6905   // should be in this block.
6906   auto *Front = E->getMainOp();
6907   auto *BB = Front->getParent();
6908   assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool {
6909     auto *I = cast<Instruction>(V);
6910     return !E->isOpcodeOrAlt(I) || I->getParent() == BB;
6911   }));
6912 
6913   auto &&FindLastInst = [E, Front]() {
6914     Instruction *LastInst = Front;
6915     for (Value *V : E->Scalars) {
6916       auto *I = dyn_cast<Instruction>(V);
6917       if (!I)
6918         continue;
6919       if (LastInst->comesBefore(I))
6920         LastInst = I;
6921     }
6922     return LastInst;
6923   };
6924 
6925   auto &&FindFirstInst = [E, Front]() {
6926     Instruction *FirstInst = Front;
6927     for (Value *V : E->Scalars) {
6928       auto *I = dyn_cast<Instruction>(V);
6929       if (!I)
6930         continue;
6931       if (I->comesBefore(FirstInst))
6932         FirstInst = I;
6933     }
6934     return FirstInst;
6935   };
6936 
6937   // Set the insert point to the beginning of the basic block if the entry
6938   // should not be scheduled.
6939   if (E->State != TreeEntry::NeedToGather &&
6940       doesNotNeedToSchedule(E->Scalars)) {
6941     Instruction *InsertInst;
6942     if (all_of(E->Scalars, isUsedOutsideBlock))
6943       InsertInst = FindLastInst();
6944     else
6945       InsertInst = FindFirstInst();
6946     // If the instruction is PHI, set the insert point after all the PHIs.
6947     if (isa<PHINode>(InsertInst))
6948       InsertInst = BB->getFirstNonPHI();
6949     BasicBlock::iterator InsertPt = InsertInst->getIterator();
6950     Builder.SetInsertPoint(BB, InsertPt);
6951     Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6952     return;
6953   }
6954 
6955   // The last instruction in the bundle in program order.
6956   Instruction *LastInst = nullptr;
6957 
6958   // Find the last instruction. The common case should be that BB has been
6959   // scheduled, and the last instruction is VL.back(). So we start with
6960   // VL.back() and iterate over schedule data until we reach the end of the
6961   // bundle. The end of the bundle is marked by null ScheduleData.
6962   if (BlocksSchedules.count(BB)) {
6963     Value *V = E->isOneOf(E->Scalars.back());
6964     if (doesNotNeedToBeScheduled(V))
6965       V = *find_if_not(E->Scalars, doesNotNeedToBeScheduled);
6966     auto *Bundle = BlocksSchedules[BB]->getScheduleData(V);
6967     if (Bundle && Bundle->isPartOfBundle())
6968       for (; Bundle; Bundle = Bundle->NextInBundle)
6969         if (Bundle->OpValue == Bundle->Inst)
6970           LastInst = Bundle->Inst;
6971   }
6972 
6973   // LastInst can still be null at this point if there's either not an entry
6974   // for BB in BlocksSchedules or there's no ScheduleData available for
6975   // VL.back(). This can be the case if buildTree_rec aborts for various
6976   // reasons (e.g., the maximum recursion depth is reached, the maximum region
6977   // size is reached, etc.). ScheduleData is initialized in the scheduling
6978   // "dry-run".
6979   //
6980   // If this happens, we can still find the last instruction by brute force. We
6981   // iterate forwards from Front (inclusive) until we either see all
6982   // instructions in the bundle or reach the end of the block. If Front is the
6983   // last instruction in program order, LastInst will be set to Front, and we
6984   // will visit all the remaining instructions in the block.
6985   //
6986   // One of the reasons we exit early from buildTree_rec is to place an upper
6987   // bound on compile-time. Thus, taking an additional compile-time hit here is
6988   // not ideal. However, this should be exceedingly rare since it requires that
6989   // we both exit early from buildTree_rec and that the bundle be out-of-order
6990   // (causing us to iterate all the way to the end of the block).
6991   if (!LastInst) {
6992     LastInst = FindLastInst();
6993     // If the instruction is PHI, set the insert point after all the PHIs.
6994     if (isa<PHINode>(LastInst))
6995       LastInst = BB->getFirstNonPHI()->getPrevNode();
6996   }
6997   assert(LastInst && "Failed to find last instruction in bundle");
6998 
6999   // Set the insertion point after the last instruction in the bundle. Set the
7000   // debug location to Front.
7001   Builder.SetInsertPoint(BB, std::next(LastInst->getIterator()));
7002   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
7003 }
7004 
7005 Value *BoUpSLP::gather(ArrayRef<Value *> VL) {
7006   // List of instructions/lanes from current block and/or the blocks which are
7007   // part of the current loop. These instructions will be inserted at the end to
7008   // make it possible to optimize loops and hoist invariant instructions out of
7009   // the loops body with better chances for success.
7010   SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts;
7011   SmallSet<int, 4> PostponedIndices;
7012   Loop *L = LI->getLoopFor(Builder.GetInsertBlock());
7013   auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) {
7014     SmallPtrSet<BasicBlock *, 4> Visited;
7015     while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second)
7016       InsertBB = InsertBB->getSinglePredecessor();
7017     return InsertBB && InsertBB == InstBB;
7018   };
7019   for (int I = 0, E = VL.size(); I < E; ++I) {
7020     if (auto *Inst = dyn_cast<Instruction>(VL[I]))
7021       if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) ||
7022            getTreeEntry(Inst) || (L && (L->contains(Inst)))) &&
7023           PostponedIndices.insert(I).second)
7024         PostponedInsts.emplace_back(Inst, I);
7025   }
7026 
7027   auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) {
7028     Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos));
7029     auto *InsElt = dyn_cast<InsertElementInst>(Vec);
7030     if (!InsElt)
7031       return Vec;
7032     GatherShuffleSeq.insert(InsElt);
7033     CSEBlocks.insert(InsElt->getParent());
7034     // Add to our 'need-to-extract' list.
7035     if (TreeEntry *Entry = getTreeEntry(V)) {
7036       // Find which lane we need to extract.
7037       unsigned FoundLane = Entry->findLaneForValue(V);
7038       ExternalUses.emplace_back(V, InsElt, FoundLane);
7039     }
7040     return Vec;
7041   };
7042   Value *Val0 =
7043       isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0];
7044   FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size());
7045   Value *Vec = PoisonValue::get(VecTy);
7046   SmallVector<int> NonConsts;
7047   // Insert constant values at first.
7048   for (int I = 0, E = VL.size(); I < E; ++I) {
7049     if (PostponedIndices.contains(I))
7050       continue;
7051     if (!isConstant(VL[I])) {
7052       NonConsts.push_back(I);
7053       continue;
7054     }
7055     Vec = CreateInsertElement(Vec, VL[I], I);
7056   }
7057   // Insert non-constant values.
7058   for (int I : NonConsts)
7059     Vec = CreateInsertElement(Vec, VL[I], I);
7060   // Append instructions, which are/may be part of the loop, in the end to make
7061   // it possible to hoist non-loop-based instructions.
7062   for (const std::pair<Value *, unsigned> &Pair : PostponedInsts)
7063     Vec = CreateInsertElement(Vec, Pair.first, Pair.second);
7064 
7065   return Vec;
7066 }
7067 
7068 namespace {
7069 /// Merges shuffle masks and emits final shuffle instruction, if required.
7070 class ShuffleInstructionBuilder {
7071   IRBuilderBase &Builder;
7072   const unsigned VF = 0;
7073   bool IsFinalized = false;
7074   SmallVector<int, 4> Mask;
7075   /// Holds all of the instructions that we gathered.
7076   SetVector<Instruction *> &GatherShuffleSeq;
7077   /// A list of blocks that we are going to CSE.
7078   SetVector<BasicBlock *> &CSEBlocks;
7079 
7080 public:
7081   ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF,
7082                             SetVector<Instruction *> &GatherShuffleSeq,
7083                             SetVector<BasicBlock *> &CSEBlocks)
7084       : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq),
7085         CSEBlocks(CSEBlocks) {}
7086 
7087   /// Adds a mask, inverting it before applying.
7088   void addInversedMask(ArrayRef<unsigned> SubMask) {
7089     if (SubMask.empty())
7090       return;
7091     SmallVector<int, 4> NewMask;
7092     inversePermutation(SubMask, NewMask);
7093     addMask(NewMask);
7094   }
7095 
7096   /// Functions adds masks, merging them into  single one.
7097   void addMask(ArrayRef<unsigned> SubMask) {
7098     SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end());
7099     addMask(NewMask);
7100   }
7101 
7102   void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); }
7103 
7104   Value *finalize(Value *V) {
7105     IsFinalized = true;
7106     unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements();
7107     if (VF == ValueVF && Mask.empty())
7108       return V;
7109     SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem);
7110     std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0);
7111     addMask(NormalizedMask);
7112 
7113     if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask))
7114       return V;
7115     Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle");
7116     if (auto *I = dyn_cast<Instruction>(Vec)) {
7117       GatherShuffleSeq.insert(I);
7118       CSEBlocks.insert(I->getParent());
7119     }
7120     return Vec;
7121   }
7122 
7123   ~ShuffleInstructionBuilder() {
7124     assert((IsFinalized || Mask.empty()) &&
7125            "Shuffle construction must be finalized.");
7126   }
7127 };
7128 } // namespace
7129 
7130 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
7131   const unsigned VF = VL.size();
7132   InstructionsState S = getSameOpcode(VL);
7133   if (S.getOpcode()) {
7134     if (TreeEntry *E = getTreeEntry(S.OpValue))
7135       if (E->isSame(VL)) {
7136         Value *V = vectorizeTree(E);
7137         if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) {
7138           if (!E->ReuseShuffleIndices.empty()) {
7139             // Reshuffle to get only unique values.
7140             // If some of the scalars are duplicated in the vectorization tree
7141             // entry, we do not vectorize them but instead generate a mask for
7142             // the reuses. But if there are several users of the same entry,
7143             // they may have different vectorization factors. This is especially
7144             // important for PHI nodes. In this case, we need to adapt the
7145             // resulting instruction for the user vectorization factor and have
7146             // to reshuffle it again to take only unique elements of the vector.
7147             // Without this code the function incorrectly returns reduced vector
7148             // instruction with the same elements, not with the unique ones.
7149 
7150             // block:
7151             // %phi = phi <2 x > { .., %entry} {%shuffle, %block}
7152             // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0>
7153             // ... (use %2)
7154             // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0}
7155             // br %block
7156             SmallVector<int> UniqueIdxs(VF, UndefMaskElem);
7157             SmallSet<int, 4> UsedIdxs;
7158             int Pos = 0;
7159             int Sz = VL.size();
7160             for (int Idx : E->ReuseShuffleIndices) {
7161               if (Idx != Sz && Idx != UndefMaskElem &&
7162                   UsedIdxs.insert(Idx).second)
7163                 UniqueIdxs[Idx] = Pos;
7164               ++Pos;
7165             }
7166             assert(VF >= UsedIdxs.size() && "Expected vectorization factor "
7167                                             "less than original vector size.");
7168             UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem);
7169             V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle");
7170           } else {
7171             assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() &&
7172                    "Expected vectorization factor less "
7173                    "than original vector size.");
7174             SmallVector<int> UniformMask(VF, 0);
7175             std::iota(UniformMask.begin(), UniformMask.end(), 0);
7176             V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle");
7177           }
7178           if (auto *I = dyn_cast<Instruction>(V)) {
7179             GatherShuffleSeq.insert(I);
7180             CSEBlocks.insert(I->getParent());
7181           }
7182         }
7183         return V;
7184       }
7185   }
7186 
7187   // Can't vectorize this, so simply build a new vector with each lane
7188   // corresponding to the requested value.
7189   return createBuildVector(VL);
7190 }
7191 Value *BoUpSLP::createBuildVector(ArrayRef<Value *> VL) {
7192   unsigned VF = VL.size();
7193   // Exploit possible reuse of values across lanes.
7194   SmallVector<int> ReuseShuffleIndicies;
7195   SmallVector<Value *> UniqueValues;
7196   if (VL.size() > 2) {
7197     DenseMap<Value *, unsigned> UniquePositions;
7198     unsigned NumValues =
7199         std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) {
7200                                     return !isa<UndefValue>(V);
7201                                   }).base());
7202     VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues));
7203     int UniqueVals = 0;
7204     for (Value *V : VL.drop_back(VL.size() - VF)) {
7205       if (isa<UndefValue>(V)) {
7206         ReuseShuffleIndicies.emplace_back(UndefMaskElem);
7207         continue;
7208       }
7209       if (isConstant(V)) {
7210         ReuseShuffleIndicies.emplace_back(UniqueValues.size());
7211         UniqueValues.emplace_back(V);
7212         continue;
7213       }
7214       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
7215       ReuseShuffleIndicies.emplace_back(Res.first->second);
7216       if (Res.second) {
7217         UniqueValues.emplace_back(V);
7218         ++UniqueVals;
7219       }
7220     }
7221     if (UniqueVals == 1 && UniqueValues.size() == 1) {
7222       // Emit pure splat vector.
7223       ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(),
7224                                   UndefMaskElem);
7225     } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) {
7226       ReuseShuffleIndicies.clear();
7227       UniqueValues.clear();
7228       UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues));
7229     }
7230     UniqueValues.append(VF - UniqueValues.size(),
7231                         PoisonValue::get(VL[0]->getType()));
7232     VL = UniqueValues;
7233   }
7234 
7235   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
7236                                            CSEBlocks);
7237   Value *Vec = gather(VL);
7238   if (!ReuseShuffleIndicies.empty()) {
7239     ShuffleBuilder.addMask(ReuseShuffleIndicies);
7240     Vec = ShuffleBuilder.finalize(Vec);
7241   }
7242   return Vec;
7243 }
7244 
7245 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
7246   IRBuilder<>::InsertPointGuard Guard(Builder);
7247 
7248   if (E->VectorizedValue) {
7249     LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
7250     return E->VectorizedValue;
7251   }
7252 
7253   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
7254   unsigned VF = E->getVectorFactor();
7255   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
7256                                            CSEBlocks);
7257   if (E->State == TreeEntry::NeedToGather) {
7258     if (E->getMainOp())
7259       setInsertPointAfterBundle(E);
7260     Value *Vec;
7261     SmallVector<int> Mask;
7262     SmallVector<const TreeEntry *> Entries;
7263     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
7264         isGatherShuffledEntry(E, Mask, Entries);
7265     if (Shuffle.hasValue()) {
7266       assert((Entries.size() == 1 || Entries.size() == 2) &&
7267              "Expected shuffle of 1 or 2 entries.");
7268       Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue,
7269                                         Entries.back()->VectorizedValue, Mask);
7270       if (auto *I = dyn_cast<Instruction>(Vec)) {
7271         GatherShuffleSeq.insert(I);
7272         CSEBlocks.insert(I->getParent());
7273       }
7274     } else {
7275       Vec = gather(E->Scalars);
7276     }
7277     if (NeedToShuffleReuses) {
7278       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7279       Vec = ShuffleBuilder.finalize(Vec);
7280     }
7281     E->VectorizedValue = Vec;
7282     return Vec;
7283   }
7284 
7285   assert((E->State == TreeEntry::Vectorize ||
7286           E->State == TreeEntry::ScatterVectorize) &&
7287          "Unhandled state");
7288   unsigned ShuffleOrOp =
7289       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
7290   Instruction *VL0 = E->getMainOp();
7291   Type *ScalarTy = VL0->getType();
7292   if (auto *Store = dyn_cast<StoreInst>(VL0))
7293     ScalarTy = Store->getValueOperand()->getType();
7294   else if (auto *IE = dyn_cast<InsertElementInst>(VL0))
7295     ScalarTy = IE->getOperand(1)->getType();
7296   auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
7297   switch (ShuffleOrOp) {
7298     case Instruction::PHI: {
7299       assert(
7300           (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) &&
7301           "PHI reordering is free.");
7302       auto *PH = cast<PHINode>(VL0);
7303       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
7304       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
7305       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
7306       Value *V = NewPhi;
7307 
7308       // Adjust insertion point once all PHI's have been generated.
7309       Builder.SetInsertPoint(&*PH->getParent()->getFirstInsertionPt());
7310       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
7311 
7312       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7313       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7314       V = ShuffleBuilder.finalize(V);
7315 
7316       E->VectorizedValue = V;
7317 
7318       // PHINodes may have multiple entries from the same block. We want to
7319       // visit every block once.
7320       SmallPtrSet<BasicBlock*, 4> VisitedBBs;
7321 
7322       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
7323         ValueList Operands;
7324         BasicBlock *IBB = PH->getIncomingBlock(i);
7325 
7326         if (!VisitedBBs.insert(IBB).second) {
7327           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
7328           continue;
7329         }
7330 
7331         Builder.SetInsertPoint(IBB->getTerminator());
7332         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
7333         Value *Vec = vectorizeTree(E->getOperand(i));
7334         NewPhi->addIncoming(Vec, IBB);
7335       }
7336 
7337       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
7338              "Invalid number of incoming values");
7339       return V;
7340     }
7341 
7342     case Instruction::ExtractElement: {
7343       Value *V = E->getSingleOperand(0);
7344       Builder.SetInsertPoint(VL0);
7345       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7346       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7347       V = ShuffleBuilder.finalize(V);
7348       E->VectorizedValue = V;
7349       return V;
7350     }
7351     case Instruction::ExtractValue: {
7352       auto *LI = cast<LoadInst>(E->getSingleOperand(0));
7353       Builder.SetInsertPoint(LI);
7354       auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
7355       Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
7356       LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
7357       Value *NewV = propagateMetadata(V, E->Scalars);
7358       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7359       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7360       NewV = ShuffleBuilder.finalize(NewV);
7361       E->VectorizedValue = NewV;
7362       return NewV;
7363     }
7364     case Instruction::InsertElement: {
7365       assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique");
7366       Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back()));
7367       Value *V = vectorizeTree(E->getOperand(1));
7368 
7369       // Create InsertVector shuffle if necessary
7370       auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
7371         return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0));
7372       }));
7373       const unsigned NumElts =
7374           cast<FixedVectorType>(FirstInsert->getType())->getNumElements();
7375       const unsigned NumScalars = E->Scalars.size();
7376 
7377       unsigned Offset = *getInsertIndex(VL0);
7378       assert(Offset < NumElts && "Failed to find vector index offset");
7379 
7380       // Create shuffle to resize vector
7381       SmallVector<int> Mask;
7382       if (!E->ReorderIndices.empty()) {
7383         inversePermutation(E->ReorderIndices, Mask);
7384         Mask.append(NumElts - NumScalars, UndefMaskElem);
7385       } else {
7386         Mask.assign(NumElts, UndefMaskElem);
7387         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
7388       }
7389       // Create InsertVector shuffle if necessary
7390       bool IsIdentity = true;
7391       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
7392       Mask.swap(PrevMask);
7393       for (unsigned I = 0; I < NumScalars; ++I) {
7394         Value *Scalar = E->Scalars[PrevMask[I]];
7395         unsigned InsertIdx = *getInsertIndex(Scalar);
7396         IsIdentity &= InsertIdx - Offset == I;
7397         Mask[InsertIdx - Offset] = I;
7398       }
7399       if (!IsIdentity || NumElts != NumScalars) {
7400         V = Builder.CreateShuffleVector(V, Mask);
7401         if (auto *I = dyn_cast<Instruction>(V)) {
7402           GatherShuffleSeq.insert(I);
7403           CSEBlocks.insert(I->getParent());
7404         }
7405       }
7406 
7407       if ((!IsIdentity || Offset != 0 ||
7408            !isUndefVector(FirstInsert->getOperand(0))) &&
7409           NumElts != NumScalars) {
7410         SmallVector<int> InsertMask(NumElts);
7411         std::iota(InsertMask.begin(), InsertMask.end(), 0);
7412         for (unsigned I = 0; I < NumElts; I++) {
7413           if (Mask[I] != UndefMaskElem)
7414             InsertMask[Offset + I] = NumElts + I;
7415         }
7416 
7417         V = Builder.CreateShuffleVector(
7418             FirstInsert->getOperand(0), V, InsertMask,
7419             cast<Instruction>(E->Scalars.back())->getName());
7420         if (auto *I = dyn_cast<Instruction>(V)) {
7421           GatherShuffleSeq.insert(I);
7422           CSEBlocks.insert(I->getParent());
7423         }
7424       }
7425 
7426       ++NumVectorInstructions;
7427       E->VectorizedValue = V;
7428       return V;
7429     }
7430     case Instruction::ZExt:
7431     case Instruction::SExt:
7432     case Instruction::FPToUI:
7433     case Instruction::FPToSI:
7434     case Instruction::FPExt:
7435     case Instruction::PtrToInt:
7436     case Instruction::IntToPtr:
7437     case Instruction::SIToFP:
7438     case Instruction::UIToFP:
7439     case Instruction::Trunc:
7440     case Instruction::FPTrunc:
7441     case Instruction::BitCast: {
7442       setInsertPointAfterBundle(E);
7443 
7444       Value *InVec = vectorizeTree(E->getOperand(0));
7445 
7446       if (E->VectorizedValue) {
7447         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7448         return E->VectorizedValue;
7449       }
7450 
7451       auto *CI = cast<CastInst>(VL0);
7452       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
7453       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7454       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7455       V = ShuffleBuilder.finalize(V);
7456 
7457       E->VectorizedValue = V;
7458       ++NumVectorInstructions;
7459       return V;
7460     }
7461     case Instruction::FCmp:
7462     case Instruction::ICmp: {
7463       setInsertPointAfterBundle(E);
7464 
7465       Value *L = vectorizeTree(E->getOperand(0));
7466       Value *R = vectorizeTree(E->getOperand(1));
7467 
7468       if (E->VectorizedValue) {
7469         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7470         return E->VectorizedValue;
7471       }
7472 
7473       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
7474       Value *V = Builder.CreateCmp(P0, L, R);
7475       propagateIRFlags(V, E->Scalars, VL0);
7476       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7477       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7478       V = ShuffleBuilder.finalize(V);
7479 
7480       E->VectorizedValue = V;
7481       ++NumVectorInstructions;
7482       return V;
7483     }
7484     case Instruction::Select: {
7485       setInsertPointAfterBundle(E);
7486 
7487       Value *Cond = vectorizeTree(E->getOperand(0));
7488       Value *True = vectorizeTree(E->getOperand(1));
7489       Value *False = vectorizeTree(E->getOperand(2));
7490 
7491       if (E->VectorizedValue) {
7492         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7493         return E->VectorizedValue;
7494       }
7495 
7496       Value *V = Builder.CreateSelect(Cond, True, False);
7497       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7498       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7499       V = ShuffleBuilder.finalize(V);
7500 
7501       E->VectorizedValue = V;
7502       ++NumVectorInstructions;
7503       return V;
7504     }
7505     case Instruction::FNeg: {
7506       setInsertPointAfterBundle(E);
7507 
7508       Value *Op = vectorizeTree(E->getOperand(0));
7509 
7510       if (E->VectorizedValue) {
7511         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7512         return E->VectorizedValue;
7513       }
7514 
7515       Value *V = Builder.CreateUnOp(
7516           static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
7517       propagateIRFlags(V, E->Scalars, VL0);
7518       if (auto *I = dyn_cast<Instruction>(V))
7519         V = propagateMetadata(I, E->Scalars);
7520 
7521       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7522       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7523       V = ShuffleBuilder.finalize(V);
7524 
7525       E->VectorizedValue = V;
7526       ++NumVectorInstructions;
7527 
7528       return V;
7529     }
7530     case Instruction::Add:
7531     case Instruction::FAdd:
7532     case Instruction::Sub:
7533     case Instruction::FSub:
7534     case Instruction::Mul:
7535     case Instruction::FMul:
7536     case Instruction::UDiv:
7537     case Instruction::SDiv:
7538     case Instruction::FDiv:
7539     case Instruction::URem:
7540     case Instruction::SRem:
7541     case Instruction::FRem:
7542     case Instruction::Shl:
7543     case Instruction::LShr:
7544     case Instruction::AShr:
7545     case Instruction::And:
7546     case Instruction::Or:
7547     case Instruction::Xor: {
7548       setInsertPointAfterBundle(E);
7549 
7550       Value *LHS = vectorizeTree(E->getOperand(0));
7551       Value *RHS = vectorizeTree(E->getOperand(1));
7552 
7553       if (E->VectorizedValue) {
7554         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7555         return E->VectorizedValue;
7556       }
7557 
7558       Value *V = Builder.CreateBinOp(
7559           static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
7560           RHS);
7561       propagateIRFlags(V, E->Scalars, VL0);
7562       if (auto *I = dyn_cast<Instruction>(V))
7563         V = propagateMetadata(I, E->Scalars);
7564 
7565       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7566       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7567       V = ShuffleBuilder.finalize(V);
7568 
7569       E->VectorizedValue = V;
7570       ++NumVectorInstructions;
7571 
7572       return V;
7573     }
7574     case Instruction::Load: {
7575       // Loads are inserted at the head of the tree because we don't want to
7576       // sink them all the way down past store instructions.
7577       setInsertPointAfterBundle(E);
7578 
7579       LoadInst *LI = cast<LoadInst>(VL0);
7580       Instruction *NewLI;
7581       unsigned AS = LI->getPointerAddressSpace();
7582       Value *PO = LI->getPointerOperand();
7583       if (E->State == TreeEntry::Vectorize) {
7584         Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS));
7585         NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
7586 
7587         // The pointer operand uses an in-tree scalar so we add the new BitCast
7588         // or LoadInst to ExternalUses list to make sure that an extract will
7589         // be generated in the future.
7590         if (TreeEntry *Entry = getTreeEntry(PO)) {
7591           // Find which lane we need to extract.
7592           unsigned FoundLane = Entry->findLaneForValue(PO);
7593           ExternalUses.emplace_back(
7594               PO, PO != VecPtr ? cast<User>(VecPtr) : NewLI, FoundLane);
7595         }
7596       } else {
7597         assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state");
7598         Value *VecPtr = vectorizeTree(E->getOperand(0));
7599         // Use the minimum alignment of the gathered loads.
7600         Align CommonAlignment = LI->getAlign();
7601         for (Value *V : E->Scalars)
7602           CommonAlignment =
7603               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
7604         NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment);
7605       }
7606       Value *V = propagateMetadata(NewLI, E->Scalars);
7607 
7608       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7609       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7610       V = ShuffleBuilder.finalize(V);
7611       E->VectorizedValue = V;
7612       ++NumVectorInstructions;
7613       return V;
7614     }
7615     case Instruction::Store: {
7616       auto *SI = cast<StoreInst>(VL0);
7617       unsigned AS = SI->getPointerAddressSpace();
7618 
7619       setInsertPointAfterBundle(E);
7620 
7621       Value *VecValue = vectorizeTree(E->getOperand(0));
7622       ShuffleBuilder.addMask(E->ReorderIndices);
7623       VecValue = ShuffleBuilder.finalize(VecValue);
7624 
7625       Value *ScalarPtr = SI->getPointerOperand();
7626       Value *VecPtr = Builder.CreateBitCast(
7627           ScalarPtr, VecValue->getType()->getPointerTo(AS));
7628       StoreInst *ST =
7629           Builder.CreateAlignedStore(VecValue, VecPtr, SI->getAlign());
7630 
7631       // The pointer operand uses an in-tree scalar, so add the new BitCast or
7632       // StoreInst to ExternalUses to make sure that an extract will be
7633       // generated in the future.
7634       if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) {
7635         // Find which lane we need to extract.
7636         unsigned FoundLane = Entry->findLaneForValue(ScalarPtr);
7637         ExternalUses.push_back(ExternalUser(
7638             ScalarPtr, ScalarPtr != VecPtr ? cast<User>(VecPtr) : ST,
7639             FoundLane));
7640       }
7641 
7642       Value *V = propagateMetadata(ST, E->Scalars);
7643 
7644       E->VectorizedValue = V;
7645       ++NumVectorInstructions;
7646       return V;
7647     }
7648     case Instruction::GetElementPtr: {
7649       auto *GEP0 = cast<GetElementPtrInst>(VL0);
7650       setInsertPointAfterBundle(E);
7651 
7652       Value *Op0 = vectorizeTree(E->getOperand(0));
7653 
7654       SmallVector<Value *> OpVecs;
7655       for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) {
7656         Value *OpVec = vectorizeTree(E->getOperand(J));
7657         OpVecs.push_back(OpVec);
7658       }
7659 
7660       Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs);
7661       if (Instruction *I = dyn_cast<Instruction>(V))
7662         V = propagateMetadata(I, E->Scalars);
7663 
7664       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7665       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7666       V = ShuffleBuilder.finalize(V);
7667 
7668       E->VectorizedValue = V;
7669       ++NumVectorInstructions;
7670 
7671       return V;
7672     }
7673     case Instruction::Call: {
7674       CallInst *CI = cast<CallInst>(VL0);
7675       setInsertPointAfterBundle(E);
7676 
7677       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
7678       if (Function *FI = CI->getCalledFunction())
7679         IID = FI->getIntrinsicID();
7680 
7681       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
7682 
7683       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
7684       bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
7685                           VecCallCosts.first <= VecCallCosts.second;
7686 
7687       Value *ScalarArg = nullptr;
7688       std::vector<Value *> OpVecs;
7689       SmallVector<Type *, 2> TysForDecl =
7690           {FixedVectorType::get(CI->getType(), E->Scalars.size())};
7691       for (int j = 0, e = CI->arg_size(); j < e; ++j) {
7692         ValueList OpVL;
7693         // Some intrinsics have scalar arguments. This argument should not be
7694         // vectorized.
7695         if (UseIntrinsic && isVectorIntrinsicWithScalarOpAtArg(IID, j)) {
7696           CallInst *CEI = cast<CallInst>(VL0);
7697           ScalarArg = CEI->getArgOperand(j);
7698           OpVecs.push_back(CEI->getArgOperand(j));
7699           if (isVectorIntrinsicWithOverloadTypeAtArg(IID, j))
7700             TysForDecl.push_back(ScalarArg->getType());
7701           continue;
7702         }
7703 
7704         Value *OpVec = vectorizeTree(E->getOperand(j));
7705         LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
7706         OpVecs.push_back(OpVec);
7707         if (isVectorIntrinsicWithOverloadTypeAtArg(IID, j))
7708           TysForDecl.push_back(OpVec->getType());
7709       }
7710 
7711       Function *CF;
7712       if (!UseIntrinsic) {
7713         VFShape Shape =
7714             VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
7715                                   VecTy->getNumElements())),
7716                          false /*HasGlobalPred*/);
7717         CF = VFDatabase(*CI).getVectorizedFunction(Shape);
7718       } else {
7719         CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl);
7720       }
7721 
7722       SmallVector<OperandBundleDef, 1> OpBundles;
7723       CI->getOperandBundlesAsDefs(OpBundles);
7724       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
7725 
7726       // The scalar argument uses an in-tree scalar so we add the new vectorized
7727       // call to ExternalUses list to make sure that an extract will be
7728       // generated in the future.
7729       if (ScalarArg) {
7730         if (TreeEntry *Entry = getTreeEntry(ScalarArg)) {
7731           // Find which lane we need to extract.
7732           unsigned FoundLane = Entry->findLaneForValue(ScalarArg);
7733           ExternalUses.push_back(
7734               ExternalUser(ScalarArg, cast<User>(V), FoundLane));
7735         }
7736       }
7737 
7738       propagateIRFlags(V, E->Scalars, VL0);
7739       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7740       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7741       V = ShuffleBuilder.finalize(V);
7742 
7743       E->VectorizedValue = V;
7744       ++NumVectorInstructions;
7745       return V;
7746     }
7747     case Instruction::ShuffleVector: {
7748       assert(E->isAltShuffle() &&
7749              ((Instruction::isBinaryOp(E->getOpcode()) &&
7750                Instruction::isBinaryOp(E->getAltOpcode())) ||
7751               (Instruction::isCast(E->getOpcode()) &&
7752                Instruction::isCast(E->getAltOpcode())) ||
7753               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
7754              "Invalid Shuffle Vector Operand");
7755 
7756       Value *LHS = nullptr, *RHS = nullptr;
7757       if (Instruction::isBinaryOp(E->getOpcode()) || isa<CmpInst>(VL0)) {
7758         setInsertPointAfterBundle(E);
7759         LHS = vectorizeTree(E->getOperand(0));
7760         RHS = vectorizeTree(E->getOperand(1));
7761       } else {
7762         setInsertPointAfterBundle(E);
7763         LHS = vectorizeTree(E->getOperand(0));
7764       }
7765 
7766       if (E->VectorizedValue) {
7767         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7768         return E->VectorizedValue;
7769       }
7770 
7771       Value *V0, *V1;
7772       if (Instruction::isBinaryOp(E->getOpcode())) {
7773         V0 = Builder.CreateBinOp(
7774             static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
7775         V1 = Builder.CreateBinOp(
7776             static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
7777       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
7778         V0 = Builder.CreateCmp(CI0->getPredicate(), LHS, RHS);
7779         auto *AltCI = cast<CmpInst>(E->getAltOp());
7780         CmpInst::Predicate AltPred = AltCI->getPredicate();
7781         V1 = Builder.CreateCmp(AltPred, LHS, RHS);
7782       } else {
7783         V0 = Builder.CreateCast(
7784             static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
7785         V1 = Builder.CreateCast(
7786             static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
7787       }
7788       // Add V0 and V1 to later analysis to try to find and remove matching
7789       // instruction, if any.
7790       for (Value *V : {V0, V1}) {
7791         if (auto *I = dyn_cast<Instruction>(V)) {
7792           GatherShuffleSeq.insert(I);
7793           CSEBlocks.insert(I->getParent());
7794         }
7795       }
7796 
7797       // Create shuffle to take alternate operations from the vector.
7798       // Also, gather up main and alt scalar ops to propagate IR flags to
7799       // each vector operation.
7800       ValueList OpScalars, AltScalars;
7801       SmallVector<int> Mask;
7802       buildShuffleEntryMask(
7803           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
7804           [E](Instruction *I) {
7805             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
7806             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
7807           },
7808           Mask, &OpScalars, &AltScalars);
7809 
7810       propagateIRFlags(V0, OpScalars);
7811       propagateIRFlags(V1, AltScalars);
7812 
7813       Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
7814       if (auto *I = dyn_cast<Instruction>(V)) {
7815         V = propagateMetadata(I, E->Scalars);
7816         GatherShuffleSeq.insert(I);
7817         CSEBlocks.insert(I->getParent());
7818       }
7819       V = ShuffleBuilder.finalize(V);
7820 
7821       E->VectorizedValue = V;
7822       ++NumVectorInstructions;
7823 
7824       return V;
7825     }
7826     default:
7827     llvm_unreachable("unknown inst");
7828   }
7829   return nullptr;
7830 }
7831 
7832 Value *BoUpSLP::vectorizeTree() {
7833   ExtraValueToDebugLocsMap ExternallyUsedValues;
7834   return vectorizeTree(ExternallyUsedValues);
7835 }
7836 
7837 Value *
7838 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
7839   // All blocks must be scheduled before any instructions are inserted.
7840   for (auto &BSIter : BlocksSchedules) {
7841     scheduleBlock(BSIter.second.get());
7842   }
7843 
7844   Builder.SetInsertPoint(&F->getEntryBlock().front());
7845   auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
7846 
7847   // If the vectorized tree can be rewritten in a smaller type, we truncate the
7848   // vectorized root. InstCombine will then rewrite the entire expression. We
7849   // sign extend the extracted values below.
7850   auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
7851   if (MinBWs.count(ScalarRoot)) {
7852     if (auto *I = dyn_cast<Instruction>(VectorRoot)) {
7853       // If current instr is a phi and not the last phi, insert it after the
7854       // last phi node.
7855       if (isa<PHINode>(I))
7856         Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt());
7857       else
7858         Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
7859     }
7860     auto BundleWidth = VectorizableTree[0]->Scalars.size();
7861     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
7862     auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
7863     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
7864     VectorizableTree[0]->VectorizedValue = Trunc;
7865   }
7866 
7867   LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
7868                     << " values .\n");
7869 
7870   // Extract all of the elements with the external uses.
7871   for (const auto &ExternalUse : ExternalUses) {
7872     Value *Scalar = ExternalUse.Scalar;
7873     llvm::User *User = ExternalUse.User;
7874 
7875     // Skip users that we already RAUW. This happens when one instruction
7876     // has multiple uses of the same value.
7877     if (User && !is_contained(Scalar->users(), User))
7878       continue;
7879     TreeEntry *E = getTreeEntry(Scalar);
7880     assert(E && "Invalid scalar");
7881     assert(E->State != TreeEntry::NeedToGather &&
7882            "Extracting from a gather list");
7883 
7884     Value *Vec = E->VectorizedValue;
7885     assert(Vec && "Can't find vectorizable value");
7886 
7887     Value *Lane = Builder.getInt32(ExternalUse.Lane);
7888     auto ExtractAndExtendIfNeeded = [&](Value *Vec) {
7889       if (Scalar->getType() != Vec->getType()) {
7890         Value *Ex;
7891         // "Reuse" the existing extract to improve final codegen.
7892         if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) {
7893           Ex = Builder.CreateExtractElement(ES->getOperand(0),
7894                                             ES->getOperand(1));
7895         } else {
7896           Ex = Builder.CreateExtractElement(Vec, Lane);
7897         }
7898         // If necessary, sign-extend or zero-extend ScalarRoot
7899         // to the larger type.
7900         if (!MinBWs.count(ScalarRoot))
7901           return Ex;
7902         if (MinBWs[ScalarRoot].second)
7903           return Builder.CreateSExt(Ex, Scalar->getType());
7904         return Builder.CreateZExt(Ex, Scalar->getType());
7905       }
7906       assert(isa<FixedVectorType>(Scalar->getType()) &&
7907              isa<InsertElementInst>(Scalar) &&
7908              "In-tree scalar of vector type is not insertelement?");
7909       return Vec;
7910     };
7911     // If User == nullptr, the Scalar is used as extra arg. Generate
7912     // ExtractElement instruction and update the record for this scalar in
7913     // ExternallyUsedValues.
7914     if (!User) {
7915       assert(ExternallyUsedValues.count(Scalar) &&
7916              "Scalar with nullptr as an external user must be registered in "
7917              "ExternallyUsedValues map");
7918       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7919         Builder.SetInsertPoint(VecI->getParent(),
7920                                std::next(VecI->getIterator()));
7921       } else {
7922         Builder.SetInsertPoint(&F->getEntryBlock().front());
7923       }
7924       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7925       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
7926       auto &NewInstLocs = ExternallyUsedValues[NewInst];
7927       auto It = ExternallyUsedValues.find(Scalar);
7928       assert(It != ExternallyUsedValues.end() &&
7929              "Externally used scalar is not found in ExternallyUsedValues");
7930       NewInstLocs.append(It->second);
7931       ExternallyUsedValues.erase(Scalar);
7932       // Required to update internally referenced instructions.
7933       Scalar->replaceAllUsesWith(NewInst);
7934       continue;
7935     }
7936 
7937     // Generate extracts for out-of-tree users.
7938     // Find the insertion point for the extractelement lane.
7939     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7940       if (PHINode *PH = dyn_cast<PHINode>(User)) {
7941         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
7942           if (PH->getIncomingValue(i) == Scalar) {
7943             Instruction *IncomingTerminator =
7944                 PH->getIncomingBlock(i)->getTerminator();
7945             if (isa<CatchSwitchInst>(IncomingTerminator)) {
7946               Builder.SetInsertPoint(VecI->getParent(),
7947                                      std::next(VecI->getIterator()));
7948             } else {
7949               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
7950             }
7951             Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7952             CSEBlocks.insert(PH->getIncomingBlock(i));
7953             PH->setOperand(i, NewInst);
7954           }
7955         }
7956       } else {
7957         Builder.SetInsertPoint(cast<Instruction>(User));
7958         Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7959         CSEBlocks.insert(cast<Instruction>(User)->getParent());
7960         User->replaceUsesOfWith(Scalar, NewInst);
7961       }
7962     } else {
7963       Builder.SetInsertPoint(&F->getEntryBlock().front());
7964       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7965       CSEBlocks.insert(&F->getEntryBlock());
7966       User->replaceUsesOfWith(Scalar, NewInst);
7967     }
7968 
7969     LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
7970   }
7971 
7972   // For each vectorized value:
7973   for (auto &TEPtr : VectorizableTree) {
7974     TreeEntry *Entry = TEPtr.get();
7975 
7976     // No need to handle users of gathered values.
7977     if (Entry->State == TreeEntry::NeedToGather)
7978       continue;
7979 
7980     assert(Entry->VectorizedValue && "Can't find vectorizable value");
7981 
7982     // For each lane:
7983     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
7984       Value *Scalar = Entry->Scalars[Lane];
7985 
7986 #ifndef NDEBUG
7987       Type *Ty = Scalar->getType();
7988       if (!Ty->isVoidTy()) {
7989         for (User *U : Scalar->users()) {
7990           LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
7991 
7992           // It is legal to delete users in the ignorelist.
7993           assert((getTreeEntry(U) || is_contained(UserIgnoreList, U) ||
7994                   (isa_and_nonnull<Instruction>(U) &&
7995                    isDeleted(cast<Instruction>(U)))) &&
7996                  "Deleting out-of-tree value");
7997         }
7998       }
7999 #endif
8000       LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
8001       eraseInstruction(cast<Instruction>(Scalar));
8002     }
8003   }
8004 
8005   Builder.ClearInsertionPoint();
8006   InstrElementSize.clear();
8007 
8008   return VectorizableTree[0]->VectorizedValue;
8009 }
8010 
8011 void BoUpSLP::optimizeGatherSequence() {
8012   LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleSeq.size()
8013                     << " gather sequences instructions.\n");
8014   // LICM InsertElementInst sequences.
8015   for (Instruction *I : GatherShuffleSeq) {
8016     if (isDeleted(I))
8017       continue;
8018 
8019     // Check if this block is inside a loop.
8020     Loop *L = LI->getLoopFor(I->getParent());
8021     if (!L)
8022       continue;
8023 
8024     // Check if it has a preheader.
8025     BasicBlock *PreHeader = L->getLoopPreheader();
8026     if (!PreHeader)
8027       continue;
8028 
8029     // If the vector or the element that we insert into it are
8030     // instructions that are defined in this basic block then we can't
8031     // hoist this instruction.
8032     if (any_of(I->operands(), [L](Value *V) {
8033           auto *OpI = dyn_cast<Instruction>(V);
8034           return OpI && L->contains(OpI);
8035         }))
8036       continue;
8037 
8038     // We can hoist this instruction. Move it to the pre-header.
8039     I->moveBefore(PreHeader->getTerminator());
8040   }
8041 
8042   // Make a list of all reachable blocks in our CSE queue.
8043   SmallVector<const DomTreeNode *, 8> CSEWorkList;
8044   CSEWorkList.reserve(CSEBlocks.size());
8045   for (BasicBlock *BB : CSEBlocks)
8046     if (DomTreeNode *N = DT->getNode(BB)) {
8047       assert(DT->isReachableFromEntry(N));
8048       CSEWorkList.push_back(N);
8049     }
8050 
8051   // Sort blocks by domination. This ensures we visit a block after all blocks
8052   // dominating it are visited.
8053   llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) {
8054     assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) &&
8055            "Different nodes should have different DFS numbers");
8056     return A->getDFSNumIn() < B->getDFSNumIn();
8057   });
8058 
8059   // Less defined shuffles can be replaced by the more defined copies.
8060   // Between two shuffles one is less defined if it has the same vector operands
8061   // and its mask indeces are the same as in the first one or undefs. E.g.
8062   // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0,
8063   // poison, <0, 0, 0, 0>.
8064   auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2,
8065                                            SmallVectorImpl<int> &NewMask) {
8066     if (I1->getType() != I2->getType())
8067       return false;
8068     auto *SI1 = dyn_cast<ShuffleVectorInst>(I1);
8069     auto *SI2 = dyn_cast<ShuffleVectorInst>(I2);
8070     if (!SI1 || !SI2)
8071       return I1->isIdenticalTo(I2);
8072     if (SI1->isIdenticalTo(SI2))
8073       return true;
8074     for (int I = 0, E = SI1->getNumOperands(); I < E; ++I)
8075       if (SI1->getOperand(I) != SI2->getOperand(I))
8076         return false;
8077     // Check if the second instruction is more defined than the first one.
8078     NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end());
8079     ArrayRef<int> SM1 = SI1->getShuffleMask();
8080     // Count trailing undefs in the mask to check the final number of used
8081     // registers.
8082     unsigned LastUndefsCnt = 0;
8083     for (int I = 0, E = NewMask.size(); I < E; ++I) {
8084       if (SM1[I] == UndefMaskElem)
8085         ++LastUndefsCnt;
8086       else
8087         LastUndefsCnt = 0;
8088       if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem &&
8089           NewMask[I] != SM1[I])
8090         return false;
8091       if (NewMask[I] == UndefMaskElem)
8092         NewMask[I] = SM1[I];
8093     }
8094     // Check if the last undefs actually change the final number of used vector
8095     // registers.
8096     return SM1.size() - LastUndefsCnt > 1 &&
8097            TTI->getNumberOfParts(SI1->getType()) ==
8098                TTI->getNumberOfParts(
8099                    FixedVectorType::get(SI1->getType()->getElementType(),
8100                                         SM1.size() - LastUndefsCnt));
8101   };
8102   // Perform O(N^2) search over the gather/shuffle sequences and merge identical
8103   // instructions. TODO: We can further optimize this scan if we split the
8104   // instructions into different buckets based on the insert lane.
8105   SmallVector<Instruction *, 16> Visited;
8106   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
8107     assert(*I &&
8108            (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
8109            "Worklist not sorted properly!");
8110     BasicBlock *BB = (*I)->getBlock();
8111     // For all instructions in blocks containing gather sequences:
8112     for (Instruction &In : llvm::make_early_inc_range(*BB)) {
8113       if (isDeleted(&In))
8114         continue;
8115       if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) &&
8116           !isa<ShuffleVectorInst>(&In) && !GatherShuffleSeq.contains(&In))
8117         continue;
8118 
8119       // Check if we can replace this instruction with any of the
8120       // visited instructions.
8121       bool Replaced = false;
8122       for (Instruction *&V : Visited) {
8123         SmallVector<int> NewMask;
8124         if (IsIdenticalOrLessDefined(&In, V, NewMask) &&
8125             DT->dominates(V->getParent(), In.getParent())) {
8126           In.replaceAllUsesWith(V);
8127           eraseInstruction(&In);
8128           if (auto *SI = dyn_cast<ShuffleVectorInst>(V))
8129             if (!NewMask.empty())
8130               SI->setShuffleMask(NewMask);
8131           Replaced = true;
8132           break;
8133         }
8134         if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) &&
8135             GatherShuffleSeq.contains(V) &&
8136             IsIdenticalOrLessDefined(V, &In, NewMask) &&
8137             DT->dominates(In.getParent(), V->getParent())) {
8138           In.moveAfter(V);
8139           V->replaceAllUsesWith(&In);
8140           eraseInstruction(V);
8141           if (auto *SI = dyn_cast<ShuffleVectorInst>(&In))
8142             if (!NewMask.empty())
8143               SI->setShuffleMask(NewMask);
8144           V = &In;
8145           Replaced = true;
8146           break;
8147         }
8148       }
8149       if (!Replaced) {
8150         assert(!is_contained(Visited, &In));
8151         Visited.push_back(&In);
8152       }
8153     }
8154   }
8155   CSEBlocks.clear();
8156   GatherShuffleSeq.clear();
8157 }
8158 
8159 BoUpSLP::ScheduleData *
8160 BoUpSLP::BlockScheduling::buildBundle(ArrayRef<Value *> VL) {
8161   ScheduleData *Bundle = nullptr;
8162   ScheduleData *PrevInBundle = nullptr;
8163   for (Value *V : VL) {
8164     if (doesNotNeedToBeScheduled(V))
8165       continue;
8166     ScheduleData *BundleMember = getScheduleData(V);
8167     assert(BundleMember &&
8168            "no ScheduleData for bundle member "
8169            "(maybe not in same basic block)");
8170     assert(BundleMember->isSchedulingEntity() &&
8171            "bundle member already part of other bundle");
8172     if (PrevInBundle) {
8173       PrevInBundle->NextInBundle = BundleMember;
8174     } else {
8175       Bundle = BundleMember;
8176     }
8177 
8178     // Group the instructions to a bundle.
8179     BundleMember->FirstInBundle = Bundle;
8180     PrevInBundle = BundleMember;
8181   }
8182   assert(Bundle && "Failed to find schedule bundle");
8183   return Bundle;
8184 }
8185 
8186 // Groups the instructions to a bundle (which is then a single scheduling entity)
8187 // and schedules instructions until the bundle gets ready.
8188 Optional<BoUpSLP::ScheduleData *>
8189 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
8190                                             const InstructionsState &S) {
8191   // No need to schedule PHIs, insertelement, extractelement and extractvalue
8192   // instructions.
8193   if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue) ||
8194       doesNotNeedToSchedule(VL))
8195     return nullptr;
8196 
8197   // Initialize the instruction bundle.
8198   Instruction *OldScheduleEnd = ScheduleEnd;
8199   LLVM_DEBUG(dbgs() << "SLP:  bundle: " << *S.OpValue << "\n");
8200 
8201   auto TryScheduleBundleImpl = [this, OldScheduleEnd, SLP](bool ReSchedule,
8202                                                          ScheduleData *Bundle) {
8203     // The scheduling region got new instructions at the lower end (or it is a
8204     // new region for the first bundle). This makes it necessary to
8205     // recalculate all dependencies.
8206     // It is seldom that this needs to be done a second time after adding the
8207     // initial bundle to the region.
8208     if (ScheduleEnd != OldScheduleEnd) {
8209       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode())
8210         doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); });
8211       ReSchedule = true;
8212     }
8213     if (Bundle) {
8214       LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle
8215                         << " in block " << BB->getName() << "\n");
8216       calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP);
8217     }
8218 
8219     if (ReSchedule) {
8220       resetSchedule();
8221       initialFillReadyList(ReadyInsts);
8222     }
8223 
8224     // Now try to schedule the new bundle or (if no bundle) just calculate
8225     // dependencies. As soon as the bundle is "ready" it means that there are no
8226     // cyclic dependencies and we can schedule it. Note that's important that we
8227     // don't "schedule" the bundle yet (see cancelScheduling).
8228     while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) &&
8229            !ReadyInsts.empty()) {
8230       ScheduleData *Picked = ReadyInsts.pop_back_val();
8231       assert(Picked->isSchedulingEntity() && Picked->isReady() &&
8232              "must be ready to schedule");
8233       schedule(Picked, ReadyInsts);
8234     }
8235   };
8236 
8237   // Make sure that the scheduling region contains all
8238   // instructions of the bundle.
8239   for (Value *V : VL) {
8240     if (doesNotNeedToBeScheduled(V))
8241       continue;
8242     if (!extendSchedulingRegion(V, S)) {
8243       // If the scheduling region got new instructions at the lower end (or it
8244       // is a new region for the first bundle). This makes it necessary to
8245       // recalculate all dependencies.
8246       // Otherwise the compiler may crash trying to incorrectly calculate
8247       // dependencies and emit instruction in the wrong order at the actual
8248       // scheduling.
8249       TryScheduleBundleImpl(/*ReSchedule=*/false, nullptr);
8250       return None;
8251     }
8252   }
8253 
8254   bool ReSchedule = false;
8255   for (Value *V : VL) {
8256     if (doesNotNeedToBeScheduled(V))
8257       continue;
8258     ScheduleData *BundleMember = getScheduleData(V);
8259     assert(BundleMember &&
8260            "no ScheduleData for bundle member (maybe not in same basic block)");
8261 
8262     // Make sure we don't leave the pieces of the bundle in the ready list when
8263     // whole bundle might not be ready.
8264     ReadyInsts.remove(BundleMember);
8265 
8266     if (!BundleMember->IsScheduled)
8267       continue;
8268     // A bundle member was scheduled as single instruction before and now
8269     // needs to be scheduled as part of the bundle. We just get rid of the
8270     // existing schedule.
8271     LLVM_DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
8272                       << " was already scheduled\n");
8273     ReSchedule = true;
8274   }
8275 
8276   auto *Bundle = buildBundle(VL);
8277   TryScheduleBundleImpl(ReSchedule, Bundle);
8278   if (!Bundle->isReady()) {
8279     cancelScheduling(VL, S.OpValue);
8280     return None;
8281   }
8282   return Bundle;
8283 }
8284 
8285 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
8286                                                 Value *OpValue) {
8287   if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue) ||
8288       doesNotNeedToSchedule(VL))
8289     return;
8290 
8291   if (doesNotNeedToBeScheduled(OpValue))
8292     OpValue = *find_if_not(VL, doesNotNeedToBeScheduled);
8293   ScheduleData *Bundle = getScheduleData(OpValue);
8294   LLVM_DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
8295   assert(!Bundle->IsScheduled &&
8296          "Can't cancel bundle which is already scheduled");
8297   assert(Bundle->isSchedulingEntity() &&
8298          (Bundle->isPartOfBundle() || needToScheduleSingleInstruction(VL)) &&
8299          "tried to unbundle something which is not a bundle");
8300 
8301   // Remove the bundle from the ready list.
8302   if (Bundle->isReady())
8303     ReadyInsts.remove(Bundle);
8304 
8305   // Un-bundle: make single instructions out of the bundle.
8306   ScheduleData *BundleMember = Bundle;
8307   while (BundleMember) {
8308     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
8309     BundleMember->FirstInBundle = BundleMember;
8310     ScheduleData *Next = BundleMember->NextInBundle;
8311     BundleMember->NextInBundle = nullptr;
8312     BundleMember->TE = nullptr;
8313     if (BundleMember->unscheduledDepsInBundle() == 0) {
8314       ReadyInsts.insert(BundleMember);
8315     }
8316     BundleMember = Next;
8317   }
8318 }
8319 
8320 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
8321   // Allocate a new ScheduleData for the instruction.
8322   if (ChunkPos >= ChunkSize) {
8323     ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
8324     ChunkPos = 0;
8325   }
8326   return &(ScheduleDataChunks.back()[ChunkPos++]);
8327 }
8328 
8329 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
8330                                                       const InstructionsState &S) {
8331   if (getScheduleData(V, isOneOf(S, V)))
8332     return true;
8333   Instruction *I = dyn_cast<Instruction>(V);
8334   assert(I && "bundle member must be an instruction");
8335   assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) &&
8336          !doesNotNeedToBeScheduled(I) &&
8337          "phi nodes/insertelements/extractelements/extractvalues don't need to "
8338          "be scheduled");
8339   auto &&CheckScheduleForI = [this, &S](Instruction *I) -> bool {
8340     ScheduleData *ISD = getScheduleData(I);
8341     if (!ISD)
8342       return false;
8343     assert(isInSchedulingRegion(ISD) &&
8344            "ScheduleData not in scheduling region");
8345     ScheduleData *SD = allocateScheduleDataChunks();
8346     SD->Inst = I;
8347     SD->init(SchedulingRegionID, S.OpValue);
8348     ExtraScheduleDataMap[I][S.OpValue] = SD;
8349     return true;
8350   };
8351   if (CheckScheduleForI(I))
8352     return true;
8353   if (!ScheduleStart) {
8354     // It's the first instruction in the new region.
8355     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
8356     ScheduleStart = I;
8357     ScheduleEnd = I->getNextNode();
8358     if (isOneOf(S, I) != I)
8359       CheckScheduleForI(I);
8360     assert(ScheduleEnd && "tried to vectorize a terminator?");
8361     LLVM_DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
8362     return true;
8363   }
8364   // Search up and down at the same time, because we don't know if the new
8365   // instruction is above or below the existing scheduling region.
8366   BasicBlock::reverse_iterator UpIter =
8367       ++ScheduleStart->getIterator().getReverse();
8368   BasicBlock::reverse_iterator UpperEnd = BB->rend();
8369   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
8370   BasicBlock::iterator LowerEnd = BB->end();
8371   while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I &&
8372          &*DownIter != I) {
8373     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
8374       LLVM_DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
8375       return false;
8376     }
8377 
8378     ++UpIter;
8379     ++DownIter;
8380   }
8381   if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) {
8382     assert(I->getParent() == ScheduleStart->getParent() &&
8383            "Instruction is in wrong basic block.");
8384     initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
8385     ScheduleStart = I;
8386     if (isOneOf(S, I) != I)
8387       CheckScheduleForI(I);
8388     LLVM_DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I
8389                       << "\n");
8390     return true;
8391   }
8392   assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) &&
8393          "Expected to reach top of the basic block or instruction down the "
8394          "lower end.");
8395   assert(I->getParent() == ScheduleEnd->getParent() &&
8396          "Instruction is in wrong basic block.");
8397   initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
8398                    nullptr);
8399   ScheduleEnd = I->getNextNode();
8400   if (isOneOf(S, I) != I)
8401     CheckScheduleForI(I);
8402   assert(ScheduleEnd && "tried to vectorize a terminator?");
8403   LLVM_DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
8404   return true;
8405 }
8406 
8407 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
8408                                                 Instruction *ToI,
8409                                                 ScheduleData *PrevLoadStore,
8410                                                 ScheduleData *NextLoadStore) {
8411   ScheduleData *CurrentLoadStore = PrevLoadStore;
8412   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
8413     // No need to allocate data for non-schedulable instructions.
8414     if (doesNotNeedToBeScheduled(I))
8415       continue;
8416     ScheduleData *SD = ScheduleDataMap.lookup(I);
8417     if (!SD) {
8418       SD = allocateScheduleDataChunks();
8419       ScheduleDataMap[I] = SD;
8420       SD->Inst = I;
8421     }
8422     assert(!isInSchedulingRegion(SD) &&
8423            "new ScheduleData already in scheduling region");
8424     SD->init(SchedulingRegionID, I);
8425 
8426     if (I->mayReadOrWriteMemory() &&
8427         (!isa<IntrinsicInst>(I) ||
8428          (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect &&
8429           cast<IntrinsicInst>(I)->getIntrinsicID() !=
8430               Intrinsic::pseudoprobe))) {
8431       // Update the linked list of memory accessing instructions.
8432       if (CurrentLoadStore) {
8433         CurrentLoadStore->NextLoadStore = SD;
8434       } else {
8435         FirstLoadStoreInRegion = SD;
8436       }
8437       CurrentLoadStore = SD;
8438     }
8439 
8440     if (match(I, m_Intrinsic<Intrinsic::stacksave>()) ||
8441         match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8442       RegionHasStackSave = true;
8443   }
8444   if (NextLoadStore) {
8445     if (CurrentLoadStore)
8446       CurrentLoadStore->NextLoadStore = NextLoadStore;
8447   } else {
8448     LastLoadStoreInRegion = CurrentLoadStore;
8449   }
8450 }
8451 
8452 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
8453                                                      bool InsertInReadyList,
8454                                                      BoUpSLP *SLP) {
8455   assert(SD->isSchedulingEntity());
8456 
8457   SmallVector<ScheduleData *, 10> WorkList;
8458   WorkList.push_back(SD);
8459 
8460   while (!WorkList.empty()) {
8461     ScheduleData *SD = WorkList.pop_back_val();
8462     for (ScheduleData *BundleMember = SD; BundleMember;
8463          BundleMember = BundleMember->NextInBundle) {
8464       assert(isInSchedulingRegion(BundleMember));
8465       if (BundleMember->hasValidDependencies())
8466         continue;
8467 
8468       LLVM_DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember
8469                  << "\n");
8470       BundleMember->Dependencies = 0;
8471       BundleMember->resetUnscheduledDeps();
8472 
8473       // Handle def-use chain dependencies.
8474       if (BundleMember->OpValue != BundleMember->Inst) {
8475         if (ScheduleData *UseSD = getScheduleData(BundleMember->Inst)) {
8476           BundleMember->Dependencies++;
8477           ScheduleData *DestBundle = UseSD->FirstInBundle;
8478           if (!DestBundle->IsScheduled)
8479             BundleMember->incrementUnscheduledDeps(1);
8480           if (!DestBundle->hasValidDependencies())
8481             WorkList.push_back(DestBundle);
8482         }
8483       } else {
8484         for (User *U : BundleMember->Inst->users()) {
8485           if (ScheduleData *UseSD = getScheduleData(cast<Instruction>(U))) {
8486             BundleMember->Dependencies++;
8487             ScheduleData *DestBundle = UseSD->FirstInBundle;
8488             if (!DestBundle->IsScheduled)
8489               BundleMember->incrementUnscheduledDeps(1);
8490             if (!DestBundle->hasValidDependencies())
8491               WorkList.push_back(DestBundle);
8492           }
8493         }
8494       }
8495 
8496       auto makeControlDependent = [&](Instruction *I) {
8497         auto *DepDest = getScheduleData(I);
8498         assert(DepDest && "must be in schedule window");
8499         DepDest->ControlDependencies.push_back(BundleMember);
8500         BundleMember->Dependencies++;
8501         ScheduleData *DestBundle = DepDest->FirstInBundle;
8502         if (!DestBundle->IsScheduled)
8503           BundleMember->incrementUnscheduledDeps(1);
8504         if (!DestBundle->hasValidDependencies())
8505           WorkList.push_back(DestBundle);
8506       };
8507 
8508       // Any instruction which isn't safe to speculate at the begining of the
8509       // block is control dependend on any early exit or non-willreturn call
8510       // which proceeds it.
8511       if (!isGuaranteedToTransferExecutionToSuccessor(BundleMember->Inst)) {
8512         for (Instruction *I = BundleMember->Inst->getNextNode();
8513              I != ScheduleEnd; I = I->getNextNode()) {
8514           if (isSafeToSpeculativelyExecute(I, &*BB->begin()))
8515             continue;
8516 
8517           // Add the dependency
8518           makeControlDependent(I);
8519 
8520           if (!isGuaranteedToTransferExecutionToSuccessor(I))
8521             // Everything past here must be control dependent on I.
8522             break;
8523         }
8524       }
8525 
8526       if (RegionHasStackSave) {
8527         // If we have an inalloc alloca instruction, it needs to be scheduled
8528         // after any preceeding stacksave.  We also need to prevent any alloca
8529         // from reordering above a preceeding stackrestore.
8530         if (match(BundleMember->Inst, m_Intrinsic<Intrinsic::stacksave>()) ||
8531             match(BundleMember->Inst, m_Intrinsic<Intrinsic::stackrestore>())) {
8532           for (Instruction *I = BundleMember->Inst->getNextNode();
8533                I != ScheduleEnd; I = I->getNextNode()) {
8534             if (match(I, m_Intrinsic<Intrinsic::stacksave>()) ||
8535                 match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8536               // Any allocas past here must be control dependent on I, and I
8537               // must be memory dependend on BundleMember->Inst.
8538               break;
8539 
8540             if (!isa<AllocaInst>(I))
8541               continue;
8542 
8543             // Add the dependency
8544             makeControlDependent(I);
8545           }
8546         }
8547 
8548         // In addition to the cases handle just above, we need to prevent
8549         // allocas from moving below a stacksave.  The stackrestore case
8550         // is currently thought to be conservatism.
8551         if (isa<AllocaInst>(BundleMember->Inst)) {
8552           for (Instruction *I = BundleMember->Inst->getNextNode();
8553                I != ScheduleEnd; I = I->getNextNode()) {
8554             if (!match(I, m_Intrinsic<Intrinsic::stacksave>()) &&
8555                 !match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8556               continue;
8557 
8558             // Add the dependency
8559             makeControlDependent(I);
8560             break;
8561           }
8562         }
8563       }
8564 
8565       // Handle the memory dependencies (if any).
8566       ScheduleData *DepDest = BundleMember->NextLoadStore;
8567       if (!DepDest)
8568         continue;
8569       Instruction *SrcInst = BundleMember->Inst;
8570       assert(SrcInst->mayReadOrWriteMemory() &&
8571              "NextLoadStore list for non memory effecting bundle?");
8572       MemoryLocation SrcLoc = getLocation(SrcInst);
8573       bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
8574       unsigned numAliased = 0;
8575       unsigned DistToSrc = 1;
8576 
8577       for ( ; DepDest; DepDest = DepDest->NextLoadStore) {
8578         assert(isInSchedulingRegion(DepDest));
8579 
8580         // We have two limits to reduce the complexity:
8581         // 1) AliasedCheckLimit: It's a small limit to reduce calls to
8582         //    SLP->isAliased (which is the expensive part in this loop).
8583         // 2) MaxMemDepDistance: It's for very large blocks and it aborts
8584         //    the whole loop (even if the loop is fast, it's quadratic).
8585         //    It's important for the loop break condition (see below) to
8586         //    check this limit even between two read-only instructions.
8587         if (DistToSrc >= MaxMemDepDistance ||
8588             ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
8589              (numAliased >= AliasedCheckLimit ||
8590               SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
8591 
8592           // We increment the counter only if the locations are aliased
8593           // (instead of counting all alias checks). This gives a better
8594           // balance between reduced runtime and accurate dependencies.
8595           numAliased++;
8596 
8597           DepDest->MemoryDependencies.push_back(BundleMember);
8598           BundleMember->Dependencies++;
8599           ScheduleData *DestBundle = DepDest->FirstInBundle;
8600           if (!DestBundle->IsScheduled) {
8601             BundleMember->incrementUnscheduledDeps(1);
8602           }
8603           if (!DestBundle->hasValidDependencies()) {
8604             WorkList.push_back(DestBundle);
8605           }
8606         }
8607 
8608         // Example, explaining the loop break condition: Let's assume our
8609         // starting instruction is i0 and MaxMemDepDistance = 3.
8610         //
8611         //                      +--------v--v--v
8612         //             i0,i1,i2,i3,i4,i5,i6,i7,i8
8613         //             +--------^--^--^
8614         //
8615         // MaxMemDepDistance let us stop alias-checking at i3 and we add
8616         // dependencies from i0 to i3,i4,.. (even if they are not aliased).
8617         // Previously we already added dependencies from i3 to i6,i7,i8
8618         // (because of MaxMemDepDistance). As we added a dependency from
8619         // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
8620         // and we can abort this loop at i6.
8621         if (DistToSrc >= 2 * MaxMemDepDistance)
8622           break;
8623         DistToSrc++;
8624       }
8625     }
8626     if (InsertInReadyList && SD->isReady()) {
8627       ReadyInsts.insert(SD);
8628       LLVM_DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst
8629                         << "\n");
8630     }
8631   }
8632 }
8633 
8634 void BoUpSLP::BlockScheduling::resetSchedule() {
8635   assert(ScheduleStart &&
8636          "tried to reset schedule on block which has not been scheduled");
8637   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
8638     doForAllOpcodes(I, [&](ScheduleData *SD) {
8639       assert(isInSchedulingRegion(SD) &&
8640              "ScheduleData not in scheduling region");
8641       SD->IsScheduled = false;
8642       SD->resetUnscheduledDeps();
8643     });
8644   }
8645   ReadyInsts.clear();
8646 }
8647 
8648 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
8649   if (!BS->ScheduleStart)
8650     return;
8651 
8652   LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
8653 
8654   // A key point - if we got here, pre-scheduling was able to find a valid
8655   // scheduling of the sub-graph of the scheduling window which consists
8656   // of all vector bundles and their transitive users.  As such, we do not
8657   // need to reschedule anything *outside of* that subgraph.
8658 
8659   BS->resetSchedule();
8660 
8661   // For the real scheduling we use a more sophisticated ready-list: it is
8662   // sorted by the original instruction location. This lets the final schedule
8663   // be as  close as possible to the original instruction order.
8664   // WARNING: If changing this order causes a correctness issue, that means
8665   // there is some missing dependence edge in the schedule data graph.
8666   struct ScheduleDataCompare {
8667     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
8668       return SD2->SchedulingPriority < SD1->SchedulingPriority;
8669     }
8670   };
8671   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
8672 
8673   // Ensure that all dependency data is updated (for nodes in the sub-graph)
8674   // and fill the ready-list with initial instructions.
8675   int Idx = 0;
8676   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
8677        I = I->getNextNode()) {
8678     BS->doForAllOpcodes(I, [this, &Idx, BS](ScheduleData *SD) {
8679       TreeEntry *SDTE = getTreeEntry(SD->Inst);
8680       (void)SDTE;
8681       assert((isVectorLikeInstWithConstOps(SD->Inst) ||
8682               SD->isPartOfBundle() ==
8683                   (SDTE && !doesNotNeedToSchedule(SDTE->Scalars))) &&
8684              "scheduler and vectorizer bundle mismatch");
8685       SD->FirstInBundle->SchedulingPriority = Idx++;
8686 
8687       if (SD->isSchedulingEntity() && SD->isPartOfBundle())
8688         BS->calculateDependencies(SD, false, this);
8689     });
8690   }
8691   BS->initialFillReadyList(ReadyInsts);
8692 
8693   Instruction *LastScheduledInst = BS->ScheduleEnd;
8694 
8695   // Do the "real" scheduling.
8696   while (!ReadyInsts.empty()) {
8697     ScheduleData *picked = *ReadyInsts.begin();
8698     ReadyInsts.erase(ReadyInsts.begin());
8699 
8700     // Move the scheduled instruction(s) to their dedicated places, if not
8701     // there yet.
8702     for (ScheduleData *BundleMember = picked; BundleMember;
8703          BundleMember = BundleMember->NextInBundle) {
8704       Instruction *pickedInst = BundleMember->Inst;
8705       if (pickedInst->getNextNode() != LastScheduledInst)
8706         pickedInst->moveBefore(LastScheduledInst);
8707       LastScheduledInst = pickedInst;
8708     }
8709 
8710     BS->schedule(picked, ReadyInsts);
8711   }
8712 
8713   // Check that we didn't break any of our invariants.
8714 #ifdef EXPENSIVE_CHECKS
8715   BS->verify();
8716 #endif
8717 
8718 #if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS)
8719   // Check that all schedulable entities got scheduled
8720   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; I = I->getNextNode()) {
8721     BS->doForAllOpcodes(I, [&](ScheduleData *SD) {
8722       if (SD->isSchedulingEntity() && SD->hasValidDependencies()) {
8723         assert(SD->IsScheduled && "must be scheduled at this point");
8724       }
8725     });
8726   }
8727 #endif
8728 
8729   // Avoid duplicate scheduling of the block.
8730   BS->ScheduleStart = nullptr;
8731 }
8732 
8733 unsigned BoUpSLP::getVectorElementSize(Value *V) {
8734   // If V is a store, just return the width of the stored value (or value
8735   // truncated just before storing) without traversing the expression tree.
8736   // This is the common case.
8737   if (auto *Store = dyn_cast<StoreInst>(V)) {
8738     if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand()))
8739       return DL->getTypeSizeInBits(Trunc->getSrcTy());
8740     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
8741   }
8742 
8743   if (auto *IEI = dyn_cast<InsertElementInst>(V))
8744     return getVectorElementSize(IEI->getOperand(1));
8745 
8746   auto E = InstrElementSize.find(V);
8747   if (E != InstrElementSize.end())
8748     return E->second;
8749 
8750   // If V is not a store, we can traverse the expression tree to find loads
8751   // that feed it. The type of the loaded value may indicate a more suitable
8752   // width than V's type. We want to base the vector element size on the width
8753   // of memory operations where possible.
8754   SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist;
8755   SmallPtrSet<Instruction *, 16> Visited;
8756   if (auto *I = dyn_cast<Instruction>(V)) {
8757     Worklist.emplace_back(I, I->getParent());
8758     Visited.insert(I);
8759   }
8760 
8761   // Traverse the expression tree in bottom-up order looking for loads. If we
8762   // encounter an instruction we don't yet handle, we give up.
8763   auto Width = 0u;
8764   while (!Worklist.empty()) {
8765     Instruction *I;
8766     BasicBlock *Parent;
8767     std::tie(I, Parent) = Worklist.pop_back_val();
8768 
8769     // We should only be looking at scalar instructions here. If the current
8770     // instruction has a vector type, skip.
8771     auto *Ty = I->getType();
8772     if (isa<VectorType>(Ty))
8773       continue;
8774 
8775     // If the current instruction is a load, update MaxWidth to reflect the
8776     // width of the loaded value.
8777     if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) ||
8778         isa<ExtractValueInst>(I))
8779       Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty));
8780 
8781     // Otherwise, we need to visit the operands of the instruction. We only
8782     // handle the interesting cases from buildTree here. If an operand is an
8783     // instruction we haven't yet visited and from the same basic block as the
8784     // user or the use is a PHI node, we add it to the worklist.
8785     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
8786              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) ||
8787              isa<UnaryOperator>(I)) {
8788       for (Use &U : I->operands())
8789         if (auto *J = dyn_cast<Instruction>(U.get()))
8790           if (Visited.insert(J).second &&
8791               (isa<PHINode>(I) || J->getParent() == Parent))
8792             Worklist.emplace_back(J, J->getParent());
8793     } else {
8794       break;
8795     }
8796   }
8797 
8798   // If we didn't encounter a memory access in the expression tree, or if we
8799   // gave up for some reason, just return the width of V. Otherwise, return the
8800   // maximum width we found.
8801   if (!Width) {
8802     if (auto *CI = dyn_cast<CmpInst>(V))
8803       V = CI->getOperand(0);
8804     Width = DL->getTypeSizeInBits(V->getType());
8805   }
8806 
8807   for (Instruction *I : Visited)
8808     InstrElementSize[I] = Width;
8809 
8810   return Width;
8811 }
8812 
8813 // Determine if a value V in a vectorizable expression Expr can be demoted to a
8814 // smaller type with a truncation. We collect the values that will be demoted
8815 // in ToDemote and additional roots that require investigating in Roots.
8816 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
8817                                   SmallVectorImpl<Value *> &ToDemote,
8818                                   SmallVectorImpl<Value *> &Roots) {
8819   // We can always demote constants.
8820   if (isa<Constant>(V)) {
8821     ToDemote.push_back(V);
8822     return true;
8823   }
8824 
8825   // If the value is not an instruction in the expression with only one use, it
8826   // cannot be demoted.
8827   auto *I = dyn_cast<Instruction>(V);
8828   if (!I || !I->hasOneUse() || !Expr.count(I))
8829     return false;
8830 
8831   switch (I->getOpcode()) {
8832 
8833   // We can always demote truncations and extensions. Since truncations can
8834   // seed additional demotion, we save the truncated value.
8835   case Instruction::Trunc:
8836     Roots.push_back(I->getOperand(0));
8837     break;
8838   case Instruction::ZExt:
8839   case Instruction::SExt:
8840     if (isa<ExtractElementInst>(I->getOperand(0)) ||
8841         isa<InsertElementInst>(I->getOperand(0)))
8842       return false;
8843     break;
8844 
8845   // We can demote certain binary operations if we can demote both of their
8846   // operands.
8847   case Instruction::Add:
8848   case Instruction::Sub:
8849   case Instruction::Mul:
8850   case Instruction::And:
8851   case Instruction::Or:
8852   case Instruction::Xor:
8853     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
8854         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
8855       return false;
8856     break;
8857 
8858   // We can demote selects if we can demote their true and false values.
8859   case Instruction::Select: {
8860     SelectInst *SI = cast<SelectInst>(I);
8861     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
8862         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
8863       return false;
8864     break;
8865   }
8866 
8867   // We can demote phis if we can demote all their incoming operands. Note that
8868   // we don't need to worry about cycles since we ensure single use above.
8869   case Instruction::PHI: {
8870     PHINode *PN = cast<PHINode>(I);
8871     for (Value *IncValue : PN->incoming_values())
8872       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
8873         return false;
8874     break;
8875   }
8876 
8877   // Otherwise, conservatively give up.
8878   default:
8879     return false;
8880   }
8881 
8882   // Record the value that we can demote.
8883   ToDemote.push_back(V);
8884   return true;
8885 }
8886 
8887 void BoUpSLP::computeMinimumValueSizes() {
8888   // If there are no external uses, the expression tree must be rooted by a
8889   // store. We can't demote in-memory values, so there is nothing to do here.
8890   if (ExternalUses.empty())
8891     return;
8892 
8893   // We only attempt to truncate integer expressions.
8894   auto &TreeRoot = VectorizableTree[0]->Scalars;
8895   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
8896   if (!TreeRootIT)
8897     return;
8898 
8899   // If the expression is not rooted by a store, these roots should have
8900   // external uses. We will rely on InstCombine to rewrite the expression in
8901   // the narrower type. However, InstCombine only rewrites single-use values.
8902   // This means that if a tree entry other than a root is used externally, it
8903   // must have multiple uses and InstCombine will not rewrite it. The code
8904   // below ensures that only the roots are used externally.
8905   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
8906   for (auto &EU : ExternalUses)
8907     if (!Expr.erase(EU.Scalar))
8908       return;
8909   if (!Expr.empty())
8910     return;
8911 
8912   // Collect the scalar values of the vectorizable expression. We will use this
8913   // context to determine which values can be demoted. If we see a truncation,
8914   // we mark it as seeding another demotion.
8915   for (auto &EntryPtr : VectorizableTree)
8916     Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
8917 
8918   // Ensure the roots of the vectorizable tree don't form a cycle. They must
8919   // have a single external user that is not in the vectorizable tree.
8920   for (auto *Root : TreeRoot)
8921     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
8922       return;
8923 
8924   // Conservatively determine if we can actually truncate the roots of the
8925   // expression. Collect the values that can be demoted in ToDemote and
8926   // additional roots that require investigating in Roots.
8927   SmallVector<Value *, 32> ToDemote;
8928   SmallVector<Value *, 4> Roots;
8929   for (auto *Root : TreeRoot)
8930     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
8931       return;
8932 
8933   // The maximum bit width required to represent all the values that can be
8934   // demoted without loss of precision. It would be safe to truncate the roots
8935   // of the expression to this width.
8936   auto MaxBitWidth = 8u;
8937 
8938   // We first check if all the bits of the roots are demanded. If they're not,
8939   // we can truncate the roots to this narrower type.
8940   for (auto *Root : TreeRoot) {
8941     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
8942     MaxBitWidth = std::max<unsigned>(
8943         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
8944   }
8945 
8946   // True if the roots can be zero-extended back to their original type, rather
8947   // than sign-extended. We know that if the leading bits are not demanded, we
8948   // can safely zero-extend. So we initialize IsKnownPositive to True.
8949   bool IsKnownPositive = true;
8950 
8951   // If all the bits of the roots are demanded, we can try a little harder to
8952   // compute a narrower type. This can happen, for example, if the roots are
8953   // getelementptr indices. InstCombine promotes these indices to the pointer
8954   // width. Thus, all their bits are technically demanded even though the
8955   // address computation might be vectorized in a smaller type.
8956   //
8957   // We start by looking at each entry that can be demoted. We compute the
8958   // maximum bit width required to store the scalar by using ValueTracking to
8959   // compute the number of high-order bits we can truncate.
8960   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
8961       llvm::all_of(TreeRoot, [](Value *R) {
8962         assert(R->hasOneUse() && "Root should have only one use!");
8963         return isa<GetElementPtrInst>(R->user_back());
8964       })) {
8965     MaxBitWidth = 8u;
8966 
8967     // Determine if the sign bit of all the roots is known to be zero. If not,
8968     // IsKnownPositive is set to False.
8969     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
8970       KnownBits Known = computeKnownBits(R, *DL);
8971       return Known.isNonNegative();
8972     });
8973 
8974     // Determine the maximum number of bits required to store the scalar
8975     // values.
8976     for (auto *Scalar : ToDemote) {
8977       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
8978       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
8979       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
8980     }
8981 
8982     // If we can't prove that the sign bit is zero, we must add one to the
8983     // maximum bit width to account for the unknown sign bit. This preserves
8984     // the existing sign bit so we can safely sign-extend the root back to the
8985     // original type. Otherwise, if we know the sign bit is zero, we will
8986     // zero-extend the root instead.
8987     //
8988     // FIXME: This is somewhat suboptimal, as there will be cases where adding
8989     //        one to the maximum bit width will yield a larger-than-necessary
8990     //        type. In general, we need to add an extra bit only if we can't
8991     //        prove that the upper bit of the original type is equal to the
8992     //        upper bit of the proposed smaller type. If these two bits are the
8993     //        same (either zero or one) we know that sign-extending from the
8994     //        smaller type will result in the same value. Here, since we can't
8995     //        yet prove this, we are just making the proposed smaller type
8996     //        larger to ensure correctness.
8997     if (!IsKnownPositive)
8998       ++MaxBitWidth;
8999   }
9000 
9001   // Round MaxBitWidth up to the next power-of-two.
9002   if (!isPowerOf2_64(MaxBitWidth))
9003     MaxBitWidth = NextPowerOf2(MaxBitWidth);
9004 
9005   // If the maximum bit width we compute is less than the with of the roots'
9006   // type, we can proceed with the narrowing. Otherwise, do nothing.
9007   if (MaxBitWidth >= TreeRootIT->getBitWidth())
9008     return;
9009 
9010   // If we can truncate the root, we must collect additional values that might
9011   // be demoted as a result. That is, those seeded by truncations we will
9012   // modify.
9013   while (!Roots.empty())
9014     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
9015 
9016   // Finally, map the values we can demote to the maximum bit with we computed.
9017   for (auto *Scalar : ToDemote)
9018     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
9019 }
9020 
9021 namespace {
9022 
9023 /// The SLPVectorizer Pass.
9024 struct SLPVectorizer : public FunctionPass {
9025   SLPVectorizerPass Impl;
9026 
9027   /// Pass identification, replacement for typeid
9028   static char ID;
9029 
9030   explicit SLPVectorizer() : FunctionPass(ID) {
9031     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
9032   }
9033 
9034   bool doInitialization(Module &M) override { return false; }
9035 
9036   bool runOnFunction(Function &F) override {
9037     if (skipFunction(F))
9038       return false;
9039 
9040     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
9041     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
9042     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
9043     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
9044     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
9045     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
9046     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
9047     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
9048     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
9049     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
9050 
9051     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
9052   }
9053 
9054   void getAnalysisUsage(AnalysisUsage &AU) const override {
9055     FunctionPass::getAnalysisUsage(AU);
9056     AU.addRequired<AssumptionCacheTracker>();
9057     AU.addRequired<ScalarEvolutionWrapperPass>();
9058     AU.addRequired<AAResultsWrapperPass>();
9059     AU.addRequired<TargetTransformInfoWrapperPass>();
9060     AU.addRequired<LoopInfoWrapperPass>();
9061     AU.addRequired<DominatorTreeWrapperPass>();
9062     AU.addRequired<DemandedBitsWrapperPass>();
9063     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
9064     AU.addRequired<InjectTLIMappingsLegacy>();
9065     AU.addPreserved<LoopInfoWrapperPass>();
9066     AU.addPreserved<DominatorTreeWrapperPass>();
9067     AU.addPreserved<AAResultsWrapperPass>();
9068     AU.addPreserved<GlobalsAAWrapperPass>();
9069     AU.setPreservesCFG();
9070   }
9071 };
9072 
9073 } // end anonymous namespace
9074 
9075 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
9076   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
9077   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
9078   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
9079   auto *AA = &AM.getResult<AAManager>(F);
9080   auto *LI = &AM.getResult<LoopAnalysis>(F);
9081   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
9082   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
9083   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
9084   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
9085 
9086   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
9087   if (!Changed)
9088     return PreservedAnalyses::all();
9089 
9090   PreservedAnalyses PA;
9091   PA.preserveSet<CFGAnalyses>();
9092   return PA;
9093 }
9094 
9095 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
9096                                 TargetTransformInfo *TTI_,
9097                                 TargetLibraryInfo *TLI_, AAResults *AA_,
9098                                 LoopInfo *LI_, DominatorTree *DT_,
9099                                 AssumptionCache *AC_, DemandedBits *DB_,
9100                                 OptimizationRemarkEmitter *ORE_) {
9101   if (!RunSLPVectorization)
9102     return false;
9103   SE = SE_;
9104   TTI = TTI_;
9105   TLI = TLI_;
9106   AA = AA_;
9107   LI = LI_;
9108   DT = DT_;
9109   AC = AC_;
9110   DB = DB_;
9111   DL = &F.getParent()->getDataLayout();
9112 
9113   Stores.clear();
9114   GEPs.clear();
9115   bool Changed = false;
9116 
9117   // If the target claims to have no vector registers don't attempt
9118   // vectorization.
9119   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true))) {
9120     LLVM_DEBUG(
9121         dbgs() << "SLP: Didn't find any vector registers for target, abort.\n");
9122     return false;
9123   }
9124 
9125   // Don't vectorize when the attribute NoImplicitFloat is used.
9126   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
9127     return false;
9128 
9129   LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
9130 
9131   // Use the bottom up slp vectorizer to construct chains that start with
9132   // store instructions.
9133   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
9134 
9135   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
9136   // delete instructions.
9137 
9138   // Update DFS numbers now so that we can use them for ordering.
9139   DT->updateDFSNumbers();
9140 
9141   // Scan the blocks in the function in post order.
9142   for (auto BB : post_order(&F.getEntryBlock())) {
9143     // Start new block - clear the list of reduction roots.
9144     R.clearReductionData();
9145     collectSeedInstructions(BB);
9146 
9147     // Vectorize trees that end at stores.
9148     if (!Stores.empty()) {
9149       LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
9150                         << " underlying objects.\n");
9151       Changed |= vectorizeStoreChains(R);
9152     }
9153 
9154     // Vectorize trees that end at reductions.
9155     Changed |= vectorizeChainsInBlock(BB, R);
9156 
9157     // Vectorize the index computations of getelementptr instructions. This
9158     // is primarily intended to catch gather-like idioms ending at
9159     // non-consecutive loads.
9160     if (!GEPs.empty()) {
9161       LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
9162                         << " underlying objects.\n");
9163       Changed |= vectorizeGEPIndices(BB, R);
9164     }
9165   }
9166 
9167   if (Changed) {
9168     R.optimizeGatherSequence();
9169     LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
9170   }
9171   return Changed;
9172 }
9173 
9174 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
9175                                             unsigned Idx) {
9176   LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()
9177                     << "\n");
9178   const unsigned Sz = R.getVectorElementSize(Chain[0]);
9179   const unsigned MinVF = R.getMinVecRegSize() / Sz;
9180   unsigned VF = Chain.size();
9181 
9182   if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
9183     return false;
9184 
9185   LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx
9186                     << "\n");
9187 
9188   R.buildTree(Chain);
9189   if (R.isTreeTinyAndNotFullyVectorizable())
9190     return false;
9191   if (R.isLoadCombineCandidate())
9192     return false;
9193   R.reorderTopToBottom();
9194   R.reorderBottomToTop();
9195   R.buildExternalUses();
9196 
9197   R.computeMinimumValueSizes();
9198 
9199   InstructionCost Cost = R.getTreeCost();
9200 
9201   LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n");
9202   if (Cost < -SLPCostThreshold) {
9203     LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n");
9204 
9205     using namespace ore;
9206 
9207     R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
9208                                         cast<StoreInst>(Chain[0]))
9209                      << "Stores SLP vectorized with cost " << NV("Cost", Cost)
9210                      << " and with tree size "
9211                      << NV("TreeSize", R.getTreeSize()));
9212 
9213     R.vectorizeTree();
9214     return true;
9215   }
9216 
9217   return false;
9218 }
9219 
9220 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
9221                                         BoUpSLP &R) {
9222   // We may run into multiple chains that merge into a single chain. We mark the
9223   // stores that we vectorized so that we don't visit the same store twice.
9224   BoUpSLP::ValueSet VectorizedStores;
9225   bool Changed = false;
9226 
9227   int E = Stores.size();
9228   SmallBitVector Tails(E, false);
9229   int MaxIter = MaxStoreLookup.getValue();
9230   SmallVector<std::pair<int, int>, 16> ConsecutiveChain(
9231       E, std::make_pair(E, INT_MAX));
9232   SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false));
9233   int IterCnt;
9234   auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
9235                                   &CheckedPairs,
9236                                   &ConsecutiveChain](int K, int Idx) {
9237     if (IterCnt >= MaxIter)
9238       return true;
9239     if (CheckedPairs[Idx].test(K))
9240       return ConsecutiveChain[K].second == 1 &&
9241              ConsecutiveChain[K].first == Idx;
9242     ++IterCnt;
9243     CheckedPairs[Idx].set(K);
9244     CheckedPairs[K].set(Idx);
9245     Optional<int> Diff = getPointersDiff(
9246         Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(),
9247         Stores[Idx]->getValueOperand()->getType(),
9248         Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true);
9249     if (!Diff || *Diff == 0)
9250       return false;
9251     int Val = *Diff;
9252     if (Val < 0) {
9253       if (ConsecutiveChain[Idx].second > -Val) {
9254         Tails.set(K);
9255         ConsecutiveChain[Idx] = std::make_pair(K, -Val);
9256       }
9257       return false;
9258     }
9259     if (ConsecutiveChain[K].second <= Val)
9260       return false;
9261 
9262     Tails.set(Idx);
9263     ConsecutiveChain[K] = std::make_pair(Idx, Val);
9264     return Val == 1;
9265   };
9266   // Do a quadratic search on all of the given stores in reverse order and find
9267   // all of the pairs of stores that follow each other.
9268   for (int Idx = E - 1; Idx >= 0; --Idx) {
9269     // If a store has multiple consecutive store candidates, search according
9270     // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
9271     // This is because usually pairing with immediate succeeding or preceding
9272     // candidate create the best chance to find slp vectorization opportunity.
9273     const int MaxLookDepth = std::max(E - Idx, Idx + 1);
9274     IterCnt = 0;
9275     for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
9276       if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
9277           (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
9278         break;
9279   }
9280 
9281   // Tracks if we tried to vectorize stores starting from the given tail
9282   // already.
9283   SmallBitVector TriedTails(E, false);
9284   // For stores that start but don't end a link in the chain:
9285   for (int Cnt = E; Cnt > 0; --Cnt) {
9286     int I = Cnt - 1;
9287     if (ConsecutiveChain[I].first == E || Tails.test(I))
9288       continue;
9289     // We found a store instr that starts a chain. Now follow the chain and try
9290     // to vectorize it.
9291     BoUpSLP::ValueList Operands;
9292     // Collect the chain into a list.
9293     while (I != E && !VectorizedStores.count(Stores[I])) {
9294       Operands.push_back(Stores[I]);
9295       Tails.set(I);
9296       if (ConsecutiveChain[I].second != 1) {
9297         // Mark the new end in the chain and go back, if required. It might be
9298         // required if the original stores come in reversed order, for example.
9299         if (ConsecutiveChain[I].first != E &&
9300             Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) &&
9301             !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) {
9302           TriedTails.set(I);
9303           Tails.reset(ConsecutiveChain[I].first);
9304           if (Cnt < ConsecutiveChain[I].first + 2)
9305             Cnt = ConsecutiveChain[I].first + 2;
9306         }
9307         break;
9308       }
9309       // Move to the next value in the chain.
9310       I = ConsecutiveChain[I].first;
9311     }
9312     assert(!Operands.empty() && "Expected non-empty list of stores.");
9313 
9314     unsigned MaxVecRegSize = R.getMaxVecRegSize();
9315     unsigned EltSize = R.getVectorElementSize(Operands[0]);
9316     unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize);
9317 
9318     unsigned MinVF = R.getMinVF(EltSize);
9319     unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store),
9320                               MaxElts);
9321 
9322     // FIXME: Is division-by-2 the correct step? Should we assert that the
9323     // register size is a power-of-2?
9324     unsigned StartIdx = 0;
9325     for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) {
9326       for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
9327         ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size);
9328         if (!VectorizedStores.count(Slice.front()) &&
9329             !VectorizedStores.count(Slice.back()) &&
9330             vectorizeStoreChain(Slice, R, Cnt)) {
9331           // Mark the vectorized stores so that we don't vectorize them again.
9332           VectorizedStores.insert(Slice.begin(), Slice.end());
9333           Changed = true;
9334           // If we vectorized initial block, no need to try to vectorize it
9335           // again.
9336           if (Cnt == StartIdx)
9337             StartIdx += Size;
9338           Cnt += Size;
9339           continue;
9340         }
9341         ++Cnt;
9342       }
9343       // Check if the whole array was vectorized already - exit.
9344       if (StartIdx >= Operands.size())
9345         break;
9346     }
9347   }
9348 
9349   return Changed;
9350 }
9351 
9352 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
9353   // Initialize the collections. We will make a single pass over the block.
9354   Stores.clear();
9355   GEPs.clear();
9356 
9357   // Visit the store and getelementptr instructions in BB and organize them in
9358   // Stores and GEPs according to the underlying objects of their pointer
9359   // operands.
9360   for (Instruction &I : *BB) {
9361     // Ignore store instructions that are volatile or have a pointer operand
9362     // that doesn't point to a scalar type.
9363     if (auto *SI = dyn_cast<StoreInst>(&I)) {
9364       if (!SI->isSimple())
9365         continue;
9366       if (!isValidElementType(SI->getValueOperand()->getType()))
9367         continue;
9368       Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI);
9369     }
9370 
9371     // Ignore getelementptr instructions that have more than one index, a
9372     // constant index, or a pointer operand that doesn't point to a scalar
9373     // type.
9374     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
9375       auto Idx = GEP->idx_begin()->get();
9376       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
9377         continue;
9378       if (!isValidElementType(Idx->getType()))
9379         continue;
9380       if (GEP->getType()->isVectorTy())
9381         continue;
9382       GEPs[GEP->getPointerOperand()].push_back(GEP);
9383     }
9384   }
9385 }
9386 
9387 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
9388   if (!A || !B)
9389     return false;
9390   if (isa<InsertElementInst>(A) || isa<InsertElementInst>(B))
9391     return false;
9392   Value *VL[] = {A, B};
9393   return tryToVectorizeList(VL, R);
9394 }
9395 
9396 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
9397                                            bool LimitForRegisterSize) {
9398   if (VL.size() < 2)
9399     return false;
9400 
9401   LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
9402                     << VL.size() << ".\n");
9403 
9404   // Check that all of the parts are instructions of the same type,
9405   // we permit an alternate opcode via InstructionsState.
9406   InstructionsState S = getSameOpcode(VL);
9407   if (!S.getOpcode())
9408     return false;
9409 
9410   Instruction *I0 = cast<Instruction>(S.OpValue);
9411   // Make sure invalid types (including vector type) are rejected before
9412   // determining vectorization factor for scalar instructions.
9413   for (Value *V : VL) {
9414     Type *Ty = V->getType();
9415     if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) {
9416       // NOTE: the following will give user internal llvm type name, which may
9417       // not be useful.
9418       R.getORE()->emit([&]() {
9419         std::string type_str;
9420         llvm::raw_string_ostream rso(type_str);
9421         Ty->print(rso);
9422         return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
9423                << "Cannot SLP vectorize list: type "
9424                << rso.str() + " is unsupported by vectorizer";
9425       });
9426       return false;
9427     }
9428   }
9429 
9430   unsigned Sz = R.getVectorElementSize(I0);
9431   unsigned MinVF = R.getMinVF(Sz);
9432   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
9433   MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF);
9434   if (MaxVF < 2) {
9435     R.getORE()->emit([&]() {
9436       return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
9437              << "Cannot SLP vectorize list: vectorization factor "
9438              << "less than 2 is not supported";
9439     });
9440     return false;
9441   }
9442 
9443   bool Changed = false;
9444   bool CandidateFound = false;
9445   InstructionCost MinCost = SLPCostThreshold.getValue();
9446   Type *ScalarTy = VL[0]->getType();
9447   if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
9448     ScalarTy = IE->getOperand(1)->getType();
9449 
9450   unsigned NextInst = 0, MaxInst = VL.size();
9451   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
9452     // No actual vectorization should happen, if number of parts is the same as
9453     // provided vectorization factor (i.e. the scalar type is used for vector
9454     // code during codegen).
9455     auto *VecTy = FixedVectorType::get(ScalarTy, VF);
9456     if (TTI->getNumberOfParts(VecTy) == VF)
9457       continue;
9458     for (unsigned I = NextInst; I < MaxInst; ++I) {
9459       unsigned OpsWidth = 0;
9460 
9461       if (I + VF > MaxInst)
9462         OpsWidth = MaxInst - I;
9463       else
9464         OpsWidth = VF;
9465 
9466       if (!isPowerOf2_32(OpsWidth))
9467         continue;
9468 
9469       if ((LimitForRegisterSize && OpsWidth < MaxVF) ||
9470           (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2))
9471         break;
9472 
9473       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
9474       // Check that a previous iteration of this loop did not delete the Value.
9475       if (llvm::any_of(Ops, [&R](Value *V) {
9476             auto *I = dyn_cast<Instruction>(V);
9477             return I && R.isDeleted(I);
9478           }))
9479         continue;
9480 
9481       LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
9482                         << "\n");
9483 
9484       R.buildTree(Ops);
9485       if (R.isTreeTinyAndNotFullyVectorizable())
9486         continue;
9487       R.reorderTopToBottom();
9488       R.reorderBottomToTop(!isa<InsertElementInst>(Ops.front()));
9489       R.buildExternalUses();
9490 
9491       R.computeMinimumValueSizes();
9492       InstructionCost Cost = R.getTreeCost();
9493       CandidateFound = true;
9494       MinCost = std::min(MinCost, Cost);
9495 
9496       if (Cost < -SLPCostThreshold) {
9497         LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
9498         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
9499                                                     cast<Instruction>(Ops[0]))
9500                                  << "SLP vectorized with cost " << ore::NV("Cost", Cost)
9501                                  << " and with tree size "
9502                                  << ore::NV("TreeSize", R.getTreeSize()));
9503 
9504         R.vectorizeTree();
9505         // Move to the next bundle.
9506         I += VF - 1;
9507         NextInst = I + 1;
9508         Changed = true;
9509       }
9510     }
9511   }
9512 
9513   if (!Changed && CandidateFound) {
9514     R.getORE()->emit([&]() {
9515       return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
9516              << "List vectorization was possible but not beneficial with cost "
9517              << ore::NV("Cost", MinCost) << " >= "
9518              << ore::NV("Treshold", -SLPCostThreshold);
9519     });
9520   } else if (!Changed) {
9521     R.getORE()->emit([&]() {
9522       return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
9523              << "Cannot SLP vectorize list: vectorization was impossible"
9524              << " with available vectorization factors";
9525     });
9526   }
9527   return Changed;
9528 }
9529 
9530 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
9531   if (!I)
9532     return false;
9533 
9534   if ((!isa<BinaryOperator>(I) && !isa<CmpInst>(I)) ||
9535       isa<VectorType>(I->getType()))
9536     return false;
9537 
9538   Value *P = I->getParent();
9539 
9540   // Vectorize in current basic block only.
9541   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
9542   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
9543   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
9544     return false;
9545 
9546   // First collect all possible candidates
9547   SmallVector<std::pair<Value *, Value *>, 4> Candidates;
9548   Candidates.emplace_back(Op0, Op1);
9549 
9550   auto *A = dyn_cast<BinaryOperator>(Op0);
9551   auto *B = dyn_cast<BinaryOperator>(Op1);
9552   // Try to skip B.
9553   if (A && B && B->hasOneUse()) {
9554     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
9555     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
9556     if (B0 && B0->getParent() == P)
9557       Candidates.emplace_back(A, B0);
9558     if (B1 && B1->getParent() == P)
9559       Candidates.emplace_back(A, B1);
9560   }
9561   // Try to skip A.
9562   if (B && A && A->hasOneUse()) {
9563     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
9564     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
9565     if (A0 && A0->getParent() == P)
9566       Candidates.emplace_back(A0, B);
9567     if (A1 && A1->getParent() == P)
9568       Candidates.emplace_back(A1, B);
9569   }
9570 
9571   if (Candidates.size() == 1)
9572     return tryToVectorizePair(Op0, Op1, R);
9573 
9574   // We have multiple options. Try to pick the single best.
9575   Optional<int> BestCandidate = R.findBestRootPair(Candidates);
9576   if (!BestCandidate)
9577     return false;
9578   return tryToVectorizePair(Candidates[*BestCandidate].first,
9579                             Candidates[*BestCandidate].second, R);
9580 }
9581 
9582 namespace {
9583 
9584 /// Model horizontal reductions.
9585 ///
9586 /// A horizontal reduction is a tree of reduction instructions that has values
9587 /// that can be put into a vector as its leaves. For example:
9588 ///
9589 /// mul mul mul mul
9590 ///  \  /    \  /
9591 ///   +       +
9592 ///    \     /
9593 ///       +
9594 /// This tree has "mul" as its leaf values and "+" as its reduction
9595 /// instructions. A reduction can feed into a store or a binary operation
9596 /// feeding a phi.
9597 ///    ...
9598 ///    \  /
9599 ///     +
9600 ///     |
9601 ///  phi +=
9602 ///
9603 ///  Or:
9604 ///    ...
9605 ///    \  /
9606 ///     +
9607 ///     |
9608 ///   *p =
9609 ///
9610 class HorizontalReduction {
9611   using ReductionOpsType = SmallVector<Value *, 16>;
9612   using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
9613   ReductionOpsListType ReductionOps;
9614   /// List of possibly reduced values.
9615   SmallVector<SmallVector<Value *>> ReducedVals;
9616   /// Maps reduced value to the corresponding reduction operation.
9617   DenseMap<Value *, SmallVector<Instruction *>> ReducedValsToOps;
9618   // Use map vector to make stable output.
9619   MapVector<Instruction *, Value *> ExtraArgs;
9620   WeakTrackingVH ReductionRoot;
9621   /// The type of reduction operation.
9622   RecurKind RdxKind;
9623 
9624   static bool isCmpSelMinMax(Instruction *I) {
9625     return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) &&
9626            RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I));
9627   }
9628 
9629   // And/or are potentially poison-safe logical patterns like:
9630   // select x, y, false
9631   // select x, true, y
9632   static bool isBoolLogicOp(Instruction *I) {
9633     return match(I, m_LogicalAnd(m_Value(), m_Value())) ||
9634            match(I, m_LogicalOr(m_Value(), m_Value()));
9635   }
9636 
9637   /// Checks if instruction is associative and can be vectorized.
9638   static bool isVectorizable(RecurKind Kind, Instruction *I) {
9639     if (Kind == RecurKind::None)
9640       return false;
9641 
9642     // Integer ops that map to select instructions or intrinsics are fine.
9643     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) ||
9644         isBoolLogicOp(I))
9645       return true;
9646 
9647     if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) {
9648       // FP min/max are associative except for NaN and -0.0. We do not
9649       // have to rule out -0.0 here because the intrinsic semantics do not
9650       // specify a fixed result for it.
9651       return I->getFastMathFlags().noNaNs();
9652     }
9653 
9654     return I->isAssociative();
9655   }
9656 
9657   static Value *getRdxOperand(Instruction *I, unsigned Index) {
9658     // Poison-safe 'or' takes the form: select X, true, Y
9659     // To make that work with the normal operand processing, we skip the
9660     // true value operand.
9661     // TODO: Change the code and data structures to handle this without a hack.
9662     if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1)
9663       return I->getOperand(2);
9664     return I->getOperand(Index);
9665   }
9666 
9667   /// Creates reduction operation with the current opcode.
9668   static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS,
9669                          Value *RHS, const Twine &Name, bool UseSelect) {
9670     unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind);
9671     switch (Kind) {
9672     case RecurKind::Or:
9673       if (UseSelect &&
9674           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9675         return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name);
9676       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9677                                  Name);
9678     case RecurKind::And:
9679       if (UseSelect &&
9680           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9681         return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name);
9682       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9683                                  Name);
9684     case RecurKind::Add:
9685     case RecurKind::Mul:
9686     case RecurKind::Xor:
9687     case RecurKind::FAdd:
9688     case RecurKind::FMul:
9689       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9690                                  Name);
9691     case RecurKind::FMax:
9692       return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS);
9693     case RecurKind::FMin:
9694       return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS);
9695     case RecurKind::SMax:
9696       if (UseSelect) {
9697         Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name);
9698         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9699       }
9700       return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS);
9701     case RecurKind::SMin:
9702       if (UseSelect) {
9703         Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name);
9704         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9705       }
9706       return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS);
9707     case RecurKind::UMax:
9708       if (UseSelect) {
9709         Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name);
9710         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9711       }
9712       return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS);
9713     case RecurKind::UMin:
9714       if (UseSelect) {
9715         Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name);
9716         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9717       }
9718       return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS);
9719     default:
9720       llvm_unreachable("Unknown reduction operation.");
9721     }
9722   }
9723 
9724   /// Creates reduction operation with the current opcode with the IR flags
9725   /// from \p ReductionOps.
9726   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9727                          Value *RHS, const Twine &Name,
9728                          const ReductionOpsListType &ReductionOps) {
9729     bool UseSelect = ReductionOps.size() == 2 ||
9730                      // Logical or/and.
9731                      (ReductionOps.size() == 1 &&
9732                       isa<SelectInst>(ReductionOps.front().front()));
9733     assert((!UseSelect || ReductionOps.size() != 2 ||
9734             isa<SelectInst>(ReductionOps[1][0])) &&
9735            "Expected cmp + select pairs for reduction");
9736     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect);
9737     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9738       if (auto *Sel = dyn_cast<SelectInst>(Op)) {
9739         propagateIRFlags(Sel->getCondition(), ReductionOps[0]);
9740         propagateIRFlags(Op, ReductionOps[1]);
9741         return Op;
9742       }
9743     }
9744     propagateIRFlags(Op, ReductionOps[0]);
9745     return Op;
9746   }
9747 
9748   /// Creates reduction operation with the current opcode with the IR flags
9749   /// from \p I.
9750   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9751                          Value *RHS, const Twine &Name, Value *I) {
9752     auto *SelI = dyn_cast<SelectInst>(I);
9753     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, SelI != nullptr);
9754     if (SelI && RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9755       if (auto *Sel = dyn_cast<SelectInst>(Op))
9756         propagateIRFlags(Sel->getCondition(), SelI->getCondition());
9757     }
9758     propagateIRFlags(Op, I);
9759     return Op;
9760   }
9761 
9762   static RecurKind getRdxKind(Value *V) {
9763     auto *I = dyn_cast<Instruction>(V);
9764     if (!I)
9765       return RecurKind::None;
9766     if (match(I, m_Add(m_Value(), m_Value())))
9767       return RecurKind::Add;
9768     if (match(I, m_Mul(m_Value(), m_Value())))
9769       return RecurKind::Mul;
9770     if (match(I, m_And(m_Value(), m_Value())) ||
9771         match(I, m_LogicalAnd(m_Value(), m_Value())))
9772       return RecurKind::And;
9773     if (match(I, m_Or(m_Value(), m_Value())) ||
9774         match(I, m_LogicalOr(m_Value(), m_Value())))
9775       return RecurKind::Or;
9776     if (match(I, m_Xor(m_Value(), m_Value())))
9777       return RecurKind::Xor;
9778     if (match(I, m_FAdd(m_Value(), m_Value())))
9779       return RecurKind::FAdd;
9780     if (match(I, m_FMul(m_Value(), m_Value())))
9781       return RecurKind::FMul;
9782 
9783     if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value())))
9784       return RecurKind::FMax;
9785     if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value())))
9786       return RecurKind::FMin;
9787 
9788     // This matches either cmp+select or intrinsics. SLP is expected to handle
9789     // either form.
9790     // TODO: If we are canonicalizing to intrinsics, we can remove several
9791     //       special-case paths that deal with selects.
9792     if (match(I, m_SMax(m_Value(), m_Value())))
9793       return RecurKind::SMax;
9794     if (match(I, m_SMin(m_Value(), m_Value())))
9795       return RecurKind::SMin;
9796     if (match(I, m_UMax(m_Value(), m_Value())))
9797       return RecurKind::UMax;
9798     if (match(I, m_UMin(m_Value(), m_Value())))
9799       return RecurKind::UMin;
9800 
9801     if (auto *Select = dyn_cast<SelectInst>(I)) {
9802       // Try harder: look for min/max pattern based on instructions producing
9803       // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
9804       // During the intermediate stages of SLP, it's very common to have
9805       // pattern like this (since optimizeGatherSequence is run only once
9806       // at the end):
9807       // %1 = extractelement <2 x i32> %a, i32 0
9808       // %2 = extractelement <2 x i32> %a, i32 1
9809       // %cond = icmp sgt i32 %1, %2
9810       // %3 = extractelement <2 x i32> %a, i32 0
9811       // %4 = extractelement <2 x i32> %a, i32 1
9812       // %select = select i1 %cond, i32 %3, i32 %4
9813       CmpInst::Predicate Pred;
9814       Instruction *L1;
9815       Instruction *L2;
9816 
9817       Value *LHS = Select->getTrueValue();
9818       Value *RHS = Select->getFalseValue();
9819       Value *Cond = Select->getCondition();
9820 
9821       // TODO: Support inverse predicates.
9822       if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
9823         if (!isa<ExtractElementInst>(RHS) ||
9824             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9825           return RecurKind::None;
9826       } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
9827         if (!isa<ExtractElementInst>(LHS) ||
9828             !L1->isIdenticalTo(cast<Instruction>(LHS)))
9829           return RecurKind::None;
9830       } else {
9831         if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
9832           return RecurKind::None;
9833         if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
9834             !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
9835             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9836           return RecurKind::None;
9837       }
9838 
9839       switch (Pred) {
9840       default:
9841         return RecurKind::None;
9842       case CmpInst::ICMP_SGT:
9843       case CmpInst::ICMP_SGE:
9844         return RecurKind::SMax;
9845       case CmpInst::ICMP_SLT:
9846       case CmpInst::ICMP_SLE:
9847         return RecurKind::SMin;
9848       case CmpInst::ICMP_UGT:
9849       case CmpInst::ICMP_UGE:
9850         return RecurKind::UMax;
9851       case CmpInst::ICMP_ULT:
9852       case CmpInst::ICMP_ULE:
9853         return RecurKind::UMin;
9854       }
9855     }
9856     return RecurKind::None;
9857   }
9858 
9859   /// Get the index of the first operand.
9860   static unsigned getFirstOperandIndex(Instruction *I) {
9861     return isCmpSelMinMax(I) ? 1 : 0;
9862   }
9863 
9864   /// Total number of operands in the reduction operation.
9865   static unsigned getNumberOfOperands(Instruction *I) {
9866     return isCmpSelMinMax(I) ? 3 : 2;
9867   }
9868 
9869   /// Checks if the instruction is in basic block \p BB.
9870   /// For a cmp+sel min/max reduction check that both ops are in \p BB.
9871   static bool hasSameParent(Instruction *I, BasicBlock *BB) {
9872     if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) {
9873       auto *Sel = cast<SelectInst>(I);
9874       auto *Cmp = dyn_cast<Instruction>(Sel->getCondition());
9875       return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB;
9876     }
9877     return I->getParent() == BB;
9878   }
9879 
9880   /// Expected number of uses for reduction operations/reduced values.
9881   static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) {
9882     if (IsCmpSelMinMax) {
9883       // SelectInst must be used twice while the condition op must have single
9884       // use only.
9885       if (auto *Sel = dyn_cast<SelectInst>(I))
9886         return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse();
9887       return I->hasNUses(2);
9888     }
9889 
9890     // Arithmetic reduction operation must be used once only.
9891     return I->hasOneUse();
9892   }
9893 
9894   /// Initializes the list of reduction operations.
9895   void initReductionOps(Instruction *I) {
9896     if (isCmpSelMinMax(I))
9897       ReductionOps.assign(2, ReductionOpsType());
9898     else
9899       ReductionOps.assign(1, ReductionOpsType());
9900   }
9901 
9902   /// Add all reduction operations for the reduction instruction \p I.
9903   void addReductionOps(Instruction *I) {
9904     if (isCmpSelMinMax(I)) {
9905       ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
9906       ReductionOps[1].emplace_back(I);
9907     } else {
9908       ReductionOps[0].emplace_back(I);
9909     }
9910   }
9911 
9912   static Value *getLHS(RecurKind Kind, Instruction *I) {
9913     if (Kind == RecurKind::None)
9914       return nullptr;
9915     return I->getOperand(getFirstOperandIndex(I));
9916   }
9917   static Value *getRHS(RecurKind Kind, Instruction *I) {
9918     if (Kind == RecurKind::None)
9919       return nullptr;
9920     return I->getOperand(getFirstOperandIndex(I) + 1);
9921   }
9922 
9923 public:
9924   HorizontalReduction() = default;
9925 
9926   /// Try to find a reduction tree.
9927   bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst,
9928                                  ScalarEvolution &SE, const DataLayout &DL,
9929                                  const TargetLibraryInfo &TLI) {
9930     assert((!Phi || is_contained(Phi->operands(), Inst)) &&
9931            "Phi needs to use the binary operator");
9932     assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) ||
9933             isa<IntrinsicInst>(Inst)) &&
9934            "Expected binop, select, or intrinsic for reduction matching");
9935     RdxKind = getRdxKind(Inst);
9936 
9937     // We could have a initial reductions that is not an add.
9938     //  r *= v1 + v2 + v3 + v4
9939     // In such a case start looking for a tree rooted in the first '+'.
9940     if (Phi) {
9941       if (getLHS(RdxKind, Inst) == Phi) {
9942         Phi = nullptr;
9943         Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst));
9944         if (!Inst)
9945           return false;
9946         RdxKind = getRdxKind(Inst);
9947       } else if (getRHS(RdxKind, Inst) == Phi) {
9948         Phi = nullptr;
9949         Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst));
9950         if (!Inst)
9951           return false;
9952         RdxKind = getRdxKind(Inst);
9953       }
9954     }
9955 
9956     if (!isVectorizable(RdxKind, Inst))
9957       return false;
9958 
9959     // Analyze "regular" integer/FP types for reductions - no target-specific
9960     // types or pointers.
9961     Type *Ty = Inst->getType();
9962     if (!isValidElementType(Ty) || Ty->isPointerTy())
9963       return false;
9964 
9965     // Though the ultimate reduction may have multiple uses, its condition must
9966     // have only single use.
9967     if (auto *Sel = dyn_cast<SelectInst>(Inst))
9968       if (!Sel->getCondition()->hasOneUse())
9969         return false;
9970 
9971     ReductionRoot = Inst;
9972 
9973     // Iterate through all the operands of the possible reduction tree and
9974     // gather all the reduced values, sorting them by their value id.
9975     BasicBlock *BB = Inst->getParent();
9976     bool IsCmpSelMinMax = isCmpSelMinMax(Inst);
9977     SmallVector<Instruction *> Worklist(1, Inst);
9978     // Checks if the operands of the \p TreeN instruction are also reduction
9979     // operations or should be treated as reduced values or an extra argument,
9980     // which is not part of the reduction.
9981     auto &&CheckOperands = [this, IsCmpSelMinMax,
9982                             BB](Instruction *TreeN,
9983                                 SmallVectorImpl<Value *> &ExtraArgs,
9984                                 SmallVectorImpl<Value *> &PossibleReducedVals,
9985                                 SmallVectorImpl<Instruction *> &ReductionOps) {
9986       for (int I = getFirstOperandIndex(TreeN),
9987                End = getNumberOfOperands(TreeN);
9988            I < End; ++I) {
9989         Value *EdgeVal = getRdxOperand(TreeN, I);
9990         ReducedValsToOps[EdgeVal].push_back(TreeN);
9991         auto *EdgeInst = dyn_cast<Instruction>(EdgeVal);
9992         // Edge has wrong parent - mark as an extra argument.
9993         if (EdgeInst && !isVectorLikeInstWithConstOps(EdgeInst) &&
9994             !hasSameParent(EdgeInst, BB)) {
9995           ExtraArgs.push_back(EdgeVal);
9996           continue;
9997         }
9998         // If the edge is not an instruction, or it is different from the main
9999         // reduction opcode or has too many uses - possible reduced value.
10000         if (!EdgeInst || getRdxKind(EdgeInst) != RdxKind ||
10001             !hasRequiredNumberOfUses(IsCmpSelMinMax, EdgeInst) ||
10002             !isVectorizable(getRdxKind(EdgeInst), EdgeInst)) {
10003           PossibleReducedVals.push_back(EdgeVal);
10004           continue;
10005         }
10006         ReductionOps.push_back(EdgeInst);
10007       }
10008     };
10009     // Try to regroup reduced values so that it gets more profitable to try to
10010     // reduce them. Values are grouped by their value ids, instructions - by
10011     // instruction op id and/or alternate op id, plus do extra analysis for
10012     // loads (grouping them by the distabce between pointers) and cmp
10013     // instructions (grouping them by the predicate).
10014     MapVector<size_t, MapVector<size_t, MapVector<Value *, unsigned>>>
10015         PossibleReducedVals;
10016     initReductionOps(Inst);
10017     while (!Worklist.empty()) {
10018       Instruction *TreeN = Worklist.pop_back_val();
10019       SmallVector<Value *> Args;
10020       SmallVector<Value *> PossibleRedVals;
10021       SmallVector<Instruction *> PossibleReductionOps;
10022       CheckOperands(TreeN, Args, PossibleRedVals, PossibleReductionOps);
10023       // If too many extra args - mark the instruction itself as a reduction
10024       // value, not a reduction operation.
10025       if (Args.size() < 2) {
10026         addReductionOps(TreeN);
10027         // Add extra args.
10028         if (!Args.empty()) {
10029           assert(Args.size() == 1 && "Expected only single argument.");
10030           ExtraArgs[TreeN] = Args.front();
10031         }
10032         // Add reduction values. The values are sorted for better vectorization
10033         // results.
10034         for (Value *V : PossibleRedVals) {
10035           size_t Key, Idx;
10036           std::tie(Key, Idx) = generateKeySubkey(
10037               V, &TLI,
10038               [&PossibleReducedVals, &DL, &SE](size_t Key, LoadInst *LI) {
10039                 for (const auto &LoadData : PossibleReducedVals[Key]) {
10040                   auto *RLI = cast<LoadInst>(LoadData.second.front().first);
10041                   if (getPointersDiff(RLI->getType(), RLI->getPointerOperand(),
10042                                       LI->getType(), LI->getPointerOperand(),
10043                                       DL, SE, /*StrictCheck=*/true))
10044                     return hash_value(RLI->getPointerOperand());
10045                 }
10046                 return hash_value(LI->getPointerOperand());
10047               },
10048               /*AllowAlternate=*/false);
10049           ++PossibleReducedVals[Key][Idx]
10050                 .insert(std::make_pair(V, 0))
10051                 .first->second;
10052         }
10053         Worklist.append(PossibleReductionOps.rbegin(),
10054                         PossibleReductionOps.rend());
10055       } else {
10056         size_t Key, Idx;
10057         std::tie(Key, Idx) = generateKeySubkey(
10058             TreeN, &TLI,
10059             [&PossibleReducedVals, &DL, &SE](size_t Key, LoadInst *LI) {
10060               for (const auto &LoadData : PossibleReducedVals[Key]) {
10061                 auto *RLI = cast<LoadInst>(LoadData.second.front().first);
10062                 if (getPointersDiff(RLI->getType(), RLI->getPointerOperand(),
10063                                     LI->getType(), LI->getPointerOperand(), DL,
10064                                     SE, /*StrictCheck=*/true))
10065                   return hash_value(RLI->getPointerOperand());
10066               }
10067               return hash_value(LI->getPointerOperand());
10068             },
10069             /*AllowAlternate=*/false);
10070         ++PossibleReducedVals[Key][Idx]
10071               .insert(std::make_pair(TreeN, 0))
10072               .first->second;
10073       }
10074     }
10075     auto PossibleReducedValsVect = PossibleReducedVals.takeVector();
10076     // Sort values by the total number of values kinds to start the reduction
10077     // from the longest possible reduced values sequences.
10078     for (auto &PossibleReducedVals : PossibleReducedValsVect) {
10079       auto PossibleRedVals = PossibleReducedVals.second.takeVector();
10080       SmallVector<SmallVector<Value *>> PossibleRedValsVect;
10081       for (auto It = PossibleRedVals.begin(), E = PossibleRedVals.end();
10082            It != E; ++It) {
10083         PossibleRedValsVect.emplace_back();
10084         auto RedValsVect = It->second.takeVector();
10085         stable_sort(RedValsVect, [](const auto &P1, const auto &P2) {
10086           return P1.second < P2.second;
10087         });
10088         for (const std::pair<Value *, unsigned> &Data : RedValsVect)
10089           PossibleRedValsVect.back().append(Data.second, Data.first);
10090       }
10091       stable_sort(PossibleRedValsVect, [](const auto &P1, const auto &P2) {
10092         return P1.size() > P2.size();
10093       });
10094       ReducedVals.emplace_back();
10095       for (ArrayRef<Value *> Data : PossibleRedValsVect)
10096         ReducedVals.back().append(Data.rbegin(), Data.rend());
10097     }
10098     // Sort the reduced values by number of same/alternate opcode and/or pointer
10099     // operand.
10100     stable_sort(ReducedVals, [](ArrayRef<Value *> P1, ArrayRef<Value *> P2) {
10101       return P1.size() > P2.size();
10102     });
10103     return true;
10104   }
10105 
10106   /// Attempt to vectorize the tree found by matchAssociativeReduction.
10107   Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
10108     constexpr int ReductionLimit = 4;
10109     // If there are a sufficient number of reduction values, reduce
10110     // to a nearby power-of-2. We can safely generate oversized
10111     // vectors and rely on the backend to split them to legal sizes.
10112     unsigned NumReducedVals = std::accumulate(
10113         ReducedVals.begin(), ReducedVals.end(), 0,
10114         [](int Num, ArrayRef<Value *> Vals) { return Num + Vals.size(); });
10115     if (NumReducedVals < ReductionLimit)
10116       return nullptr;
10117 
10118     IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
10119 
10120     // Track the reduced values in case if they are replaced by extractelement
10121     // because of the vectorization.
10122     DenseMap<Value *, WeakTrackingVH> TrackedVals;
10123     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
10124     // The same extra argument may be used several times, so log each attempt
10125     // to use it.
10126     for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) {
10127       assert(Pair.first && "DebugLoc must be set.");
10128       ExternallyUsedValues[Pair.second].push_back(Pair.first);
10129       TrackedVals.try_emplace(Pair.second, Pair.second);
10130     }
10131 
10132     // The compare instruction of a min/max is the insertion point for new
10133     // instructions and may be replaced with a new compare instruction.
10134     auto &&GetCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
10135       assert(isa<SelectInst>(RdxRootInst) &&
10136              "Expected min/max reduction to have select root instruction");
10137       Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
10138       assert(isa<Instruction>(ScalarCond) &&
10139              "Expected min/max reduction to have compare condition");
10140       return cast<Instruction>(ScalarCond);
10141     };
10142 
10143     // The reduction root is used as the insertion point for new instructions,
10144     // so set it as externally used to prevent it from being deleted.
10145     ExternallyUsedValues[ReductionRoot];
10146     SmallVector<Value *> IgnoreList;
10147     for (ReductionOpsType &RdxOps : ReductionOps)
10148       for (Value *RdxOp : RdxOps) {
10149         if (!RdxOp)
10150           continue;
10151         IgnoreList.push_back(RdxOp);
10152       }
10153     bool IsCmpSelMinMax = isCmpSelMinMax(cast<Instruction>(ReductionRoot));
10154 
10155     // Need to track reduced vals, they may be changed during vectorization of
10156     // subvectors.
10157     for (ArrayRef<Value *> Candidates : ReducedVals)
10158       for (Value *V : Candidates)
10159         TrackedVals.try_emplace(V, V);
10160 
10161     DenseMap<Value *, unsigned> VectorizedVals;
10162     Value *VectorizedTree = nullptr;
10163     bool CheckForReusedReductionOps = false;
10164     // Try to vectorize elements based on their type.
10165     for (unsigned I = 0, E = ReducedVals.size(); I < E; ++I) {
10166       ArrayRef<Value *> OrigReducedVals = ReducedVals[I];
10167       InstructionsState S = getSameOpcode(OrigReducedVals);
10168       SmallVector<Value *> Candidates;
10169       DenseMap<Value *, Value *> TrackedToOrig;
10170       for (unsigned Cnt = 0, Sz = OrigReducedVals.size(); Cnt < Sz; ++Cnt) {
10171         Value *RdxVal = TrackedVals.find(OrigReducedVals[Cnt])->second;
10172         // Check if the reduction value was not overriden by the extractelement
10173         // instruction because of the vectorization and exclude it, if it is not
10174         // compatible with other values.
10175         if (auto *Inst = dyn_cast<Instruction>(RdxVal))
10176           if (isVectorLikeInstWithConstOps(Inst) &&
10177               (!S.getOpcode() || !S.isOpcodeOrAlt(Inst)))
10178             continue;
10179         Candidates.push_back(RdxVal);
10180         TrackedToOrig.try_emplace(RdxVal, OrigReducedVals[Cnt]);
10181       }
10182       bool ShuffledExtracts = false;
10183       // Try to handle shuffled extractelements.
10184       if (S.getOpcode() == Instruction::ExtractElement && !S.isAltShuffle() &&
10185           I + 1 < E) {
10186         InstructionsState NextS = getSameOpcode(ReducedVals[I + 1]);
10187         if (NextS.getOpcode() == Instruction::ExtractElement &&
10188             !NextS.isAltShuffle()) {
10189           SmallVector<Value *> CommonCandidates(Candidates);
10190           for (Value *RV : ReducedVals[I + 1]) {
10191             Value *RdxVal = TrackedVals.find(RV)->second;
10192             // Check if the reduction value was not overriden by the
10193             // extractelement instruction because of the vectorization and
10194             // exclude it, if it is not compatible with other values.
10195             if (auto *Inst = dyn_cast<Instruction>(RdxVal))
10196               if (!NextS.getOpcode() || !NextS.isOpcodeOrAlt(Inst))
10197                 continue;
10198             CommonCandidates.push_back(RdxVal);
10199             TrackedToOrig.try_emplace(RdxVal, RV);
10200           }
10201           SmallVector<int> Mask;
10202           if (isFixedVectorShuffle(CommonCandidates, Mask)) {
10203             ++I;
10204             Candidates.swap(CommonCandidates);
10205             ShuffledExtracts = true;
10206           }
10207         }
10208       }
10209       unsigned NumReducedVals = Candidates.size();
10210       if (NumReducedVals < ReductionLimit)
10211         continue;
10212 
10213       unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
10214       unsigned Start = 0;
10215       unsigned Pos = Start;
10216       // Restarts vectorization attempt with lower vector factor.
10217       unsigned PrevReduxWidth = ReduxWidth;
10218       bool CheckForReusedReductionOpsLocal = false;
10219       auto &&AdjustReducedVals = [&Pos, &Start, &ReduxWidth, NumReducedVals,
10220                                   &CheckForReusedReductionOpsLocal,
10221                                   &PrevReduxWidth, &V,
10222                                   &IgnoreList](bool IgnoreVL = false) {
10223         bool IsAnyRedOpGathered =
10224             !IgnoreVL && any_of(IgnoreList, [&V](Value *RedOp) {
10225               return V.isGathered(RedOp);
10226             });
10227         if (!CheckForReusedReductionOpsLocal && PrevReduxWidth == ReduxWidth) {
10228           // Check if any of the reduction ops are gathered. If so, worth
10229           // trying again with less number of reduction ops.
10230           CheckForReusedReductionOpsLocal |= IsAnyRedOpGathered;
10231         }
10232         ++Pos;
10233         if (Pos < NumReducedVals - ReduxWidth + 1)
10234           return IsAnyRedOpGathered;
10235         Pos = Start;
10236         ReduxWidth /= 2;
10237         return IsAnyRedOpGathered;
10238       };
10239       while (Pos < NumReducedVals - ReduxWidth + 1 &&
10240              ReduxWidth >= ReductionLimit) {
10241         // Dependency in tree of the reduction ops - drop this attempt, try
10242         // later.
10243         if (CheckForReusedReductionOpsLocal && PrevReduxWidth != ReduxWidth &&
10244             Start == 0) {
10245           CheckForReusedReductionOps = true;
10246           break;
10247         }
10248         PrevReduxWidth = ReduxWidth;
10249         ArrayRef<Value *> VL(std::next(Candidates.begin(), Pos), ReduxWidth);
10250         // Beeing analyzed already - skip.
10251         if (V.areAnalyzedReductionVals(VL)) {
10252           (void)AdjustReducedVals(/*IgnoreVL=*/true);
10253           continue;
10254         }
10255         // Early exit if any of the reduction values were deleted during
10256         // previous vectorization attempts.
10257         if (any_of(VL, [&V](Value *RedVal) {
10258               auto *RedValI = dyn_cast<Instruction>(RedVal);
10259               if (!RedValI)
10260                 return false;
10261               return V.isDeleted(RedValI);
10262             }))
10263           break;
10264         V.buildTree(VL, IgnoreList);
10265         if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true)) {
10266           if (!AdjustReducedVals())
10267             V.analyzedReductionVals(VL);
10268           continue;
10269         }
10270         if (V.isLoadCombineReductionCandidate(RdxKind)) {
10271           if (!AdjustReducedVals())
10272             V.analyzedReductionVals(VL);
10273           continue;
10274         }
10275         V.reorderTopToBottom();
10276         // No need to reorder the root node at all.
10277         V.reorderBottomToTop(/*IgnoreReorder=*/true);
10278         // Keep extracted other reduction values, if they are used in the
10279         // vectorization trees.
10280         BoUpSLP::ExtraValueToDebugLocsMap LocalExternallyUsedValues(
10281             ExternallyUsedValues);
10282         for (unsigned Cnt = 0, Sz = ReducedVals.size(); Cnt < Sz; ++Cnt) {
10283           if (Cnt == I || (ShuffledExtracts && Cnt == I - 1))
10284             continue;
10285           for_each(ReducedVals[Cnt],
10286                    [&LocalExternallyUsedValues, &TrackedVals](Value *V) {
10287                      if (isa<Instruction>(V))
10288                        LocalExternallyUsedValues[TrackedVals[V]];
10289                    });
10290         }
10291         for (unsigned Cnt = 0; Cnt < NumReducedVals; ++Cnt) {
10292           if (Cnt >= Pos && Cnt < Pos + ReduxWidth)
10293             continue;
10294           if (VectorizedVals.count(Candidates[Cnt]))
10295             continue;
10296           LocalExternallyUsedValues[Candidates[Cnt]];
10297         }
10298         V.buildExternalUses(LocalExternallyUsedValues);
10299 
10300         V.computeMinimumValueSizes();
10301 
10302         // Intersect the fast-math-flags from all reduction operations.
10303         FastMathFlags RdxFMF;
10304         RdxFMF.set();
10305         for (Value *U : IgnoreList)
10306           if (auto *FPMO = dyn_cast<FPMathOperator>(U))
10307             RdxFMF &= FPMO->getFastMathFlags();
10308         // Estimate cost.
10309         InstructionCost TreeCost = V.getTreeCost(VL);
10310         InstructionCost ReductionCost =
10311             getReductionCost(TTI, VL[0], ReduxWidth, RdxFMF);
10312         InstructionCost Cost = TreeCost + ReductionCost;
10313         if (!Cost.isValid()) {
10314           LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n");
10315           return nullptr;
10316         }
10317         if (Cost >= -SLPCostThreshold) {
10318           V.getORE()->emit([&]() {
10319             return OptimizationRemarkMissed(
10320                        SV_NAME, "HorSLPNotBeneficial",
10321                        ReducedValsToOps.find(VL[0])->second.front())
10322                    << "Vectorizing horizontal reduction is possible"
10323                    << "but not beneficial with cost " << ore::NV("Cost", Cost)
10324                    << " and threshold "
10325                    << ore::NV("Threshold", -SLPCostThreshold);
10326           });
10327           if (!AdjustReducedVals())
10328             V.analyzedReductionVals(VL);
10329           continue;
10330         }
10331 
10332         LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
10333                           << Cost << ". (HorRdx)\n");
10334         V.getORE()->emit([&]() {
10335           return OptimizationRemark(
10336                      SV_NAME, "VectorizedHorizontalReduction",
10337                      ReducedValsToOps.find(VL[0])->second.front())
10338                  << "Vectorized horizontal reduction with cost "
10339                  << ore::NV("Cost", Cost) << " and with tree size "
10340                  << ore::NV("TreeSize", V.getTreeSize());
10341         });
10342 
10343         Builder.setFastMathFlags(RdxFMF);
10344 
10345         // Vectorize a tree.
10346         Value *VectorizedRoot = V.vectorizeTree(LocalExternallyUsedValues);
10347 
10348         // Emit a reduction. If the root is a select (min/max idiom), the insert
10349         // point is the compare condition of that select.
10350         Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
10351         if (IsCmpSelMinMax)
10352           Builder.SetInsertPoint(GetCmpForMinMaxReduction(RdxRootInst));
10353         else
10354           Builder.SetInsertPoint(RdxRootInst);
10355 
10356         // To prevent poison from leaking across what used to be sequential,
10357         // safe, scalar boolean logic operations, the reduction operand must be
10358         // frozen.
10359         if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst))
10360           VectorizedRoot = Builder.CreateFreeze(VectorizedRoot);
10361 
10362         Value *ReducedSubTree =
10363             emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
10364 
10365         if (!VectorizedTree) {
10366           // Initialize the final value in the reduction.
10367           VectorizedTree = ReducedSubTree;
10368         } else {
10369           // Update the final value in the reduction.
10370           Builder.SetCurrentDebugLocation(
10371               cast<Instruction>(ReductionOps.front().front())->getDebugLoc());
10372           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
10373                                     ReducedSubTree, "op.rdx", ReductionOps);
10374         }
10375         // Count vectorized reduced values to exclude them from final reduction.
10376         for (Value *V : VL)
10377           ++VectorizedVals.try_emplace(TrackedToOrig.find(V)->second, 0)
10378                 .first->getSecond();
10379         Pos += ReduxWidth;
10380         Start = Pos;
10381         ReduxWidth = PowerOf2Floor(NumReducedVals - Pos);
10382       }
10383     }
10384     if (VectorizedTree) {
10385       // Finish the reduction.
10386       // Need to add extra arguments and not vectorized possible reduction
10387       // values.
10388       SmallPtrSet<Value *, 8> Visited;
10389       for (unsigned I = 0, E = ReducedVals.size(); I < E; ++I) {
10390         ArrayRef<Value *> Candidates = ReducedVals[I];
10391         for (Value *RdxVal : Candidates) {
10392           if (!Visited.insert(RdxVal).second)
10393             continue;
10394           Value *StableRdxVal = RdxVal;
10395           auto TVIt = TrackedVals.find(RdxVal);
10396           if (TVIt != TrackedVals.end())
10397             StableRdxVal = TVIt->second;
10398           unsigned NumOps = 0;
10399           auto It = VectorizedVals.find(RdxVal);
10400           if (It != VectorizedVals.end())
10401             NumOps = It->second;
10402           for (Instruction *RedOp :
10403                makeArrayRef(ReducedValsToOps.find(RdxVal)->second)
10404                    .drop_back(NumOps)) {
10405             Builder.SetCurrentDebugLocation(RedOp->getDebugLoc());
10406             ReductionOpsListType Ops;
10407             if (auto *Sel = dyn_cast<SelectInst>(RedOp))
10408               Ops.emplace_back().push_back(Sel->getCondition());
10409             Ops.emplace_back().push_back(RedOp);
10410             VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
10411                                       StableRdxVal, "op.rdx", Ops);
10412           }
10413         }
10414       }
10415       for (auto &Pair : ExternallyUsedValues) {
10416         // Add each externally used value to the final reduction.
10417         for (auto *I : Pair.second) {
10418           Builder.SetCurrentDebugLocation(I->getDebugLoc());
10419           ReductionOpsListType Ops;
10420           if (auto *Sel = dyn_cast<SelectInst>(I))
10421             Ops.emplace_back().push_back(Sel->getCondition());
10422           Ops.emplace_back().push_back(I);
10423           Value *StableRdxVal = Pair.first;
10424           auto TVIt = TrackedVals.find(Pair.first);
10425           if (TVIt != TrackedVals.end())
10426             StableRdxVal = TVIt->second;
10427           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
10428                                     StableRdxVal, "op.rdx", Ops);
10429         }
10430       }
10431 
10432       ReductionRoot->replaceAllUsesWith(VectorizedTree);
10433 
10434       // The original scalar reduction is expected to have no remaining
10435       // uses outside the reduction tree itself.  Assert that we got this
10436       // correct, replace internal uses with undef, and mark for eventual
10437       // deletion.
10438 #ifndef NDEBUG
10439       SmallSet<Value *, 4> IgnoreSet;
10440       for (ArrayRef<Value *> RdxOps : ReductionOps)
10441         IgnoreSet.insert(RdxOps.begin(), RdxOps.end());
10442 #endif
10443       for (ArrayRef<Value *> RdxOps : ReductionOps) {
10444         for (Value *Ignore : RdxOps) {
10445           if (!Ignore)
10446             continue;
10447 #ifndef NDEBUG
10448           for (auto *U : Ignore->users()) {
10449             assert(IgnoreSet.count(U) &&
10450                    "All users must be either in the reduction ops list.");
10451           }
10452 #endif
10453           if (!Ignore->use_empty()) {
10454             Value *Undef = UndefValue::get(Ignore->getType());
10455             Ignore->replaceAllUsesWith(Undef);
10456           }
10457           V.eraseInstruction(cast<Instruction>(Ignore));
10458         }
10459       }
10460     } else if (!CheckForReusedReductionOps) {
10461       for (ReductionOpsType &RdxOps : ReductionOps)
10462         for (Value *RdxOp : RdxOps)
10463           V.analyzedReductionRoot(cast<Instruction>(RdxOp));
10464     }
10465     return VectorizedTree;
10466   }
10467 
10468   unsigned numReductionValues() const { return ReducedVals.size(); }
10469 
10470 private:
10471   /// Calculate the cost of a reduction.
10472   InstructionCost getReductionCost(TargetTransformInfo *TTI,
10473                                    Value *FirstReducedVal, unsigned ReduxWidth,
10474                                    FastMathFlags FMF) {
10475     TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
10476     Type *ScalarTy = FirstReducedVal->getType();
10477     FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth);
10478     InstructionCost VectorCost, ScalarCost;
10479     switch (RdxKind) {
10480     case RecurKind::Add:
10481     case RecurKind::Mul:
10482     case RecurKind::Or:
10483     case RecurKind::And:
10484     case RecurKind::Xor:
10485     case RecurKind::FAdd:
10486     case RecurKind::FMul: {
10487       unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind);
10488       VectorCost =
10489           TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind);
10490       ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind);
10491       break;
10492     }
10493     case RecurKind::FMax:
10494     case RecurKind::FMin: {
10495       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
10496       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
10497       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
10498                                                /*IsUnsigned=*/false, CostKind);
10499       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
10500       ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy,
10501                                            SclCondTy, RdxPred, CostKind) +
10502                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
10503                                            SclCondTy, RdxPred, CostKind);
10504       break;
10505     }
10506     case RecurKind::SMax:
10507     case RecurKind::SMin:
10508     case RecurKind::UMax:
10509     case RecurKind::UMin: {
10510       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
10511       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
10512       bool IsUnsigned =
10513           RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin;
10514       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, IsUnsigned,
10515                                                CostKind);
10516       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
10517       ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
10518                                            SclCondTy, RdxPred, CostKind) +
10519                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
10520                                            SclCondTy, RdxPred, CostKind);
10521       break;
10522     }
10523     default:
10524       llvm_unreachable("Expected arithmetic or min/max reduction operation");
10525     }
10526 
10527     // Scalar cost is repeated for N-1 elements.
10528     ScalarCost *= (ReduxWidth - 1);
10529     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost
10530                       << " for reduction that starts with " << *FirstReducedVal
10531                       << " (It is a splitting reduction)\n");
10532     return VectorCost - ScalarCost;
10533   }
10534 
10535   /// Emit a horizontal reduction of the vectorized value.
10536   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
10537                        unsigned ReduxWidth, const TargetTransformInfo *TTI) {
10538     assert(VectorizedValue && "Need to have a vectorized tree node");
10539     assert(isPowerOf2_32(ReduxWidth) &&
10540            "We only handle power-of-two reductions for now");
10541     assert(RdxKind != RecurKind::FMulAdd &&
10542            "A call to the llvm.fmuladd intrinsic is not handled yet");
10543 
10544     ++NumVectorInstructions;
10545     return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind);
10546   }
10547 };
10548 
10549 } // end anonymous namespace
10550 
10551 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) {
10552   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
10553     return cast<FixedVectorType>(IE->getType())->getNumElements();
10554 
10555   unsigned AggregateSize = 1;
10556   auto *IV = cast<InsertValueInst>(InsertInst);
10557   Type *CurrentType = IV->getType();
10558   do {
10559     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
10560       for (auto *Elt : ST->elements())
10561         if (Elt != ST->getElementType(0)) // check homogeneity
10562           return None;
10563       AggregateSize *= ST->getNumElements();
10564       CurrentType = ST->getElementType(0);
10565     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
10566       AggregateSize *= AT->getNumElements();
10567       CurrentType = AT->getElementType();
10568     } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
10569       AggregateSize *= VT->getNumElements();
10570       return AggregateSize;
10571     } else if (CurrentType->isSingleValueType()) {
10572       return AggregateSize;
10573     } else {
10574       return None;
10575     }
10576   } while (true);
10577 }
10578 
10579 static void findBuildAggregate_rec(Instruction *LastInsertInst,
10580                                    TargetTransformInfo *TTI,
10581                                    SmallVectorImpl<Value *> &BuildVectorOpds,
10582                                    SmallVectorImpl<Value *> &InsertElts,
10583                                    unsigned OperandOffset) {
10584   do {
10585     Value *InsertedOperand = LastInsertInst->getOperand(1);
10586     Optional<unsigned> OperandIndex =
10587         getInsertIndex(LastInsertInst, OperandOffset);
10588     if (!OperandIndex)
10589       return;
10590     if (isa<InsertElementInst>(InsertedOperand) ||
10591         isa<InsertValueInst>(InsertedOperand)) {
10592       findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI,
10593                              BuildVectorOpds, InsertElts, *OperandIndex);
10594 
10595     } else {
10596       BuildVectorOpds[*OperandIndex] = InsertedOperand;
10597       InsertElts[*OperandIndex] = LastInsertInst;
10598     }
10599     LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0));
10600   } while (LastInsertInst != nullptr &&
10601            (isa<InsertValueInst>(LastInsertInst) ||
10602             isa<InsertElementInst>(LastInsertInst)) &&
10603            LastInsertInst->hasOneUse());
10604 }
10605 
10606 /// Recognize construction of vectors like
10607 ///  %ra = insertelement <4 x float> poison, float %s0, i32 0
10608 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
10609 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
10610 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
10611 ///  starting from the last insertelement or insertvalue instruction.
10612 ///
10613 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>},
10614 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
10615 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
10616 ///
10617 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
10618 ///
10619 /// \return true if it matches.
10620 static bool findBuildAggregate(Instruction *LastInsertInst,
10621                                TargetTransformInfo *TTI,
10622                                SmallVectorImpl<Value *> &BuildVectorOpds,
10623                                SmallVectorImpl<Value *> &InsertElts) {
10624 
10625   assert((isa<InsertElementInst>(LastInsertInst) ||
10626           isa<InsertValueInst>(LastInsertInst)) &&
10627          "Expected insertelement or insertvalue instruction!");
10628 
10629   assert((BuildVectorOpds.empty() && InsertElts.empty()) &&
10630          "Expected empty result vectors!");
10631 
10632   Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst);
10633   if (!AggregateSize)
10634     return false;
10635   BuildVectorOpds.resize(*AggregateSize);
10636   InsertElts.resize(*AggregateSize);
10637 
10638   findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts, 0);
10639   llvm::erase_value(BuildVectorOpds, nullptr);
10640   llvm::erase_value(InsertElts, nullptr);
10641   if (BuildVectorOpds.size() >= 2)
10642     return true;
10643 
10644   return false;
10645 }
10646 
10647 /// Try and get a reduction value from a phi node.
10648 ///
10649 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
10650 /// if they come from either \p ParentBB or a containing loop latch.
10651 ///
10652 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
10653 /// if not possible.
10654 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
10655                                 BasicBlock *ParentBB, LoopInfo *LI) {
10656   // There are situations where the reduction value is not dominated by the
10657   // reduction phi. Vectorizing such cases has been reported to cause
10658   // miscompiles. See PR25787.
10659   auto DominatedReduxValue = [&](Value *R) {
10660     return isa<Instruction>(R) &&
10661            DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
10662   };
10663 
10664   Value *Rdx = nullptr;
10665 
10666   // Return the incoming value if it comes from the same BB as the phi node.
10667   if (P->getIncomingBlock(0) == ParentBB) {
10668     Rdx = P->getIncomingValue(0);
10669   } else if (P->getIncomingBlock(1) == ParentBB) {
10670     Rdx = P->getIncomingValue(1);
10671   }
10672 
10673   if (Rdx && DominatedReduxValue(Rdx))
10674     return Rdx;
10675 
10676   // Otherwise, check whether we have a loop latch to look at.
10677   Loop *BBL = LI->getLoopFor(ParentBB);
10678   if (!BBL)
10679     return nullptr;
10680   BasicBlock *BBLatch = BBL->getLoopLatch();
10681   if (!BBLatch)
10682     return nullptr;
10683 
10684   // There is a loop latch, return the incoming value if it comes from
10685   // that. This reduction pattern occasionally turns up.
10686   if (P->getIncomingBlock(0) == BBLatch) {
10687     Rdx = P->getIncomingValue(0);
10688   } else if (P->getIncomingBlock(1) == BBLatch) {
10689     Rdx = P->getIncomingValue(1);
10690   }
10691 
10692   if (Rdx && DominatedReduxValue(Rdx))
10693     return Rdx;
10694 
10695   return nullptr;
10696 }
10697 
10698 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) {
10699   if (match(I, m_BinOp(m_Value(V0), m_Value(V1))))
10700     return true;
10701   if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1))))
10702     return true;
10703   if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1))))
10704     return true;
10705   if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1))))
10706     return true;
10707   if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1))))
10708     return true;
10709   if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1))))
10710     return true;
10711   if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1))))
10712     return true;
10713   return false;
10714 }
10715 
10716 /// Attempt to reduce a horizontal reduction.
10717 /// If it is legal to match a horizontal reduction feeding the phi node \a P
10718 /// with reduction operators \a Root (or one of its operands) in a basic block
10719 /// \a BB, then check if it can be done. If horizontal reduction is not found
10720 /// and root instruction is a binary operation, vectorization of the operands is
10721 /// attempted.
10722 /// \returns true if a horizontal reduction was matched and reduced or operands
10723 /// of one of the binary instruction were vectorized.
10724 /// \returns false if a horizontal reduction was not matched (or not possible)
10725 /// or no vectorization of any binary operation feeding \a Root instruction was
10726 /// performed.
10727 static bool tryToVectorizeHorReductionOrInstOperands(
10728     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
10729     TargetTransformInfo *TTI, ScalarEvolution &SE, const DataLayout &DL,
10730     const TargetLibraryInfo &TLI,
10731     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
10732   if (!ShouldVectorizeHor)
10733     return false;
10734 
10735   if (!Root)
10736     return false;
10737 
10738   if (Root->getParent() != BB || isa<PHINode>(Root))
10739     return false;
10740   // Start analysis starting from Root instruction. If horizontal reduction is
10741   // found, try to vectorize it. If it is not a horizontal reduction or
10742   // vectorization is not possible or not effective, and currently analyzed
10743   // instruction is a binary operation, try to vectorize the operands, using
10744   // pre-order DFS traversal order. If the operands were not vectorized, repeat
10745   // the same procedure considering each operand as a possible root of the
10746   // horizontal reduction.
10747   // Interrupt the process if the Root instruction itself was vectorized or all
10748   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
10749   // Skip the analysis of CmpInsts. Compiler implements postanalysis of the
10750   // CmpInsts so we can skip extra attempts in
10751   // tryToVectorizeHorReductionOrInstOperands and save compile time.
10752   std::queue<std::pair<Instruction *, unsigned>> Stack;
10753   Stack.emplace(Root, 0);
10754   SmallPtrSet<Value *, 8> VisitedInstrs;
10755   SmallVector<WeakTrackingVH> PostponedInsts;
10756   bool Res = false;
10757   auto &&TryToReduce = [TTI, &SE, &DL, &P, &R, &TLI](Instruction *Inst,
10758                                                      Value *&B0,
10759                                                      Value *&B1) -> Value * {
10760     if (R.isAnalizedReductionRoot(Inst))
10761       return nullptr;
10762     bool IsBinop = matchRdxBop(Inst, B0, B1);
10763     bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value()));
10764     if (IsBinop || IsSelect) {
10765       HorizontalReduction HorRdx;
10766       if (HorRdx.matchAssociativeReduction(P, Inst, SE, DL, TLI))
10767         return HorRdx.tryToReduce(R, TTI);
10768     }
10769     return nullptr;
10770   };
10771   while (!Stack.empty()) {
10772     Instruction *Inst;
10773     unsigned Level;
10774     std::tie(Inst, Level) = Stack.front();
10775     Stack.pop();
10776     // Do not try to analyze instruction that has already been vectorized.
10777     // This may happen when we vectorize instruction operands on a previous
10778     // iteration while stack was populated before that happened.
10779     if (R.isDeleted(Inst))
10780       continue;
10781     Value *B0 = nullptr, *B1 = nullptr;
10782     if (Value *V = TryToReduce(Inst, B0, B1)) {
10783       Res = true;
10784       // Set P to nullptr to avoid re-analysis of phi node in
10785       // matchAssociativeReduction function unless this is the root node.
10786       P = nullptr;
10787       if (auto *I = dyn_cast<Instruction>(V)) {
10788         // Try to find another reduction.
10789         Stack.emplace(I, Level);
10790         continue;
10791       }
10792     } else {
10793       bool IsBinop = B0 && B1;
10794       if (P && IsBinop) {
10795         Inst = dyn_cast<Instruction>(B0);
10796         if (Inst == P)
10797           Inst = dyn_cast<Instruction>(B1);
10798         if (!Inst) {
10799           // Set P to nullptr to avoid re-analysis of phi node in
10800           // matchAssociativeReduction function unless this is the root node.
10801           P = nullptr;
10802           continue;
10803         }
10804       }
10805       // Set P to nullptr to avoid re-analysis of phi node in
10806       // matchAssociativeReduction function unless this is the root node.
10807       P = nullptr;
10808       // Do not try to vectorize CmpInst operands, this is done separately.
10809       // Final attempt for binop args vectorization should happen after the loop
10810       // to try to find reductions.
10811       if (!isa<CmpInst, InsertElementInst, InsertValueInst>(Inst))
10812         PostponedInsts.push_back(Inst);
10813     }
10814 
10815     // Try to vectorize operands.
10816     // Continue analysis for the instruction from the same basic block only to
10817     // save compile time.
10818     if (++Level < RecursionMaxDepth)
10819       for (auto *Op : Inst->operand_values())
10820         if (VisitedInstrs.insert(Op).second)
10821           if (auto *I = dyn_cast<Instruction>(Op))
10822             // Do not try to vectorize CmpInst operands,  this is done
10823             // separately.
10824             if (!isa<PHINode, CmpInst, InsertElementInst, InsertValueInst>(I) &&
10825                 !R.isDeleted(I) && I->getParent() == BB)
10826               Stack.emplace(I, Level);
10827   }
10828   // Try to vectorized binops where reductions were not found.
10829   for (Value *V : PostponedInsts)
10830     if (auto *Inst = dyn_cast<Instruction>(V))
10831       if (!R.isDeleted(Inst))
10832         Res |= Vectorize(Inst, R);
10833   return Res;
10834 }
10835 
10836 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
10837                                                  BasicBlock *BB, BoUpSLP &R,
10838                                                  TargetTransformInfo *TTI) {
10839   auto *I = dyn_cast_or_null<Instruction>(V);
10840   if (!I)
10841     return false;
10842 
10843   if (!isa<BinaryOperator>(I))
10844     P = nullptr;
10845   // Try to match and vectorize a horizontal reduction.
10846   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
10847     return tryToVectorize(I, R);
10848   };
10849   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI, *SE, *DL,
10850                                                   *TLI, ExtraVectorization);
10851 }
10852 
10853 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
10854                                                  BasicBlock *BB, BoUpSLP &R) {
10855   const DataLayout &DL = BB->getModule()->getDataLayout();
10856   if (!R.canMapToVector(IVI->getType(), DL))
10857     return false;
10858 
10859   SmallVector<Value *, 16> BuildVectorOpds;
10860   SmallVector<Value *, 16> BuildVectorInsts;
10861   if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts))
10862     return false;
10863 
10864   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
10865   // Aggregate value is unlikely to be processed in vector register.
10866   return tryToVectorizeList(BuildVectorOpds, R);
10867 }
10868 
10869 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
10870                                                    BasicBlock *BB, BoUpSLP &R) {
10871   SmallVector<Value *, 16> BuildVectorInsts;
10872   SmallVector<Value *, 16> BuildVectorOpds;
10873   SmallVector<int> Mask;
10874   if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
10875       (llvm::all_of(
10876            BuildVectorOpds,
10877            [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) &&
10878        isFixedVectorShuffle(BuildVectorOpds, Mask)))
10879     return false;
10880 
10881   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n");
10882   return tryToVectorizeList(BuildVectorInsts, R);
10883 }
10884 
10885 template <typename T>
10886 static bool
10887 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming,
10888                        function_ref<unsigned(T *)> Limit,
10889                        function_ref<bool(T *, T *)> Comparator,
10890                        function_ref<bool(T *, T *)> AreCompatible,
10891                        function_ref<bool(ArrayRef<T *>, bool)> TryToVectorizeHelper,
10892                        bool LimitForRegisterSize) {
10893   bool Changed = false;
10894   // Sort by type, parent, operands.
10895   stable_sort(Incoming, Comparator);
10896 
10897   // Try to vectorize elements base on their type.
10898   SmallVector<T *> Candidates;
10899   for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) {
10900     // Look for the next elements with the same type, parent and operand
10901     // kinds.
10902     auto *SameTypeIt = IncIt;
10903     while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt))
10904       ++SameTypeIt;
10905 
10906     // Try to vectorize them.
10907     unsigned NumElts = (SameTypeIt - IncIt);
10908     LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes ("
10909                       << NumElts << ")\n");
10910     // The vectorization is a 3-state attempt:
10911     // 1. Try to vectorize instructions with the same/alternate opcodes with the
10912     // size of maximal register at first.
10913     // 2. Try to vectorize remaining instructions with the same type, if
10914     // possible. This may result in the better vectorization results rather than
10915     // if we try just to vectorize instructions with the same/alternate opcodes.
10916     // 3. Final attempt to try to vectorize all instructions with the
10917     // same/alternate ops only, this may result in some extra final
10918     // vectorization.
10919     if (NumElts > 1 &&
10920         TryToVectorizeHelper(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) {
10921       // Success start over because instructions might have been changed.
10922       Changed = true;
10923     } else if (NumElts < Limit(*IncIt) &&
10924                (Candidates.empty() ||
10925                 Candidates.front()->getType() == (*IncIt)->getType())) {
10926       Candidates.append(IncIt, std::next(IncIt, NumElts));
10927     }
10928     // Final attempt to vectorize instructions with the same types.
10929     if (Candidates.size() > 1 &&
10930         (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) {
10931       if (TryToVectorizeHelper(Candidates, /*LimitForRegisterSize=*/false)) {
10932         // Success start over because instructions might have been changed.
10933         Changed = true;
10934       } else if (LimitForRegisterSize) {
10935         // Try to vectorize using small vectors.
10936         for (auto *It = Candidates.begin(), *End = Candidates.end();
10937              It != End;) {
10938           auto *SameTypeIt = It;
10939           while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It))
10940             ++SameTypeIt;
10941           unsigned NumElts = (SameTypeIt - It);
10942           if (NumElts > 1 && TryToVectorizeHelper(makeArrayRef(It, NumElts),
10943                                             /*LimitForRegisterSize=*/false))
10944             Changed = true;
10945           It = SameTypeIt;
10946         }
10947       }
10948       Candidates.clear();
10949     }
10950 
10951     // Start over at the next instruction of a different type (or the end).
10952     IncIt = SameTypeIt;
10953   }
10954   return Changed;
10955 }
10956 
10957 /// Compare two cmp instructions. If IsCompatibility is true, function returns
10958 /// true if 2 cmps have same/swapped predicates and mos compatible corresponding
10959 /// operands. If IsCompatibility is false, function implements strict weak
10960 /// ordering relation between two cmp instructions, returning true if the first
10961 /// instruction is "less" than the second, i.e. its predicate is less than the
10962 /// predicate of the second or the operands IDs are less than the operands IDs
10963 /// of the second cmp instruction.
10964 template <bool IsCompatibility>
10965 static bool compareCmp(Value *V, Value *V2,
10966                        function_ref<bool(Instruction *)> IsDeleted) {
10967   auto *CI1 = cast<CmpInst>(V);
10968   auto *CI2 = cast<CmpInst>(V2);
10969   if (IsDeleted(CI2) || !isValidElementType(CI2->getType()))
10970     return false;
10971   if (CI1->getOperand(0)->getType()->getTypeID() <
10972       CI2->getOperand(0)->getType()->getTypeID())
10973     return !IsCompatibility;
10974   if (CI1->getOperand(0)->getType()->getTypeID() >
10975       CI2->getOperand(0)->getType()->getTypeID())
10976     return false;
10977   CmpInst::Predicate Pred1 = CI1->getPredicate();
10978   CmpInst::Predicate Pred2 = CI2->getPredicate();
10979   CmpInst::Predicate SwapPred1 = CmpInst::getSwappedPredicate(Pred1);
10980   CmpInst::Predicate SwapPred2 = CmpInst::getSwappedPredicate(Pred2);
10981   CmpInst::Predicate BasePred1 = std::min(Pred1, SwapPred1);
10982   CmpInst::Predicate BasePred2 = std::min(Pred2, SwapPred2);
10983   if (BasePred1 < BasePred2)
10984     return !IsCompatibility;
10985   if (BasePred1 > BasePred2)
10986     return false;
10987   // Compare operands.
10988   bool LEPreds = Pred1 <= Pred2;
10989   bool GEPreds = Pred1 >= Pred2;
10990   for (int I = 0, E = CI1->getNumOperands(); I < E; ++I) {
10991     auto *Op1 = CI1->getOperand(LEPreds ? I : E - I - 1);
10992     auto *Op2 = CI2->getOperand(GEPreds ? I : E - I - 1);
10993     if (Op1->getValueID() < Op2->getValueID())
10994       return !IsCompatibility;
10995     if (Op1->getValueID() > Op2->getValueID())
10996       return false;
10997     if (auto *I1 = dyn_cast<Instruction>(Op1))
10998       if (auto *I2 = dyn_cast<Instruction>(Op2)) {
10999         if (I1->getParent() != I2->getParent())
11000           return false;
11001         InstructionsState S = getSameOpcode({I1, I2});
11002         if (S.getOpcode())
11003           continue;
11004         return false;
11005       }
11006   }
11007   return IsCompatibility;
11008 }
11009 
11010 bool SLPVectorizerPass::vectorizeSimpleInstructions(
11011     SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R,
11012     bool AtTerminator) {
11013   bool OpsChanged = false;
11014   SmallVector<Instruction *, 4> PostponedCmps;
11015   for (auto *I : reverse(Instructions)) {
11016     if (R.isDeleted(I))
11017       continue;
11018     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I)) {
11019       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
11020     } else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I)) {
11021       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
11022     } else if (isa<CmpInst>(I)) {
11023       PostponedCmps.push_back(I);
11024       continue;
11025     }
11026     // Try to find reductions in buildvector sequnces.
11027     OpsChanged |= vectorizeRootInstruction(nullptr, I, BB, R, TTI);
11028   }
11029   if (AtTerminator) {
11030     // Try to find reductions first.
11031     for (Instruction *I : PostponedCmps) {
11032       if (R.isDeleted(I))
11033         continue;
11034       for (Value *Op : I->operands())
11035         OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI);
11036     }
11037     // Try to vectorize operands as vector bundles.
11038     for (Instruction *I : PostponedCmps) {
11039       if (R.isDeleted(I))
11040         continue;
11041       OpsChanged |= tryToVectorize(I, R);
11042     }
11043     // Try to vectorize list of compares.
11044     // Sort by type, compare predicate, etc.
11045     auto &&CompareSorter = [&R](Value *V, Value *V2) {
11046       return compareCmp<false>(V, V2,
11047                                [&R](Instruction *I) { return R.isDeleted(I); });
11048     };
11049 
11050     auto &&AreCompatibleCompares = [&R](Value *V1, Value *V2) {
11051       if (V1 == V2)
11052         return true;
11053       return compareCmp<true>(V1, V2,
11054                               [&R](Instruction *I) { return R.isDeleted(I); });
11055     };
11056     auto Limit = [&R](Value *V) {
11057       unsigned EltSize = R.getVectorElementSize(V);
11058       return std::max(2U, R.getMaxVecRegSize() / EltSize);
11059     };
11060 
11061     SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end());
11062     OpsChanged |= tryToVectorizeSequence<Value>(
11063         Vals, Limit, CompareSorter, AreCompatibleCompares,
11064         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
11065           // Exclude possible reductions from other blocks.
11066           bool ArePossiblyReducedInOtherBlock =
11067               any_of(Candidates, [](Value *V) {
11068                 return any_of(V->users(), [V](User *U) {
11069                   return isa<SelectInst>(U) &&
11070                          cast<SelectInst>(U)->getParent() !=
11071                              cast<Instruction>(V)->getParent();
11072                 });
11073               });
11074           if (ArePossiblyReducedInOtherBlock)
11075             return false;
11076           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
11077         },
11078         /*LimitForRegisterSize=*/true);
11079     Instructions.clear();
11080   } else {
11081     // Insert in reverse order since the PostponedCmps vector was filled in
11082     // reverse order.
11083     Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend());
11084   }
11085   return OpsChanged;
11086 }
11087 
11088 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
11089   bool Changed = false;
11090   SmallVector<Value *, 4> Incoming;
11091   SmallPtrSet<Value *, 16> VisitedInstrs;
11092   // Maps phi nodes to the non-phi nodes found in the use tree for each phi
11093   // node. Allows better to identify the chains that can be vectorized in the
11094   // better way.
11095   DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes;
11096   auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) {
11097     assert(isValidElementType(V1->getType()) &&
11098            isValidElementType(V2->getType()) &&
11099            "Expected vectorizable types only.");
11100     // It is fine to compare type IDs here, since we expect only vectorizable
11101     // types, like ints, floats and pointers, we don't care about other type.
11102     if (V1->getType()->getTypeID() < V2->getType()->getTypeID())
11103       return true;
11104     if (V1->getType()->getTypeID() > V2->getType()->getTypeID())
11105       return false;
11106     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
11107     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
11108     if (Opcodes1.size() < Opcodes2.size())
11109       return true;
11110     if (Opcodes1.size() > Opcodes2.size())
11111       return false;
11112     Optional<bool> ConstOrder;
11113     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
11114       // Undefs are compatible with any other value.
11115       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) {
11116         if (!ConstOrder)
11117           ConstOrder =
11118               !isa<UndefValue>(Opcodes1[I]) && isa<UndefValue>(Opcodes2[I]);
11119         continue;
11120       }
11121       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
11122         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
11123           DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent());
11124           DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent());
11125           if (!NodeI1)
11126             return NodeI2 != nullptr;
11127           if (!NodeI2)
11128             return false;
11129           assert((NodeI1 == NodeI2) ==
11130                      (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
11131                  "Different nodes should have different DFS numbers");
11132           if (NodeI1 != NodeI2)
11133             return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
11134           InstructionsState S = getSameOpcode({I1, I2});
11135           if (S.getOpcode())
11136             continue;
11137           return I1->getOpcode() < I2->getOpcode();
11138         }
11139       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) {
11140         if (!ConstOrder)
11141           ConstOrder = Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID();
11142         continue;
11143       }
11144       if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID())
11145         return true;
11146       if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID())
11147         return false;
11148     }
11149     return ConstOrder && *ConstOrder;
11150   };
11151   auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) {
11152     if (V1 == V2)
11153       return true;
11154     if (V1->getType() != V2->getType())
11155       return false;
11156     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
11157     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
11158     if (Opcodes1.size() != Opcodes2.size())
11159       return false;
11160     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
11161       // Undefs are compatible with any other value.
11162       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
11163         continue;
11164       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
11165         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
11166           if (I1->getParent() != I2->getParent())
11167             return false;
11168           InstructionsState S = getSameOpcode({I1, I2});
11169           if (S.getOpcode())
11170             continue;
11171           return false;
11172         }
11173       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
11174         continue;
11175       if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID())
11176         return false;
11177     }
11178     return true;
11179   };
11180   auto Limit = [&R](Value *V) {
11181     unsigned EltSize = R.getVectorElementSize(V);
11182     return std::max(2U, R.getMaxVecRegSize() / EltSize);
11183   };
11184 
11185   bool HaveVectorizedPhiNodes = false;
11186   do {
11187     // Collect the incoming values from the PHIs.
11188     Incoming.clear();
11189     for (Instruction &I : *BB) {
11190       PHINode *P = dyn_cast<PHINode>(&I);
11191       if (!P)
11192         break;
11193 
11194       // No need to analyze deleted, vectorized and non-vectorizable
11195       // instructions.
11196       if (!VisitedInstrs.count(P) && !R.isDeleted(P) &&
11197           isValidElementType(P->getType()))
11198         Incoming.push_back(P);
11199     }
11200 
11201     // Find the corresponding non-phi nodes for better matching when trying to
11202     // build the tree.
11203     for (Value *V : Incoming) {
11204       SmallVectorImpl<Value *> &Opcodes =
11205           PHIToOpcodes.try_emplace(V).first->getSecond();
11206       if (!Opcodes.empty())
11207         continue;
11208       SmallVector<Value *, 4> Nodes(1, V);
11209       SmallPtrSet<Value *, 4> Visited;
11210       while (!Nodes.empty()) {
11211         auto *PHI = cast<PHINode>(Nodes.pop_back_val());
11212         if (!Visited.insert(PHI).second)
11213           continue;
11214         for (Value *V : PHI->incoming_values()) {
11215           if (auto *PHI1 = dyn_cast<PHINode>((V))) {
11216             Nodes.push_back(PHI1);
11217             continue;
11218           }
11219           Opcodes.emplace_back(V);
11220         }
11221       }
11222     }
11223 
11224     HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>(
11225         Incoming, Limit, PHICompare, AreCompatiblePHIs,
11226         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
11227           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
11228         },
11229         /*LimitForRegisterSize=*/true);
11230     Changed |= HaveVectorizedPhiNodes;
11231     VisitedInstrs.insert(Incoming.begin(), Incoming.end());
11232   } while (HaveVectorizedPhiNodes);
11233 
11234   VisitedInstrs.clear();
11235 
11236   SmallVector<Instruction *, 8> PostProcessInstructions;
11237   SmallDenseSet<Instruction *, 4> KeyNodes;
11238   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
11239     // Skip instructions with scalable type. The num of elements is unknown at
11240     // compile-time for scalable type.
11241     if (isa<ScalableVectorType>(it->getType()))
11242       continue;
11243 
11244     // Skip instructions marked for the deletion.
11245     if (R.isDeleted(&*it))
11246       continue;
11247     // We may go through BB multiple times so skip the one we have checked.
11248     if (!VisitedInstrs.insert(&*it).second) {
11249       if (it->use_empty() && KeyNodes.contains(&*it) &&
11250           vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
11251                                       it->isTerminator())) {
11252         // We would like to start over since some instructions are deleted
11253         // and the iterator may become invalid value.
11254         Changed = true;
11255         it = BB->begin();
11256         e = BB->end();
11257       }
11258       continue;
11259     }
11260 
11261     if (isa<DbgInfoIntrinsic>(it))
11262       continue;
11263 
11264     // Try to vectorize reductions that use PHINodes.
11265     if (PHINode *P = dyn_cast<PHINode>(it)) {
11266       // Check that the PHI is a reduction PHI.
11267       if (P->getNumIncomingValues() == 2) {
11268         // Try to match and vectorize a horizontal reduction.
11269         if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
11270                                      TTI)) {
11271           Changed = true;
11272           it = BB->begin();
11273           e = BB->end();
11274           continue;
11275         }
11276       }
11277       // Try to vectorize the incoming values of the PHI, to catch reductions
11278       // that feed into PHIs.
11279       for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) {
11280         // Skip if the incoming block is the current BB for now. Also, bypass
11281         // unreachable IR for efficiency and to avoid crashing.
11282         // TODO: Collect the skipped incoming values and try to vectorize them
11283         // after processing BB.
11284         if (BB == P->getIncomingBlock(I) ||
11285             !DT->isReachableFromEntry(P->getIncomingBlock(I)))
11286           continue;
11287 
11288         Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I),
11289                                             P->getIncomingBlock(I), R, TTI);
11290       }
11291       continue;
11292     }
11293 
11294     // Ran into an instruction without users, like terminator, or function call
11295     // with ignored return value, store. Ignore unused instructions (basing on
11296     // instruction type, except for CallInst and InvokeInst).
11297     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
11298                             isa<InvokeInst>(it))) {
11299       KeyNodes.insert(&*it);
11300       bool OpsChanged = false;
11301       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
11302         for (auto *V : it->operand_values()) {
11303           // Try to match and vectorize a horizontal reduction.
11304           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
11305         }
11306       }
11307       // Start vectorization of post-process list of instructions from the
11308       // top-tree instructions to try to vectorize as many instructions as
11309       // possible.
11310       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
11311                                                 it->isTerminator());
11312       if (OpsChanged) {
11313         // We would like to start over since some instructions are deleted
11314         // and the iterator may become invalid value.
11315         Changed = true;
11316         it = BB->begin();
11317         e = BB->end();
11318         continue;
11319       }
11320     }
11321 
11322     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
11323         isa<InsertValueInst>(it))
11324       PostProcessInstructions.push_back(&*it);
11325   }
11326 
11327   return Changed;
11328 }
11329 
11330 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
11331   auto Changed = false;
11332   for (auto &Entry : GEPs) {
11333     // If the getelementptr list has fewer than two elements, there's nothing
11334     // to do.
11335     if (Entry.second.size() < 2)
11336       continue;
11337 
11338     LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
11339                       << Entry.second.size() << ".\n");
11340 
11341     // Process the GEP list in chunks suitable for the target's supported
11342     // vector size. If a vector register can't hold 1 element, we are done. We
11343     // are trying to vectorize the index computations, so the maximum number of
11344     // elements is based on the size of the index expression, rather than the
11345     // size of the GEP itself (the target's pointer size).
11346     unsigned MaxVecRegSize = R.getMaxVecRegSize();
11347     unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin());
11348     if (MaxVecRegSize < EltSize)
11349       continue;
11350 
11351     unsigned MaxElts = MaxVecRegSize / EltSize;
11352     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
11353       auto Len = std::min<unsigned>(BE - BI, MaxElts);
11354       ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len);
11355 
11356       // Initialize a set a candidate getelementptrs. Note that we use a
11357       // SetVector here to preserve program order. If the index computations
11358       // are vectorizable and begin with loads, we want to minimize the chance
11359       // of having to reorder them later.
11360       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
11361 
11362       // Some of the candidates may have already been vectorized after we
11363       // initially collected them. If so, they are marked as deleted, so remove
11364       // them from the set of candidates.
11365       Candidates.remove_if(
11366           [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
11367 
11368       // Remove from the set of candidates all pairs of getelementptrs with
11369       // constant differences. Such getelementptrs are likely not good
11370       // candidates for vectorization in a bottom-up phase since one can be
11371       // computed from the other. We also ensure all candidate getelementptr
11372       // indices are unique.
11373       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
11374         auto *GEPI = GEPList[I];
11375         if (!Candidates.count(GEPI))
11376           continue;
11377         auto *SCEVI = SE->getSCEV(GEPList[I]);
11378         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
11379           auto *GEPJ = GEPList[J];
11380           auto *SCEVJ = SE->getSCEV(GEPList[J]);
11381           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
11382             Candidates.remove(GEPI);
11383             Candidates.remove(GEPJ);
11384           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
11385             Candidates.remove(GEPJ);
11386           }
11387         }
11388       }
11389 
11390       // We break out of the above computation as soon as we know there are
11391       // fewer than two candidates remaining.
11392       if (Candidates.size() < 2)
11393         continue;
11394 
11395       // Add the single, non-constant index of each candidate to the bundle. We
11396       // ensured the indices met these constraints when we originally collected
11397       // the getelementptrs.
11398       SmallVector<Value *, 16> Bundle(Candidates.size());
11399       auto BundleIndex = 0u;
11400       for (auto *V : Candidates) {
11401         auto *GEP = cast<GetElementPtrInst>(V);
11402         auto *GEPIdx = GEP->idx_begin()->get();
11403         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
11404         Bundle[BundleIndex++] = GEPIdx;
11405       }
11406 
11407       // Try and vectorize the indices. We are currently only interested in
11408       // gather-like cases of the form:
11409       //
11410       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
11411       //
11412       // where the loads of "a", the loads of "b", and the subtractions can be
11413       // performed in parallel. It's likely that detecting this pattern in a
11414       // bottom-up phase will be simpler and less costly than building a
11415       // full-blown top-down phase beginning at the consecutive loads.
11416       Changed |= tryToVectorizeList(Bundle, R);
11417     }
11418   }
11419   return Changed;
11420 }
11421 
11422 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
11423   bool Changed = false;
11424   // Sort by type, base pointers and values operand. Value operands must be
11425   // compatible (have the same opcode, same parent), otherwise it is
11426   // definitely not profitable to try to vectorize them.
11427   auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) {
11428     if (V->getPointerOperandType()->getTypeID() <
11429         V2->getPointerOperandType()->getTypeID())
11430       return true;
11431     if (V->getPointerOperandType()->getTypeID() >
11432         V2->getPointerOperandType()->getTypeID())
11433       return false;
11434     // UndefValues are compatible with all other values.
11435     if (isa<UndefValue>(V->getValueOperand()) ||
11436         isa<UndefValue>(V2->getValueOperand()))
11437       return false;
11438     if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand()))
11439       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
11440         DomTreeNodeBase<llvm::BasicBlock> *NodeI1 =
11441             DT->getNode(I1->getParent());
11442         DomTreeNodeBase<llvm::BasicBlock> *NodeI2 =
11443             DT->getNode(I2->getParent());
11444         assert(NodeI1 && "Should only process reachable instructions");
11445         assert(NodeI2 && "Should only process reachable instructions");
11446         assert((NodeI1 == NodeI2) ==
11447                    (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
11448                "Different nodes should have different DFS numbers");
11449         if (NodeI1 != NodeI2)
11450           return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
11451         InstructionsState S = getSameOpcode({I1, I2});
11452         if (S.getOpcode())
11453           return false;
11454         return I1->getOpcode() < I2->getOpcode();
11455       }
11456     if (isa<Constant>(V->getValueOperand()) &&
11457         isa<Constant>(V2->getValueOperand()))
11458       return false;
11459     return V->getValueOperand()->getValueID() <
11460            V2->getValueOperand()->getValueID();
11461   };
11462 
11463   auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) {
11464     if (V1 == V2)
11465       return true;
11466     if (V1->getPointerOperandType() != V2->getPointerOperandType())
11467       return false;
11468     // Undefs are compatible with any other value.
11469     if (isa<UndefValue>(V1->getValueOperand()) ||
11470         isa<UndefValue>(V2->getValueOperand()))
11471       return true;
11472     if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand()))
11473       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
11474         if (I1->getParent() != I2->getParent())
11475           return false;
11476         InstructionsState S = getSameOpcode({I1, I2});
11477         return S.getOpcode() > 0;
11478       }
11479     if (isa<Constant>(V1->getValueOperand()) &&
11480         isa<Constant>(V2->getValueOperand()))
11481       return true;
11482     return V1->getValueOperand()->getValueID() ==
11483            V2->getValueOperand()->getValueID();
11484   };
11485   auto Limit = [&R, this](StoreInst *SI) {
11486     unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
11487     return R.getMinVF(EltSize);
11488   };
11489 
11490   // Attempt to sort and vectorize each of the store-groups.
11491   for (auto &Pair : Stores) {
11492     if (Pair.second.size() < 2)
11493       continue;
11494 
11495     LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
11496                       << Pair.second.size() << ".\n");
11497 
11498     if (!isValidElementType(Pair.second.front()->getValueOperand()->getType()))
11499       continue;
11500 
11501     Changed |= tryToVectorizeSequence<StoreInst>(
11502         Pair.second, Limit, StoreSorter, AreCompatibleStores,
11503         [this, &R](ArrayRef<StoreInst *> Candidates, bool) {
11504           return vectorizeStores(Candidates, R);
11505         },
11506         /*LimitForRegisterSize=*/false);
11507   }
11508   return Changed;
11509 }
11510 
11511 char SLPVectorizer::ID = 0;
11512 
11513 static const char lv_name[] = "SLP Vectorizer";
11514 
11515 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
11516 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
11517 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
11518 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
11519 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
11520 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
11521 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
11522 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
11523 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
11524 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
11525 
11526 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
11527