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 
2188   /// Helper for `findExternalStoreUsersReorderIndices()`. It iterates over the
2189   /// users of \p TE and collects the stores. It returns the map from the store
2190   /// pointers to the collected stores.
2191   DenseMap<Value *, SmallVector<StoreInst *, 4>>
2192   collectUserStores(const BoUpSLP::TreeEntry *TE) const;
2193 
2194   /// Helper for `findExternalStoreUsersReorderIndices()`. It checks if the
2195   /// stores in \p StoresVec can for a vector instruction. If so it returns true
2196   /// and populates \p ReorderIndices with the shuffle indices of the the stores
2197   /// when compared to the sorted vector.
2198   bool CanFormVector(const SmallVector<StoreInst *, 4> &StoresVec,
2199                      OrdersType &ReorderIndices) const;
2200 
2201   /// Iterates through the users of \p TE, looking for scalar stores that can be
2202   /// potentially vectorized in a future SLP-tree. If found, it keeps track of
2203   /// their order and builds an order index vector for each store bundle. It
2204   /// returns all these order vectors found.
2205   /// We run this after the tree has formed, otherwise we may come across user
2206   /// instructions that are not yet in the tree.
2207   SmallVector<OrdersType, 1>
2208   findExternalStoreUsersReorderIndices(TreeEntry *TE) const;
2209 
2210   struct TreeEntry {
2211     using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>;
2212     TreeEntry(VecTreeTy &Container) : Container(Container) {}
2213 
2214     /// \returns true if the scalars in VL are equal to this entry.
2215     bool isSame(ArrayRef<Value *> VL) const {
2216       auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) {
2217         if (Mask.size() != VL.size() && VL.size() == Scalars.size())
2218           return std::equal(VL.begin(), VL.end(), Scalars.begin());
2219         return VL.size() == Mask.size() &&
2220                std::equal(VL.begin(), VL.end(), Mask.begin(),
2221                           [Scalars](Value *V, int Idx) {
2222                             return (isa<UndefValue>(V) &&
2223                                     Idx == UndefMaskElem) ||
2224                                    (Idx != UndefMaskElem && V == Scalars[Idx]);
2225                           });
2226       };
2227       if (!ReorderIndices.empty()) {
2228         // TODO: implement matching if the nodes are just reordered, still can
2229         // treat the vector as the same if the list of scalars matches VL
2230         // directly, without reordering.
2231         SmallVector<int> Mask;
2232         inversePermutation(ReorderIndices, Mask);
2233         if (VL.size() == Scalars.size())
2234           return IsSame(Scalars, Mask);
2235         if (VL.size() == ReuseShuffleIndices.size()) {
2236           ::addMask(Mask, ReuseShuffleIndices);
2237           return IsSame(Scalars, Mask);
2238         }
2239         return false;
2240       }
2241       return IsSame(Scalars, ReuseShuffleIndices);
2242     }
2243 
2244     /// \returns true if current entry has same operands as \p TE.
2245     bool hasEqualOperands(const TreeEntry &TE) const {
2246       if (TE.getNumOperands() != getNumOperands())
2247         return false;
2248       SmallBitVector Used(getNumOperands());
2249       for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
2250         unsigned PrevCount = Used.count();
2251         for (unsigned K = 0; K < E; ++K) {
2252           if (Used.test(K))
2253             continue;
2254           if (getOperand(K) == TE.getOperand(I)) {
2255             Used.set(K);
2256             break;
2257           }
2258         }
2259         // Check if we actually found the matching operand.
2260         if (PrevCount == Used.count())
2261           return false;
2262       }
2263       return true;
2264     }
2265 
2266     /// \return Final vectorization factor for the node. Defined by the total
2267     /// number of vectorized scalars, including those, used several times in the
2268     /// entry and counted in the \a ReuseShuffleIndices, if any.
2269     unsigned getVectorFactor() const {
2270       if (!ReuseShuffleIndices.empty())
2271         return ReuseShuffleIndices.size();
2272       return Scalars.size();
2273     };
2274 
2275     /// A vector of scalars.
2276     ValueList Scalars;
2277 
2278     /// The Scalars are vectorized into this value. It is initialized to Null.
2279     Value *VectorizedValue = nullptr;
2280 
2281     /// Do we need to gather this sequence or vectorize it
2282     /// (either with vector instruction or with scatter/gather
2283     /// intrinsics for store/load)?
2284     enum EntryState { Vectorize, ScatterVectorize, NeedToGather };
2285     EntryState State;
2286 
2287     /// Does this sequence require some shuffling?
2288     SmallVector<int, 4> ReuseShuffleIndices;
2289 
2290     /// Does this entry require reordering?
2291     SmallVector<unsigned, 4> ReorderIndices;
2292 
2293     /// Points back to the VectorizableTree.
2294     ///
2295     /// Only used for Graphviz right now.  Unfortunately GraphTrait::NodeRef has
2296     /// to be a pointer and needs to be able to initialize the child iterator.
2297     /// Thus we need a reference back to the container to translate the indices
2298     /// to entries.
2299     VecTreeTy &Container;
2300 
2301     /// The TreeEntry index containing the user of this entry.  We can actually
2302     /// have multiple users so the data structure is not truly a tree.
2303     SmallVector<EdgeInfo, 1> UserTreeIndices;
2304 
2305     /// The index of this treeEntry in VectorizableTree.
2306     int Idx = -1;
2307 
2308   private:
2309     /// The operands of each instruction in each lane Operands[op_index][lane].
2310     /// Note: This helps avoid the replication of the code that performs the
2311     /// reordering of operands during buildTree_rec() and vectorizeTree().
2312     SmallVector<ValueList, 2> Operands;
2313 
2314     /// The main/alternate instruction.
2315     Instruction *MainOp = nullptr;
2316     Instruction *AltOp = nullptr;
2317 
2318   public:
2319     /// Set this bundle's \p OpIdx'th operand to \p OpVL.
2320     void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) {
2321       if (Operands.size() < OpIdx + 1)
2322         Operands.resize(OpIdx + 1);
2323       assert(Operands[OpIdx].empty() && "Already resized?");
2324       assert(OpVL.size() <= Scalars.size() &&
2325              "Number of operands is greater than the number of scalars.");
2326       Operands[OpIdx].resize(OpVL.size());
2327       copy(OpVL, Operands[OpIdx].begin());
2328     }
2329 
2330     /// Set the operands of this bundle in their original order.
2331     void setOperandsInOrder() {
2332       assert(Operands.empty() && "Already initialized?");
2333       auto *I0 = cast<Instruction>(Scalars[0]);
2334       Operands.resize(I0->getNumOperands());
2335       unsigned NumLanes = Scalars.size();
2336       for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands();
2337            OpIdx != NumOperands; ++OpIdx) {
2338         Operands[OpIdx].resize(NumLanes);
2339         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
2340           auto *I = cast<Instruction>(Scalars[Lane]);
2341           assert(I->getNumOperands() == NumOperands &&
2342                  "Expected same number of operands");
2343           Operands[OpIdx][Lane] = I->getOperand(OpIdx);
2344         }
2345       }
2346     }
2347 
2348     /// Reorders operands of the node to the given mask \p Mask.
2349     void reorderOperands(ArrayRef<int> Mask) {
2350       for (ValueList &Operand : Operands)
2351         reorderScalars(Operand, Mask);
2352     }
2353 
2354     /// \returns the \p OpIdx operand of this TreeEntry.
2355     ValueList &getOperand(unsigned OpIdx) {
2356       assert(OpIdx < Operands.size() && "Off bounds");
2357       return Operands[OpIdx];
2358     }
2359 
2360     /// \returns the \p OpIdx operand of this TreeEntry.
2361     ArrayRef<Value *> getOperand(unsigned OpIdx) const {
2362       assert(OpIdx < Operands.size() && "Off bounds");
2363       return Operands[OpIdx];
2364     }
2365 
2366     /// \returns the number of operands.
2367     unsigned getNumOperands() const { return Operands.size(); }
2368 
2369     /// \return the single \p OpIdx operand.
2370     Value *getSingleOperand(unsigned OpIdx) const {
2371       assert(OpIdx < Operands.size() && "Off bounds");
2372       assert(!Operands[OpIdx].empty() && "No operand available");
2373       return Operands[OpIdx][0];
2374     }
2375 
2376     /// Some of the instructions in the list have alternate opcodes.
2377     bool isAltShuffle() const { return MainOp != AltOp; }
2378 
2379     bool isOpcodeOrAlt(Instruction *I) const {
2380       unsigned CheckedOpcode = I->getOpcode();
2381       return (getOpcode() == CheckedOpcode ||
2382               getAltOpcode() == CheckedOpcode);
2383     }
2384 
2385     /// Chooses the correct key for scheduling data. If \p Op has the same (or
2386     /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is
2387     /// \p OpValue.
2388     Value *isOneOf(Value *Op) const {
2389       auto *I = dyn_cast<Instruction>(Op);
2390       if (I && isOpcodeOrAlt(I))
2391         return Op;
2392       return MainOp;
2393     }
2394 
2395     void setOperations(const InstructionsState &S) {
2396       MainOp = S.MainOp;
2397       AltOp = S.AltOp;
2398     }
2399 
2400     Instruction *getMainOp() const {
2401       return MainOp;
2402     }
2403 
2404     Instruction *getAltOp() const {
2405       return AltOp;
2406     }
2407 
2408     /// The main/alternate opcodes for the list of instructions.
2409     unsigned getOpcode() const {
2410       return MainOp ? MainOp->getOpcode() : 0;
2411     }
2412 
2413     unsigned getAltOpcode() const {
2414       return AltOp ? AltOp->getOpcode() : 0;
2415     }
2416 
2417     /// When ReuseReorderShuffleIndices is empty it just returns position of \p
2418     /// V within vector of Scalars. Otherwise, try to remap on its reuse index.
2419     int findLaneForValue(Value *V) const {
2420       unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V));
2421       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2422       if (!ReorderIndices.empty())
2423         FoundLane = ReorderIndices[FoundLane];
2424       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2425       if (!ReuseShuffleIndices.empty()) {
2426         FoundLane = std::distance(ReuseShuffleIndices.begin(),
2427                                   find(ReuseShuffleIndices, FoundLane));
2428       }
2429       return FoundLane;
2430     }
2431 
2432 #ifndef NDEBUG
2433     /// Debug printer.
2434     LLVM_DUMP_METHOD void dump() const {
2435       dbgs() << Idx << ".\n";
2436       for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) {
2437         dbgs() << "Operand " << OpI << ":\n";
2438         for (const Value *V : Operands[OpI])
2439           dbgs().indent(2) << *V << "\n";
2440       }
2441       dbgs() << "Scalars: \n";
2442       for (Value *V : Scalars)
2443         dbgs().indent(2) << *V << "\n";
2444       dbgs() << "State: ";
2445       switch (State) {
2446       case Vectorize:
2447         dbgs() << "Vectorize\n";
2448         break;
2449       case ScatterVectorize:
2450         dbgs() << "ScatterVectorize\n";
2451         break;
2452       case NeedToGather:
2453         dbgs() << "NeedToGather\n";
2454         break;
2455       }
2456       dbgs() << "MainOp: ";
2457       if (MainOp)
2458         dbgs() << *MainOp << "\n";
2459       else
2460         dbgs() << "NULL\n";
2461       dbgs() << "AltOp: ";
2462       if (AltOp)
2463         dbgs() << *AltOp << "\n";
2464       else
2465         dbgs() << "NULL\n";
2466       dbgs() << "VectorizedValue: ";
2467       if (VectorizedValue)
2468         dbgs() << *VectorizedValue << "\n";
2469       else
2470         dbgs() << "NULL\n";
2471       dbgs() << "ReuseShuffleIndices: ";
2472       if (ReuseShuffleIndices.empty())
2473         dbgs() << "Empty";
2474       else
2475         for (int ReuseIdx : ReuseShuffleIndices)
2476           dbgs() << ReuseIdx << ", ";
2477       dbgs() << "\n";
2478       dbgs() << "ReorderIndices: ";
2479       for (unsigned ReorderIdx : ReorderIndices)
2480         dbgs() << ReorderIdx << ", ";
2481       dbgs() << "\n";
2482       dbgs() << "UserTreeIndices: ";
2483       for (const auto &EInfo : UserTreeIndices)
2484         dbgs() << EInfo << ", ";
2485       dbgs() << "\n";
2486     }
2487 #endif
2488   };
2489 
2490 #ifndef NDEBUG
2491   void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost,
2492                      InstructionCost VecCost,
2493                      InstructionCost ScalarCost) const {
2494     dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump();
2495     dbgs() << "SLP: Costs:\n";
2496     dbgs() << "SLP:     ReuseShuffleCost = " << ReuseShuffleCost << "\n";
2497     dbgs() << "SLP:     VectorCost = " << VecCost << "\n";
2498     dbgs() << "SLP:     ScalarCost = " << ScalarCost << "\n";
2499     dbgs() << "SLP:     ReuseShuffleCost + VecCost - ScalarCost = " <<
2500                ReuseShuffleCost + VecCost - ScalarCost << "\n";
2501   }
2502 #endif
2503 
2504   /// Create a new VectorizableTree entry.
2505   TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle,
2506                           const InstructionsState &S,
2507                           const EdgeInfo &UserTreeIdx,
2508                           ArrayRef<int> ReuseShuffleIndices = None,
2509                           ArrayRef<unsigned> ReorderIndices = None) {
2510     TreeEntry::EntryState EntryState =
2511         Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather;
2512     return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx,
2513                         ReuseShuffleIndices, ReorderIndices);
2514   }
2515 
2516   TreeEntry *newTreeEntry(ArrayRef<Value *> VL,
2517                           TreeEntry::EntryState EntryState,
2518                           Optional<ScheduleData *> Bundle,
2519                           const InstructionsState &S,
2520                           const EdgeInfo &UserTreeIdx,
2521                           ArrayRef<int> ReuseShuffleIndices = None,
2522                           ArrayRef<unsigned> ReorderIndices = None) {
2523     assert(((!Bundle && EntryState == TreeEntry::NeedToGather) ||
2524             (Bundle && EntryState != TreeEntry::NeedToGather)) &&
2525            "Need to vectorize gather entry?");
2526     VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree));
2527     TreeEntry *Last = VectorizableTree.back().get();
2528     Last->Idx = VectorizableTree.size() - 1;
2529     Last->State = EntryState;
2530     Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
2531                                      ReuseShuffleIndices.end());
2532     if (ReorderIndices.empty()) {
2533       Last->Scalars.assign(VL.begin(), VL.end());
2534       Last->setOperations(S);
2535     } else {
2536       // Reorder scalars and build final mask.
2537       Last->Scalars.assign(VL.size(), nullptr);
2538       transform(ReorderIndices, Last->Scalars.begin(),
2539                 [VL](unsigned Idx) -> Value * {
2540                   if (Idx >= VL.size())
2541                     return UndefValue::get(VL.front()->getType());
2542                   return VL[Idx];
2543                 });
2544       InstructionsState S = getSameOpcode(Last->Scalars);
2545       Last->setOperations(S);
2546       Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end());
2547     }
2548     if (Last->State != TreeEntry::NeedToGather) {
2549       for (Value *V : VL) {
2550         assert(!getTreeEntry(V) && "Scalar already in tree!");
2551         ScalarToTreeEntry[V] = Last;
2552       }
2553       // Update the scheduler bundle to point to this TreeEntry.
2554       ScheduleData *BundleMember = Bundle.getValue();
2555       assert((BundleMember || isa<PHINode>(S.MainOp) ||
2556               isVectorLikeInstWithConstOps(S.MainOp) ||
2557               doesNotNeedToSchedule(VL)) &&
2558              "Bundle and VL out of sync");
2559       if (BundleMember) {
2560         for (Value *V : VL) {
2561           if (doesNotNeedToBeScheduled(V))
2562             continue;
2563           assert(BundleMember && "Unexpected end of bundle.");
2564           BundleMember->TE = Last;
2565           BundleMember = BundleMember->NextInBundle;
2566         }
2567       }
2568       assert(!BundleMember && "Bundle and VL out of sync");
2569     } else {
2570       MustGather.insert(VL.begin(), VL.end());
2571     }
2572 
2573     if (UserTreeIdx.UserTE)
2574       Last->UserTreeIndices.push_back(UserTreeIdx);
2575 
2576     return Last;
2577   }
2578 
2579   /// -- Vectorization State --
2580   /// Holds all of the tree entries.
2581   TreeEntry::VecTreeTy VectorizableTree;
2582 
2583 #ifndef NDEBUG
2584   /// Debug printer.
2585   LLVM_DUMP_METHOD void dumpVectorizableTree() const {
2586     for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) {
2587       VectorizableTree[Id]->dump();
2588       dbgs() << "\n";
2589     }
2590   }
2591 #endif
2592 
2593   TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); }
2594 
2595   const TreeEntry *getTreeEntry(Value *V) const {
2596     return ScalarToTreeEntry.lookup(V);
2597   }
2598 
2599   /// Maps a specific scalar to its tree entry.
2600   SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry;
2601 
2602   /// Maps a value to the proposed vectorizable size.
2603   SmallDenseMap<Value *, unsigned> InstrElementSize;
2604 
2605   /// A list of scalars that we found that we need to keep as scalars.
2606   ValueSet MustGather;
2607 
2608   /// This POD struct describes one external user in the vectorized tree.
2609   struct ExternalUser {
2610     ExternalUser(Value *S, llvm::User *U, int L)
2611         : Scalar(S), User(U), Lane(L) {}
2612 
2613     // Which scalar in our function.
2614     Value *Scalar;
2615 
2616     // Which user that uses the scalar.
2617     llvm::User *User;
2618 
2619     // Which lane does the scalar belong to.
2620     int Lane;
2621   };
2622   using UserList = SmallVector<ExternalUser, 16>;
2623 
2624   /// Checks if two instructions may access the same memory.
2625   ///
2626   /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
2627   /// is invariant in the calling loop.
2628   bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
2629                  Instruction *Inst2) {
2630     // First check if the result is already in the cache.
2631     AliasCacheKey key = std::make_pair(Inst1, Inst2);
2632     Optional<bool> &result = AliasCache[key];
2633     if (result.hasValue()) {
2634       return result.getValue();
2635     }
2636     bool aliased = true;
2637     if (Loc1.Ptr && isSimple(Inst1))
2638       aliased = isModOrRefSet(BatchAA.getModRefInfo(Inst2, Loc1));
2639     // Store the result in the cache.
2640     result = aliased;
2641     return aliased;
2642   }
2643 
2644   using AliasCacheKey = std::pair<Instruction *, Instruction *>;
2645 
2646   /// Cache for alias results.
2647   /// TODO: consider moving this to the AliasAnalysis itself.
2648   DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
2649 
2650   // Cache for pointerMayBeCaptured calls inside AA.  This is preserved
2651   // globally through SLP because we don't perform any action which
2652   // invalidates capture results.
2653   BatchAAResults BatchAA;
2654 
2655   /// Temporary store for deleted instructions. Instructions will be deleted
2656   /// eventually when the BoUpSLP is destructed.  The deferral is required to
2657   /// ensure that there are no incorrect collisions in the AliasCache, which
2658   /// can happen if a new instruction is allocated at the same address as a
2659   /// previously deleted instruction.
2660   DenseSet<Instruction *> DeletedInstructions;
2661 
2662   /// Set of the instruction, being analyzed already for reductions.
2663   SmallPtrSet<Instruction *, 16> AnalizedReductionsRoots;
2664 
2665   /// Set of hashes for the list of reduction values already being analyzed.
2666   DenseSet<size_t> AnalyzedReductionVals;
2667 
2668   /// A list of values that need to extracted out of the tree.
2669   /// This list holds pairs of (Internal Scalar : External User). External User
2670   /// can be nullptr, it means that this Internal Scalar will be used later,
2671   /// after vectorization.
2672   UserList ExternalUses;
2673 
2674   /// Values used only by @llvm.assume calls.
2675   SmallPtrSet<const Value *, 32> EphValues;
2676 
2677   /// Holds all of the instructions that we gathered.
2678   SetVector<Instruction *> GatherShuffleSeq;
2679 
2680   /// A list of blocks that we are going to CSE.
2681   SetVector<BasicBlock *> CSEBlocks;
2682 
2683   /// Contains all scheduling relevant data for an instruction.
2684   /// A ScheduleData either represents a single instruction or a member of an
2685   /// instruction bundle (= a group of instructions which is combined into a
2686   /// vector instruction).
2687   struct ScheduleData {
2688     // The initial value for the dependency counters. It means that the
2689     // dependencies are not calculated yet.
2690     enum { InvalidDeps = -1 };
2691 
2692     ScheduleData() = default;
2693 
2694     void init(int BlockSchedulingRegionID, Value *OpVal) {
2695       FirstInBundle = this;
2696       NextInBundle = nullptr;
2697       NextLoadStore = nullptr;
2698       IsScheduled = false;
2699       SchedulingRegionID = BlockSchedulingRegionID;
2700       clearDependencies();
2701       OpValue = OpVal;
2702       TE = nullptr;
2703     }
2704 
2705     /// Verify basic self consistency properties
2706     void verify() {
2707       if (hasValidDependencies()) {
2708         assert(UnscheduledDeps <= Dependencies && "invariant");
2709       } else {
2710         assert(UnscheduledDeps == Dependencies && "invariant");
2711       }
2712 
2713       if (IsScheduled) {
2714         assert(isSchedulingEntity() &&
2715                 "unexpected scheduled state");
2716         for (const ScheduleData *BundleMember = this; BundleMember;
2717              BundleMember = BundleMember->NextInBundle) {
2718           assert(BundleMember->hasValidDependencies() &&
2719                  BundleMember->UnscheduledDeps == 0 &&
2720                  "unexpected scheduled state");
2721           assert((BundleMember == this || !BundleMember->IsScheduled) &&
2722                  "only bundle is marked scheduled");
2723         }
2724       }
2725 
2726       assert(Inst->getParent() == FirstInBundle->Inst->getParent() &&
2727              "all bundle members must be in same basic block");
2728     }
2729 
2730     /// Returns true if the dependency information has been calculated.
2731     /// Note that depenendency validity can vary between instructions within
2732     /// a single bundle.
2733     bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
2734 
2735     /// Returns true for single instructions and for bundle representatives
2736     /// (= the head of a bundle).
2737     bool isSchedulingEntity() const { return FirstInBundle == this; }
2738 
2739     /// Returns true if it represents an instruction bundle and not only a
2740     /// single instruction.
2741     bool isPartOfBundle() const {
2742       return NextInBundle != nullptr || FirstInBundle != this || TE;
2743     }
2744 
2745     /// Returns true if it is ready for scheduling, i.e. it has no more
2746     /// unscheduled depending instructions/bundles.
2747     bool isReady() const {
2748       assert(isSchedulingEntity() &&
2749              "can't consider non-scheduling entity for ready list");
2750       return unscheduledDepsInBundle() == 0 && !IsScheduled;
2751     }
2752 
2753     /// Modifies the number of unscheduled dependencies for this instruction,
2754     /// and returns the number of remaining dependencies for the containing
2755     /// bundle.
2756     int incrementUnscheduledDeps(int Incr) {
2757       assert(hasValidDependencies() &&
2758              "increment of unscheduled deps would be meaningless");
2759       UnscheduledDeps += Incr;
2760       return FirstInBundle->unscheduledDepsInBundle();
2761     }
2762 
2763     /// Sets the number of unscheduled dependencies to the number of
2764     /// dependencies.
2765     void resetUnscheduledDeps() {
2766       UnscheduledDeps = Dependencies;
2767     }
2768 
2769     /// Clears all dependency information.
2770     void clearDependencies() {
2771       Dependencies = InvalidDeps;
2772       resetUnscheduledDeps();
2773       MemoryDependencies.clear();
2774       ControlDependencies.clear();
2775     }
2776 
2777     int unscheduledDepsInBundle() const {
2778       assert(isSchedulingEntity() && "only meaningful on the bundle");
2779       int Sum = 0;
2780       for (const ScheduleData *BundleMember = this; BundleMember;
2781            BundleMember = BundleMember->NextInBundle) {
2782         if (BundleMember->UnscheduledDeps == InvalidDeps)
2783           return InvalidDeps;
2784         Sum += BundleMember->UnscheduledDeps;
2785       }
2786       return Sum;
2787     }
2788 
2789     void dump(raw_ostream &os) const {
2790       if (!isSchedulingEntity()) {
2791         os << "/ " << *Inst;
2792       } else if (NextInBundle) {
2793         os << '[' << *Inst;
2794         ScheduleData *SD = NextInBundle;
2795         while (SD) {
2796           os << ';' << *SD->Inst;
2797           SD = SD->NextInBundle;
2798         }
2799         os << ']';
2800       } else {
2801         os << *Inst;
2802       }
2803     }
2804 
2805     Instruction *Inst = nullptr;
2806 
2807     /// Opcode of the current instruction in the schedule data.
2808     Value *OpValue = nullptr;
2809 
2810     /// The TreeEntry that this instruction corresponds to.
2811     TreeEntry *TE = nullptr;
2812 
2813     /// Points to the head in an instruction bundle (and always to this for
2814     /// single instructions).
2815     ScheduleData *FirstInBundle = nullptr;
2816 
2817     /// Single linked list of all instructions in a bundle. Null if it is a
2818     /// single instruction.
2819     ScheduleData *NextInBundle = nullptr;
2820 
2821     /// Single linked list of all memory instructions (e.g. load, store, call)
2822     /// in the block - until the end of the scheduling region.
2823     ScheduleData *NextLoadStore = nullptr;
2824 
2825     /// The dependent memory instructions.
2826     /// This list is derived on demand in calculateDependencies().
2827     SmallVector<ScheduleData *, 4> MemoryDependencies;
2828 
2829     /// List of instructions which this instruction could be control dependent
2830     /// on.  Allowing such nodes to be scheduled below this one could introduce
2831     /// a runtime fault which didn't exist in the original program.
2832     /// ex: this is a load or udiv following a readonly call which inf loops
2833     SmallVector<ScheduleData *, 4> ControlDependencies;
2834 
2835     /// This ScheduleData is in the current scheduling region if this matches
2836     /// the current SchedulingRegionID of BlockScheduling.
2837     int SchedulingRegionID = 0;
2838 
2839     /// Used for getting a "good" final ordering of instructions.
2840     int SchedulingPriority = 0;
2841 
2842     /// The number of dependencies. Constitutes of the number of users of the
2843     /// instruction plus the number of dependent memory instructions (if any).
2844     /// This value is calculated on demand.
2845     /// If InvalidDeps, the number of dependencies is not calculated yet.
2846     int Dependencies = InvalidDeps;
2847 
2848     /// The number of dependencies minus the number of dependencies of scheduled
2849     /// instructions. As soon as this is zero, the instruction/bundle gets ready
2850     /// for scheduling.
2851     /// Note that this is negative as long as Dependencies is not calculated.
2852     int UnscheduledDeps = InvalidDeps;
2853 
2854     /// True if this instruction is scheduled (or considered as scheduled in the
2855     /// dry-run).
2856     bool IsScheduled = false;
2857   };
2858 
2859 #ifndef NDEBUG
2860   friend inline raw_ostream &operator<<(raw_ostream &os,
2861                                         const BoUpSLP::ScheduleData &SD) {
2862     SD.dump(os);
2863     return os;
2864   }
2865 #endif
2866 
2867   friend struct GraphTraits<BoUpSLP *>;
2868   friend struct DOTGraphTraits<BoUpSLP *>;
2869 
2870   /// Contains all scheduling data for a basic block.
2871   /// It does not schedules instructions, which are not memory read/write
2872   /// instructions and their operands are either constants, or arguments, or
2873   /// phis, or instructions from others blocks, or their users are phis or from
2874   /// the other blocks. The resulting vector instructions can be placed at the
2875   /// beginning of the basic block without scheduling (if operands does not need
2876   /// to be scheduled) or at the end of the block (if users are outside of the
2877   /// block). It allows to save some compile time and memory used by the
2878   /// compiler.
2879   /// ScheduleData is assigned for each instruction in between the boundaries of
2880   /// the tree entry, even for those, which are not part of the graph. It is
2881   /// required to correctly follow the dependencies between the instructions and
2882   /// their correct scheduling. The ScheduleData is not allocated for the
2883   /// instructions, which do not require scheduling, like phis, nodes with
2884   /// extractelements/insertelements only or nodes with instructions, with
2885   /// uses/operands outside of the block.
2886   struct BlockScheduling {
2887     BlockScheduling(BasicBlock *BB)
2888         : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
2889 
2890     void clear() {
2891       ReadyInsts.clear();
2892       ScheduleStart = nullptr;
2893       ScheduleEnd = nullptr;
2894       FirstLoadStoreInRegion = nullptr;
2895       LastLoadStoreInRegion = nullptr;
2896       RegionHasStackSave = false;
2897 
2898       // Reduce the maximum schedule region size by the size of the
2899       // previous scheduling run.
2900       ScheduleRegionSizeLimit -= ScheduleRegionSize;
2901       if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
2902         ScheduleRegionSizeLimit = MinScheduleRegionSize;
2903       ScheduleRegionSize = 0;
2904 
2905       // Make a new scheduling region, i.e. all existing ScheduleData is not
2906       // in the new region yet.
2907       ++SchedulingRegionID;
2908     }
2909 
2910     ScheduleData *getScheduleData(Instruction *I) {
2911       if (BB != I->getParent())
2912         // Avoid lookup if can't possibly be in map.
2913         return nullptr;
2914       ScheduleData *SD = ScheduleDataMap.lookup(I);
2915       if (SD && isInSchedulingRegion(SD))
2916         return SD;
2917       return nullptr;
2918     }
2919 
2920     ScheduleData *getScheduleData(Value *V) {
2921       if (auto *I = dyn_cast<Instruction>(V))
2922         return getScheduleData(I);
2923       return nullptr;
2924     }
2925 
2926     ScheduleData *getScheduleData(Value *V, Value *Key) {
2927       if (V == Key)
2928         return getScheduleData(V);
2929       auto I = ExtraScheduleDataMap.find(V);
2930       if (I != ExtraScheduleDataMap.end()) {
2931         ScheduleData *SD = I->second.lookup(Key);
2932         if (SD && isInSchedulingRegion(SD))
2933           return SD;
2934       }
2935       return nullptr;
2936     }
2937 
2938     bool isInSchedulingRegion(ScheduleData *SD) const {
2939       return SD->SchedulingRegionID == SchedulingRegionID;
2940     }
2941 
2942     /// Marks an instruction as scheduled and puts all dependent ready
2943     /// instructions into the ready-list.
2944     template <typename ReadyListType>
2945     void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
2946       SD->IsScheduled = true;
2947       LLVM_DEBUG(dbgs() << "SLP:   schedule " << *SD << "\n");
2948 
2949       for (ScheduleData *BundleMember = SD; BundleMember;
2950            BundleMember = BundleMember->NextInBundle) {
2951         if (BundleMember->Inst != BundleMember->OpValue)
2952           continue;
2953 
2954         // Handle the def-use chain dependencies.
2955 
2956         // Decrement the unscheduled counter and insert to ready list if ready.
2957         auto &&DecrUnsched = [this, &ReadyList](Instruction *I) {
2958           doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
2959             if (OpDef && OpDef->hasValidDependencies() &&
2960                 OpDef->incrementUnscheduledDeps(-1) == 0) {
2961               // There are no more unscheduled dependencies after
2962               // decrementing, so we can put the dependent instruction
2963               // into the ready list.
2964               ScheduleData *DepBundle = OpDef->FirstInBundle;
2965               assert(!DepBundle->IsScheduled &&
2966                      "already scheduled bundle gets ready");
2967               ReadyList.insert(DepBundle);
2968               LLVM_DEBUG(dbgs()
2969                          << "SLP:    gets ready (def): " << *DepBundle << "\n");
2970             }
2971           });
2972         };
2973 
2974         // If BundleMember is a vector bundle, its operands may have been
2975         // reordered during buildTree(). We therefore need to get its operands
2976         // through the TreeEntry.
2977         if (TreeEntry *TE = BundleMember->TE) {
2978           // Need to search for the lane since the tree entry can be reordered.
2979           int Lane = std::distance(TE->Scalars.begin(),
2980                                    find(TE->Scalars, BundleMember->Inst));
2981           assert(Lane >= 0 && "Lane not set");
2982 
2983           // Since vectorization tree is being built recursively this assertion
2984           // ensures that the tree entry has all operands set before reaching
2985           // this code. Couple of exceptions known at the moment are extracts
2986           // where their second (immediate) operand is not added. Since
2987           // immediates do not affect scheduler behavior this is considered
2988           // okay.
2989           auto *In = BundleMember->Inst;
2990           assert(In &&
2991                  (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) ||
2992                   In->getNumOperands() == TE->getNumOperands()) &&
2993                  "Missed TreeEntry operands?");
2994           (void)In; // fake use to avoid build failure when assertions disabled
2995 
2996           for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands();
2997                OpIdx != NumOperands; ++OpIdx)
2998             if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane]))
2999               DecrUnsched(I);
3000         } else {
3001           // If BundleMember is a stand-alone instruction, no operand reordering
3002           // has taken place, so we directly access its operands.
3003           for (Use &U : BundleMember->Inst->operands())
3004             if (auto *I = dyn_cast<Instruction>(U.get()))
3005               DecrUnsched(I);
3006         }
3007         // Handle the memory dependencies.
3008         for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
3009           if (MemoryDepSD->hasValidDependencies() &&
3010               MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
3011             // There are no more unscheduled dependencies after decrementing,
3012             // so we can put the dependent instruction into the ready list.
3013             ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
3014             assert(!DepBundle->IsScheduled &&
3015                    "already scheduled bundle gets ready");
3016             ReadyList.insert(DepBundle);
3017             LLVM_DEBUG(dbgs()
3018                        << "SLP:    gets ready (mem): " << *DepBundle << "\n");
3019           }
3020         }
3021         // Handle the control dependencies.
3022         for (ScheduleData *DepSD : BundleMember->ControlDependencies) {
3023           if (DepSD->incrementUnscheduledDeps(-1) == 0) {
3024             // There are no more unscheduled dependencies after decrementing,
3025             // so we can put the dependent instruction into the ready list.
3026             ScheduleData *DepBundle = DepSD->FirstInBundle;
3027             assert(!DepBundle->IsScheduled &&
3028                    "already scheduled bundle gets ready");
3029             ReadyList.insert(DepBundle);
3030             LLVM_DEBUG(dbgs()
3031                        << "SLP:    gets ready (ctl): " << *DepBundle << "\n");
3032           }
3033         }
3034 
3035       }
3036     }
3037 
3038     /// Verify basic self consistency properties of the data structure.
3039     void verify() {
3040       if (!ScheduleStart)
3041         return;
3042 
3043       assert(ScheduleStart->getParent() == ScheduleEnd->getParent() &&
3044              ScheduleStart->comesBefore(ScheduleEnd) &&
3045              "Not a valid scheduling region?");
3046 
3047       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
3048         auto *SD = getScheduleData(I);
3049         if (!SD)
3050           continue;
3051         assert(isInSchedulingRegion(SD) &&
3052                "primary schedule data not in window?");
3053         assert(isInSchedulingRegion(SD->FirstInBundle) &&
3054                "entire bundle in window!");
3055         (void)SD;
3056         doForAllOpcodes(I, [](ScheduleData *SD) { SD->verify(); });
3057       }
3058 
3059       for (auto *SD : ReadyInsts) {
3060         assert(SD->isSchedulingEntity() && SD->isReady() &&
3061                "item in ready list not ready?");
3062         (void)SD;
3063       }
3064     }
3065 
3066     void doForAllOpcodes(Value *V,
3067                          function_ref<void(ScheduleData *SD)> Action) {
3068       if (ScheduleData *SD = getScheduleData(V))
3069         Action(SD);
3070       auto I = ExtraScheduleDataMap.find(V);
3071       if (I != ExtraScheduleDataMap.end())
3072         for (auto &P : I->second)
3073           if (isInSchedulingRegion(P.second))
3074             Action(P.second);
3075     }
3076 
3077     /// Put all instructions into the ReadyList which are ready for scheduling.
3078     template <typename ReadyListType>
3079     void initialFillReadyList(ReadyListType &ReadyList) {
3080       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
3081         doForAllOpcodes(I, [&](ScheduleData *SD) {
3082           if (SD->isSchedulingEntity() && SD->hasValidDependencies() &&
3083               SD->isReady()) {
3084             ReadyList.insert(SD);
3085             LLVM_DEBUG(dbgs()
3086                        << "SLP:    initially in ready list: " << *SD << "\n");
3087           }
3088         });
3089       }
3090     }
3091 
3092     /// Build a bundle from the ScheduleData nodes corresponding to the
3093     /// scalar instruction for each lane.
3094     ScheduleData *buildBundle(ArrayRef<Value *> VL);
3095 
3096     /// Checks if a bundle of instructions can be scheduled, i.e. has no
3097     /// cyclic dependencies. This is only a dry-run, no instructions are
3098     /// actually moved at this stage.
3099     /// \returns the scheduling bundle. The returned Optional value is non-None
3100     /// if \p VL is allowed to be scheduled.
3101     Optional<ScheduleData *>
3102     tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
3103                       const InstructionsState &S);
3104 
3105     /// Un-bundles a group of instructions.
3106     void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
3107 
3108     /// Allocates schedule data chunk.
3109     ScheduleData *allocateScheduleDataChunks();
3110 
3111     /// Extends the scheduling region so that V is inside the region.
3112     /// \returns true if the region size is within the limit.
3113     bool extendSchedulingRegion(Value *V, const InstructionsState &S);
3114 
3115     /// Initialize the ScheduleData structures for new instructions in the
3116     /// scheduling region.
3117     void initScheduleData(Instruction *FromI, Instruction *ToI,
3118                           ScheduleData *PrevLoadStore,
3119                           ScheduleData *NextLoadStore);
3120 
3121     /// Updates the dependency information of a bundle and of all instructions/
3122     /// bundles which depend on the original bundle.
3123     void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
3124                                BoUpSLP *SLP);
3125 
3126     /// Sets all instruction in the scheduling region to un-scheduled.
3127     void resetSchedule();
3128 
3129     BasicBlock *BB;
3130 
3131     /// Simple memory allocation for ScheduleData.
3132     std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
3133 
3134     /// The size of a ScheduleData array in ScheduleDataChunks.
3135     int ChunkSize;
3136 
3137     /// The allocator position in the current chunk, which is the last entry
3138     /// of ScheduleDataChunks.
3139     int ChunkPos;
3140 
3141     /// Attaches ScheduleData to Instruction.
3142     /// Note that the mapping survives during all vectorization iterations, i.e.
3143     /// ScheduleData structures are recycled.
3144     DenseMap<Instruction *, ScheduleData *> ScheduleDataMap;
3145 
3146     /// Attaches ScheduleData to Instruction with the leading key.
3147     DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
3148         ExtraScheduleDataMap;
3149 
3150     /// The ready-list for scheduling (only used for the dry-run).
3151     SetVector<ScheduleData *> ReadyInsts;
3152 
3153     /// The first instruction of the scheduling region.
3154     Instruction *ScheduleStart = nullptr;
3155 
3156     /// The first instruction _after_ the scheduling region.
3157     Instruction *ScheduleEnd = nullptr;
3158 
3159     /// The first memory accessing instruction in the scheduling region
3160     /// (can be null).
3161     ScheduleData *FirstLoadStoreInRegion = nullptr;
3162 
3163     /// The last memory accessing instruction in the scheduling region
3164     /// (can be null).
3165     ScheduleData *LastLoadStoreInRegion = nullptr;
3166 
3167     /// Is there an llvm.stacksave or llvm.stackrestore in the scheduling
3168     /// region?  Used to optimize the dependence calculation for the
3169     /// common case where there isn't.
3170     bool RegionHasStackSave = false;
3171 
3172     /// The current size of the scheduling region.
3173     int ScheduleRegionSize = 0;
3174 
3175     /// The maximum size allowed for the scheduling region.
3176     int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
3177 
3178     /// The ID of the scheduling region. For a new vectorization iteration this
3179     /// is incremented which "removes" all ScheduleData from the region.
3180     /// Make sure that the initial SchedulingRegionID is greater than the
3181     /// initial SchedulingRegionID in ScheduleData (which is 0).
3182     int SchedulingRegionID = 1;
3183   };
3184 
3185   /// Attaches the BlockScheduling structures to basic blocks.
3186   MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
3187 
3188   /// Performs the "real" scheduling. Done before vectorization is actually
3189   /// performed in a basic block.
3190   void scheduleBlock(BlockScheduling *BS);
3191 
3192   /// List of users to ignore during scheduling and that don't need extracting.
3193   ArrayRef<Value *> UserIgnoreList;
3194 
3195   /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
3196   /// sorted SmallVectors of unsigned.
3197   struct OrdersTypeDenseMapInfo {
3198     static OrdersType getEmptyKey() {
3199       OrdersType V;
3200       V.push_back(~1U);
3201       return V;
3202     }
3203 
3204     static OrdersType getTombstoneKey() {
3205       OrdersType V;
3206       V.push_back(~2U);
3207       return V;
3208     }
3209 
3210     static unsigned getHashValue(const OrdersType &V) {
3211       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
3212     }
3213 
3214     static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
3215       return LHS == RHS;
3216     }
3217   };
3218 
3219   // Analysis and block reference.
3220   Function *F;
3221   ScalarEvolution *SE;
3222   TargetTransformInfo *TTI;
3223   TargetLibraryInfo *TLI;
3224   LoopInfo *LI;
3225   DominatorTree *DT;
3226   AssumptionCache *AC;
3227   DemandedBits *DB;
3228   const DataLayout *DL;
3229   OptimizationRemarkEmitter *ORE;
3230 
3231   unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
3232   unsigned MinVecRegSize; // Set by cl::opt (default: 128).
3233 
3234   /// Instruction builder to construct the vectorized tree.
3235   IRBuilder<> Builder;
3236 
3237   /// A map of scalar integer values to the smallest bit width with which they
3238   /// can legally be represented. The values map to (width, signed) pairs,
3239   /// where "width" indicates the minimum bit width and "signed" is True if the
3240   /// value must be signed-extended, rather than zero-extended, back to its
3241   /// original width.
3242   MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
3243 };
3244 
3245 } // end namespace slpvectorizer
3246 
3247 template <> struct GraphTraits<BoUpSLP *> {
3248   using TreeEntry = BoUpSLP::TreeEntry;
3249 
3250   /// NodeRef has to be a pointer per the GraphWriter.
3251   using NodeRef = TreeEntry *;
3252 
3253   using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy;
3254 
3255   /// Add the VectorizableTree to the index iterator to be able to return
3256   /// TreeEntry pointers.
3257   struct ChildIteratorType
3258       : public iterator_adaptor_base<
3259             ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
3260     ContainerTy &VectorizableTree;
3261 
3262     ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W,
3263                       ContainerTy &VT)
3264         : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
3265 
3266     NodeRef operator*() { return I->UserTE; }
3267   };
3268 
3269   static NodeRef getEntryNode(BoUpSLP &R) {
3270     return R.VectorizableTree[0].get();
3271   }
3272 
3273   static ChildIteratorType child_begin(NodeRef N) {
3274     return {N->UserTreeIndices.begin(), N->Container};
3275   }
3276 
3277   static ChildIteratorType child_end(NodeRef N) {
3278     return {N->UserTreeIndices.end(), N->Container};
3279   }
3280 
3281   /// For the node iterator we just need to turn the TreeEntry iterator into a
3282   /// TreeEntry* iterator so that it dereferences to NodeRef.
3283   class nodes_iterator {
3284     using ItTy = ContainerTy::iterator;
3285     ItTy It;
3286 
3287   public:
3288     nodes_iterator(const ItTy &It2) : It(It2) {}
3289     NodeRef operator*() { return It->get(); }
3290     nodes_iterator operator++() {
3291       ++It;
3292       return *this;
3293     }
3294     bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
3295   };
3296 
3297   static nodes_iterator nodes_begin(BoUpSLP *R) {
3298     return nodes_iterator(R->VectorizableTree.begin());
3299   }
3300 
3301   static nodes_iterator nodes_end(BoUpSLP *R) {
3302     return nodes_iterator(R->VectorizableTree.end());
3303   }
3304 
3305   static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
3306 };
3307 
3308 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
3309   using TreeEntry = BoUpSLP::TreeEntry;
3310 
3311   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
3312 
3313   std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
3314     std::string Str;
3315     raw_string_ostream OS(Str);
3316     if (isSplat(Entry->Scalars))
3317       OS << "<splat> ";
3318     for (auto V : Entry->Scalars) {
3319       OS << *V;
3320       if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) {
3321             return EU.Scalar == V;
3322           }))
3323         OS << " <extract>";
3324       OS << "\n";
3325     }
3326     return Str;
3327   }
3328 
3329   static std::string getNodeAttributes(const TreeEntry *Entry,
3330                                        const BoUpSLP *) {
3331     if (Entry->State == TreeEntry::NeedToGather)
3332       return "color=red";
3333     return "";
3334   }
3335 };
3336 
3337 } // end namespace llvm
3338 
3339 BoUpSLP::~BoUpSLP() {
3340   SmallVector<WeakTrackingVH> DeadInsts;
3341   for (auto *I : DeletedInstructions) {
3342     for (Use &U : I->operands()) {
3343       auto *Op = dyn_cast<Instruction>(U.get());
3344       if (Op && !DeletedInstructions.count(Op) && Op->hasOneUser() &&
3345           wouldInstructionBeTriviallyDead(Op, TLI))
3346         DeadInsts.emplace_back(Op);
3347     }
3348     I->dropAllReferences();
3349   }
3350   for (auto *I : DeletedInstructions) {
3351     assert(I->use_empty() &&
3352            "trying to erase instruction with users.");
3353     I->eraseFromParent();
3354   }
3355 
3356   // Cleanup any dead scalar code feeding the vectorized instructions
3357   RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI);
3358 
3359 #ifdef EXPENSIVE_CHECKS
3360   // If we could guarantee that this call is not extremely slow, we could
3361   // remove the ifdef limitation (see PR47712).
3362   assert(!verifyFunction(*F, &dbgs()));
3363 #endif
3364 }
3365 
3366 /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses
3367 /// contains original mask for the scalars reused in the node. Procedure
3368 /// transform this mask in accordance with the given \p Mask.
3369 static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) {
3370   assert(!Mask.empty() && Reuses.size() == Mask.size() &&
3371          "Expected non-empty mask.");
3372   SmallVector<int> Prev(Reuses.begin(), Reuses.end());
3373   Prev.swap(Reuses);
3374   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
3375     if (Mask[I] != UndefMaskElem)
3376       Reuses[Mask[I]] = Prev[I];
3377 }
3378 
3379 /// Reorders the given \p Order according to the given \p Mask. \p Order - is
3380 /// the original order of the scalars. Procedure transforms the provided order
3381 /// in accordance with the given \p Mask. If the resulting \p Order is just an
3382 /// identity order, \p Order is cleared.
3383 static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) {
3384   assert(!Mask.empty() && "Expected non-empty mask.");
3385   SmallVector<int> MaskOrder;
3386   if (Order.empty()) {
3387     MaskOrder.resize(Mask.size());
3388     std::iota(MaskOrder.begin(), MaskOrder.end(), 0);
3389   } else {
3390     inversePermutation(Order, MaskOrder);
3391   }
3392   reorderReuses(MaskOrder, Mask);
3393   if (ShuffleVectorInst::isIdentityMask(MaskOrder)) {
3394     Order.clear();
3395     return;
3396   }
3397   Order.assign(Mask.size(), Mask.size());
3398   for (unsigned I = 0, E = Mask.size(); I < E; ++I)
3399     if (MaskOrder[I] != UndefMaskElem)
3400       Order[MaskOrder[I]] = I;
3401   fixupOrderingIndices(Order);
3402 }
3403 
3404 Optional<BoUpSLP::OrdersType>
3405 BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) {
3406   assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
3407   unsigned NumScalars = TE.Scalars.size();
3408   OrdersType CurrentOrder(NumScalars, NumScalars);
3409   SmallVector<int> Positions;
3410   SmallBitVector UsedPositions(NumScalars);
3411   const TreeEntry *STE = nullptr;
3412   // Try to find all gathered scalars that are gets vectorized in other
3413   // vectorize node. Here we can have only one single tree vector node to
3414   // correctly identify order of the gathered scalars.
3415   for (unsigned I = 0; I < NumScalars; ++I) {
3416     Value *V = TE.Scalars[I];
3417     if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V))
3418       continue;
3419     if (const auto *LocalSTE = getTreeEntry(V)) {
3420       if (!STE)
3421         STE = LocalSTE;
3422       else if (STE != LocalSTE)
3423         // Take the order only from the single vector node.
3424         return None;
3425       unsigned Lane =
3426           std::distance(STE->Scalars.begin(), find(STE->Scalars, V));
3427       if (Lane >= NumScalars)
3428         return None;
3429       if (CurrentOrder[Lane] != NumScalars) {
3430         if (Lane != I)
3431           continue;
3432         UsedPositions.reset(CurrentOrder[Lane]);
3433       }
3434       // The partial identity (where only some elements of the gather node are
3435       // in the identity order) is good.
3436       CurrentOrder[Lane] = I;
3437       UsedPositions.set(I);
3438     }
3439   }
3440   // Need to keep the order if we have a vector entry and at least 2 scalars or
3441   // the vectorized entry has just 2 scalars.
3442   if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) {
3443     auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) {
3444       for (unsigned I = 0; I < NumScalars; ++I)
3445         if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars)
3446           return false;
3447       return true;
3448     };
3449     if (IsIdentityOrder(CurrentOrder)) {
3450       CurrentOrder.clear();
3451       return CurrentOrder;
3452     }
3453     auto *It = CurrentOrder.begin();
3454     for (unsigned I = 0; I < NumScalars;) {
3455       if (UsedPositions.test(I)) {
3456         ++I;
3457         continue;
3458       }
3459       if (*It == NumScalars) {
3460         *It = I;
3461         ++I;
3462       }
3463       ++It;
3464     }
3465     return CurrentOrder;
3466   }
3467   return None;
3468 }
3469 
3470 bool clusterSortPtrAccesses(ArrayRef<Value *> VL, Type *ElemTy,
3471                             const DataLayout &DL, ScalarEvolution &SE,
3472                             SmallVectorImpl<unsigned> &SortedIndices) {
3473   assert(llvm::all_of(
3474              VL, [](const Value *V) { return V->getType()->isPointerTy(); }) &&
3475          "Expected list of pointer operands.");
3476   // Map from bases to a vector of (Ptr, Offset, OrigIdx), which we insert each
3477   // Ptr into, sort and return the sorted indices with values next to one
3478   // another.
3479   MapVector<Value *, SmallVector<std::tuple<Value *, int, unsigned>>> Bases;
3480   Bases[VL[0]].push_back(std::make_tuple(VL[0], 0U, 0U));
3481 
3482   unsigned Cnt = 1;
3483   for (Value *Ptr : VL.drop_front()) {
3484     bool Found = any_of(Bases, [&](auto &Base) {
3485       Optional<int> Diff =
3486           getPointersDiff(ElemTy, Base.first, ElemTy, Ptr, DL, SE,
3487                           /*StrictCheck=*/true);
3488       if (!Diff)
3489         return false;
3490 
3491       Base.second.emplace_back(Ptr, *Diff, Cnt++);
3492       return true;
3493     });
3494 
3495     if (!Found) {
3496       // If we haven't found enough to usefully cluster, return early.
3497       if (Bases.size() > VL.size() / 2 - 1)
3498         return false;
3499 
3500       // Not found already - add a new Base
3501       Bases[Ptr].emplace_back(Ptr, 0, Cnt++);
3502     }
3503   }
3504 
3505   // For each of the bases sort the pointers by Offset and check if any of the
3506   // base become consecutively allocated.
3507   bool AnyConsecutive = false;
3508   for (auto &Base : Bases) {
3509     auto &Vec = Base.second;
3510     if (Vec.size() > 1) {
3511       llvm::stable_sort(Vec, [](const std::tuple<Value *, int, unsigned> &X,
3512                                 const std::tuple<Value *, int, unsigned> &Y) {
3513         return std::get<1>(X) < std::get<1>(Y);
3514       });
3515       int InitialOffset = std::get<1>(Vec[0]);
3516       AnyConsecutive |= all_of(enumerate(Vec), [InitialOffset](auto &P) {
3517         return std::get<1>(P.value()) == int(P.index()) + InitialOffset;
3518       });
3519     }
3520   }
3521 
3522   // Fill SortedIndices array only if it looks worth-while to sort the ptrs.
3523   SortedIndices.clear();
3524   if (!AnyConsecutive)
3525     return false;
3526 
3527   for (auto &Base : Bases) {
3528     for (auto &T : Base.second)
3529       SortedIndices.push_back(std::get<2>(T));
3530   }
3531 
3532   assert(SortedIndices.size() == VL.size() &&
3533          "Expected SortedIndices to be the size of VL");
3534   return true;
3535 }
3536 
3537 Optional<BoUpSLP::OrdersType>
3538 BoUpSLP::findPartiallyOrderedLoads(const BoUpSLP::TreeEntry &TE) {
3539   assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
3540   Type *ScalarTy = TE.Scalars[0]->getType();
3541 
3542   SmallVector<Value *> Ptrs;
3543   Ptrs.reserve(TE.Scalars.size());
3544   for (Value *V : TE.Scalars) {
3545     auto *L = dyn_cast<LoadInst>(V);
3546     if (!L || !L->isSimple())
3547       return None;
3548     Ptrs.push_back(L->getPointerOperand());
3549   }
3550 
3551   BoUpSLP::OrdersType Order;
3552   if (clusterSortPtrAccesses(Ptrs, ScalarTy, *DL, *SE, Order))
3553     return Order;
3554   return None;
3555 }
3556 
3557 Optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE,
3558                                                          bool TopToBottom) {
3559   // No need to reorder if need to shuffle reuses, still need to shuffle the
3560   // node.
3561   if (!TE.ReuseShuffleIndices.empty())
3562     return None;
3563   if (TE.State == TreeEntry::Vectorize &&
3564       (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) ||
3565        (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) &&
3566       !TE.isAltShuffle())
3567     return TE.ReorderIndices;
3568   if (TE.State == TreeEntry::NeedToGather) {
3569     // TODO: add analysis of other gather nodes with extractelement
3570     // instructions and other values/instructions, not only undefs.
3571     if (((TE.getOpcode() == Instruction::ExtractElement &&
3572           !TE.isAltShuffle()) ||
3573          (all_of(TE.Scalars,
3574                  [](Value *V) {
3575                    return isa<UndefValue, ExtractElementInst>(V);
3576                  }) &&
3577           any_of(TE.Scalars,
3578                  [](Value *V) { return isa<ExtractElementInst>(V); }))) &&
3579         all_of(TE.Scalars,
3580                [](Value *V) {
3581                  auto *EE = dyn_cast<ExtractElementInst>(V);
3582                  return !EE || isa<FixedVectorType>(EE->getVectorOperandType());
3583                }) &&
3584         allSameType(TE.Scalars)) {
3585       // Check that gather of extractelements can be represented as
3586       // just a shuffle of a single vector.
3587       OrdersType CurrentOrder;
3588       bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder);
3589       if (Reuse || !CurrentOrder.empty()) {
3590         if (!CurrentOrder.empty())
3591           fixupOrderingIndices(CurrentOrder);
3592         return CurrentOrder;
3593       }
3594     }
3595     if (Optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE))
3596       return CurrentOrder;
3597     if (TE.Scalars.size() >= 4)
3598       if (Optional<OrdersType> Order = findPartiallyOrderedLoads(TE))
3599         return Order;
3600   }
3601   return None;
3602 }
3603 
3604 void BoUpSLP::reorderTopToBottom() {
3605   // Maps VF to the graph nodes.
3606   DenseMap<unsigned, SetVector<TreeEntry *>> VFToOrderedEntries;
3607   // ExtractElement gather nodes which can be vectorized and need to handle
3608   // their ordering.
3609   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3610 
3611   // Maps a TreeEntry to the reorder indices of external users.
3612   DenseMap<const TreeEntry *, SmallVector<OrdersType, 1>>
3613       ExternalUserReorderMap;
3614   // Find all reorderable nodes with the given VF.
3615   // Currently the are vectorized stores,loads,extracts + some gathering of
3616   // extracts.
3617   for_each(VectorizableTree, [this, &VFToOrderedEntries, &GathersToOrders,
3618                               &ExternalUserReorderMap](
3619                                  const std::unique_ptr<TreeEntry> &TE) {
3620     // Look for external users that will probably be vectorized.
3621     SmallVector<OrdersType, 1> ExternalUserReorderIndices =
3622         findExternalStoreUsersReorderIndices(TE.get());
3623     if (!ExternalUserReorderIndices.empty()) {
3624       VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
3625       ExternalUserReorderMap.try_emplace(TE.get(),
3626                                          std::move(ExternalUserReorderIndices));
3627     }
3628 
3629     if (Optional<OrdersType> CurrentOrder =
3630             getReorderingData(*TE, /*TopToBottom=*/true)) {
3631       // Do not include ordering for nodes used in the alt opcode vectorization,
3632       // better to reorder them during bottom-to-top stage. If follow the order
3633       // here, it causes reordering of the whole graph though actually it is
3634       // profitable just to reorder the subgraph that starts from the alternate
3635       // opcode vectorization node. Such nodes already end-up with the shuffle
3636       // instruction and it is just enough to change this shuffle rather than
3637       // rotate the scalars for the whole graph.
3638       unsigned Cnt = 0;
3639       const TreeEntry *UserTE = TE.get();
3640       while (UserTE && Cnt < RecursionMaxDepth) {
3641         if (UserTE->UserTreeIndices.size() != 1)
3642           break;
3643         if (all_of(UserTE->UserTreeIndices, [](const EdgeInfo &EI) {
3644               return EI.UserTE->State == TreeEntry::Vectorize &&
3645                      EI.UserTE->isAltShuffle() && EI.UserTE->Idx != 0;
3646             }))
3647           return;
3648         if (UserTE->UserTreeIndices.empty())
3649           UserTE = nullptr;
3650         else
3651           UserTE = UserTE->UserTreeIndices.back().UserTE;
3652         ++Cnt;
3653       }
3654       VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
3655       if (TE->State != TreeEntry::Vectorize)
3656         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3657     }
3658   });
3659 
3660   // Reorder the graph nodes according to their vectorization factor.
3661   for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1;
3662        VF /= 2) {
3663     auto It = VFToOrderedEntries.find(VF);
3664     if (It == VFToOrderedEntries.end())
3665       continue;
3666     // Try to find the most profitable order. We just are looking for the most
3667     // used order and reorder scalar elements in the nodes according to this
3668     // mostly used order.
3669     ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef();
3670     // All operands are reordered and used only in this node - propagate the
3671     // most used order to the user node.
3672     MapVector<OrdersType, unsigned,
3673               DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3674         OrdersUses;
3675     SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3676     for (const TreeEntry *OpTE : OrderedEntries) {
3677       // No need to reorder this nodes, still need to extend and to use shuffle,
3678       // just need to merge reordering shuffle and the reuse shuffle.
3679       if (!OpTE->ReuseShuffleIndices.empty())
3680         continue;
3681       // Count number of orders uses.
3682       const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3683         if (OpTE->State == TreeEntry::NeedToGather) {
3684           auto It = GathersToOrders.find(OpTE);
3685           if (It != GathersToOrders.end())
3686             return It->second;
3687         }
3688         return OpTE->ReorderIndices;
3689       }();
3690       // First consider the order of the external scalar users.
3691       auto It = ExternalUserReorderMap.find(OpTE);
3692       if (It != ExternalUserReorderMap.end()) {
3693         const auto &ExternalUserReorderIndices = It->second;
3694         for (const OrdersType &ExtOrder : ExternalUserReorderIndices)
3695           ++OrdersUses.insert(std::make_pair(ExtOrder, 0)).first->second;
3696         // No other useful reorder data in this entry.
3697         if (Order.empty())
3698           continue;
3699       }
3700       // Stores actually store the mask, not the order, need to invert.
3701       if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3702           OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3703         SmallVector<int> Mask;
3704         inversePermutation(Order, Mask);
3705         unsigned E = Order.size();
3706         OrdersType CurrentOrder(E, E);
3707         transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3708           return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3709         });
3710         fixupOrderingIndices(CurrentOrder);
3711         ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
3712       } else {
3713         ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
3714       }
3715     }
3716     // Set order of the user node.
3717     if (OrdersUses.empty())
3718       continue;
3719     // Choose the most used order.
3720     ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3721     unsigned Cnt = OrdersUses.front().second;
3722     for (const auto &Pair : drop_begin(OrdersUses)) {
3723       if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3724         BestOrder = Pair.first;
3725         Cnt = Pair.second;
3726       }
3727     }
3728     // Set order of the user node.
3729     if (BestOrder.empty())
3730       continue;
3731     SmallVector<int> Mask;
3732     inversePermutation(BestOrder, Mask);
3733     SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3734     unsigned E = BestOrder.size();
3735     transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3736       return I < E ? static_cast<int>(I) : UndefMaskElem;
3737     });
3738     // Do an actual reordering, if profitable.
3739     for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
3740       // Just do the reordering for the nodes with the given VF.
3741       if (TE->Scalars.size() != VF) {
3742         if (TE->ReuseShuffleIndices.size() == VF) {
3743           // Need to reorder the reuses masks of the operands with smaller VF to
3744           // be able to find the match between the graph nodes and scalar
3745           // operands of the given node during vectorization/cost estimation.
3746           assert(all_of(TE->UserTreeIndices,
3747                         [VF, &TE](const EdgeInfo &EI) {
3748                           return EI.UserTE->Scalars.size() == VF ||
3749                                  EI.UserTE->Scalars.size() ==
3750                                      TE->Scalars.size();
3751                         }) &&
3752                  "All users must be of VF size.");
3753           // Update ordering of the operands with the smaller VF than the given
3754           // one.
3755           reorderReuses(TE->ReuseShuffleIndices, Mask);
3756         }
3757         continue;
3758       }
3759       if (TE->State == TreeEntry::Vectorize &&
3760           isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst,
3761               InsertElementInst>(TE->getMainOp()) &&
3762           !TE->isAltShuffle()) {
3763         // Build correct orders for extract{element,value}, loads and
3764         // stores.
3765         reorderOrder(TE->ReorderIndices, Mask);
3766         if (isa<InsertElementInst, StoreInst>(TE->getMainOp()))
3767           TE->reorderOperands(Mask);
3768       } else {
3769         // Reorder the node and its operands.
3770         TE->reorderOperands(Mask);
3771         assert(TE->ReorderIndices.empty() &&
3772                "Expected empty reorder sequence.");
3773         reorderScalars(TE->Scalars, Mask);
3774       }
3775       if (!TE->ReuseShuffleIndices.empty()) {
3776         // Apply reversed order to keep the original ordering of the reused
3777         // elements to avoid extra reorder indices shuffling.
3778         OrdersType CurrentOrder;
3779         reorderOrder(CurrentOrder, MaskOrder);
3780         SmallVector<int> NewReuses;
3781         inversePermutation(CurrentOrder, NewReuses);
3782         addMask(NewReuses, TE->ReuseShuffleIndices);
3783         TE->ReuseShuffleIndices.swap(NewReuses);
3784       }
3785     }
3786   }
3787 }
3788 
3789 bool BoUpSLP::canReorderOperands(
3790     TreeEntry *UserTE, SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
3791     ArrayRef<TreeEntry *> ReorderableGathers,
3792     SmallVectorImpl<TreeEntry *> &GatherOps) {
3793   for (unsigned I = 0, E = UserTE->getNumOperands(); I < E; ++I) {
3794     if (any_of(Edges, [I](const std::pair<unsigned, TreeEntry *> &OpData) {
3795           return OpData.first == I &&
3796                  OpData.second->State == TreeEntry::Vectorize;
3797         }))
3798       continue;
3799     if (TreeEntry *TE = getVectorizedOperand(UserTE, I)) {
3800       // Do not reorder if operand node is used by many user nodes.
3801       if (any_of(TE->UserTreeIndices,
3802                  [UserTE](const EdgeInfo &EI) { return EI.UserTE != UserTE; }))
3803         return false;
3804       // Add the node to the list of the ordered nodes with the identity
3805       // order.
3806       Edges.emplace_back(I, TE);
3807       continue;
3808     }
3809     ArrayRef<Value *> VL = UserTE->getOperand(I);
3810     TreeEntry *Gather = nullptr;
3811     if (count_if(ReorderableGathers, [VL, &Gather](TreeEntry *TE) {
3812           assert(TE->State != TreeEntry::Vectorize &&
3813                  "Only non-vectorized nodes are expected.");
3814           if (TE->isSame(VL)) {
3815             Gather = TE;
3816             return true;
3817           }
3818           return false;
3819         }) > 1)
3820       return false;
3821     if (Gather)
3822       GatherOps.push_back(Gather);
3823   }
3824   return true;
3825 }
3826 
3827 void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) {
3828   SetVector<TreeEntry *> OrderedEntries;
3829   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3830   // Find all reorderable leaf nodes with the given VF.
3831   // Currently the are vectorized loads,extracts without alternate operands +
3832   // some gathering of extracts.
3833   SmallVector<TreeEntry *> NonVectorized;
3834   for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders,
3835                               &NonVectorized](
3836                                  const std::unique_ptr<TreeEntry> &TE) {
3837     if (TE->State != TreeEntry::Vectorize)
3838       NonVectorized.push_back(TE.get());
3839     if (Optional<OrdersType> CurrentOrder =
3840             getReorderingData(*TE, /*TopToBottom=*/false)) {
3841       OrderedEntries.insert(TE.get());
3842       if (TE->State != TreeEntry::Vectorize)
3843         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3844     }
3845   });
3846 
3847   // 1. Propagate order to the graph nodes, which use only reordered nodes.
3848   // I.e., if the node has operands, that are reordered, try to make at least
3849   // one operand order in the natural order and reorder others + reorder the
3850   // user node itself.
3851   SmallPtrSet<const TreeEntry *, 4> Visited;
3852   while (!OrderedEntries.empty()) {
3853     // 1. Filter out only reordered nodes.
3854     // 2. If the entry has multiple uses - skip it and jump to the next node.
3855     MapVector<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users;
3856     SmallVector<TreeEntry *> Filtered;
3857     for (TreeEntry *TE : OrderedEntries) {
3858       if (!(TE->State == TreeEntry::Vectorize ||
3859             (TE->State == TreeEntry::NeedToGather &&
3860              GathersToOrders.count(TE))) ||
3861           TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3862           !all_of(drop_begin(TE->UserTreeIndices),
3863                   [TE](const EdgeInfo &EI) {
3864                     return EI.UserTE == TE->UserTreeIndices.front().UserTE;
3865                   }) ||
3866           !Visited.insert(TE).second) {
3867         Filtered.push_back(TE);
3868         continue;
3869       }
3870       // Build a map between user nodes and their operands order to speedup
3871       // search. The graph currently does not provide this dependency directly.
3872       for (EdgeInfo &EI : TE->UserTreeIndices) {
3873         TreeEntry *UserTE = EI.UserTE;
3874         auto It = Users.find(UserTE);
3875         if (It == Users.end())
3876           It = Users.insert({UserTE, {}}).first;
3877         It->second.emplace_back(EI.EdgeIdx, TE);
3878       }
3879     }
3880     // Erase filtered entries.
3881     for_each(Filtered,
3882              [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); });
3883     for (auto &Data : Users) {
3884       // Check that operands are used only in the User node.
3885       SmallVector<TreeEntry *> GatherOps;
3886       if (!canReorderOperands(Data.first, Data.second, NonVectorized,
3887                               GatherOps)) {
3888         for_each(Data.second,
3889                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3890                    OrderedEntries.remove(Op.second);
3891                  });
3892         continue;
3893       }
3894       // All operands are reordered and used only in this node - propagate the
3895       // most used order to the user node.
3896       MapVector<OrdersType, unsigned,
3897                 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3898           OrdersUses;
3899       // Do the analysis for each tree entry only once, otherwise the order of
3900       // the same node my be considered several times, though might be not
3901       // profitable.
3902       SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3903       SmallPtrSet<const TreeEntry *, 4> VisitedUsers;
3904       for (const auto &Op : Data.second) {
3905         TreeEntry *OpTE = Op.second;
3906         if (!VisitedOps.insert(OpTE).second)
3907           continue;
3908         if (!OpTE->ReuseShuffleIndices.empty() ||
3909             (IgnoreReorder && OpTE == VectorizableTree.front().get()))
3910           continue;
3911         const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3912           if (OpTE->State == TreeEntry::NeedToGather)
3913             return GathersToOrders.find(OpTE)->second;
3914           return OpTE->ReorderIndices;
3915         }();
3916         unsigned NumOps = count_if(
3917             Data.second, [OpTE](const std::pair<unsigned, TreeEntry *> &P) {
3918               return P.second == OpTE;
3919             });
3920         // Stores actually store the mask, not the order, need to invert.
3921         if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3922             OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3923           SmallVector<int> Mask;
3924           inversePermutation(Order, Mask);
3925           unsigned E = Order.size();
3926           OrdersType CurrentOrder(E, E);
3927           transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3928             return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3929           });
3930           fixupOrderingIndices(CurrentOrder);
3931           OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second +=
3932               NumOps;
3933         } else {
3934           OrdersUses.insert(std::make_pair(Order, 0)).first->second += NumOps;
3935         }
3936         auto Res = OrdersUses.insert(std::make_pair(OrdersType(), 0));
3937         const auto &&AllowsReordering = [IgnoreReorder, &GathersToOrders](
3938                                             const TreeEntry *TE) {
3939           if (!TE->ReorderIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3940               (TE->State == TreeEntry::Vectorize && TE->isAltShuffle()) ||
3941               (IgnoreReorder && TE->Idx == 0))
3942             return true;
3943           if (TE->State == TreeEntry::NeedToGather) {
3944             auto It = GathersToOrders.find(TE);
3945             if (It != GathersToOrders.end())
3946               return !It->second.empty();
3947             return true;
3948           }
3949           return false;
3950         };
3951         for (const EdgeInfo &EI : OpTE->UserTreeIndices) {
3952           TreeEntry *UserTE = EI.UserTE;
3953           if (!VisitedUsers.insert(UserTE).second)
3954             continue;
3955           // May reorder user node if it requires reordering, has reused
3956           // scalars, is an alternate op vectorize node or its op nodes require
3957           // reordering.
3958           if (AllowsReordering(UserTE))
3959             continue;
3960           // Check if users allow reordering.
3961           // Currently look up just 1 level of operands to avoid increase of
3962           // the compile time.
3963           // Profitable to reorder if definitely more operands allow
3964           // reordering rather than those with natural order.
3965           ArrayRef<std::pair<unsigned, TreeEntry *>> Ops = Users[UserTE];
3966           if (static_cast<unsigned>(count_if(
3967                   Ops, [UserTE, &AllowsReordering](
3968                            const std::pair<unsigned, TreeEntry *> &Op) {
3969                     return AllowsReordering(Op.second) &&
3970                            all_of(Op.second->UserTreeIndices,
3971                                   [UserTE](const EdgeInfo &EI) {
3972                                     return EI.UserTE == UserTE;
3973                                   });
3974                   })) <= Ops.size() / 2)
3975             ++Res.first->second;
3976         }
3977       }
3978       // If no orders - skip current nodes and jump to the next one, if any.
3979       if (OrdersUses.empty()) {
3980         for_each(Data.second,
3981                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3982                    OrderedEntries.remove(Op.second);
3983                  });
3984         continue;
3985       }
3986       // Choose the best order.
3987       ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3988       unsigned Cnt = OrdersUses.front().second;
3989       for (const auto &Pair : drop_begin(OrdersUses)) {
3990         if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3991           BestOrder = Pair.first;
3992           Cnt = Pair.second;
3993         }
3994       }
3995       // Set order of the user node (reordering of operands and user nodes).
3996       if (BestOrder.empty()) {
3997         for_each(Data.second,
3998                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3999                    OrderedEntries.remove(Op.second);
4000                  });
4001         continue;
4002       }
4003       // Erase operands from OrderedEntries list and adjust their orders.
4004       VisitedOps.clear();
4005       SmallVector<int> Mask;
4006       inversePermutation(BestOrder, Mask);
4007       SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
4008       unsigned E = BestOrder.size();
4009       transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
4010         return I < E ? static_cast<int>(I) : UndefMaskElem;
4011       });
4012       for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) {
4013         TreeEntry *TE = Op.second;
4014         OrderedEntries.remove(TE);
4015         if (!VisitedOps.insert(TE).second)
4016           continue;
4017         if (TE->ReuseShuffleIndices.size() == BestOrder.size()) {
4018           // Just reorder reuses indices.
4019           reorderReuses(TE->ReuseShuffleIndices, Mask);
4020           continue;
4021         }
4022         // Gathers are processed separately.
4023         if (TE->State != TreeEntry::Vectorize)
4024           continue;
4025         assert((BestOrder.size() == TE->ReorderIndices.size() ||
4026                 TE->ReorderIndices.empty()) &&
4027                "Non-matching sizes of user/operand entries.");
4028         reorderOrder(TE->ReorderIndices, Mask);
4029       }
4030       // For gathers just need to reorder its scalars.
4031       for (TreeEntry *Gather : GatherOps) {
4032         assert(Gather->ReorderIndices.empty() &&
4033                "Unexpected reordering of gathers.");
4034         if (!Gather->ReuseShuffleIndices.empty()) {
4035           // Just reorder reuses indices.
4036           reorderReuses(Gather->ReuseShuffleIndices, Mask);
4037           continue;
4038         }
4039         reorderScalars(Gather->Scalars, Mask);
4040         OrderedEntries.remove(Gather);
4041       }
4042       // Reorder operands of the user node and set the ordering for the user
4043       // node itself.
4044       if (Data.first->State != TreeEntry::Vectorize ||
4045           !isa<ExtractElementInst, ExtractValueInst, LoadInst>(
4046               Data.first->getMainOp()) ||
4047           Data.first->isAltShuffle())
4048         Data.first->reorderOperands(Mask);
4049       if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) ||
4050           Data.first->isAltShuffle()) {
4051         reorderScalars(Data.first->Scalars, Mask);
4052         reorderOrder(Data.first->ReorderIndices, MaskOrder);
4053         if (Data.first->ReuseShuffleIndices.empty() &&
4054             !Data.first->ReorderIndices.empty() &&
4055             !Data.first->isAltShuffle()) {
4056           // Insert user node to the list to try to sink reordering deeper in
4057           // the graph.
4058           OrderedEntries.insert(Data.first);
4059         }
4060       } else {
4061         reorderOrder(Data.first->ReorderIndices, Mask);
4062       }
4063     }
4064   }
4065   // If the reordering is unnecessary, just remove the reorder.
4066   if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() &&
4067       VectorizableTree.front()->ReuseShuffleIndices.empty())
4068     VectorizableTree.front()->ReorderIndices.clear();
4069 }
4070 
4071 void BoUpSLP::buildExternalUses(
4072     const ExtraValueToDebugLocsMap &ExternallyUsedValues) {
4073   // Collect the values that we need to extract from the tree.
4074   for (auto &TEPtr : VectorizableTree) {
4075     TreeEntry *Entry = TEPtr.get();
4076 
4077     // No need to handle users of gathered values.
4078     if (Entry->State == TreeEntry::NeedToGather)
4079       continue;
4080 
4081     // For each lane:
4082     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
4083       Value *Scalar = Entry->Scalars[Lane];
4084       int FoundLane = Entry->findLaneForValue(Scalar);
4085 
4086       // Check if the scalar is externally used as an extra arg.
4087       auto ExtI = ExternallyUsedValues.find(Scalar);
4088       if (ExtI != ExternallyUsedValues.end()) {
4089         LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
4090                           << Lane << " from " << *Scalar << ".\n");
4091         ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
4092       }
4093       for (User *U : Scalar->users()) {
4094         LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
4095 
4096         Instruction *UserInst = dyn_cast<Instruction>(U);
4097         if (!UserInst)
4098           continue;
4099 
4100         if (isDeleted(UserInst))
4101           continue;
4102 
4103         // Skip in-tree scalars that become vectors
4104         if (TreeEntry *UseEntry = getTreeEntry(U)) {
4105           Value *UseScalar = UseEntry->Scalars[0];
4106           // Some in-tree scalars will remain as scalar in vectorized
4107           // instructions. If that is the case, the one in Lane 0 will
4108           // be used.
4109           if (UseScalar != U ||
4110               UseEntry->State == TreeEntry::ScatterVectorize ||
4111               !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
4112             LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
4113                               << ".\n");
4114             assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state");
4115             continue;
4116           }
4117         }
4118 
4119         // Ignore users in the user ignore list.
4120         if (is_contained(UserIgnoreList, UserInst))
4121           continue;
4122 
4123         LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
4124                           << Lane << " from " << *Scalar << ".\n");
4125         ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
4126       }
4127     }
4128   }
4129 }
4130 
4131 DenseMap<Value *, SmallVector<StoreInst *, 4>>
4132 BoUpSLP::collectUserStores(const BoUpSLP::TreeEntry *TE) const {
4133   DenseMap<Value *, SmallVector<StoreInst *, 4>> PtrToStoresMap;
4134   for (unsigned Lane : seq<unsigned>(0, TE->Scalars.size())) {
4135     Value *V = TE->Scalars[Lane];
4136     // To save compilation time we don't visit if we have too many users.
4137     static constexpr unsigned UsersLimit = 4;
4138     if (V->hasNUsesOrMore(UsersLimit))
4139       break;
4140 
4141     // Collect stores per pointer object.
4142     for (User *U : V->users()) {
4143       auto *SI = dyn_cast<StoreInst>(U);
4144       if (SI == nullptr || !SI->isSimple() ||
4145           !isValidElementType(SI->getValueOperand()->getType()))
4146         continue;
4147       // Skip entry if already
4148       if (getTreeEntry(U))
4149         continue;
4150 
4151       Value *Ptr = getUnderlyingObject(SI->getPointerOperand());
4152       auto &StoresVec = PtrToStoresMap[Ptr];
4153       // For now just keep one store per pointer object per lane.
4154       // TODO: Extend this to support multiple stores per pointer per lane
4155       if (StoresVec.size() > Lane)
4156         continue;
4157       // Skip if in different BBs.
4158       if (!StoresVec.empty() &&
4159           SI->getParent() != StoresVec.back()->getParent())
4160         continue;
4161       // Make sure that the stores are of the same type.
4162       if (!StoresVec.empty() &&
4163           SI->getValueOperand()->getType() !=
4164               StoresVec.back()->getValueOperand()->getType())
4165         continue;
4166       StoresVec.push_back(SI);
4167     }
4168   }
4169   return PtrToStoresMap;
4170 }
4171 
4172 bool BoUpSLP::CanFormVector(const SmallVector<StoreInst *, 4> &StoresVec,
4173                             OrdersType &ReorderIndices) const {
4174   // We check whether the stores in StoreVec can form a vector by sorting them
4175   // and checking whether they are consecutive.
4176 
4177   // To avoid calling getPointersDiff() while sorting we create a vector of
4178   // pairs {store, offset from first} and sort this instead.
4179   SmallVector<std::pair<StoreInst *, int>, 4> StoreOffsetVec(StoresVec.size());
4180   StoreInst *S0 = StoresVec[0];
4181   StoreOffsetVec[0] = {S0, 0};
4182   Type *S0Ty = S0->getValueOperand()->getType();
4183   Value *S0Ptr = S0->getPointerOperand();
4184   for (unsigned Idx : seq<unsigned>(1, StoresVec.size())) {
4185     StoreInst *SI = StoresVec[Idx];
4186     Optional<int> Diff =
4187         getPointersDiff(S0Ty, S0Ptr, SI->getValueOperand()->getType(),
4188                         SI->getPointerOperand(), *DL, *SE,
4189                         /*StrictCheck=*/true);
4190     // We failed to compare the pointers so just abandon this StoresVec.
4191     if (!Diff)
4192       return false;
4193     StoreOffsetVec[Idx] = {StoresVec[Idx], *Diff};
4194   }
4195 
4196   // Sort the vector based on the pointers. We create a copy because we may
4197   // need the original later for calculating the reorder (shuffle) indices.
4198   stable_sort(StoreOffsetVec, [](const std::pair<StoreInst *, int> &Pair1,
4199                                  const std::pair<StoreInst *, int> &Pair2) {
4200     int Offset1 = Pair1.second;
4201     int Offset2 = Pair2.second;
4202     return Offset1 < Offset2;
4203   });
4204 
4205   // Check if the stores are consecutive by checking if their difference is 1.
4206   for (unsigned Idx : seq<unsigned>(1, StoreOffsetVec.size()))
4207     if (StoreOffsetVec[Idx].second != StoreOffsetVec[Idx-1].second + 1)
4208       return false;
4209 
4210   // Calculate the shuffle indices according to their offset against the sorted
4211   // StoreOffsetVec.
4212   ReorderIndices.reserve(StoresVec.size());
4213   for (StoreInst *SI : StoresVec) {
4214     unsigned Idx = find_if(StoreOffsetVec,
4215                            [SI](const std::pair<StoreInst *, int> &Pair) {
4216                              return Pair.first == SI;
4217                            }) -
4218                    StoreOffsetVec.begin();
4219     ReorderIndices.push_back(Idx);
4220   }
4221   // Identity order (e.g., {0,1,2,3}) is modeled as an empty OrdersType in
4222   // reorderTopToBottom() and reorderBottomToTop(), so we are following the
4223   // same convention here.
4224   auto IsIdentityOrder = [](const OrdersType &Order) {
4225     for (unsigned Idx : seq<unsigned>(0, Order.size()))
4226       if (Idx != Order[Idx])
4227         return false;
4228     return true;
4229   };
4230   if (IsIdentityOrder(ReorderIndices))
4231     ReorderIndices.clear();
4232 
4233   return true;
4234 }
4235 
4236 #ifndef NDEBUG
4237 LLVM_DUMP_METHOD static void dumpOrder(const BoUpSLP::OrdersType &Order) {
4238   for (unsigned Idx : Order)
4239     dbgs() << Idx << ", ";
4240   dbgs() << "\n";
4241 }
4242 #endif
4243 
4244 SmallVector<BoUpSLP::OrdersType, 1>
4245 BoUpSLP::findExternalStoreUsersReorderIndices(TreeEntry *TE) const {
4246   unsigned NumLanes = TE->Scalars.size();
4247 
4248   DenseMap<Value *, SmallVector<StoreInst *, 4>> PtrToStoresMap =
4249       collectUserStores(TE);
4250 
4251   // Holds the reorder indices for each candidate store vector that is a user of
4252   // the current TreeEntry.
4253   SmallVector<OrdersType, 1> ExternalReorderIndices;
4254 
4255   // Now inspect the stores collected per pointer and look for vectorization
4256   // candidates. For each candidate calculate the reorder index vector and push
4257   // it into `ExternalReorderIndices`
4258   for (const auto &Pair : PtrToStoresMap) {
4259     auto &StoresVec = Pair.second;
4260     // If we have fewer than NumLanes stores, then we can't form a vector.
4261     if (StoresVec.size() != NumLanes)
4262       continue;
4263 
4264     // If the stores are not consecutive then abandon this StoresVec.
4265     OrdersType ReorderIndices;
4266     if (!CanFormVector(StoresVec, ReorderIndices))
4267       continue;
4268 
4269     // We now know that the scalars in StoresVec can form a vector instruction,
4270     // so set the reorder indices.
4271     ExternalReorderIndices.push_back(ReorderIndices);
4272   }
4273   return ExternalReorderIndices;
4274 }
4275 
4276 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
4277                         ArrayRef<Value *> UserIgnoreLst) {
4278   deleteTree();
4279   UserIgnoreList = UserIgnoreLst;
4280   if (!allSameType(Roots))
4281     return;
4282   buildTree_rec(Roots, 0, EdgeInfo());
4283 }
4284 
4285 namespace {
4286 /// Tracks the state we can represent the loads in the given sequence.
4287 enum class LoadsState { Gather, Vectorize, ScatterVectorize };
4288 } // anonymous namespace
4289 
4290 /// Checks if the given array of loads can be represented as a vectorized,
4291 /// scatter or just simple gather.
4292 static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0,
4293                                     const TargetTransformInfo &TTI,
4294                                     const DataLayout &DL, ScalarEvolution &SE,
4295                                     SmallVectorImpl<unsigned> &Order,
4296                                     SmallVectorImpl<Value *> &PointerOps) {
4297   // Check that a vectorized load would load the same memory as a scalar
4298   // load. For example, we don't want to vectorize loads that are smaller
4299   // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
4300   // treats loading/storing it as an i8 struct. If we vectorize loads/stores
4301   // from such a struct, we read/write packed bits disagreeing with the
4302   // unvectorized version.
4303   Type *ScalarTy = VL0->getType();
4304 
4305   if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy))
4306     return LoadsState::Gather;
4307 
4308   // Make sure all loads in the bundle are simple - we can't vectorize
4309   // atomic or volatile loads.
4310   PointerOps.clear();
4311   PointerOps.resize(VL.size());
4312   auto *POIter = PointerOps.begin();
4313   for (Value *V : VL) {
4314     auto *L = cast<LoadInst>(V);
4315     if (!L->isSimple())
4316       return LoadsState::Gather;
4317     *POIter = L->getPointerOperand();
4318     ++POIter;
4319   }
4320 
4321   Order.clear();
4322   // Check the order of pointer operands.
4323   if (llvm::sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order)) {
4324     Value *Ptr0;
4325     Value *PtrN;
4326     if (Order.empty()) {
4327       Ptr0 = PointerOps.front();
4328       PtrN = PointerOps.back();
4329     } else {
4330       Ptr0 = PointerOps[Order.front()];
4331       PtrN = PointerOps[Order.back()];
4332     }
4333     Optional<int> Diff =
4334         getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE);
4335     // Check that the sorted loads are consecutive.
4336     if (static_cast<unsigned>(*Diff) == VL.size() - 1)
4337       return LoadsState::Vectorize;
4338     Align CommonAlignment = cast<LoadInst>(VL0)->getAlign();
4339     for (Value *V : VL)
4340       CommonAlignment =
4341           commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
4342     if (TTI.isLegalMaskedGather(FixedVectorType::get(ScalarTy, VL.size()),
4343                                 CommonAlignment))
4344       return LoadsState::ScatterVectorize;
4345   }
4346 
4347   return LoadsState::Gather;
4348 }
4349 
4350 /// \return true if the specified list of values has only one instruction that
4351 /// requires scheduling, false otherwise.
4352 #ifndef NDEBUG
4353 static bool needToScheduleSingleInstruction(ArrayRef<Value *> VL) {
4354   Value *NeedsScheduling = nullptr;
4355   for (Value *V : VL) {
4356     if (doesNotNeedToBeScheduled(V))
4357       continue;
4358     if (!NeedsScheduling) {
4359       NeedsScheduling = V;
4360       continue;
4361     }
4362     return false;
4363   }
4364   return NeedsScheduling;
4365 }
4366 #endif
4367 
4368 /// Generates key/subkey pair for the given value to provide effective sorting
4369 /// of the values and better detection of the vectorizable values sequences. The
4370 /// keys/subkeys can be used for better sorting of the values themselves (keys)
4371 /// and in values subgroups (subkeys).
4372 static std::pair<size_t, size_t> generateKeySubkey(
4373     Value *V, const TargetLibraryInfo *TLI,
4374     function_ref<hash_code(size_t, LoadInst *)> LoadsSubkeyGenerator,
4375     bool AllowAlternate) {
4376   hash_code Key = hash_value(V->getValueID() + 2);
4377   hash_code SubKey = hash_value(0);
4378   // Sort the loads by the distance between the pointers.
4379   if (auto *LI = dyn_cast<LoadInst>(V)) {
4380     Key = hash_combine(hash_value(Instruction::Load), Key);
4381     if (LI->isSimple())
4382       SubKey = hash_value(LoadsSubkeyGenerator(Key, LI));
4383     else
4384       SubKey = hash_value(LI);
4385   } else if (isVectorLikeInstWithConstOps(V)) {
4386     // Sort extracts by the vector operands.
4387     if (isa<ExtractElementInst, UndefValue>(V))
4388       Key = hash_value(Value::UndefValueVal + 1);
4389     if (auto *EI = dyn_cast<ExtractElementInst>(V)) {
4390       if (!isUndefVector(EI->getVectorOperand()) &&
4391           !isa<UndefValue>(EI->getIndexOperand()))
4392         SubKey = hash_value(EI->getVectorOperand());
4393     }
4394   } else if (auto *I = dyn_cast<Instruction>(V)) {
4395     // Sort other instructions just by the opcodes except for CMPInst.
4396     // For CMP also sort by the predicate kind.
4397     if ((isa<BinaryOperator>(I) || isa<CastInst>(I)) &&
4398         isValidForAlternation(I->getOpcode())) {
4399       if (AllowAlternate)
4400         Key = hash_value(isa<BinaryOperator>(I) ? 1 : 0);
4401       else
4402         Key = hash_combine(hash_value(I->getOpcode()), Key);
4403       SubKey = hash_combine(
4404           hash_value(I->getOpcode()), hash_value(I->getType()),
4405           hash_value(isa<BinaryOperator>(I)
4406                          ? I->getType()
4407                          : cast<CastInst>(I)->getOperand(0)->getType()));
4408     } else if (auto *CI = dyn_cast<CmpInst>(I)) {
4409       CmpInst::Predicate Pred = CI->getPredicate();
4410       if (CI->isCommutative())
4411         Pred = std::min(Pred, CmpInst::getInversePredicate(Pred));
4412       CmpInst::Predicate SwapPred = CmpInst::getSwappedPredicate(Pred);
4413       SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(Pred),
4414                             hash_value(SwapPred),
4415                             hash_value(CI->getOperand(0)->getType()));
4416     } else if (auto *Call = dyn_cast<CallInst>(I)) {
4417       Intrinsic::ID ID = getVectorIntrinsicIDForCall(Call, TLI);
4418       if (isTriviallyVectorizable(ID))
4419         SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(ID));
4420       else if (!VFDatabase(*Call).getMappings(*Call).empty())
4421         SubKey = hash_combine(hash_value(I->getOpcode()),
4422                               hash_value(Call->getCalledFunction()));
4423       else
4424         SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(Call));
4425       for (const CallBase::BundleOpInfo &Op : Call->bundle_op_infos())
4426         SubKey = hash_combine(hash_value(Op.Begin), hash_value(Op.End),
4427                               hash_value(Op.Tag), SubKey);
4428     } else if (auto *Gep = dyn_cast<GetElementPtrInst>(I)) {
4429       if (Gep->getNumOperands() == 2 && isa<ConstantInt>(Gep->getOperand(1)))
4430         SubKey = hash_value(Gep->getPointerOperand());
4431       else
4432         SubKey = hash_value(Gep);
4433     } else if (BinaryOperator::isIntDivRem(I->getOpcode()) &&
4434                !isa<ConstantInt>(I->getOperand(1))) {
4435       // Do not try to vectorize instructions with potentially high cost.
4436       SubKey = hash_value(I);
4437     } else {
4438       SubKey = hash_value(I->getOpcode());
4439     }
4440     Key = hash_combine(hash_value(I->getParent()), Key);
4441   }
4442   return std::make_pair(Key, SubKey);
4443 }
4444 
4445 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
4446                             const EdgeInfo &UserTreeIdx) {
4447   assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
4448 
4449   SmallVector<int> ReuseShuffleIndicies;
4450   SmallVector<Value *> UniqueValues;
4451   auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues,
4452                                 &UserTreeIdx,
4453                                 this](const InstructionsState &S) {
4454     // Check that every instruction appears once in this bundle.
4455     DenseMap<Value *, unsigned> UniquePositions;
4456     for (Value *V : VL) {
4457       if (isConstant(V)) {
4458         ReuseShuffleIndicies.emplace_back(
4459             isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size());
4460         UniqueValues.emplace_back(V);
4461         continue;
4462       }
4463       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
4464       ReuseShuffleIndicies.emplace_back(Res.first->second);
4465       if (Res.second)
4466         UniqueValues.emplace_back(V);
4467     }
4468     size_t NumUniqueScalarValues = UniqueValues.size();
4469     if (NumUniqueScalarValues == VL.size()) {
4470       ReuseShuffleIndicies.clear();
4471     } else {
4472       LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
4473       if (NumUniqueScalarValues <= 1 ||
4474           (UniquePositions.size() == 1 && all_of(UniqueValues,
4475                                                  [](Value *V) {
4476                                                    return isa<UndefValue>(V) ||
4477                                                           !isConstant(V);
4478                                                  })) ||
4479           !llvm::isPowerOf2_32(NumUniqueScalarValues)) {
4480         LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
4481         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4482         return false;
4483       }
4484       VL = UniqueValues;
4485     }
4486     return true;
4487   };
4488 
4489   InstructionsState S = getSameOpcode(VL);
4490   if (Depth == RecursionMaxDepth) {
4491     LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
4492     if (TryToFindDuplicates(S))
4493       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4494                    ReuseShuffleIndicies);
4495     return;
4496   }
4497 
4498   // Don't handle scalable vectors
4499   if (S.getOpcode() == Instruction::ExtractElement &&
4500       isa<ScalableVectorType>(
4501           cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) {
4502     LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n");
4503     if (TryToFindDuplicates(S))
4504       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4505                    ReuseShuffleIndicies);
4506     return;
4507   }
4508 
4509   // Don't handle vectors.
4510   if (S.OpValue->getType()->isVectorTy() &&
4511       !isa<InsertElementInst>(S.OpValue)) {
4512     LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
4513     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4514     return;
4515   }
4516 
4517   if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
4518     if (SI->getValueOperand()->getType()->isVectorTy()) {
4519       LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
4520       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4521       return;
4522     }
4523 
4524   // If all of the operands are identical or constant we have a simple solution.
4525   // If we deal with insert/extract instructions, they all must have constant
4526   // indices, otherwise we should gather them, not try to vectorize.
4527   if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode() ||
4528       (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(S.MainOp) &&
4529        !all_of(VL, isVectorLikeInstWithConstOps))) {
4530     LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
4531     if (TryToFindDuplicates(S))
4532       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4533                    ReuseShuffleIndicies);
4534     return;
4535   }
4536 
4537   // We now know that this is a vector of instructions of the same type from
4538   // the same block.
4539 
4540   // Don't vectorize ephemeral values.
4541   for (Value *V : VL) {
4542     if (EphValues.count(V)) {
4543       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
4544                         << ") is ephemeral.\n");
4545       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4546       return;
4547     }
4548   }
4549 
4550   // Check if this is a duplicate of another entry.
4551   if (TreeEntry *E = getTreeEntry(S.OpValue)) {
4552     LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n");
4553     if (!E->isSame(VL)) {
4554       LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
4555       if (TryToFindDuplicates(S))
4556         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4557                      ReuseShuffleIndicies);
4558       return;
4559     }
4560     // Record the reuse of the tree node.  FIXME, currently this is only used to
4561     // properly draw the graph rather than for the actual vectorization.
4562     E->UserTreeIndices.push_back(UserTreeIdx);
4563     LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue
4564                       << ".\n");
4565     return;
4566   }
4567 
4568   // Check that none of the instructions in the bundle are already in the tree.
4569   for (Value *V : VL) {
4570     auto *I = dyn_cast<Instruction>(V);
4571     if (!I)
4572       continue;
4573     if (getTreeEntry(I)) {
4574       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
4575                         << ") is already in tree.\n");
4576       if (TryToFindDuplicates(S))
4577         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4578                      ReuseShuffleIndicies);
4579       return;
4580     }
4581   }
4582 
4583   // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
4584   for (Value *V : VL) {
4585     if (is_contained(UserIgnoreList, V)) {
4586       LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
4587       if (TryToFindDuplicates(S))
4588         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4589                      ReuseShuffleIndicies);
4590       return;
4591     }
4592   }
4593 
4594   // Check that all of the users of the scalars that we want to vectorize are
4595   // schedulable.
4596   auto *VL0 = cast<Instruction>(S.OpValue);
4597   BasicBlock *BB = VL0->getParent();
4598 
4599   if (!DT->isReachableFromEntry(BB)) {
4600     // Don't go into unreachable blocks. They may contain instructions with
4601     // dependency cycles which confuse the final scheduling.
4602     LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
4603     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4604     return;
4605   }
4606 
4607   // Check that every instruction appears once in this bundle.
4608   if (!TryToFindDuplicates(S))
4609     return;
4610 
4611   auto &BSRef = BlocksSchedules[BB];
4612   if (!BSRef)
4613     BSRef = std::make_unique<BlockScheduling>(BB);
4614 
4615   BlockScheduling &BS = *BSRef;
4616 
4617   Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S);
4618 #ifdef EXPENSIVE_CHECKS
4619   // Make sure we didn't break any internal invariants
4620   BS.verify();
4621 #endif
4622   if (!Bundle) {
4623     LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
4624     assert((!BS.getScheduleData(VL0) ||
4625             !BS.getScheduleData(VL0)->isPartOfBundle()) &&
4626            "tryScheduleBundle should cancelScheduling on failure");
4627     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4628                  ReuseShuffleIndicies);
4629     return;
4630   }
4631   LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
4632 
4633   unsigned ShuffleOrOp = S.isAltShuffle() ?
4634                 (unsigned) Instruction::ShuffleVector : S.getOpcode();
4635   switch (ShuffleOrOp) {
4636     case Instruction::PHI: {
4637       auto *PH = cast<PHINode>(VL0);
4638 
4639       // Check for terminator values (e.g. invoke).
4640       for (Value *V : VL)
4641         for (Value *Incoming : cast<PHINode>(V)->incoming_values()) {
4642           Instruction *Term = dyn_cast<Instruction>(Incoming);
4643           if (Term && Term->isTerminator()) {
4644             LLVM_DEBUG(dbgs()
4645                        << "SLP: Need to swizzle PHINodes (terminator use).\n");
4646             BS.cancelScheduling(VL, VL0);
4647             newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4648                          ReuseShuffleIndicies);
4649             return;
4650           }
4651         }
4652 
4653       TreeEntry *TE =
4654           newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies);
4655       LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
4656 
4657       // Keeps the reordered operands to avoid code duplication.
4658       SmallVector<ValueList, 2> OperandsVec;
4659       for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
4660         if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) {
4661           ValueList Operands(VL.size(), PoisonValue::get(PH->getType()));
4662           TE->setOperand(I, Operands);
4663           OperandsVec.push_back(Operands);
4664           continue;
4665         }
4666         ValueList Operands;
4667         // Prepare the operand vector.
4668         for (Value *V : VL)
4669           Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(
4670               PH->getIncomingBlock(I)));
4671         TE->setOperand(I, Operands);
4672         OperandsVec.push_back(Operands);
4673       }
4674       for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx)
4675         buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx});
4676       return;
4677     }
4678     case Instruction::ExtractValue:
4679     case Instruction::ExtractElement: {
4680       OrdersType CurrentOrder;
4681       bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
4682       if (Reuse) {
4683         LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
4684         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4685                      ReuseShuffleIndicies);
4686         // This is a special case, as it does not gather, but at the same time
4687         // we are not extending buildTree_rec() towards the operands.
4688         ValueList Op0;
4689         Op0.assign(VL.size(), VL0->getOperand(0));
4690         VectorizableTree.back()->setOperand(0, Op0);
4691         return;
4692       }
4693       if (!CurrentOrder.empty()) {
4694         LLVM_DEBUG({
4695           dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
4696                     "with order";
4697           for (unsigned Idx : CurrentOrder)
4698             dbgs() << " " << Idx;
4699           dbgs() << "\n";
4700         });
4701         fixupOrderingIndices(CurrentOrder);
4702         // Insert new order with initial value 0, if it does not exist,
4703         // otherwise return the iterator to the existing one.
4704         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4705                      ReuseShuffleIndicies, CurrentOrder);
4706         // This is a special case, as it does not gather, but at the same time
4707         // we are not extending buildTree_rec() towards the operands.
4708         ValueList Op0;
4709         Op0.assign(VL.size(), VL0->getOperand(0));
4710         VectorizableTree.back()->setOperand(0, Op0);
4711         return;
4712       }
4713       LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
4714       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4715                    ReuseShuffleIndicies);
4716       BS.cancelScheduling(VL, VL0);
4717       return;
4718     }
4719     case Instruction::InsertElement: {
4720       assert(ReuseShuffleIndicies.empty() && "All inserts should be unique");
4721 
4722       // Check that we have a buildvector and not a shuffle of 2 or more
4723       // different vectors.
4724       ValueSet SourceVectors;
4725       for (Value *V : VL) {
4726         SourceVectors.insert(cast<Instruction>(V)->getOperand(0));
4727         assert(getInsertIndex(V) != None && "Non-constant or undef index?");
4728       }
4729 
4730       if (count_if(VL, [&SourceVectors](Value *V) {
4731             return !SourceVectors.contains(V);
4732           }) >= 2) {
4733         // Found 2nd source vector - cancel.
4734         LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with "
4735                              "different source vectors.\n");
4736         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4737         BS.cancelScheduling(VL, VL0);
4738         return;
4739       }
4740 
4741       auto OrdCompare = [](const std::pair<int, int> &P1,
4742                            const std::pair<int, int> &P2) {
4743         return P1.first > P2.first;
4744       };
4745       PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>,
4746                     decltype(OrdCompare)>
4747           Indices(OrdCompare);
4748       for (int I = 0, E = VL.size(); I < E; ++I) {
4749         unsigned Idx = *getInsertIndex(VL[I]);
4750         Indices.emplace(Idx, I);
4751       }
4752       OrdersType CurrentOrder(VL.size(), VL.size());
4753       bool IsIdentity = true;
4754       for (int I = 0, E = VL.size(); I < E; ++I) {
4755         CurrentOrder[Indices.top().second] = I;
4756         IsIdentity &= Indices.top().second == I;
4757         Indices.pop();
4758       }
4759       if (IsIdentity)
4760         CurrentOrder.clear();
4761       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4762                                    None, CurrentOrder);
4763       LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n");
4764 
4765       constexpr int NumOps = 2;
4766       ValueList VectorOperands[NumOps];
4767       for (int I = 0; I < NumOps; ++I) {
4768         for (Value *V : VL)
4769           VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I));
4770 
4771         TE->setOperand(I, VectorOperands[I]);
4772       }
4773       buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1});
4774       return;
4775     }
4776     case Instruction::Load: {
4777       // Check that a vectorized load would load the same memory as a scalar
4778       // load. For example, we don't want to vectorize loads that are smaller
4779       // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
4780       // treats loading/storing it as an i8 struct. If we vectorize loads/stores
4781       // from such a struct, we read/write packed bits disagreeing with the
4782       // unvectorized version.
4783       SmallVector<Value *> PointerOps;
4784       OrdersType CurrentOrder;
4785       TreeEntry *TE = nullptr;
4786       switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, CurrentOrder,
4787                                 PointerOps)) {
4788       case LoadsState::Vectorize:
4789         if (CurrentOrder.empty()) {
4790           // Original loads are consecutive and does not require reordering.
4791           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4792                             ReuseShuffleIndicies);
4793           LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
4794         } else {
4795           fixupOrderingIndices(CurrentOrder);
4796           // Need to reorder.
4797           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4798                             ReuseShuffleIndicies, CurrentOrder);
4799           LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
4800         }
4801         TE->setOperandsInOrder();
4802         break;
4803       case LoadsState::ScatterVectorize:
4804         // Vectorizing non-consecutive loads with `llvm.masked.gather`.
4805         TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S,
4806                           UserTreeIdx, ReuseShuffleIndicies);
4807         TE->setOperandsInOrder();
4808         buildTree_rec(PointerOps, Depth + 1, {TE, 0});
4809         LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n");
4810         break;
4811       case LoadsState::Gather:
4812         BS.cancelScheduling(VL, VL0);
4813         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4814                      ReuseShuffleIndicies);
4815 #ifndef NDEBUG
4816         Type *ScalarTy = VL0->getType();
4817         if (DL->getTypeSizeInBits(ScalarTy) !=
4818             DL->getTypeAllocSizeInBits(ScalarTy))
4819           LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
4820         else if (any_of(VL, [](Value *V) {
4821                    return !cast<LoadInst>(V)->isSimple();
4822                  }))
4823           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
4824         else
4825           LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
4826 #endif // NDEBUG
4827         break;
4828       }
4829       return;
4830     }
4831     case Instruction::ZExt:
4832     case Instruction::SExt:
4833     case Instruction::FPToUI:
4834     case Instruction::FPToSI:
4835     case Instruction::FPExt:
4836     case Instruction::PtrToInt:
4837     case Instruction::IntToPtr:
4838     case Instruction::SIToFP:
4839     case Instruction::UIToFP:
4840     case Instruction::Trunc:
4841     case Instruction::FPTrunc:
4842     case Instruction::BitCast: {
4843       Type *SrcTy = VL0->getOperand(0)->getType();
4844       for (Value *V : VL) {
4845         Type *Ty = cast<Instruction>(V)->getOperand(0)->getType();
4846         if (Ty != SrcTy || !isValidElementType(Ty)) {
4847           BS.cancelScheduling(VL, VL0);
4848           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4849                        ReuseShuffleIndicies);
4850           LLVM_DEBUG(dbgs()
4851                      << "SLP: Gathering casts with different src types.\n");
4852           return;
4853         }
4854       }
4855       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4856                                    ReuseShuffleIndicies);
4857       LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
4858 
4859       TE->setOperandsInOrder();
4860       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4861         ValueList Operands;
4862         // Prepare the operand vector.
4863         for (Value *V : VL)
4864           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4865 
4866         buildTree_rec(Operands, Depth + 1, {TE, i});
4867       }
4868       return;
4869     }
4870     case Instruction::ICmp:
4871     case Instruction::FCmp: {
4872       // Check that all of the compares have the same predicate.
4873       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
4874       CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0);
4875       Type *ComparedTy = VL0->getOperand(0)->getType();
4876       for (Value *V : VL) {
4877         CmpInst *Cmp = cast<CmpInst>(V);
4878         if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) ||
4879             Cmp->getOperand(0)->getType() != ComparedTy) {
4880           BS.cancelScheduling(VL, VL0);
4881           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4882                        ReuseShuffleIndicies);
4883           LLVM_DEBUG(dbgs()
4884                      << "SLP: Gathering cmp with different predicate.\n");
4885           return;
4886         }
4887       }
4888 
4889       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4890                                    ReuseShuffleIndicies);
4891       LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
4892 
4893       ValueList Left, Right;
4894       if (cast<CmpInst>(VL0)->isCommutative()) {
4895         // Commutative predicate - collect + sort operands of the instructions
4896         // so that each side is more likely to have the same opcode.
4897         assert(P0 == SwapP0 && "Commutative Predicate mismatch");
4898         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4899       } else {
4900         // Collect operands - commute if it uses the swapped predicate.
4901         for (Value *V : VL) {
4902           auto *Cmp = cast<CmpInst>(V);
4903           Value *LHS = Cmp->getOperand(0);
4904           Value *RHS = Cmp->getOperand(1);
4905           if (Cmp->getPredicate() != P0)
4906             std::swap(LHS, RHS);
4907           Left.push_back(LHS);
4908           Right.push_back(RHS);
4909         }
4910       }
4911       TE->setOperand(0, Left);
4912       TE->setOperand(1, Right);
4913       buildTree_rec(Left, Depth + 1, {TE, 0});
4914       buildTree_rec(Right, Depth + 1, {TE, 1});
4915       return;
4916     }
4917     case Instruction::Select:
4918     case Instruction::FNeg:
4919     case Instruction::Add:
4920     case Instruction::FAdd:
4921     case Instruction::Sub:
4922     case Instruction::FSub:
4923     case Instruction::Mul:
4924     case Instruction::FMul:
4925     case Instruction::UDiv:
4926     case Instruction::SDiv:
4927     case Instruction::FDiv:
4928     case Instruction::URem:
4929     case Instruction::SRem:
4930     case Instruction::FRem:
4931     case Instruction::Shl:
4932     case Instruction::LShr:
4933     case Instruction::AShr:
4934     case Instruction::And:
4935     case Instruction::Or:
4936     case Instruction::Xor: {
4937       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4938                                    ReuseShuffleIndicies);
4939       LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n");
4940 
4941       // Sort operands of the instructions so that each side is more likely to
4942       // have the same opcode.
4943       if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
4944         ValueList Left, Right;
4945         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4946         TE->setOperand(0, Left);
4947         TE->setOperand(1, Right);
4948         buildTree_rec(Left, Depth + 1, {TE, 0});
4949         buildTree_rec(Right, Depth + 1, {TE, 1});
4950         return;
4951       }
4952 
4953       TE->setOperandsInOrder();
4954       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4955         ValueList Operands;
4956         // Prepare the operand vector.
4957         for (Value *V : VL)
4958           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4959 
4960         buildTree_rec(Operands, Depth + 1, {TE, i});
4961       }
4962       return;
4963     }
4964     case Instruction::GetElementPtr: {
4965       // We don't combine GEPs with complicated (nested) indexing.
4966       for (Value *V : VL) {
4967         if (cast<Instruction>(V)->getNumOperands() != 2) {
4968           LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
4969           BS.cancelScheduling(VL, VL0);
4970           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4971                        ReuseShuffleIndicies);
4972           return;
4973         }
4974       }
4975 
4976       // We can't combine several GEPs into one vector if they operate on
4977       // different types.
4978       Type *Ty0 = cast<GEPOperator>(VL0)->getSourceElementType();
4979       for (Value *V : VL) {
4980         Type *CurTy = cast<GEPOperator>(V)->getSourceElementType();
4981         if (Ty0 != CurTy) {
4982           LLVM_DEBUG(dbgs()
4983                      << "SLP: not-vectorizable GEP (different types).\n");
4984           BS.cancelScheduling(VL, VL0);
4985           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4986                        ReuseShuffleIndicies);
4987           return;
4988         }
4989       }
4990 
4991       // We don't combine GEPs with non-constant indexes.
4992       Type *Ty1 = VL0->getOperand(1)->getType();
4993       for (Value *V : VL) {
4994         auto Op = cast<Instruction>(V)->getOperand(1);
4995         if (!isa<ConstantInt>(Op) ||
4996             (Op->getType() != Ty1 &&
4997              Op->getType()->getScalarSizeInBits() >
4998                  DL->getIndexSizeInBits(
4999                      V->getType()->getPointerAddressSpace()))) {
5000           LLVM_DEBUG(dbgs()
5001                      << "SLP: not-vectorizable GEP (non-constant indexes).\n");
5002           BS.cancelScheduling(VL, VL0);
5003           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5004                        ReuseShuffleIndicies);
5005           return;
5006         }
5007       }
5008 
5009       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
5010                                    ReuseShuffleIndicies);
5011       LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
5012       SmallVector<ValueList, 2> Operands(2);
5013       // Prepare the operand vector for pointer operands.
5014       for (Value *V : VL)
5015         Operands.front().push_back(
5016             cast<GetElementPtrInst>(V)->getPointerOperand());
5017       TE->setOperand(0, Operands.front());
5018       // Need to cast all indices to the same type before vectorization to
5019       // avoid crash.
5020       // Required to be able to find correct matches between different gather
5021       // nodes and reuse the vectorized values rather than trying to gather them
5022       // again.
5023       int IndexIdx = 1;
5024       Type *VL0Ty = VL0->getOperand(IndexIdx)->getType();
5025       Type *Ty = all_of(VL,
5026                         [VL0Ty, IndexIdx](Value *V) {
5027                           return VL0Ty == cast<GetElementPtrInst>(V)
5028                                               ->getOperand(IndexIdx)
5029                                               ->getType();
5030                         })
5031                      ? VL0Ty
5032                      : DL->getIndexType(cast<GetElementPtrInst>(VL0)
5033                                             ->getPointerOperandType()
5034                                             ->getScalarType());
5035       // Prepare the operand vector.
5036       for (Value *V : VL) {
5037         auto *Op = cast<Instruction>(V)->getOperand(IndexIdx);
5038         auto *CI = cast<ConstantInt>(Op);
5039         Operands.back().push_back(ConstantExpr::getIntegerCast(
5040             CI, Ty, CI->getValue().isSignBitSet()));
5041       }
5042       TE->setOperand(IndexIdx, Operands.back());
5043 
5044       for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I)
5045         buildTree_rec(Operands[I], Depth + 1, {TE, I});
5046       return;
5047     }
5048     case Instruction::Store: {
5049       // Check if the stores are consecutive or if we need to swizzle them.
5050       llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType();
5051       // Avoid types that are padded when being allocated as scalars, while
5052       // being packed together in a vector (such as i1).
5053       if (DL->getTypeSizeInBits(ScalarTy) !=
5054           DL->getTypeAllocSizeInBits(ScalarTy)) {
5055         BS.cancelScheduling(VL, VL0);
5056         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5057                      ReuseShuffleIndicies);
5058         LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n");
5059         return;
5060       }
5061       // Make sure all stores in the bundle are simple - we can't vectorize
5062       // atomic or volatile stores.
5063       SmallVector<Value *, 4> PointerOps(VL.size());
5064       ValueList Operands(VL.size());
5065       auto POIter = PointerOps.begin();
5066       auto OIter = Operands.begin();
5067       for (Value *V : VL) {
5068         auto *SI = cast<StoreInst>(V);
5069         if (!SI->isSimple()) {
5070           BS.cancelScheduling(VL, VL0);
5071           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5072                        ReuseShuffleIndicies);
5073           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n");
5074           return;
5075         }
5076         *POIter = SI->getPointerOperand();
5077         *OIter = SI->getValueOperand();
5078         ++POIter;
5079         ++OIter;
5080       }
5081 
5082       OrdersType CurrentOrder;
5083       // Check the order of pointer operands.
5084       if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) {
5085         Value *Ptr0;
5086         Value *PtrN;
5087         if (CurrentOrder.empty()) {
5088           Ptr0 = PointerOps.front();
5089           PtrN = PointerOps.back();
5090         } else {
5091           Ptr0 = PointerOps[CurrentOrder.front()];
5092           PtrN = PointerOps[CurrentOrder.back()];
5093         }
5094         Optional<int> Dist =
5095             getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE);
5096         // Check that the sorted pointer operands are consecutive.
5097         if (static_cast<unsigned>(*Dist) == VL.size() - 1) {
5098           if (CurrentOrder.empty()) {
5099             // Original stores are consecutive and does not require reordering.
5100             TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
5101                                          UserTreeIdx, ReuseShuffleIndicies);
5102             TE->setOperandsInOrder();
5103             buildTree_rec(Operands, Depth + 1, {TE, 0});
5104             LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
5105           } else {
5106             fixupOrderingIndices(CurrentOrder);
5107             TreeEntry *TE =
5108                 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
5109                              ReuseShuffleIndicies, CurrentOrder);
5110             TE->setOperandsInOrder();
5111             buildTree_rec(Operands, Depth + 1, {TE, 0});
5112             LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n");
5113           }
5114           return;
5115         }
5116       }
5117 
5118       BS.cancelScheduling(VL, VL0);
5119       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5120                    ReuseShuffleIndicies);
5121       LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
5122       return;
5123     }
5124     case Instruction::Call: {
5125       // Check if the calls are all to the same vectorizable intrinsic or
5126       // library function.
5127       CallInst *CI = cast<CallInst>(VL0);
5128       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5129 
5130       VFShape Shape = VFShape::get(
5131           *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())),
5132           false /*HasGlobalPred*/);
5133       Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
5134 
5135       if (!VecFunc && !isTriviallyVectorizable(ID)) {
5136         BS.cancelScheduling(VL, VL0);
5137         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5138                      ReuseShuffleIndicies);
5139         LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
5140         return;
5141       }
5142       Function *F = CI->getCalledFunction();
5143       unsigned NumArgs = CI->arg_size();
5144       SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr);
5145       for (unsigned j = 0; j != NumArgs; ++j)
5146         if (isVectorIntrinsicWithScalarOpAtArg(ID, j))
5147           ScalarArgs[j] = CI->getArgOperand(j);
5148       for (Value *V : VL) {
5149         CallInst *CI2 = dyn_cast<CallInst>(V);
5150         if (!CI2 || CI2->getCalledFunction() != F ||
5151             getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
5152             (VecFunc &&
5153              VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) ||
5154             !CI->hasIdenticalOperandBundleSchema(*CI2)) {
5155           BS.cancelScheduling(VL, VL0);
5156           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5157                        ReuseShuffleIndicies);
5158           LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V
5159                             << "\n");
5160           return;
5161         }
5162         // Some intrinsics have scalar arguments and should be same in order for
5163         // them to be vectorized.
5164         for (unsigned j = 0; j != NumArgs; ++j) {
5165           if (isVectorIntrinsicWithScalarOpAtArg(ID, j)) {
5166             Value *A1J = CI2->getArgOperand(j);
5167             if (ScalarArgs[j] != A1J) {
5168               BS.cancelScheduling(VL, VL0);
5169               newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5170                            ReuseShuffleIndicies);
5171               LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
5172                                 << " argument " << ScalarArgs[j] << "!=" << A1J
5173                                 << "\n");
5174               return;
5175             }
5176           }
5177         }
5178         // Verify that the bundle operands are identical between the two calls.
5179         if (CI->hasOperandBundles() &&
5180             !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
5181                         CI->op_begin() + CI->getBundleOperandsEndIndex(),
5182                         CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
5183           BS.cancelScheduling(VL, VL0);
5184           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5185                        ReuseShuffleIndicies);
5186           LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
5187                             << *CI << "!=" << *V << '\n');
5188           return;
5189         }
5190       }
5191 
5192       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
5193                                    ReuseShuffleIndicies);
5194       TE->setOperandsInOrder();
5195       for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
5196         // For scalar operands no need to to create an entry since no need to
5197         // vectorize it.
5198         if (isVectorIntrinsicWithScalarOpAtArg(ID, i))
5199           continue;
5200         ValueList Operands;
5201         // Prepare the operand vector.
5202         for (Value *V : VL) {
5203           auto *CI2 = cast<CallInst>(V);
5204           Operands.push_back(CI2->getArgOperand(i));
5205         }
5206         buildTree_rec(Operands, Depth + 1, {TE, i});
5207       }
5208       return;
5209     }
5210     case Instruction::ShuffleVector: {
5211       // If this is not an alternate sequence of opcode like add-sub
5212       // then do not vectorize this instruction.
5213       if (!S.isAltShuffle()) {
5214         BS.cancelScheduling(VL, VL0);
5215         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5216                      ReuseShuffleIndicies);
5217         LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
5218         return;
5219       }
5220       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
5221                                    ReuseShuffleIndicies);
5222       LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
5223 
5224       // Reorder operands if reordering would enable vectorization.
5225       auto *CI = dyn_cast<CmpInst>(VL0);
5226       if (isa<BinaryOperator>(VL0) || CI) {
5227         ValueList Left, Right;
5228         if (!CI || all_of(VL, [](Value *V) {
5229               return cast<CmpInst>(V)->isCommutative();
5230             })) {
5231           reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
5232         } else {
5233           CmpInst::Predicate P0 = CI->getPredicate();
5234           CmpInst::Predicate AltP0 = cast<CmpInst>(S.AltOp)->getPredicate();
5235           assert(P0 != AltP0 &&
5236                  "Expected different main/alternate predicates.");
5237           CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
5238           Value *BaseOp0 = VL0->getOperand(0);
5239           Value *BaseOp1 = VL0->getOperand(1);
5240           // Collect operands - commute if it uses the swapped predicate or
5241           // alternate operation.
5242           for (Value *V : VL) {
5243             auto *Cmp = cast<CmpInst>(V);
5244             Value *LHS = Cmp->getOperand(0);
5245             Value *RHS = Cmp->getOperand(1);
5246             CmpInst::Predicate CurrentPred = Cmp->getPredicate();
5247             if (P0 == AltP0Swapped) {
5248               if (CI != Cmp && S.AltOp != Cmp &&
5249                   ((P0 == CurrentPred &&
5250                     !areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)) ||
5251                    (AltP0 == CurrentPred &&
5252                     areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS))))
5253                 std::swap(LHS, RHS);
5254             } else if (P0 != CurrentPred && AltP0 != CurrentPred) {
5255               std::swap(LHS, RHS);
5256             }
5257             Left.push_back(LHS);
5258             Right.push_back(RHS);
5259           }
5260         }
5261         TE->setOperand(0, Left);
5262         TE->setOperand(1, Right);
5263         buildTree_rec(Left, Depth + 1, {TE, 0});
5264         buildTree_rec(Right, Depth + 1, {TE, 1});
5265         return;
5266       }
5267 
5268       TE->setOperandsInOrder();
5269       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
5270         ValueList Operands;
5271         // Prepare the operand vector.
5272         for (Value *V : VL)
5273           Operands.push_back(cast<Instruction>(V)->getOperand(i));
5274 
5275         buildTree_rec(Operands, Depth + 1, {TE, i});
5276       }
5277       return;
5278     }
5279     default:
5280       BS.cancelScheduling(VL, VL0);
5281       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5282                    ReuseShuffleIndicies);
5283       LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
5284       return;
5285   }
5286 }
5287 
5288 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
5289   unsigned N = 1;
5290   Type *EltTy = T;
5291 
5292   while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) ||
5293          isa<VectorType>(EltTy)) {
5294     if (auto *ST = dyn_cast<StructType>(EltTy)) {
5295       // Check that struct is homogeneous.
5296       for (const auto *Ty : ST->elements())
5297         if (Ty != *ST->element_begin())
5298           return 0;
5299       N *= ST->getNumElements();
5300       EltTy = *ST->element_begin();
5301     } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) {
5302       N *= AT->getNumElements();
5303       EltTy = AT->getElementType();
5304     } else {
5305       auto *VT = cast<FixedVectorType>(EltTy);
5306       N *= VT->getNumElements();
5307       EltTy = VT->getElementType();
5308     }
5309   }
5310 
5311   if (!isValidElementType(EltTy))
5312     return 0;
5313   uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N));
5314   if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
5315     return 0;
5316   return N;
5317 }
5318 
5319 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
5320                               SmallVectorImpl<unsigned> &CurrentOrder) const {
5321   const auto *It = find_if(VL, [](Value *V) {
5322     return isa<ExtractElementInst, ExtractValueInst>(V);
5323   });
5324   assert(It != VL.end() && "Expected at least one extract instruction.");
5325   auto *E0 = cast<Instruction>(*It);
5326   assert(all_of(VL,
5327                 [](Value *V) {
5328                   return isa<UndefValue, ExtractElementInst, ExtractValueInst>(
5329                       V);
5330                 }) &&
5331          "Invalid opcode");
5332   // Check if all of the extracts come from the same vector and from the
5333   // correct offset.
5334   Value *Vec = E0->getOperand(0);
5335 
5336   CurrentOrder.clear();
5337 
5338   // We have to extract from a vector/aggregate with the same number of elements.
5339   unsigned NElts;
5340   if (E0->getOpcode() == Instruction::ExtractValue) {
5341     const DataLayout &DL = E0->getModule()->getDataLayout();
5342     NElts = canMapToVector(Vec->getType(), DL);
5343     if (!NElts)
5344       return false;
5345     // Check if load can be rewritten as load of vector.
5346     LoadInst *LI = dyn_cast<LoadInst>(Vec);
5347     if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
5348       return false;
5349   } else {
5350     NElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
5351   }
5352 
5353   if (NElts != VL.size())
5354     return false;
5355 
5356   // Check that all of the indices extract from the correct offset.
5357   bool ShouldKeepOrder = true;
5358   unsigned E = VL.size();
5359   // Assign to all items the initial value E + 1 so we can check if the extract
5360   // instruction index was used already.
5361   // Also, later we can check that all the indices are used and we have a
5362   // consecutive access in the extract instructions, by checking that no
5363   // element of CurrentOrder still has value E + 1.
5364   CurrentOrder.assign(E, E);
5365   unsigned I = 0;
5366   for (; I < E; ++I) {
5367     auto *Inst = dyn_cast<Instruction>(VL[I]);
5368     if (!Inst)
5369       continue;
5370     if (Inst->getOperand(0) != Vec)
5371       break;
5372     if (auto *EE = dyn_cast<ExtractElementInst>(Inst))
5373       if (isa<UndefValue>(EE->getIndexOperand()))
5374         continue;
5375     Optional<unsigned> Idx = getExtractIndex(Inst);
5376     if (!Idx)
5377       break;
5378     const unsigned ExtIdx = *Idx;
5379     if (ExtIdx != I) {
5380       if (ExtIdx >= E || CurrentOrder[ExtIdx] != E)
5381         break;
5382       ShouldKeepOrder = false;
5383       CurrentOrder[ExtIdx] = I;
5384     } else {
5385       if (CurrentOrder[I] != E)
5386         break;
5387       CurrentOrder[I] = I;
5388     }
5389   }
5390   if (I < E) {
5391     CurrentOrder.clear();
5392     return false;
5393   }
5394   if (ShouldKeepOrder)
5395     CurrentOrder.clear();
5396 
5397   return ShouldKeepOrder;
5398 }
5399 
5400 bool BoUpSLP::areAllUsersVectorized(Instruction *I,
5401                                     ArrayRef<Value *> VectorizedVals) const {
5402   return (I->hasOneUse() && is_contained(VectorizedVals, I)) ||
5403          all_of(I->users(), [this](User *U) {
5404            return ScalarToTreeEntry.count(U) > 0 ||
5405                   isVectorLikeInstWithConstOps(U) ||
5406                   (isa<ExtractElementInst>(U) && MustGather.contains(U));
5407          });
5408 }
5409 
5410 static std::pair<InstructionCost, InstructionCost>
5411 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy,
5412                    TargetTransformInfo *TTI, TargetLibraryInfo *TLI) {
5413   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5414 
5415   // Calculate the cost of the scalar and vector calls.
5416   SmallVector<Type *, 4> VecTys;
5417   for (Use &Arg : CI->args())
5418     VecTys.push_back(
5419         FixedVectorType::get(Arg->getType(), VecTy->getNumElements()));
5420   FastMathFlags FMF;
5421   if (auto *FPCI = dyn_cast<FPMathOperator>(CI))
5422     FMF = FPCI->getFastMathFlags();
5423   SmallVector<const Value *> Arguments(CI->args());
5424   IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF,
5425                                     dyn_cast<IntrinsicInst>(CI));
5426   auto IntrinsicCost =
5427     TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput);
5428 
5429   auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
5430                                      VecTy->getNumElements())),
5431                             false /*HasGlobalPred*/);
5432   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
5433   auto LibCost = IntrinsicCost;
5434   if (!CI->isNoBuiltin() && VecFunc) {
5435     // Calculate the cost of the vector library call.
5436     // If the corresponding vector call is cheaper, return its cost.
5437     LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys,
5438                                     TTI::TCK_RecipThroughput);
5439   }
5440   return {IntrinsicCost, LibCost};
5441 }
5442 
5443 /// Compute the cost of creating a vector of type \p VecTy containing the
5444 /// extracted values from \p VL.
5445 static InstructionCost
5446 computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy,
5447                    TargetTransformInfo::ShuffleKind ShuffleKind,
5448                    ArrayRef<int> Mask, TargetTransformInfo &TTI) {
5449   unsigned NumOfParts = TTI.getNumberOfParts(VecTy);
5450 
5451   if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts ||
5452       VecTy->getNumElements() < NumOfParts)
5453     return TTI.getShuffleCost(ShuffleKind, VecTy, Mask);
5454 
5455   bool AllConsecutive = true;
5456   unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts;
5457   unsigned Idx = -1;
5458   InstructionCost Cost = 0;
5459 
5460   // Process extracts in blocks of EltsPerVector to check if the source vector
5461   // operand can be re-used directly. If not, add the cost of creating a shuffle
5462   // to extract the values into a vector register.
5463   SmallVector<int> RegMask(EltsPerVector, UndefMaskElem);
5464   for (auto *V : VL) {
5465     ++Idx;
5466 
5467     // Need to exclude undefs from analysis.
5468     if (isa<UndefValue>(V) || Mask[Idx] == UndefMaskElem)
5469       continue;
5470 
5471     // Reached the start of a new vector registers.
5472     if (Idx % EltsPerVector == 0) {
5473       RegMask.assign(EltsPerVector, UndefMaskElem);
5474       AllConsecutive = true;
5475       continue;
5476     }
5477 
5478     // Check all extracts for a vector register on the target directly
5479     // extract values in order.
5480     unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V));
5481     if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != UndefMaskElem) {
5482       unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1]));
5483       AllConsecutive &= PrevIdx + 1 == CurrentIdx &&
5484                         CurrentIdx % EltsPerVector == Idx % EltsPerVector;
5485       RegMask[Idx % EltsPerVector] = CurrentIdx % EltsPerVector;
5486     }
5487 
5488     if (AllConsecutive)
5489       continue;
5490 
5491     // Skip all indices, except for the last index per vector block.
5492     if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size())
5493       continue;
5494 
5495     // If we have a series of extracts which are not consecutive and hence
5496     // cannot re-use the source vector register directly, compute the shuffle
5497     // cost to extract the vector with EltsPerVector elements.
5498     Cost += TTI.getShuffleCost(
5499         TargetTransformInfo::SK_PermuteSingleSrc,
5500         FixedVectorType::get(VecTy->getElementType(), EltsPerVector), RegMask);
5501   }
5502   return Cost;
5503 }
5504 
5505 /// Build shuffle mask for shuffle graph entries and lists of main and alternate
5506 /// operations operands.
5507 static void
5508 buildShuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices,
5509                       ArrayRef<int> ReusesIndices,
5510                       const function_ref<bool(Instruction *)> IsAltOp,
5511                       SmallVectorImpl<int> &Mask,
5512                       SmallVectorImpl<Value *> *OpScalars = nullptr,
5513                       SmallVectorImpl<Value *> *AltScalars = nullptr) {
5514   unsigned Sz = VL.size();
5515   Mask.assign(Sz, UndefMaskElem);
5516   SmallVector<int> OrderMask;
5517   if (!ReorderIndices.empty())
5518     inversePermutation(ReorderIndices, OrderMask);
5519   for (unsigned I = 0; I < Sz; ++I) {
5520     unsigned Idx = I;
5521     if (!ReorderIndices.empty())
5522       Idx = OrderMask[I];
5523     auto *OpInst = cast<Instruction>(VL[Idx]);
5524     if (IsAltOp(OpInst)) {
5525       Mask[I] = Sz + Idx;
5526       if (AltScalars)
5527         AltScalars->push_back(OpInst);
5528     } else {
5529       Mask[I] = Idx;
5530       if (OpScalars)
5531         OpScalars->push_back(OpInst);
5532     }
5533   }
5534   if (!ReusesIndices.empty()) {
5535     SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem);
5536     transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) {
5537       return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem;
5538     });
5539     Mask.swap(NewMask);
5540   }
5541 }
5542 
5543 /// Checks if the specified instruction \p I is an alternate operation for the
5544 /// given \p MainOp and \p AltOp instructions.
5545 static bool isAlternateInstruction(const Instruction *I,
5546                                    const Instruction *MainOp,
5547                                    const Instruction *AltOp) {
5548   if (auto *CI0 = dyn_cast<CmpInst>(MainOp)) {
5549     auto *AltCI0 = cast<CmpInst>(AltOp);
5550     auto *CI = cast<CmpInst>(I);
5551     CmpInst::Predicate P0 = CI0->getPredicate();
5552     CmpInst::Predicate AltP0 = AltCI0->getPredicate();
5553     assert(P0 != AltP0 && "Expected different main/alternate predicates.");
5554     CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
5555     CmpInst::Predicate CurrentPred = CI->getPredicate();
5556     if (P0 == AltP0Swapped)
5557       return I == AltCI0 ||
5558              (I != MainOp &&
5559               !areCompatibleCmpOps(CI0->getOperand(0), CI0->getOperand(1),
5560                                    CI->getOperand(0), CI->getOperand(1)));
5561     return AltP0 == CurrentPred || AltP0Swapped == CurrentPred;
5562   }
5563   return I->getOpcode() == AltOp->getOpcode();
5564 }
5565 
5566 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E,
5567                                       ArrayRef<Value *> VectorizedVals) {
5568   ArrayRef<Value*> VL = E->Scalars;
5569 
5570   Type *ScalarTy = VL[0]->getType();
5571   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
5572     ScalarTy = SI->getValueOperand()->getType();
5573   else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
5574     ScalarTy = CI->getOperand(0)->getType();
5575   else if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
5576     ScalarTy = IE->getOperand(1)->getType();
5577   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
5578   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
5579 
5580   // If we have computed a smaller type for the expression, update VecTy so
5581   // that the costs will be accurate.
5582   if (MinBWs.count(VL[0]))
5583     VecTy = FixedVectorType::get(
5584         IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
5585   unsigned EntryVF = E->getVectorFactor();
5586   auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF);
5587 
5588   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
5589   // FIXME: it tries to fix a problem with MSVC buildbots.
5590   TargetTransformInfo &TTIRef = *TTI;
5591   auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy,
5592                                VectorizedVals, E](InstructionCost &Cost) {
5593     DenseMap<Value *, int> ExtractVectorsTys;
5594     SmallPtrSet<Value *, 4> CheckedExtracts;
5595     for (auto *V : VL) {
5596       if (isa<UndefValue>(V))
5597         continue;
5598       // If all users of instruction are going to be vectorized and this
5599       // instruction itself is not going to be vectorized, consider this
5600       // instruction as dead and remove its cost from the final cost of the
5601       // vectorized tree.
5602       // Also, avoid adjusting the cost for extractelements with multiple uses
5603       // in different graph entries.
5604       const TreeEntry *VE = getTreeEntry(V);
5605       if (!CheckedExtracts.insert(V).second ||
5606           !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) ||
5607           (VE && VE != E))
5608         continue;
5609       auto *EE = cast<ExtractElementInst>(V);
5610       Optional<unsigned> EEIdx = getExtractIndex(EE);
5611       if (!EEIdx)
5612         continue;
5613       unsigned Idx = *EEIdx;
5614       if (TTIRef.getNumberOfParts(VecTy) !=
5615           TTIRef.getNumberOfParts(EE->getVectorOperandType())) {
5616         auto It =
5617             ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first;
5618         It->getSecond() = std::min<int>(It->second, Idx);
5619       }
5620       // Take credit for instruction that will become dead.
5621       if (EE->hasOneUse()) {
5622         Instruction *Ext = EE->user_back();
5623         if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5624             all_of(Ext->users(),
5625                    [](User *U) { return isa<GetElementPtrInst>(U); })) {
5626           // Use getExtractWithExtendCost() to calculate the cost of
5627           // extractelement/ext pair.
5628           Cost -=
5629               TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(),
5630                                               EE->getVectorOperandType(), Idx);
5631           // Add back the cost of s|zext which is subtracted separately.
5632           Cost += TTIRef.getCastInstrCost(
5633               Ext->getOpcode(), Ext->getType(), EE->getType(),
5634               TTI::getCastContextHint(Ext), CostKind, Ext);
5635           continue;
5636         }
5637       }
5638       Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement,
5639                                         EE->getVectorOperandType(), Idx);
5640     }
5641     // Add a cost for subvector extracts/inserts if required.
5642     for (const auto &Data : ExtractVectorsTys) {
5643       auto *EEVTy = cast<FixedVectorType>(Data.first->getType());
5644       unsigned NumElts = VecTy->getNumElements();
5645       if (Data.second % NumElts == 0)
5646         continue;
5647       if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) {
5648         unsigned Idx = (Data.second / NumElts) * NumElts;
5649         unsigned EENumElts = EEVTy->getNumElements();
5650         if (Idx + NumElts <= EENumElts) {
5651           Cost +=
5652               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5653                                     EEVTy, None, Idx, VecTy);
5654         } else {
5655           // Need to round up the subvector type vectorization factor to avoid a
5656           // crash in cost model functions. Make SubVT so that Idx + VF of SubVT
5657           // <= EENumElts.
5658           auto *SubVT =
5659               FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx);
5660           Cost +=
5661               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5662                                     EEVTy, None, Idx, SubVT);
5663         }
5664       } else {
5665         Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector,
5666                                       VecTy, None, 0, EEVTy);
5667       }
5668     }
5669   };
5670   if (E->State == TreeEntry::NeedToGather) {
5671     if (allConstant(VL))
5672       return 0;
5673     if (isa<InsertElementInst>(VL[0]))
5674       return InstructionCost::getInvalid();
5675     SmallVector<int> Mask;
5676     SmallVector<const TreeEntry *> Entries;
5677     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
5678         isGatherShuffledEntry(E, Mask, Entries);
5679     if (Shuffle.hasValue()) {
5680       InstructionCost GatherCost = 0;
5681       if (ShuffleVectorInst::isIdentityMask(Mask)) {
5682         // Perfect match in the graph, will reuse the previously vectorized
5683         // node. Cost is 0.
5684         LLVM_DEBUG(
5685             dbgs()
5686             << "SLP: perfect diamond match for gather bundle that starts with "
5687             << *VL.front() << ".\n");
5688         if (NeedToShuffleReuses)
5689           GatherCost =
5690               TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5691                                   FinalVecTy, E->ReuseShuffleIndices);
5692       } else {
5693         LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size()
5694                           << " entries for bundle that starts with "
5695                           << *VL.front() << ".\n");
5696         // Detected that instead of gather we can emit a shuffle of single/two
5697         // previously vectorized nodes. Add the cost of the permutation rather
5698         // than gather.
5699         ::addMask(Mask, E->ReuseShuffleIndices);
5700         GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask);
5701       }
5702       return GatherCost;
5703     }
5704     if ((E->getOpcode() == Instruction::ExtractElement ||
5705          all_of(E->Scalars,
5706                 [](Value *V) {
5707                   return isa<ExtractElementInst, UndefValue>(V);
5708                 })) &&
5709         allSameType(VL)) {
5710       // Check that gather of extractelements can be represented as just a
5711       // shuffle of a single/two vectors the scalars are extracted from.
5712       SmallVector<int> Mask;
5713       Optional<TargetTransformInfo::ShuffleKind> ShuffleKind =
5714           isFixedVectorShuffle(VL, Mask);
5715       if (ShuffleKind.hasValue()) {
5716         // Found the bunch of extractelement instructions that must be gathered
5717         // into a vector and can be represented as a permutation elements in a
5718         // single input vector or of 2 input vectors.
5719         InstructionCost Cost =
5720             computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI);
5721         AdjustExtractsCost(Cost);
5722         if (NeedToShuffleReuses)
5723           Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5724                                       FinalVecTy, E->ReuseShuffleIndices);
5725         return Cost;
5726       }
5727     }
5728     if (isSplat(VL)) {
5729       // Found the broadcasting of the single scalar, calculate the cost as the
5730       // broadcast.
5731       assert(VecTy == FinalVecTy &&
5732              "No reused scalars expected for broadcast.");
5733       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy,
5734                                  /*Mask=*/None, /*Index=*/0,
5735                                  /*SubTp=*/nullptr, /*Args=*/VL[0]);
5736     }
5737     InstructionCost ReuseShuffleCost = 0;
5738     if (NeedToShuffleReuses)
5739       ReuseShuffleCost = TTI->getShuffleCost(
5740           TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices);
5741     // Improve gather cost for gather of loads, if we can group some of the
5742     // loads into vector loads.
5743     if (VL.size() > 2 && E->getOpcode() == Instruction::Load &&
5744         !E->isAltShuffle()) {
5745       BoUpSLP::ValueSet VectorizedLoads;
5746       unsigned StartIdx = 0;
5747       unsigned VF = VL.size() / 2;
5748       unsigned VectorizedCnt = 0;
5749       unsigned ScatterVectorizeCnt = 0;
5750       const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType());
5751       for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) {
5752         for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End;
5753              Cnt += VF) {
5754           ArrayRef<Value *> Slice = VL.slice(Cnt, VF);
5755           if (!VectorizedLoads.count(Slice.front()) &&
5756               !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) {
5757             SmallVector<Value *> PointerOps;
5758             OrdersType CurrentOrder;
5759             LoadsState LS = canVectorizeLoads(Slice, Slice.front(), *TTI, *DL,
5760                                               *SE, CurrentOrder, PointerOps);
5761             switch (LS) {
5762             case LoadsState::Vectorize:
5763             case LoadsState::ScatterVectorize:
5764               // Mark the vectorized loads so that we don't vectorize them
5765               // again.
5766               if (LS == LoadsState::Vectorize)
5767                 ++VectorizedCnt;
5768               else
5769                 ++ScatterVectorizeCnt;
5770               VectorizedLoads.insert(Slice.begin(), Slice.end());
5771               // If we vectorized initial block, no need to try to vectorize it
5772               // again.
5773               if (Cnt == StartIdx)
5774                 StartIdx += VF;
5775               break;
5776             case LoadsState::Gather:
5777               break;
5778             }
5779           }
5780         }
5781         // Check if the whole array was vectorized already - exit.
5782         if (StartIdx >= VL.size())
5783           break;
5784         // Found vectorizable parts - exit.
5785         if (!VectorizedLoads.empty())
5786           break;
5787       }
5788       if (!VectorizedLoads.empty()) {
5789         InstructionCost GatherCost = 0;
5790         unsigned NumParts = TTI->getNumberOfParts(VecTy);
5791         bool NeedInsertSubvectorAnalysis =
5792             !NumParts || (VL.size() / VF) > NumParts;
5793         // Get the cost for gathered loads.
5794         for (unsigned I = 0, End = VL.size(); I < End; I += VF) {
5795           if (VectorizedLoads.contains(VL[I]))
5796             continue;
5797           GatherCost += getGatherCost(VL.slice(I, VF));
5798         }
5799         // The cost for vectorized loads.
5800         InstructionCost ScalarsCost = 0;
5801         for (Value *V : VectorizedLoads) {
5802           auto *LI = cast<LoadInst>(V);
5803           ScalarsCost += TTI->getMemoryOpCost(
5804               Instruction::Load, LI->getType(), LI->getAlign(),
5805               LI->getPointerAddressSpace(), CostKind, LI);
5806         }
5807         auto *LI = cast<LoadInst>(E->getMainOp());
5808         auto *LoadTy = FixedVectorType::get(LI->getType(), VF);
5809         Align Alignment = LI->getAlign();
5810         GatherCost +=
5811             VectorizedCnt *
5812             TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment,
5813                                  LI->getPointerAddressSpace(), CostKind, LI);
5814         GatherCost += ScatterVectorizeCnt *
5815                       TTI->getGatherScatterOpCost(
5816                           Instruction::Load, LoadTy, LI->getPointerOperand(),
5817                           /*VariableMask=*/false, Alignment, CostKind, LI);
5818         if (NeedInsertSubvectorAnalysis) {
5819           // Add the cost for the subvectors insert.
5820           for (int I = VF, E = VL.size(); I < E; I += VF)
5821             GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy,
5822                                               None, I, LoadTy);
5823         }
5824         return ReuseShuffleCost + GatherCost - ScalarsCost;
5825       }
5826     }
5827     return ReuseShuffleCost + getGatherCost(VL);
5828   }
5829   InstructionCost CommonCost = 0;
5830   SmallVector<int> Mask;
5831   if (!E->ReorderIndices.empty()) {
5832     SmallVector<int> NewMask;
5833     if (E->getOpcode() == Instruction::Store) {
5834       // For stores the order is actually a mask.
5835       NewMask.resize(E->ReorderIndices.size());
5836       copy(E->ReorderIndices, NewMask.begin());
5837     } else {
5838       inversePermutation(E->ReorderIndices, NewMask);
5839     }
5840     ::addMask(Mask, NewMask);
5841   }
5842   if (NeedToShuffleReuses)
5843     ::addMask(Mask, E->ReuseShuffleIndices);
5844   if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask))
5845     CommonCost =
5846         TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask);
5847   assert((E->State == TreeEntry::Vectorize ||
5848           E->State == TreeEntry::ScatterVectorize) &&
5849          "Unhandled state");
5850   assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
5851   Instruction *VL0 = E->getMainOp();
5852   unsigned ShuffleOrOp =
5853       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
5854   switch (ShuffleOrOp) {
5855     case Instruction::PHI:
5856       return 0;
5857 
5858     case Instruction::ExtractValue:
5859     case Instruction::ExtractElement: {
5860       // The common cost of removal ExtractElement/ExtractValue instructions +
5861       // the cost of shuffles, if required to resuffle the original vector.
5862       if (NeedToShuffleReuses) {
5863         unsigned Idx = 0;
5864         for (unsigned I : E->ReuseShuffleIndices) {
5865           if (ShuffleOrOp == Instruction::ExtractElement) {
5866             auto *EE = cast<ExtractElementInst>(VL[I]);
5867             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5868                                                   EE->getVectorOperandType(),
5869                                                   *getExtractIndex(EE));
5870           } else {
5871             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5872                                                   VecTy, Idx);
5873             ++Idx;
5874           }
5875         }
5876         Idx = EntryVF;
5877         for (Value *V : VL) {
5878           if (ShuffleOrOp == Instruction::ExtractElement) {
5879             auto *EE = cast<ExtractElementInst>(V);
5880             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5881                                                   EE->getVectorOperandType(),
5882                                                   *getExtractIndex(EE));
5883           } else {
5884             --Idx;
5885             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5886                                                   VecTy, Idx);
5887           }
5888         }
5889       }
5890       if (ShuffleOrOp == Instruction::ExtractValue) {
5891         for (unsigned I = 0, E = VL.size(); I < E; ++I) {
5892           auto *EI = cast<Instruction>(VL[I]);
5893           // Take credit for instruction that will become dead.
5894           if (EI->hasOneUse()) {
5895             Instruction *Ext = EI->user_back();
5896             if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5897                 all_of(Ext->users(),
5898                        [](User *U) { return isa<GetElementPtrInst>(U); })) {
5899               // Use getExtractWithExtendCost() to calculate the cost of
5900               // extractelement/ext pair.
5901               CommonCost -= TTI->getExtractWithExtendCost(
5902                   Ext->getOpcode(), Ext->getType(), VecTy, I);
5903               // Add back the cost of s|zext which is subtracted separately.
5904               CommonCost += TTI->getCastInstrCost(
5905                   Ext->getOpcode(), Ext->getType(), EI->getType(),
5906                   TTI::getCastContextHint(Ext), CostKind, Ext);
5907               continue;
5908             }
5909           }
5910           CommonCost -=
5911               TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I);
5912         }
5913       } else {
5914         AdjustExtractsCost(CommonCost);
5915       }
5916       return CommonCost;
5917     }
5918     case Instruction::InsertElement: {
5919       assert(E->ReuseShuffleIndices.empty() &&
5920              "Unique insertelements only are expected.");
5921       auto *SrcVecTy = cast<FixedVectorType>(VL0->getType());
5922 
5923       unsigned const NumElts = SrcVecTy->getNumElements();
5924       unsigned const NumScalars = VL.size();
5925       APInt DemandedElts = APInt::getZero(NumElts);
5926       // TODO: Add support for Instruction::InsertValue.
5927       SmallVector<int> Mask;
5928       if (!E->ReorderIndices.empty()) {
5929         inversePermutation(E->ReorderIndices, Mask);
5930         Mask.append(NumElts - NumScalars, UndefMaskElem);
5931       } else {
5932         Mask.assign(NumElts, UndefMaskElem);
5933         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
5934       }
5935       unsigned Offset = *getInsertIndex(VL0);
5936       bool IsIdentity = true;
5937       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
5938       Mask.swap(PrevMask);
5939       for (unsigned I = 0; I < NumScalars; ++I) {
5940         unsigned InsertIdx = *getInsertIndex(VL[PrevMask[I]]);
5941         DemandedElts.setBit(InsertIdx);
5942         IsIdentity &= InsertIdx - Offset == I;
5943         Mask[InsertIdx - Offset] = I;
5944       }
5945       assert(Offset < NumElts && "Failed to find vector index offset");
5946 
5947       InstructionCost Cost = 0;
5948       Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts,
5949                                             /*Insert*/ true, /*Extract*/ false);
5950 
5951       if (IsIdentity && NumElts != NumScalars && Offset % NumScalars != 0) {
5952         // FIXME: Replace with SK_InsertSubvector once it is properly supported.
5953         unsigned Sz = PowerOf2Ceil(Offset + NumScalars);
5954         Cost += TTI->getShuffleCost(
5955             TargetTransformInfo::SK_PermuteSingleSrc,
5956             FixedVectorType::get(SrcVecTy->getElementType(), Sz));
5957       } else if (!IsIdentity) {
5958         auto *FirstInsert =
5959             cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
5960               return !is_contained(E->Scalars,
5961                                    cast<Instruction>(V)->getOperand(0));
5962             }));
5963         if (isUndefVector(FirstInsert->getOperand(0))) {
5964           Cost += TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, SrcVecTy, Mask);
5965         } else {
5966           SmallVector<int> InsertMask(NumElts);
5967           std::iota(InsertMask.begin(), InsertMask.end(), 0);
5968           for (unsigned I = 0; I < NumElts; I++) {
5969             if (Mask[I] != UndefMaskElem)
5970               InsertMask[Offset + I] = NumElts + I;
5971           }
5972           Cost +=
5973               TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVecTy, InsertMask);
5974         }
5975       }
5976 
5977       return Cost;
5978     }
5979     case Instruction::ZExt:
5980     case Instruction::SExt:
5981     case Instruction::FPToUI:
5982     case Instruction::FPToSI:
5983     case Instruction::FPExt:
5984     case Instruction::PtrToInt:
5985     case Instruction::IntToPtr:
5986     case Instruction::SIToFP:
5987     case Instruction::UIToFP:
5988     case Instruction::Trunc:
5989     case Instruction::FPTrunc:
5990     case Instruction::BitCast: {
5991       Type *SrcTy = VL0->getOperand(0)->getType();
5992       InstructionCost ScalarEltCost =
5993           TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy,
5994                                 TTI::getCastContextHint(VL0), CostKind, VL0);
5995       if (NeedToShuffleReuses) {
5996         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5997       }
5998 
5999       // Calculate the cost of this instruction.
6000       InstructionCost ScalarCost = VL.size() * ScalarEltCost;
6001 
6002       auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size());
6003       InstructionCost VecCost = 0;
6004       // Check if the values are candidates to demote.
6005       if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
6006         VecCost = CommonCost + TTI->getCastInstrCost(
6007                                    E->getOpcode(), VecTy, SrcVecTy,
6008                                    TTI::getCastContextHint(VL0), CostKind, VL0);
6009       }
6010       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
6011       return VecCost - ScalarCost;
6012     }
6013     case Instruction::FCmp:
6014     case Instruction::ICmp:
6015     case Instruction::Select: {
6016       // Calculate the cost of this instruction.
6017       InstructionCost ScalarEltCost =
6018           TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
6019                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0);
6020       if (NeedToShuffleReuses) {
6021         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
6022       }
6023       auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size());
6024       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
6025 
6026       // Check if all entries in VL are either compares or selects with compares
6027       // as condition that have the same predicates.
6028       CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE;
6029       bool First = true;
6030       for (auto *V : VL) {
6031         CmpInst::Predicate CurrentPred;
6032         auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value());
6033         if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) &&
6034              !match(V, MatchCmp)) ||
6035             (!First && VecPred != CurrentPred)) {
6036           VecPred = CmpInst::BAD_ICMP_PREDICATE;
6037           break;
6038         }
6039         First = false;
6040         VecPred = CurrentPred;
6041       }
6042 
6043       InstructionCost VecCost = TTI->getCmpSelInstrCost(
6044           E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0);
6045       // Check if it is possible and profitable to use min/max for selects in
6046       // VL.
6047       //
6048       auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL);
6049       if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) {
6050         IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy,
6051                                           {VecTy, VecTy});
6052         InstructionCost IntrinsicCost =
6053             TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
6054         // If the selects are the only uses of the compares, they will be dead
6055         // and we can adjust the cost by removing their cost.
6056         if (IntrinsicAndUse.second)
6057           IntrinsicCost -= TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy,
6058                                                    MaskTy, VecPred, CostKind);
6059         VecCost = std::min(VecCost, IntrinsicCost);
6060       }
6061       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
6062       return CommonCost + VecCost - ScalarCost;
6063     }
6064     case Instruction::FNeg:
6065     case Instruction::Add:
6066     case Instruction::FAdd:
6067     case Instruction::Sub:
6068     case Instruction::FSub:
6069     case Instruction::Mul:
6070     case Instruction::FMul:
6071     case Instruction::UDiv:
6072     case Instruction::SDiv:
6073     case Instruction::FDiv:
6074     case Instruction::URem:
6075     case Instruction::SRem:
6076     case Instruction::FRem:
6077     case Instruction::Shl:
6078     case Instruction::LShr:
6079     case Instruction::AShr:
6080     case Instruction::And:
6081     case Instruction::Or:
6082     case Instruction::Xor: {
6083       // Certain instructions can be cheaper to vectorize if they have a
6084       // constant second vector operand.
6085       TargetTransformInfo::OperandValueKind Op1VK =
6086           TargetTransformInfo::OK_AnyValue;
6087       TargetTransformInfo::OperandValueKind Op2VK =
6088           TargetTransformInfo::OK_UniformConstantValue;
6089       TargetTransformInfo::OperandValueProperties Op1VP =
6090           TargetTransformInfo::OP_None;
6091       TargetTransformInfo::OperandValueProperties Op2VP =
6092           TargetTransformInfo::OP_PowerOf2;
6093 
6094       // If all operands are exactly the same ConstantInt then set the
6095       // operand kind to OK_UniformConstantValue.
6096       // If instead not all operands are constants, then set the operand kind
6097       // to OK_AnyValue. If all operands are constants but not the same,
6098       // then set the operand kind to OK_NonUniformConstantValue.
6099       ConstantInt *CInt0 = nullptr;
6100       for (unsigned i = 0, e = VL.size(); i < e; ++i) {
6101         const Instruction *I = cast<Instruction>(VL[i]);
6102         unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0;
6103         ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx));
6104         if (!CInt) {
6105           Op2VK = TargetTransformInfo::OK_AnyValue;
6106           Op2VP = TargetTransformInfo::OP_None;
6107           break;
6108         }
6109         if (Op2VP == TargetTransformInfo::OP_PowerOf2 &&
6110             !CInt->getValue().isPowerOf2())
6111           Op2VP = TargetTransformInfo::OP_None;
6112         if (i == 0) {
6113           CInt0 = CInt;
6114           continue;
6115         }
6116         if (CInt0 != CInt)
6117           Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
6118       }
6119 
6120       SmallVector<const Value *, 4> Operands(VL0->operand_values());
6121       InstructionCost ScalarEltCost =
6122           TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK,
6123                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
6124       if (NeedToShuffleReuses) {
6125         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
6126       }
6127       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
6128       InstructionCost VecCost =
6129           TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK,
6130                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
6131       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
6132       return CommonCost + VecCost - ScalarCost;
6133     }
6134     case Instruction::GetElementPtr: {
6135       TargetTransformInfo::OperandValueKind Op1VK =
6136           TargetTransformInfo::OK_AnyValue;
6137       TargetTransformInfo::OperandValueKind Op2VK =
6138           TargetTransformInfo::OK_UniformConstantValue;
6139 
6140       InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost(
6141           Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK);
6142       if (NeedToShuffleReuses) {
6143         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
6144       }
6145       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
6146       InstructionCost VecCost = TTI->getArithmeticInstrCost(
6147           Instruction::Add, VecTy, CostKind, Op1VK, Op2VK);
6148       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
6149       return CommonCost + VecCost - ScalarCost;
6150     }
6151     case Instruction::Load: {
6152       // Cost of wide load - cost of scalar loads.
6153       Align Alignment = cast<LoadInst>(VL0)->getAlign();
6154       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
6155           Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0);
6156       if (NeedToShuffleReuses) {
6157         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
6158       }
6159       InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost;
6160       InstructionCost VecLdCost;
6161       if (E->State == TreeEntry::Vectorize) {
6162         VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0,
6163                                          CostKind, VL0);
6164       } else {
6165         assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState");
6166         Align CommonAlignment = Alignment;
6167         for (Value *V : VL)
6168           CommonAlignment =
6169               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
6170         VecLdCost = TTI->getGatherScatterOpCost(
6171             Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(),
6172             /*VariableMask=*/false, CommonAlignment, CostKind, VL0);
6173       }
6174       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost));
6175       return CommonCost + VecLdCost - ScalarLdCost;
6176     }
6177     case Instruction::Store: {
6178       // We know that we can merge the stores. Calculate the cost.
6179       bool IsReorder = !E->ReorderIndices.empty();
6180       auto *SI =
6181           cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0);
6182       Align Alignment = SI->getAlign();
6183       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
6184           Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0);
6185       InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost;
6186       InstructionCost VecStCost = TTI->getMemoryOpCost(
6187           Instruction::Store, VecTy, Alignment, 0, CostKind, VL0);
6188       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost));
6189       return CommonCost + VecStCost - ScalarStCost;
6190     }
6191     case Instruction::Call: {
6192       CallInst *CI = cast<CallInst>(VL0);
6193       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
6194 
6195       // Calculate the cost of the scalar and vector calls.
6196       IntrinsicCostAttributes CostAttrs(ID, *CI, 1);
6197       InstructionCost ScalarEltCost =
6198           TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
6199       if (NeedToShuffleReuses) {
6200         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
6201       }
6202       InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
6203 
6204       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
6205       InstructionCost VecCallCost =
6206           std::min(VecCallCosts.first, VecCallCosts.second);
6207 
6208       LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
6209                         << " (" << VecCallCost << "-" << ScalarCallCost << ")"
6210                         << " for " << *CI << "\n");
6211 
6212       return CommonCost + VecCallCost - ScalarCallCost;
6213     }
6214     case Instruction::ShuffleVector: {
6215       assert(E->isAltShuffle() &&
6216              ((Instruction::isBinaryOp(E->getOpcode()) &&
6217                Instruction::isBinaryOp(E->getAltOpcode())) ||
6218               (Instruction::isCast(E->getOpcode()) &&
6219                Instruction::isCast(E->getAltOpcode())) ||
6220               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
6221              "Invalid Shuffle Vector Operand");
6222       InstructionCost ScalarCost = 0;
6223       if (NeedToShuffleReuses) {
6224         for (unsigned Idx : E->ReuseShuffleIndices) {
6225           Instruction *I = cast<Instruction>(VL[Idx]);
6226           CommonCost -= TTI->getInstructionCost(I, CostKind);
6227         }
6228         for (Value *V : VL) {
6229           Instruction *I = cast<Instruction>(V);
6230           CommonCost += TTI->getInstructionCost(I, CostKind);
6231         }
6232       }
6233       for (Value *V : VL) {
6234         Instruction *I = cast<Instruction>(V);
6235         assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
6236         ScalarCost += TTI->getInstructionCost(I, CostKind);
6237       }
6238       // VecCost is equal to sum of the cost of creating 2 vectors
6239       // and the cost of creating shuffle.
6240       InstructionCost VecCost = 0;
6241       // Try to find the previous shuffle node with the same operands and same
6242       // main/alternate ops.
6243       auto &&TryFindNodeWithEqualOperands = [this, E]() {
6244         for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
6245           if (TE.get() == E)
6246             break;
6247           if (TE->isAltShuffle() &&
6248               ((TE->getOpcode() == E->getOpcode() &&
6249                 TE->getAltOpcode() == E->getAltOpcode()) ||
6250                (TE->getOpcode() == E->getAltOpcode() &&
6251                 TE->getAltOpcode() == E->getOpcode())) &&
6252               TE->hasEqualOperands(*E))
6253             return true;
6254         }
6255         return false;
6256       };
6257       if (TryFindNodeWithEqualOperands()) {
6258         LLVM_DEBUG({
6259           dbgs() << "SLP: diamond match for alternate node found.\n";
6260           E->dump();
6261         });
6262         // No need to add new vector costs here since we're going to reuse
6263         // same main/alternate vector ops, just do different shuffling.
6264       } else if (Instruction::isBinaryOp(E->getOpcode())) {
6265         VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind);
6266         VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy,
6267                                                CostKind);
6268       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
6269         VecCost = TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy,
6270                                           Builder.getInt1Ty(),
6271                                           CI0->getPredicate(), CostKind, VL0);
6272         VecCost += TTI->getCmpSelInstrCost(
6273             E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
6274             cast<CmpInst>(E->getAltOp())->getPredicate(), CostKind,
6275             E->getAltOp());
6276       } else {
6277         Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
6278         Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
6279         auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size());
6280         auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size());
6281         VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty,
6282                                         TTI::CastContextHint::None, CostKind);
6283         VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty,
6284                                          TTI::CastContextHint::None, CostKind);
6285       }
6286 
6287       if (E->ReuseShuffleIndices.empty()) {
6288         CommonCost =
6289             TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy);
6290       } else {
6291         SmallVector<int> Mask;
6292         buildShuffleEntryMask(
6293             E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
6294             [E](Instruction *I) {
6295               assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
6296               return I->getOpcode() == E->getAltOpcode();
6297             },
6298             Mask);
6299         CommonCost = TTI->getShuffleCost(TargetTransformInfo::SK_PermuteTwoSrc,
6300                                          FinalVecTy, Mask);
6301       }
6302       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
6303       return CommonCost + VecCost - ScalarCost;
6304     }
6305     default:
6306       llvm_unreachable("Unknown instruction");
6307   }
6308 }
6309 
6310 bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const {
6311   LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
6312                     << VectorizableTree.size() << " is fully vectorizable .\n");
6313 
6314   auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) {
6315     SmallVector<int> Mask;
6316     return TE->State == TreeEntry::NeedToGather &&
6317            !any_of(TE->Scalars,
6318                    [this](Value *V) { return EphValues.contains(V); }) &&
6319            (allConstant(TE->Scalars) || isSplat(TE->Scalars) ||
6320             TE->Scalars.size() < Limit ||
6321             ((TE->getOpcode() == Instruction::ExtractElement ||
6322               all_of(TE->Scalars,
6323                      [](Value *V) {
6324                        return isa<ExtractElementInst, UndefValue>(V);
6325                      })) &&
6326              isFixedVectorShuffle(TE->Scalars, Mask)) ||
6327             (TE->State == TreeEntry::NeedToGather &&
6328              TE->getOpcode() == Instruction::Load && !TE->isAltShuffle()));
6329   };
6330 
6331   // We only handle trees of heights 1 and 2.
6332   if (VectorizableTree.size() == 1 &&
6333       (VectorizableTree[0]->State == TreeEntry::Vectorize ||
6334        (ForReduction &&
6335         AreVectorizableGathers(VectorizableTree[0].get(),
6336                                VectorizableTree[0]->Scalars.size()) &&
6337         VectorizableTree[0]->getVectorFactor() > 2)))
6338     return true;
6339 
6340   if (VectorizableTree.size() != 2)
6341     return false;
6342 
6343   // Handle splat and all-constants stores. Also try to vectorize tiny trees
6344   // with the second gather nodes if they have less scalar operands rather than
6345   // the initial tree element (may be profitable to shuffle the second gather)
6346   // or they are extractelements, which form shuffle.
6347   SmallVector<int> Mask;
6348   if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
6349       AreVectorizableGathers(VectorizableTree[1].get(),
6350                              VectorizableTree[0]->Scalars.size()))
6351     return true;
6352 
6353   // Gathering cost would be too much for tiny trees.
6354   if (VectorizableTree[0]->State == TreeEntry::NeedToGather ||
6355       (VectorizableTree[1]->State == TreeEntry::NeedToGather &&
6356        VectorizableTree[0]->State != TreeEntry::ScatterVectorize))
6357     return false;
6358 
6359   return true;
6360 }
6361 
6362 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts,
6363                                        TargetTransformInfo *TTI,
6364                                        bool MustMatchOrInst) {
6365   // Look past the root to find a source value. Arbitrarily follow the
6366   // path through operand 0 of any 'or'. Also, peek through optional
6367   // shift-left-by-multiple-of-8-bits.
6368   Value *ZextLoad = Root;
6369   const APInt *ShAmtC;
6370   bool FoundOr = false;
6371   while (!isa<ConstantExpr>(ZextLoad) &&
6372          (match(ZextLoad, m_Or(m_Value(), m_Value())) ||
6373           (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) &&
6374            ShAmtC->urem(8) == 0))) {
6375     auto *BinOp = cast<BinaryOperator>(ZextLoad);
6376     ZextLoad = BinOp->getOperand(0);
6377     if (BinOp->getOpcode() == Instruction::Or)
6378       FoundOr = true;
6379   }
6380   // Check if the input is an extended load of the required or/shift expression.
6381   Value *Load;
6382   if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root ||
6383       !match(ZextLoad, m_ZExt(m_Value(Load))) || !isa<LoadInst>(Load))
6384     return false;
6385 
6386   // Require that the total load bit width is a legal integer type.
6387   // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
6388   // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
6389   Type *SrcTy = Load->getType();
6390   unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts;
6391   if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth)))
6392     return false;
6393 
6394   // Everything matched - assume that we can fold the whole sequence using
6395   // load combining.
6396   LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "
6397              << *(cast<Instruction>(Root)) << "\n");
6398 
6399   return true;
6400 }
6401 
6402 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const {
6403   if (RdxKind != RecurKind::Or)
6404     return false;
6405 
6406   unsigned NumElts = VectorizableTree[0]->Scalars.size();
6407   Value *FirstReduced = VectorizableTree[0]->Scalars[0];
6408   return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI,
6409                                     /* MatchOr */ false);
6410 }
6411 
6412 bool BoUpSLP::isLoadCombineCandidate() const {
6413   // Peek through a final sequence of stores and check if all operations are
6414   // likely to be load-combined.
6415   unsigned NumElts = VectorizableTree[0]->Scalars.size();
6416   for (Value *Scalar : VectorizableTree[0]->Scalars) {
6417     Value *X;
6418     if (!match(Scalar, m_Store(m_Value(X), m_Value())) ||
6419         !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true))
6420       return false;
6421   }
6422   return true;
6423 }
6424 
6425 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const {
6426   // No need to vectorize inserts of gathered values.
6427   if (VectorizableTree.size() == 2 &&
6428       isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) &&
6429       VectorizableTree[1]->State == TreeEntry::NeedToGather)
6430     return true;
6431 
6432   // We can vectorize the tree if its size is greater than or equal to the
6433   // minimum size specified by the MinTreeSize command line option.
6434   if (VectorizableTree.size() >= MinTreeSize)
6435     return false;
6436 
6437   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
6438   // can vectorize it if we can prove it fully vectorizable.
6439   if (isFullyVectorizableTinyTree(ForReduction))
6440     return false;
6441 
6442   assert(VectorizableTree.empty()
6443              ? ExternalUses.empty()
6444              : true && "We shouldn't have any external users");
6445 
6446   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
6447   // vectorizable.
6448   return true;
6449 }
6450 
6451 InstructionCost BoUpSLP::getSpillCost() const {
6452   // Walk from the bottom of the tree to the top, tracking which values are
6453   // live. When we see a call instruction that is not part of our tree,
6454   // query TTI to see if there is a cost to keeping values live over it
6455   // (for example, if spills and fills are required).
6456   unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
6457   InstructionCost Cost = 0;
6458 
6459   SmallPtrSet<Instruction*, 4> LiveValues;
6460   Instruction *PrevInst = nullptr;
6461 
6462   // The entries in VectorizableTree are not necessarily ordered by their
6463   // position in basic blocks. Collect them and order them by dominance so later
6464   // instructions are guaranteed to be visited first. For instructions in
6465   // different basic blocks, we only scan to the beginning of the block, so
6466   // their order does not matter, as long as all instructions in a basic block
6467   // are grouped together. Using dominance ensures a deterministic order.
6468   SmallVector<Instruction *, 16> OrderedScalars;
6469   for (const auto &TEPtr : VectorizableTree) {
6470     Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
6471     if (!Inst)
6472       continue;
6473     OrderedScalars.push_back(Inst);
6474   }
6475   llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) {
6476     auto *NodeA = DT->getNode(A->getParent());
6477     auto *NodeB = DT->getNode(B->getParent());
6478     assert(NodeA && "Should only process reachable instructions");
6479     assert(NodeB && "Should only process reachable instructions");
6480     assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
6481            "Different nodes should have different DFS numbers");
6482     if (NodeA != NodeB)
6483       return NodeA->getDFSNumIn() < NodeB->getDFSNumIn();
6484     return B->comesBefore(A);
6485   });
6486 
6487   for (Instruction *Inst : OrderedScalars) {
6488     if (!PrevInst) {
6489       PrevInst = Inst;
6490       continue;
6491     }
6492 
6493     // Update LiveValues.
6494     LiveValues.erase(PrevInst);
6495     for (auto &J : PrevInst->operands()) {
6496       if (isa<Instruction>(&*J) && getTreeEntry(&*J))
6497         LiveValues.insert(cast<Instruction>(&*J));
6498     }
6499 
6500     LLVM_DEBUG({
6501       dbgs() << "SLP: #LV: " << LiveValues.size();
6502       for (auto *X : LiveValues)
6503         dbgs() << " " << X->getName();
6504       dbgs() << ", Looking at ";
6505       Inst->dump();
6506     });
6507 
6508     // Now find the sequence of instructions between PrevInst and Inst.
6509     unsigned NumCalls = 0;
6510     BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
6511                                  PrevInstIt =
6512                                      PrevInst->getIterator().getReverse();
6513     while (InstIt != PrevInstIt) {
6514       if (PrevInstIt == PrevInst->getParent()->rend()) {
6515         PrevInstIt = Inst->getParent()->rbegin();
6516         continue;
6517       }
6518 
6519       // Debug information does not impact spill cost.
6520       if ((isa<CallInst>(&*PrevInstIt) &&
6521            !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
6522           &*PrevInstIt != PrevInst)
6523         NumCalls++;
6524 
6525       ++PrevInstIt;
6526     }
6527 
6528     if (NumCalls) {
6529       SmallVector<Type*, 4> V;
6530       for (auto *II : LiveValues) {
6531         auto *ScalarTy = II->getType();
6532         if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy))
6533           ScalarTy = VectorTy->getElementType();
6534         V.push_back(FixedVectorType::get(ScalarTy, BundleWidth));
6535       }
6536       Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
6537     }
6538 
6539     PrevInst = Inst;
6540   }
6541 
6542   return Cost;
6543 }
6544 
6545 /// Check if two insertelement instructions are from the same buildvector.
6546 static bool areTwoInsertFromSameBuildVector(InsertElementInst *VU,
6547                                             InsertElementInst *V) {
6548   // Instructions must be from the same basic blocks.
6549   if (VU->getParent() != V->getParent())
6550     return false;
6551   // Checks if 2 insertelements are from the same buildvector.
6552   if (VU->getType() != V->getType())
6553     return false;
6554   // Multiple used inserts are separate nodes.
6555   if (!VU->hasOneUse() && !V->hasOneUse())
6556     return false;
6557   auto *IE1 = VU;
6558   auto *IE2 = V;
6559   // Go through the vector operand of insertelement instructions trying to find
6560   // either VU as the original vector for IE2 or V as the original vector for
6561   // IE1.
6562   do {
6563     if (IE2 == VU || IE1 == V)
6564       return true;
6565     if (IE1) {
6566       if (IE1 != VU && !IE1->hasOneUse())
6567         IE1 = nullptr;
6568       else
6569         IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0));
6570     }
6571     if (IE2) {
6572       if (IE2 != V && !IE2->hasOneUse())
6573         IE2 = nullptr;
6574       else
6575         IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0));
6576     }
6577   } while (IE1 || IE2);
6578   return false;
6579 }
6580 
6581 /// Checks if the \p IE1 instructions is followed by \p IE2 instruction in the
6582 /// buildvector sequence.
6583 static bool isFirstInsertElement(const InsertElementInst *IE1,
6584                                  const InsertElementInst *IE2) {
6585   const auto *I1 = IE1;
6586   const auto *I2 = IE2;
6587   const InsertElementInst *PrevI1;
6588   const InsertElementInst *PrevI2;
6589   do {
6590     if (I2 == IE1)
6591       return true;
6592     if (I1 == IE2)
6593       return false;
6594     PrevI1 = I1;
6595     PrevI2 = I2;
6596     if (I1 && (I1 == IE1 || I1->hasOneUse()))
6597       I1 = dyn_cast<InsertElementInst>(I1->getOperand(0));
6598     if (I2 && (I2 == IE2 || I2->hasOneUse()))
6599       I2 = dyn_cast<InsertElementInst>(I2->getOperand(0));
6600   } while ((I1 && PrevI1 != I1) || (I2 && PrevI2 != I2));
6601   llvm_unreachable("Two different buildvectors not expected.");
6602 }
6603 
6604 /// Does the analysis of the provided shuffle masks and performs the requested
6605 /// actions on the vectors with the given shuffle masks. It tries to do it in
6606 /// several steps.
6607 /// 1. If the Base vector is not undef vector, resizing the very first mask to
6608 /// have common VF and perform action for 2 input vectors (including non-undef
6609 /// Base). Other shuffle masks are combined with the resulting after the 1 stage
6610 /// and processed as a shuffle of 2 elements.
6611 /// 2. If the Base is undef vector and have only 1 shuffle mask, perform the
6612 /// action only for 1 vector with the given mask, if it is not the identity
6613 /// mask.
6614 /// 3. If > 2 masks are used, perform the remaining shuffle actions for 2
6615 /// vectors, combing the masks properly between the steps.
6616 template <typename T>
6617 static T *performExtractsShuffleAction(
6618     MutableArrayRef<std::pair<T *, SmallVector<int>>> ShuffleMask, Value *Base,
6619     function_ref<unsigned(T *)> GetVF,
6620     function_ref<std::pair<T *, bool>(T *, ArrayRef<int>)> ResizeAction,
6621     function_ref<T *(ArrayRef<int>, ArrayRef<T *>)> Action) {
6622   assert(!ShuffleMask.empty() && "Empty list of shuffles for inserts.");
6623   SmallVector<int> Mask(ShuffleMask.begin()->second);
6624   auto VMIt = std::next(ShuffleMask.begin());
6625   T *Prev = nullptr;
6626   bool IsBaseNotUndef = !isUndefVector(Base);
6627   if (IsBaseNotUndef) {
6628     // Base is not undef, need to combine it with the next subvectors.
6629     std::pair<T *, bool> Res = ResizeAction(ShuffleMask.begin()->first, Mask);
6630     for (unsigned Idx = 0, VF = Mask.size(); Idx < VF; ++Idx) {
6631       if (Mask[Idx] == UndefMaskElem)
6632         Mask[Idx] = Idx;
6633       else
6634         Mask[Idx] = (Res.second ? Idx : Mask[Idx]) + VF;
6635     }
6636     Prev = Action(Mask, {nullptr, Res.first});
6637   } else if (ShuffleMask.size() == 1) {
6638     // Base is undef and only 1 vector is shuffled - perform the action only for
6639     // single vector, if the mask is not the identity mask.
6640     std::pair<T *, bool> Res = ResizeAction(ShuffleMask.begin()->first, Mask);
6641     if (Res.second)
6642       // Identity mask is found.
6643       Prev = Res.first;
6644     else
6645       Prev = Action(Mask, {ShuffleMask.begin()->first});
6646   } else {
6647     // Base is undef and at least 2 input vectors shuffled - perform 2 vectors
6648     // shuffles step by step, combining shuffle between the steps.
6649     unsigned Vec1VF = GetVF(ShuffleMask.begin()->first);
6650     unsigned Vec2VF = GetVF(VMIt->first);
6651     if (Vec1VF == Vec2VF) {
6652       // No need to resize the input vectors since they are of the same size, we
6653       // can shuffle them directly.
6654       ArrayRef<int> SecMask = VMIt->second;
6655       for (unsigned I = 0, VF = Mask.size(); I < VF; ++I) {
6656         if (SecMask[I] != UndefMaskElem) {
6657           assert(Mask[I] == UndefMaskElem && "Multiple uses of scalars.");
6658           Mask[I] = SecMask[I] + Vec1VF;
6659         }
6660       }
6661       Prev = Action(Mask, {ShuffleMask.begin()->first, VMIt->first});
6662     } else {
6663       // Vectors of different sizes - resize and reshuffle.
6664       std::pair<T *, bool> Res1 =
6665           ResizeAction(ShuffleMask.begin()->first, Mask);
6666       std::pair<T *, bool> Res2 = ResizeAction(VMIt->first, VMIt->second);
6667       ArrayRef<int> SecMask = VMIt->second;
6668       for (unsigned I = 0, VF = Mask.size(); I < VF; ++I) {
6669         if (Mask[I] != UndefMaskElem) {
6670           assert(SecMask[I] == UndefMaskElem && "Multiple uses of scalars.");
6671           if (Res1.second)
6672             Mask[I] = I;
6673         } else if (SecMask[I] != UndefMaskElem) {
6674           assert(Mask[I] == UndefMaskElem && "Multiple uses of scalars.");
6675           Mask[I] = (Res2.second ? I : SecMask[I]) + VF;
6676         }
6677       }
6678       Prev = Action(Mask, {Res1.first, Res2.first});
6679     }
6680     VMIt = std::next(VMIt);
6681   }
6682   // Perform requested actions for the remaining masks/vectors.
6683   for (auto E = ShuffleMask.end(); VMIt != E; ++VMIt) {
6684     // Shuffle other input vectors, if any.
6685     std::pair<T *, bool> Res = ResizeAction(VMIt->first, VMIt->second);
6686     ArrayRef<int> SecMask = VMIt->second;
6687     for (unsigned I = 0, VF = Mask.size(); I < VF; ++I) {
6688       if (SecMask[I] != UndefMaskElem) {
6689         assert((Mask[I] == UndefMaskElem || IsBaseNotUndef) &&
6690                "Multiple uses of scalars.");
6691         Mask[I] = (Res.second ? I : SecMask[I]) + VF;
6692       } else if (Mask[I] != UndefMaskElem) {
6693         Mask[I] = I;
6694       }
6695     }
6696     Prev = Action(Mask, {Prev, Res.first});
6697   }
6698   return Prev;
6699 }
6700 
6701 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) {
6702   InstructionCost Cost = 0;
6703   LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
6704                     << VectorizableTree.size() << ".\n");
6705 
6706   unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
6707 
6708   for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
6709     TreeEntry &TE = *VectorizableTree[I];
6710 
6711     InstructionCost C = getEntryCost(&TE, VectorizedVals);
6712     Cost += C;
6713     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6714                       << " for bundle that starts with " << *TE.Scalars[0]
6715                       << ".\n"
6716                       << "SLP: Current total cost = " << Cost << "\n");
6717   }
6718 
6719   SmallPtrSet<Value *, 16> ExtractCostCalculated;
6720   InstructionCost ExtractCost = 0;
6721   SmallVector<MapVector<const TreeEntry *, SmallVector<int>>> ShuffleMasks;
6722   SmallVector<std::pair<Value *, const TreeEntry *>> FirstUsers;
6723   SmallVector<APInt> DemandedElts;
6724   for (ExternalUser &EU : ExternalUses) {
6725     // We only add extract cost once for the same scalar.
6726     if (!isa_and_nonnull<InsertElementInst>(EU.User) &&
6727         !ExtractCostCalculated.insert(EU.Scalar).second)
6728       continue;
6729 
6730     // Uses by ephemeral values are free (because the ephemeral value will be
6731     // removed prior to code generation, and so the extraction will be
6732     // removed as well).
6733     if (EphValues.count(EU.User))
6734       continue;
6735 
6736     // No extract cost for vector "scalar"
6737     if (isa<FixedVectorType>(EU.Scalar->getType()))
6738       continue;
6739 
6740     // Already counted the cost for external uses when tried to adjust the cost
6741     // for extractelements, no need to add it again.
6742     if (isa<ExtractElementInst>(EU.Scalar))
6743       continue;
6744 
6745     // If found user is an insertelement, do not calculate extract cost but try
6746     // to detect it as a final shuffled/identity match.
6747     if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) {
6748       if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) {
6749         Optional<unsigned> InsertIdx = getInsertIndex(VU);
6750         if (InsertIdx) {
6751           const TreeEntry *ScalarTE = getTreeEntry(EU.Scalar);
6752           auto *It =
6753               find_if(FirstUsers,
6754                       [VU](const std::pair<Value *, const TreeEntry *> &Pair) {
6755                         return areTwoInsertFromSameBuildVector(
6756                             VU, cast<InsertElementInst>(Pair.first));
6757                       });
6758           int VecId = -1;
6759           if (It == FirstUsers.end()) {
6760             (void)ShuffleMasks.emplace_back();
6761             SmallVectorImpl<int> &Mask = ShuffleMasks.back()[ScalarTE];
6762             if (Mask.empty())
6763               Mask.assign(FTy->getNumElements(), UndefMaskElem);
6764             // Find the insertvector, vectorized in tree, if any.
6765             Value *Base = VU;
6766             while (auto *IEBase = dyn_cast<InsertElementInst>(Base)) {
6767               if (IEBase != EU.User && !IEBase->hasOneUse())
6768                 break;
6769               // Build the mask for the vectorized insertelement instructions.
6770               if (const TreeEntry *E = getTreeEntry(IEBase)) {
6771                 VU = IEBase;
6772                 do {
6773                   IEBase = cast<InsertElementInst>(Base);
6774                   int Idx = *getInsertIndex(IEBase);
6775                   assert(Mask[Idx] == UndefMaskElem &&
6776                          "InsertElementInstruction used already.");
6777                   Mask[Idx] = Idx;
6778                   Base = IEBase->getOperand(0);
6779                 } while (E == getTreeEntry(Base));
6780                 break;
6781               }
6782               Base = cast<InsertElementInst>(Base)->getOperand(0);
6783             }
6784             FirstUsers.emplace_back(VU, ScalarTE);
6785             DemandedElts.push_back(APInt::getZero(FTy->getNumElements()));
6786             VecId = FirstUsers.size() - 1;
6787           } else {
6788             if (isFirstInsertElement(VU, cast<InsertElementInst>(It->first)))
6789               It->first = VU;
6790             VecId = std::distance(FirstUsers.begin(), It);
6791           }
6792           int InIdx = *InsertIdx;
6793           SmallVectorImpl<int> &Mask = ShuffleMasks[VecId][ScalarTE];
6794           if (Mask.empty())
6795             Mask.assign(FTy->getNumElements(), UndefMaskElem);
6796           Mask[InIdx] = EU.Lane;
6797           DemandedElts[VecId].setBit(InIdx);
6798           continue;
6799         }
6800       }
6801     }
6802 
6803     // If we plan to rewrite the tree in a smaller type, we will need to sign
6804     // extend the extracted value back to the original type. Here, we account
6805     // for the extract and the added cost of the sign extend if needed.
6806     auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth);
6807     auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
6808     if (MinBWs.count(ScalarRoot)) {
6809       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
6810       auto Extend =
6811           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
6812       VecTy = FixedVectorType::get(MinTy, BundleWidth);
6813       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
6814                                                    VecTy, EU.Lane);
6815     } else {
6816       ExtractCost +=
6817           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
6818     }
6819   }
6820 
6821   InstructionCost SpillCost = getSpillCost();
6822   Cost += SpillCost + ExtractCost;
6823   auto &&ResizeToVF = [this, &Cost](const TreeEntry *TE, ArrayRef<int> Mask) {
6824     InstructionCost C = 0;
6825     unsigned VF = Mask.size();
6826     unsigned VecVF = TE->getVectorFactor();
6827     if (VF != VecVF &&
6828         (any_of(Mask, [VF](int Idx) { return Idx >= static_cast<int>(VF); }) ||
6829          (all_of(Mask,
6830                  [VF](int Idx) { return Idx < 2 * static_cast<int>(VF); }) &&
6831           !ShuffleVectorInst::isIdentityMask(Mask)))) {
6832       SmallVector<int> OrigMask(VecVF, UndefMaskElem);
6833       std::copy(Mask.begin(), std::next(Mask.begin(), std::min(VF, VecVF)),
6834                 OrigMask.begin());
6835       C = TTI->getShuffleCost(
6836           TTI::SK_PermuteSingleSrc,
6837           FixedVectorType::get(TE->getMainOp()->getType(), VecVF), OrigMask);
6838       LLVM_DEBUG(
6839           dbgs() << "SLP: Adding cost " << C
6840                  << " for final shuffle of insertelement external users.\n";
6841           TE->dump(); dbgs() << "SLP: Current total cost = " << Cost << "\n");
6842       Cost += C;
6843       return std::make_pair(TE, true);
6844     }
6845     return std::make_pair(TE, false);
6846   };
6847   // Calculate the cost of the reshuffled vectors, if any.
6848   for (int I = 0, E = FirstUsers.size(); I < E; ++I) {
6849     Value *Base = cast<Instruction>(FirstUsers[I].first)->getOperand(0);
6850     unsigned VF = ShuffleMasks[I].begin()->second.size();
6851     auto *FTy = FixedVectorType::get(
6852         cast<VectorType>(FirstUsers[I].first->getType())->getElementType(), VF);
6853     auto Vector = ShuffleMasks[I].takeVector();
6854     auto &&EstimateShufflesCost = [this, FTy,
6855                                    &Cost](ArrayRef<int> Mask,
6856                                           ArrayRef<const TreeEntry *> TEs) {
6857       assert((TEs.size() == 1 || TEs.size() == 2) &&
6858              "Expected exactly 1 or 2 tree entries.");
6859       if (TEs.size() == 1) {
6860         int Limit = 2 * Mask.size();
6861         if (!all_of(Mask, [Limit](int Idx) { return Idx < Limit; }) ||
6862             !ShuffleVectorInst::isIdentityMask(Mask)) {
6863           InstructionCost C =
6864               TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FTy, Mask);
6865           LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6866                             << " for final shuffle of insertelement "
6867                                "external users.\n";
6868                      TEs.front()->dump();
6869                      dbgs() << "SLP: Current total cost = " << Cost << "\n");
6870           Cost += C;
6871         }
6872       } else {
6873         InstructionCost C =
6874             TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, FTy, Mask);
6875         LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6876                           << " for final shuffle of vector node and external "
6877                              "insertelement users.\n";
6878                    if (TEs.front()) { TEs.front()->dump(); } TEs.back()->dump();
6879                    dbgs() << "SLP: Current total cost = " << Cost << "\n");
6880         Cost += C;
6881       }
6882       return TEs.back();
6883     };
6884     (void)performExtractsShuffleAction<const TreeEntry>(
6885         makeMutableArrayRef(Vector.data(), Vector.size()), Base,
6886         [](const TreeEntry *E) { return E->getVectorFactor(); }, ResizeToVF,
6887         EstimateShufflesCost);
6888     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6889         cast<FixedVectorType>(FirstUsers[I].first->getType()), DemandedElts[I],
6890         /*Insert*/ true, /*Extract*/ false);
6891     Cost -= InsertCost;
6892   }
6893 
6894 #ifndef NDEBUG
6895   SmallString<256> Str;
6896   {
6897     raw_svector_ostream OS(Str);
6898     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
6899        << "SLP: Extract Cost = " << ExtractCost << ".\n"
6900        << "SLP: Total Cost = " << Cost << ".\n";
6901   }
6902   LLVM_DEBUG(dbgs() << Str);
6903   if (ViewSLPTree)
6904     ViewGraph(this, "SLP" + F->getName(), false, Str);
6905 #endif
6906 
6907   return Cost;
6908 }
6909 
6910 Optional<TargetTransformInfo::ShuffleKind>
6911 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
6912                                SmallVectorImpl<const TreeEntry *> &Entries) {
6913   // TODO: currently checking only for Scalars in the tree entry, need to count
6914   // reused elements too for better cost estimation.
6915   Mask.assign(TE->Scalars.size(), UndefMaskElem);
6916   Entries.clear();
6917   // Build a lists of values to tree entries.
6918   DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs;
6919   for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) {
6920     if (EntryPtr.get() == TE)
6921       break;
6922     if (EntryPtr->State != TreeEntry::NeedToGather)
6923       continue;
6924     for (Value *V : EntryPtr->Scalars)
6925       ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get());
6926   }
6927   // Find all tree entries used by the gathered values. If no common entries
6928   // found - not a shuffle.
6929   // Here we build a set of tree nodes for each gathered value and trying to
6930   // find the intersection between these sets. If we have at least one common
6931   // tree node for each gathered value - we have just a permutation of the
6932   // single vector. If we have 2 different sets, we're in situation where we
6933   // have a permutation of 2 input vectors.
6934   SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs;
6935   DenseMap<Value *, int> UsedValuesEntry;
6936   for (Value *V : TE->Scalars) {
6937     if (isa<UndefValue>(V))
6938       continue;
6939     // Build a list of tree entries where V is used.
6940     SmallPtrSet<const TreeEntry *, 4> VToTEs;
6941     auto It = ValueToTEs.find(V);
6942     if (It != ValueToTEs.end())
6943       VToTEs = It->second;
6944     if (const TreeEntry *VTE = getTreeEntry(V))
6945       VToTEs.insert(VTE);
6946     if (VToTEs.empty())
6947       return None;
6948     if (UsedTEs.empty()) {
6949       // The first iteration, just insert the list of nodes to vector.
6950       UsedTEs.push_back(VToTEs);
6951     } else {
6952       // Need to check if there are any previously used tree nodes which use V.
6953       // If there are no such nodes, consider that we have another one input
6954       // vector.
6955       SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs);
6956       unsigned Idx = 0;
6957       for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) {
6958         // Do we have a non-empty intersection of previously listed tree entries
6959         // and tree entries using current V?
6960         set_intersect(VToTEs, Set);
6961         if (!VToTEs.empty()) {
6962           // Yes, write the new subset and continue analysis for the next
6963           // scalar.
6964           Set.swap(VToTEs);
6965           break;
6966         }
6967         VToTEs = SavedVToTEs;
6968         ++Idx;
6969       }
6970       // No non-empty intersection found - need to add a second set of possible
6971       // source vectors.
6972       if (Idx == UsedTEs.size()) {
6973         // If the number of input vectors is greater than 2 - not a permutation,
6974         // fallback to the regular gather.
6975         if (UsedTEs.size() == 2)
6976           return None;
6977         UsedTEs.push_back(SavedVToTEs);
6978         Idx = UsedTEs.size() - 1;
6979       }
6980       UsedValuesEntry.try_emplace(V, Idx);
6981     }
6982   }
6983 
6984   if (UsedTEs.empty()) {
6985     assert(all_of(TE->Scalars, UndefValue::classof) &&
6986            "Expected vector of undefs only.");
6987     return None;
6988   }
6989 
6990   unsigned VF = 0;
6991   if (UsedTEs.size() == 1) {
6992     // Try to find the perfect match in another gather node at first.
6993     auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) {
6994       return EntryPtr->isSame(TE->Scalars);
6995     });
6996     if (It != UsedTEs.front().end()) {
6997       Entries.push_back(*It);
6998       std::iota(Mask.begin(), Mask.end(), 0);
6999       return TargetTransformInfo::SK_PermuteSingleSrc;
7000     }
7001     // No perfect match, just shuffle, so choose the first tree node.
7002     Entries.push_back(*UsedTEs.front().begin());
7003   } else {
7004     // Try to find nodes with the same vector factor.
7005     assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries.");
7006     DenseMap<int, const TreeEntry *> VFToTE;
7007     for (const TreeEntry *TE : UsedTEs.front())
7008       VFToTE.try_emplace(TE->getVectorFactor(), TE);
7009     for (const TreeEntry *TE : UsedTEs.back()) {
7010       auto It = VFToTE.find(TE->getVectorFactor());
7011       if (It != VFToTE.end()) {
7012         VF = It->first;
7013         Entries.push_back(It->second);
7014         Entries.push_back(TE);
7015         break;
7016       }
7017     }
7018     // No 2 source vectors with the same vector factor - give up and do regular
7019     // gather.
7020     if (Entries.empty())
7021       return None;
7022   }
7023 
7024   // Build a shuffle mask for better cost estimation and vector emission.
7025   for (int I = 0, E = TE->Scalars.size(); I < E; ++I) {
7026     Value *V = TE->Scalars[I];
7027     if (isa<UndefValue>(V))
7028       continue;
7029     unsigned Idx = UsedValuesEntry.lookup(V);
7030     const TreeEntry *VTE = Entries[Idx];
7031     int FoundLane = VTE->findLaneForValue(V);
7032     Mask[I] = Idx * VF + FoundLane;
7033     // Extra check required by isSingleSourceMaskImpl function (called by
7034     // ShuffleVectorInst::isSingleSourceMask).
7035     if (Mask[I] >= 2 * E)
7036       return None;
7037   }
7038   switch (Entries.size()) {
7039   case 1:
7040     return TargetTransformInfo::SK_PermuteSingleSrc;
7041   case 2:
7042     return TargetTransformInfo::SK_PermuteTwoSrc;
7043   default:
7044     break;
7045   }
7046   return None;
7047 }
7048 
7049 InstructionCost BoUpSLP::getGatherCost(FixedVectorType *Ty,
7050                                        const APInt &ShuffledIndices,
7051                                        bool NeedToShuffle) const {
7052   InstructionCost Cost =
7053       TTI->getScalarizationOverhead(Ty, ~ShuffledIndices, /*Insert*/ true,
7054                                     /*Extract*/ false);
7055   if (NeedToShuffle)
7056     Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
7057   return Cost;
7058 }
7059 
7060 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
7061   // Find the type of the operands in VL.
7062   Type *ScalarTy = VL[0]->getType();
7063   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
7064     ScalarTy = SI->getValueOperand()->getType();
7065   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
7066   bool DuplicateNonConst = false;
7067   // Find the cost of inserting/extracting values from the vector.
7068   // Check if the same elements are inserted several times and count them as
7069   // shuffle candidates.
7070   APInt ShuffledElements = APInt::getZero(VL.size());
7071   DenseSet<Value *> UniqueElements;
7072   // Iterate in reverse order to consider insert elements with the high cost.
7073   for (unsigned I = VL.size(); I > 0; --I) {
7074     unsigned Idx = I - 1;
7075     // No need to shuffle duplicates for constants.
7076     if (isConstant(VL[Idx])) {
7077       ShuffledElements.setBit(Idx);
7078       continue;
7079     }
7080     if (!UniqueElements.insert(VL[Idx]).second) {
7081       DuplicateNonConst = true;
7082       ShuffledElements.setBit(Idx);
7083     }
7084   }
7085   return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst);
7086 }
7087 
7088 // Perform operand reordering on the instructions in VL and return the reordered
7089 // operands in Left and Right.
7090 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
7091                                              SmallVectorImpl<Value *> &Left,
7092                                              SmallVectorImpl<Value *> &Right,
7093                                              const DataLayout &DL,
7094                                              ScalarEvolution &SE,
7095                                              const BoUpSLP &R) {
7096   if (VL.empty())
7097     return;
7098   VLOperands Ops(VL, DL, SE, R);
7099   // Reorder the operands in place.
7100   Ops.reorder();
7101   Left = Ops.getVL(0);
7102   Right = Ops.getVL(1);
7103 }
7104 
7105 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) {
7106   // Get the basic block this bundle is in. All instructions in the bundle
7107   // should be in this block.
7108   auto *Front = E->getMainOp();
7109   auto *BB = Front->getParent();
7110   assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool {
7111     auto *I = cast<Instruction>(V);
7112     return !E->isOpcodeOrAlt(I) || I->getParent() == BB;
7113   }));
7114 
7115   auto &&FindLastInst = [E, Front]() {
7116     Instruction *LastInst = Front;
7117     for (Value *V : E->Scalars) {
7118       auto *I = dyn_cast<Instruction>(V);
7119       if (!I)
7120         continue;
7121       if (LastInst->comesBefore(I))
7122         LastInst = I;
7123     }
7124     return LastInst;
7125   };
7126 
7127   auto &&FindFirstInst = [E, Front]() {
7128     Instruction *FirstInst = Front;
7129     for (Value *V : E->Scalars) {
7130       auto *I = dyn_cast<Instruction>(V);
7131       if (!I)
7132         continue;
7133       if (I->comesBefore(FirstInst))
7134         FirstInst = I;
7135     }
7136     return FirstInst;
7137   };
7138 
7139   // Set the insert point to the beginning of the basic block if the entry
7140   // should not be scheduled.
7141   if (E->State != TreeEntry::NeedToGather &&
7142       doesNotNeedToSchedule(E->Scalars)) {
7143     Instruction *InsertInst;
7144     if (all_of(E->Scalars, isUsedOutsideBlock))
7145       InsertInst = FindLastInst();
7146     else
7147       InsertInst = FindFirstInst();
7148     // If the instruction is PHI, set the insert point after all the PHIs.
7149     if (isa<PHINode>(InsertInst))
7150       InsertInst = BB->getFirstNonPHI();
7151     BasicBlock::iterator InsertPt = InsertInst->getIterator();
7152     Builder.SetInsertPoint(BB, InsertPt);
7153     Builder.SetCurrentDebugLocation(Front->getDebugLoc());
7154     return;
7155   }
7156 
7157   // The last instruction in the bundle in program order.
7158   Instruction *LastInst = nullptr;
7159 
7160   // Find the last instruction. The common case should be that BB has been
7161   // scheduled, and the last instruction is VL.back(). So we start with
7162   // VL.back() and iterate over schedule data until we reach the end of the
7163   // bundle. The end of the bundle is marked by null ScheduleData.
7164   if (BlocksSchedules.count(BB)) {
7165     Value *V = E->isOneOf(E->Scalars.back());
7166     if (doesNotNeedToBeScheduled(V))
7167       V = *find_if_not(E->Scalars, doesNotNeedToBeScheduled);
7168     auto *Bundle = BlocksSchedules[BB]->getScheduleData(V);
7169     if (Bundle && Bundle->isPartOfBundle())
7170       for (; Bundle; Bundle = Bundle->NextInBundle)
7171         if (Bundle->OpValue == Bundle->Inst)
7172           LastInst = Bundle->Inst;
7173   }
7174 
7175   // LastInst can still be null at this point if there's either not an entry
7176   // for BB in BlocksSchedules or there's no ScheduleData available for
7177   // VL.back(). This can be the case if buildTree_rec aborts for various
7178   // reasons (e.g., the maximum recursion depth is reached, the maximum region
7179   // size is reached, etc.). ScheduleData is initialized in the scheduling
7180   // "dry-run".
7181   //
7182   // If this happens, we can still find the last instruction by brute force. We
7183   // iterate forwards from Front (inclusive) until we either see all
7184   // instructions in the bundle or reach the end of the block. If Front is the
7185   // last instruction in program order, LastInst will be set to Front, and we
7186   // will visit all the remaining instructions in the block.
7187   //
7188   // One of the reasons we exit early from buildTree_rec is to place an upper
7189   // bound on compile-time. Thus, taking an additional compile-time hit here is
7190   // not ideal. However, this should be exceedingly rare since it requires that
7191   // we both exit early from buildTree_rec and that the bundle be out-of-order
7192   // (causing us to iterate all the way to the end of the block).
7193   if (!LastInst) {
7194     LastInst = FindLastInst();
7195     // If the instruction is PHI, set the insert point after all the PHIs.
7196     if (isa<PHINode>(LastInst))
7197       LastInst = BB->getFirstNonPHI()->getPrevNode();
7198   }
7199   assert(LastInst && "Failed to find last instruction in bundle");
7200 
7201   // Set the insertion point after the last instruction in the bundle. Set the
7202   // debug location to Front.
7203   Builder.SetInsertPoint(BB, std::next(LastInst->getIterator()));
7204   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
7205 }
7206 
7207 Value *BoUpSLP::gather(ArrayRef<Value *> VL) {
7208   // List of instructions/lanes from current block and/or the blocks which are
7209   // part of the current loop. These instructions will be inserted at the end to
7210   // make it possible to optimize loops and hoist invariant instructions out of
7211   // the loops body with better chances for success.
7212   SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts;
7213   SmallSet<int, 4> PostponedIndices;
7214   Loop *L = LI->getLoopFor(Builder.GetInsertBlock());
7215   auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) {
7216     SmallPtrSet<BasicBlock *, 4> Visited;
7217     while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second)
7218       InsertBB = InsertBB->getSinglePredecessor();
7219     return InsertBB && InsertBB == InstBB;
7220   };
7221   for (int I = 0, E = VL.size(); I < E; ++I) {
7222     if (auto *Inst = dyn_cast<Instruction>(VL[I]))
7223       if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) ||
7224            getTreeEntry(Inst) || (L && (L->contains(Inst)))) &&
7225           PostponedIndices.insert(I).second)
7226         PostponedInsts.emplace_back(Inst, I);
7227   }
7228 
7229   auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) {
7230     Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos));
7231     auto *InsElt = dyn_cast<InsertElementInst>(Vec);
7232     if (!InsElt)
7233       return Vec;
7234     GatherShuffleSeq.insert(InsElt);
7235     CSEBlocks.insert(InsElt->getParent());
7236     // Add to our 'need-to-extract' list.
7237     if (TreeEntry *Entry = getTreeEntry(V)) {
7238       // Find which lane we need to extract.
7239       unsigned FoundLane = Entry->findLaneForValue(V);
7240       ExternalUses.emplace_back(V, InsElt, FoundLane);
7241     }
7242     return Vec;
7243   };
7244   Value *Val0 =
7245       isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0];
7246   FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size());
7247   Value *Vec = PoisonValue::get(VecTy);
7248   SmallVector<int> NonConsts;
7249   // Insert constant values at first.
7250   for (int I = 0, E = VL.size(); I < E; ++I) {
7251     if (PostponedIndices.contains(I))
7252       continue;
7253     if (!isConstant(VL[I])) {
7254       NonConsts.push_back(I);
7255       continue;
7256     }
7257     Vec = CreateInsertElement(Vec, VL[I], I);
7258   }
7259   // Insert non-constant values.
7260   for (int I : NonConsts)
7261     Vec = CreateInsertElement(Vec, VL[I], I);
7262   // Append instructions, which are/may be part of the loop, in the end to make
7263   // it possible to hoist non-loop-based instructions.
7264   for (const std::pair<Value *, unsigned> &Pair : PostponedInsts)
7265     Vec = CreateInsertElement(Vec, Pair.first, Pair.second);
7266 
7267   return Vec;
7268 }
7269 
7270 namespace {
7271 /// Merges shuffle masks and emits final shuffle instruction, if required.
7272 class ShuffleInstructionBuilder {
7273   IRBuilderBase &Builder;
7274   const unsigned VF = 0;
7275   bool IsFinalized = false;
7276   SmallVector<int, 4> Mask;
7277   /// Holds all of the instructions that we gathered.
7278   SetVector<Instruction *> &GatherShuffleSeq;
7279   /// A list of blocks that we are going to CSE.
7280   SetVector<BasicBlock *> &CSEBlocks;
7281 
7282 public:
7283   ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF,
7284                             SetVector<Instruction *> &GatherShuffleSeq,
7285                             SetVector<BasicBlock *> &CSEBlocks)
7286       : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq),
7287         CSEBlocks(CSEBlocks) {}
7288 
7289   /// Adds a mask, inverting it before applying.
7290   void addInversedMask(ArrayRef<unsigned> SubMask) {
7291     if (SubMask.empty())
7292       return;
7293     SmallVector<int, 4> NewMask;
7294     inversePermutation(SubMask, NewMask);
7295     addMask(NewMask);
7296   }
7297 
7298   /// Functions adds masks, merging them into  single one.
7299   void addMask(ArrayRef<unsigned> SubMask) {
7300     SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end());
7301     addMask(NewMask);
7302   }
7303 
7304   void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); }
7305 
7306   Value *finalize(Value *V) {
7307     IsFinalized = true;
7308     unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements();
7309     if (VF == ValueVF && Mask.empty())
7310       return V;
7311     SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem);
7312     std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0);
7313     addMask(NormalizedMask);
7314 
7315     if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask))
7316       return V;
7317     Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle");
7318     if (auto *I = dyn_cast<Instruction>(Vec)) {
7319       GatherShuffleSeq.insert(I);
7320       CSEBlocks.insert(I->getParent());
7321     }
7322     return Vec;
7323   }
7324 
7325   ~ShuffleInstructionBuilder() {
7326     assert((IsFinalized || Mask.empty()) &&
7327            "Shuffle construction must be finalized.");
7328   }
7329 };
7330 } // namespace
7331 
7332 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
7333   const unsigned VF = VL.size();
7334   InstructionsState S = getSameOpcode(VL);
7335   if (S.getOpcode()) {
7336     if (TreeEntry *E = getTreeEntry(S.OpValue))
7337       if (E->isSame(VL)) {
7338         Value *V = vectorizeTree(E);
7339         if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) {
7340           if (!E->ReuseShuffleIndices.empty()) {
7341             // Reshuffle to get only unique values.
7342             // If some of the scalars are duplicated in the vectorization tree
7343             // entry, we do not vectorize them but instead generate a mask for
7344             // the reuses. But if there are several users of the same entry,
7345             // they may have different vectorization factors. This is especially
7346             // important for PHI nodes. In this case, we need to adapt the
7347             // resulting instruction for the user vectorization factor and have
7348             // to reshuffle it again to take only unique elements of the vector.
7349             // Without this code the function incorrectly returns reduced vector
7350             // instruction with the same elements, not with the unique ones.
7351 
7352             // block:
7353             // %phi = phi <2 x > { .., %entry} {%shuffle, %block}
7354             // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0>
7355             // ... (use %2)
7356             // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0}
7357             // br %block
7358             SmallVector<int> UniqueIdxs(VF, UndefMaskElem);
7359             SmallSet<int, 4> UsedIdxs;
7360             int Pos = 0;
7361             int Sz = VL.size();
7362             for (int Idx : E->ReuseShuffleIndices) {
7363               if (Idx != Sz && Idx != UndefMaskElem &&
7364                   UsedIdxs.insert(Idx).second)
7365                 UniqueIdxs[Idx] = Pos;
7366               ++Pos;
7367             }
7368             assert(VF >= UsedIdxs.size() && "Expected vectorization factor "
7369                                             "less than original vector size.");
7370             UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem);
7371             V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle");
7372           } else {
7373             assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() &&
7374                    "Expected vectorization factor less "
7375                    "than original vector size.");
7376             SmallVector<int> UniformMask(VF, 0);
7377             std::iota(UniformMask.begin(), UniformMask.end(), 0);
7378             V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle");
7379           }
7380           if (auto *I = dyn_cast<Instruction>(V)) {
7381             GatherShuffleSeq.insert(I);
7382             CSEBlocks.insert(I->getParent());
7383           }
7384         }
7385         return V;
7386       }
7387   }
7388 
7389   // Can't vectorize this, so simply build a new vector with each lane
7390   // corresponding to the requested value.
7391   return createBuildVector(VL);
7392 }
7393 Value *BoUpSLP::createBuildVector(ArrayRef<Value *> VL) {
7394   unsigned VF = VL.size();
7395   // Exploit possible reuse of values across lanes.
7396   SmallVector<int> ReuseShuffleIndicies;
7397   SmallVector<Value *> UniqueValues;
7398   if (VL.size() > 2) {
7399     DenseMap<Value *, unsigned> UniquePositions;
7400     unsigned NumValues =
7401         std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) {
7402                                     return !isa<UndefValue>(V);
7403                                   }).base());
7404     VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues));
7405     int UniqueVals = 0;
7406     for (Value *V : VL.drop_back(VL.size() - VF)) {
7407       if (isa<UndefValue>(V)) {
7408         ReuseShuffleIndicies.emplace_back(UndefMaskElem);
7409         continue;
7410       }
7411       if (isConstant(V)) {
7412         ReuseShuffleIndicies.emplace_back(UniqueValues.size());
7413         UniqueValues.emplace_back(V);
7414         continue;
7415       }
7416       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
7417       ReuseShuffleIndicies.emplace_back(Res.first->second);
7418       if (Res.second) {
7419         UniqueValues.emplace_back(V);
7420         ++UniqueVals;
7421       }
7422     }
7423     if (UniqueVals == 1 && UniqueValues.size() == 1) {
7424       // Emit pure splat vector.
7425       ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(),
7426                                   UndefMaskElem);
7427     } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) {
7428       ReuseShuffleIndicies.clear();
7429       UniqueValues.clear();
7430       UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues));
7431     }
7432     UniqueValues.append(VF - UniqueValues.size(),
7433                         PoisonValue::get(VL[0]->getType()));
7434     VL = UniqueValues;
7435   }
7436 
7437   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
7438                                            CSEBlocks);
7439   Value *Vec = gather(VL);
7440   if (!ReuseShuffleIndicies.empty()) {
7441     ShuffleBuilder.addMask(ReuseShuffleIndicies);
7442     Vec = ShuffleBuilder.finalize(Vec);
7443   }
7444   return Vec;
7445 }
7446 
7447 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
7448   IRBuilder<>::InsertPointGuard Guard(Builder);
7449 
7450   if (E->VectorizedValue) {
7451     LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
7452     return E->VectorizedValue;
7453   }
7454 
7455   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
7456   unsigned VF = E->getVectorFactor();
7457   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
7458                                            CSEBlocks);
7459   if (E->State == TreeEntry::NeedToGather) {
7460     if (E->getMainOp())
7461       setInsertPointAfterBundle(E);
7462     Value *Vec;
7463     SmallVector<int> Mask;
7464     SmallVector<const TreeEntry *> Entries;
7465     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
7466         isGatherShuffledEntry(E, Mask, Entries);
7467     if (Shuffle.hasValue()) {
7468       assert((Entries.size() == 1 || Entries.size() == 2) &&
7469              "Expected shuffle of 1 or 2 entries.");
7470       Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue,
7471                                         Entries.back()->VectorizedValue, Mask);
7472       if (auto *I = dyn_cast<Instruction>(Vec)) {
7473         GatherShuffleSeq.insert(I);
7474         CSEBlocks.insert(I->getParent());
7475       }
7476     } else {
7477       Vec = gather(E->Scalars);
7478     }
7479     if (NeedToShuffleReuses) {
7480       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7481       Vec = ShuffleBuilder.finalize(Vec);
7482     }
7483     E->VectorizedValue = Vec;
7484     return Vec;
7485   }
7486 
7487   assert((E->State == TreeEntry::Vectorize ||
7488           E->State == TreeEntry::ScatterVectorize) &&
7489          "Unhandled state");
7490   unsigned ShuffleOrOp =
7491       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
7492   Instruction *VL0 = E->getMainOp();
7493   Type *ScalarTy = VL0->getType();
7494   if (auto *Store = dyn_cast<StoreInst>(VL0))
7495     ScalarTy = Store->getValueOperand()->getType();
7496   else if (auto *IE = dyn_cast<InsertElementInst>(VL0))
7497     ScalarTy = IE->getOperand(1)->getType();
7498   auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
7499   switch (ShuffleOrOp) {
7500     case Instruction::PHI: {
7501       assert(
7502           (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) &&
7503           "PHI reordering is free.");
7504       auto *PH = cast<PHINode>(VL0);
7505       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
7506       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
7507       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
7508       Value *V = NewPhi;
7509 
7510       // Adjust insertion point once all PHI's have been generated.
7511       Builder.SetInsertPoint(&*PH->getParent()->getFirstInsertionPt());
7512       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
7513 
7514       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7515       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7516       V = ShuffleBuilder.finalize(V);
7517 
7518       E->VectorizedValue = V;
7519 
7520       // PHINodes may have multiple entries from the same block. We want to
7521       // visit every block once.
7522       SmallPtrSet<BasicBlock*, 4> VisitedBBs;
7523 
7524       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
7525         ValueList Operands;
7526         BasicBlock *IBB = PH->getIncomingBlock(i);
7527 
7528         if (!VisitedBBs.insert(IBB).second) {
7529           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
7530           continue;
7531         }
7532 
7533         Builder.SetInsertPoint(IBB->getTerminator());
7534         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
7535         Value *Vec = vectorizeTree(E->getOperand(i));
7536         NewPhi->addIncoming(Vec, IBB);
7537       }
7538 
7539       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
7540              "Invalid number of incoming values");
7541       return V;
7542     }
7543 
7544     case Instruction::ExtractElement: {
7545       Value *V = E->getSingleOperand(0);
7546       Builder.SetInsertPoint(VL0);
7547       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7548       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7549       V = ShuffleBuilder.finalize(V);
7550       E->VectorizedValue = V;
7551       return V;
7552     }
7553     case Instruction::ExtractValue: {
7554       auto *LI = cast<LoadInst>(E->getSingleOperand(0));
7555       Builder.SetInsertPoint(LI);
7556       auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
7557       Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
7558       LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
7559       Value *NewV = propagateMetadata(V, E->Scalars);
7560       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7561       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7562       NewV = ShuffleBuilder.finalize(NewV);
7563       E->VectorizedValue = NewV;
7564       return NewV;
7565     }
7566     case Instruction::InsertElement: {
7567       assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique");
7568       Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back()));
7569       Value *V = vectorizeTree(E->getOperand(1));
7570 
7571       // Create InsertVector shuffle if necessary
7572       auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
7573         return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0));
7574       }));
7575       const unsigned NumElts =
7576           cast<FixedVectorType>(FirstInsert->getType())->getNumElements();
7577       const unsigned NumScalars = E->Scalars.size();
7578 
7579       unsigned Offset = *getInsertIndex(VL0);
7580       assert(Offset < NumElts && "Failed to find vector index offset");
7581 
7582       // Create shuffle to resize vector
7583       SmallVector<int> Mask;
7584       if (!E->ReorderIndices.empty()) {
7585         inversePermutation(E->ReorderIndices, Mask);
7586         Mask.append(NumElts - NumScalars, UndefMaskElem);
7587       } else {
7588         Mask.assign(NumElts, UndefMaskElem);
7589         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
7590       }
7591       // Create InsertVector shuffle if necessary
7592       bool IsIdentity = true;
7593       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
7594       Mask.swap(PrevMask);
7595       for (unsigned I = 0; I < NumScalars; ++I) {
7596         Value *Scalar = E->Scalars[PrevMask[I]];
7597         unsigned InsertIdx = *getInsertIndex(Scalar);
7598         IsIdentity &= InsertIdx - Offset == I;
7599         Mask[InsertIdx - Offset] = I;
7600       }
7601       if (!IsIdentity || NumElts != NumScalars) {
7602         V = Builder.CreateShuffleVector(V, Mask);
7603         if (auto *I = dyn_cast<Instruction>(V)) {
7604           GatherShuffleSeq.insert(I);
7605           CSEBlocks.insert(I->getParent());
7606         }
7607       }
7608 
7609       if ((!IsIdentity || Offset != 0 ||
7610            !isUndefVector(FirstInsert->getOperand(0))) &&
7611           NumElts != NumScalars) {
7612         SmallVector<int> InsertMask(NumElts);
7613         std::iota(InsertMask.begin(), InsertMask.end(), 0);
7614         for (unsigned I = 0; I < NumElts; I++) {
7615           if (Mask[I] != UndefMaskElem)
7616             InsertMask[Offset + I] = NumElts + I;
7617         }
7618 
7619         V = Builder.CreateShuffleVector(
7620             FirstInsert->getOperand(0), V, InsertMask,
7621             cast<Instruction>(E->Scalars.back())->getName());
7622         if (auto *I = dyn_cast<Instruction>(V)) {
7623           GatherShuffleSeq.insert(I);
7624           CSEBlocks.insert(I->getParent());
7625         }
7626       }
7627 
7628       ++NumVectorInstructions;
7629       E->VectorizedValue = V;
7630       return V;
7631     }
7632     case Instruction::ZExt:
7633     case Instruction::SExt:
7634     case Instruction::FPToUI:
7635     case Instruction::FPToSI:
7636     case Instruction::FPExt:
7637     case Instruction::PtrToInt:
7638     case Instruction::IntToPtr:
7639     case Instruction::SIToFP:
7640     case Instruction::UIToFP:
7641     case Instruction::Trunc:
7642     case Instruction::FPTrunc:
7643     case Instruction::BitCast: {
7644       setInsertPointAfterBundle(E);
7645 
7646       Value *InVec = vectorizeTree(E->getOperand(0));
7647 
7648       if (E->VectorizedValue) {
7649         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7650         return E->VectorizedValue;
7651       }
7652 
7653       auto *CI = cast<CastInst>(VL0);
7654       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
7655       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7656       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7657       V = ShuffleBuilder.finalize(V);
7658 
7659       E->VectorizedValue = V;
7660       ++NumVectorInstructions;
7661       return V;
7662     }
7663     case Instruction::FCmp:
7664     case Instruction::ICmp: {
7665       setInsertPointAfterBundle(E);
7666 
7667       Value *L = vectorizeTree(E->getOperand(0));
7668       Value *R = vectorizeTree(E->getOperand(1));
7669 
7670       if (E->VectorizedValue) {
7671         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7672         return E->VectorizedValue;
7673       }
7674 
7675       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
7676       Value *V = Builder.CreateCmp(P0, L, R);
7677       propagateIRFlags(V, E->Scalars, VL0);
7678       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7679       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7680       V = ShuffleBuilder.finalize(V);
7681 
7682       E->VectorizedValue = V;
7683       ++NumVectorInstructions;
7684       return V;
7685     }
7686     case Instruction::Select: {
7687       setInsertPointAfterBundle(E);
7688 
7689       Value *Cond = vectorizeTree(E->getOperand(0));
7690       Value *True = vectorizeTree(E->getOperand(1));
7691       Value *False = vectorizeTree(E->getOperand(2));
7692 
7693       if (E->VectorizedValue) {
7694         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7695         return E->VectorizedValue;
7696       }
7697 
7698       Value *V = Builder.CreateSelect(Cond, True, False);
7699       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7700       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7701       V = ShuffleBuilder.finalize(V);
7702 
7703       E->VectorizedValue = V;
7704       ++NumVectorInstructions;
7705       return V;
7706     }
7707     case Instruction::FNeg: {
7708       setInsertPointAfterBundle(E);
7709 
7710       Value *Op = vectorizeTree(E->getOperand(0));
7711 
7712       if (E->VectorizedValue) {
7713         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7714         return E->VectorizedValue;
7715       }
7716 
7717       Value *V = Builder.CreateUnOp(
7718           static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
7719       propagateIRFlags(V, E->Scalars, VL0);
7720       if (auto *I = dyn_cast<Instruction>(V))
7721         V = propagateMetadata(I, E->Scalars);
7722 
7723       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7724       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7725       V = ShuffleBuilder.finalize(V);
7726 
7727       E->VectorizedValue = V;
7728       ++NumVectorInstructions;
7729 
7730       return V;
7731     }
7732     case Instruction::Add:
7733     case Instruction::FAdd:
7734     case Instruction::Sub:
7735     case Instruction::FSub:
7736     case Instruction::Mul:
7737     case Instruction::FMul:
7738     case Instruction::UDiv:
7739     case Instruction::SDiv:
7740     case Instruction::FDiv:
7741     case Instruction::URem:
7742     case Instruction::SRem:
7743     case Instruction::FRem:
7744     case Instruction::Shl:
7745     case Instruction::LShr:
7746     case Instruction::AShr:
7747     case Instruction::And:
7748     case Instruction::Or:
7749     case Instruction::Xor: {
7750       setInsertPointAfterBundle(E);
7751 
7752       Value *LHS = vectorizeTree(E->getOperand(0));
7753       Value *RHS = vectorizeTree(E->getOperand(1));
7754 
7755       if (E->VectorizedValue) {
7756         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7757         return E->VectorizedValue;
7758       }
7759 
7760       Value *V = Builder.CreateBinOp(
7761           static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
7762           RHS);
7763       propagateIRFlags(V, E->Scalars, VL0);
7764       if (auto *I = dyn_cast<Instruction>(V))
7765         V = propagateMetadata(I, E->Scalars);
7766 
7767       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7768       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7769       V = ShuffleBuilder.finalize(V);
7770 
7771       E->VectorizedValue = V;
7772       ++NumVectorInstructions;
7773 
7774       return V;
7775     }
7776     case Instruction::Load: {
7777       // Loads are inserted at the head of the tree because we don't want to
7778       // sink them all the way down past store instructions.
7779       setInsertPointAfterBundle(E);
7780 
7781       LoadInst *LI = cast<LoadInst>(VL0);
7782       Instruction *NewLI;
7783       unsigned AS = LI->getPointerAddressSpace();
7784       Value *PO = LI->getPointerOperand();
7785       if (E->State == TreeEntry::Vectorize) {
7786         Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS));
7787         NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
7788 
7789         // The pointer operand uses an in-tree scalar so we add the new BitCast
7790         // or LoadInst to ExternalUses list to make sure that an extract will
7791         // be generated in the future.
7792         if (TreeEntry *Entry = getTreeEntry(PO)) {
7793           // Find which lane we need to extract.
7794           unsigned FoundLane = Entry->findLaneForValue(PO);
7795           ExternalUses.emplace_back(
7796               PO, PO != VecPtr ? cast<User>(VecPtr) : NewLI, FoundLane);
7797         }
7798       } else {
7799         assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state");
7800         Value *VecPtr = vectorizeTree(E->getOperand(0));
7801         // Use the minimum alignment of the gathered loads.
7802         Align CommonAlignment = LI->getAlign();
7803         for (Value *V : E->Scalars)
7804           CommonAlignment =
7805               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
7806         NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment);
7807       }
7808       Value *V = propagateMetadata(NewLI, E->Scalars);
7809 
7810       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7811       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7812       V = ShuffleBuilder.finalize(V);
7813       E->VectorizedValue = V;
7814       ++NumVectorInstructions;
7815       return V;
7816     }
7817     case Instruction::Store: {
7818       auto *SI = cast<StoreInst>(VL0);
7819       unsigned AS = SI->getPointerAddressSpace();
7820 
7821       setInsertPointAfterBundle(E);
7822 
7823       Value *VecValue = vectorizeTree(E->getOperand(0));
7824       ShuffleBuilder.addMask(E->ReorderIndices);
7825       VecValue = ShuffleBuilder.finalize(VecValue);
7826 
7827       Value *ScalarPtr = SI->getPointerOperand();
7828       Value *VecPtr = Builder.CreateBitCast(
7829           ScalarPtr, VecValue->getType()->getPointerTo(AS));
7830       StoreInst *ST =
7831           Builder.CreateAlignedStore(VecValue, VecPtr, SI->getAlign());
7832 
7833       // The pointer operand uses an in-tree scalar, so add the new BitCast or
7834       // StoreInst to ExternalUses to make sure that an extract will be
7835       // generated in the future.
7836       if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) {
7837         // Find which lane we need to extract.
7838         unsigned FoundLane = Entry->findLaneForValue(ScalarPtr);
7839         ExternalUses.push_back(ExternalUser(
7840             ScalarPtr, ScalarPtr != VecPtr ? cast<User>(VecPtr) : ST,
7841             FoundLane));
7842       }
7843 
7844       Value *V = propagateMetadata(ST, E->Scalars);
7845 
7846       E->VectorizedValue = V;
7847       ++NumVectorInstructions;
7848       return V;
7849     }
7850     case Instruction::GetElementPtr: {
7851       auto *GEP0 = cast<GetElementPtrInst>(VL0);
7852       setInsertPointAfterBundle(E);
7853 
7854       Value *Op0 = vectorizeTree(E->getOperand(0));
7855 
7856       SmallVector<Value *> OpVecs;
7857       for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) {
7858         Value *OpVec = vectorizeTree(E->getOperand(J));
7859         OpVecs.push_back(OpVec);
7860       }
7861 
7862       Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs);
7863       if (Instruction *I = dyn_cast<Instruction>(V))
7864         V = propagateMetadata(I, E->Scalars);
7865 
7866       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7867       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7868       V = ShuffleBuilder.finalize(V);
7869 
7870       E->VectorizedValue = V;
7871       ++NumVectorInstructions;
7872 
7873       return V;
7874     }
7875     case Instruction::Call: {
7876       CallInst *CI = cast<CallInst>(VL0);
7877       setInsertPointAfterBundle(E);
7878 
7879       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
7880       if (Function *FI = CI->getCalledFunction())
7881         IID = FI->getIntrinsicID();
7882 
7883       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
7884 
7885       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
7886       bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
7887                           VecCallCosts.first <= VecCallCosts.second;
7888 
7889       Value *ScalarArg = nullptr;
7890       std::vector<Value *> OpVecs;
7891       SmallVector<Type *, 2> TysForDecl =
7892           {FixedVectorType::get(CI->getType(), E->Scalars.size())};
7893       for (int j = 0, e = CI->arg_size(); j < e; ++j) {
7894         ValueList OpVL;
7895         // Some intrinsics have scalar arguments. This argument should not be
7896         // vectorized.
7897         if (UseIntrinsic && isVectorIntrinsicWithScalarOpAtArg(IID, j)) {
7898           CallInst *CEI = cast<CallInst>(VL0);
7899           ScalarArg = CEI->getArgOperand(j);
7900           OpVecs.push_back(CEI->getArgOperand(j));
7901           if (isVectorIntrinsicWithOverloadTypeAtArg(IID, j))
7902             TysForDecl.push_back(ScalarArg->getType());
7903           continue;
7904         }
7905 
7906         Value *OpVec = vectorizeTree(E->getOperand(j));
7907         LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
7908         OpVecs.push_back(OpVec);
7909         if (isVectorIntrinsicWithOverloadTypeAtArg(IID, j))
7910           TysForDecl.push_back(OpVec->getType());
7911       }
7912 
7913       Function *CF;
7914       if (!UseIntrinsic) {
7915         VFShape Shape =
7916             VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
7917                                   VecTy->getNumElements())),
7918                          false /*HasGlobalPred*/);
7919         CF = VFDatabase(*CI).getVectorizedFunction(Shape);
7920       } else {
7921         CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl);
7922       }
7923 
7924       SmallVector<OperandBundleDef, 1> OpBundles;
7925       CI->getOperandBundlesAsDefs(OpBundles);
7926       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
7927 
7928       // The scalar argument uses an in-tree scalar so we add the new vectorized
7929       // call to ExternalUses list to make sure that an extract will be
7930       // generated in the future.
7931       if (ScalarArg) {
7932         if (TreeEntry *Entry = getTreeEntry(ScalarArg)) {
7933           // Find which lane we need to extract.
7934           unsigned FoundLane = Entry->findLaneForValue(ScalarArg);
7935           ExternalUses.push_back(
7936               ExternalUser(ScalarArg, cast<User>(V), FoundLane));
7937         }
7938       }
7939 
7940       propagateIRFlags(V, E->Scalars, VL0);
7941       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7942       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7943       V = ShuffleBuilder.finalize(V);
7944 
7945       E->VectorizedValue = V;
7946       ++NumVectorInstructions;
7947       return V;
7948     }
7949     case Instruction::ShuffleVector: {
7950       assert(E->isAltShuffle() &&
7951              ((Instruction::isBinaryOp(E->getOpcode()) &&
7952                Instruction::isBinaryOp(E->getAltOpcode())) ||
7953               (Instruction::isCast(E->getOpcode()) &&
7954                Instruction::isCast(E->getAltOpcode())) ||
7955               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
7956              "Invalid Shuffle Vector Operand");
7957 
7958       Value *LHS = nullptr, *RHS = nullptr;
7959       if (Instruction::isBinaryOp(E->getOpcode()) || isa<CmpInst>(VL0)) {
7960         setInsertPointAfterBundle(E);
7961         LHS = vectorizeTree(E->getOperand(0));
7962         RHS = vectorizeTree(E->getOperand(1));
7963       } else {
7964         setInsertPointAfterBundle(E);
7965         LHS = vectorizeTree(E->getOperand(0));
7966       }
7967 
7968       if (E->VectorizedValue) {
7969         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7970         return E->VectorizedValue;
7971       }
7972 
7973       Value *V0, *V1;
7974       if (Instruction::isBinaryOp(E->getOpcode())) {
7975         V0 = Builder.CreateBinOp(
7976             static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
7977         V1 = Builder.CreateBinOp(
7978             static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
7979       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
7980         V0 = Builder.CreateCmp(CI0->getPredicate(), LHS, RHS);
7981         auto *AltCI = cast<CmpInst>(E->getAltOp());
7982         CmpInst::Predicate AltPred = AltCI->getPredicate();
7983         V1 = Builder.CreateCmp(AltPred, LHS, RHS);
7984       } else {
7985         V0 = Builder.CreateCast(
7986             static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
7987         V1 = Builder.CreateCast(
7988             static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
7989       }
7990       // Add V0 and V1 to later analysis to try to find and remove matching
7991       // instruction, if any.
7992       for (Value *V : {V0, V1}) {
7993         if (auto *I = dyn_cast<Instruction>(V)) {
7994           GatherShuffleSeq.insert(I);
7995           CSEBlocks.insert(I->getParent());
7996         }
7997       }
7998 
7999       // Create shuffle to take alternate operations from the vector.
8000       // Also, gather up main and alt scalar ops to propagate IR flags to
8001       // each vector operation.
8002       ValueList OpScalars, AltScalars;
8003       SmallVector<int> Mask;
8004       buildShuffleEntryMask(
8005           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
8006           [E](Instruction *I) {
8007             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
8008             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
8009           },
8010           Mask, &OpScalars, &AltScalars);
8011 
8012       propagateIRFlags(V0, OpScalars);
8013       propagateIRFlags(V1, AltScalars);
8014 
8015       Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
8016       if (auto *I = dyn_cast<Instruction>(V)) {
8017         V = propagateMetadata(I, E->Scalars);
8018         GatherShuffleSeq.insert(I);
8019         CSEBlocks.insert(I->getParent());
8020       }
8021       V = ShuffleBuilder.finalize(V);
8022 
8023       E->VectorizedValue = V;
8024       ++NumVectorInstructions;
8025 
8026       return V;
8027     }
8028     default:
8029     llvm_unreachable("unknown inst");
8030   }
8031   return nullptr;
8032 }
8033 
8034 Value *BoUpSLP::vectorizeTree() {
8035   ExtraValueToDebugLocsMap ExternallyUsedValues;
8036   return vectorizeTree(ExternallyUsedValues);
8037 }
8038 
8039 Value *
8040 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
8041   // All blocks must be scheduled before any instructions are inserted.
8042   for (auto &BSIter : BlocksSchedules) {
8043     scheduleBlock(BSIter.second.get());
8044   }
8045 
8046   Builder.SetInsertPoint(&F->getEntryBlock().front());
8047   auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
8048 
8049   // If the vectorized tree can be rewritten in a smaller type, we truncate the
8050   // vectorized root. InstCombine will then rewrite the entire expression. We
8051   // sign extend the extracted values below.
8052   auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
8053   if (MinBWs.count(ScalarRoot)) {
8054     if (auto *I = dyn_cast<Instruction>(VectorRoot)) {
8055       // If current instr is a phi and not the last phi, insert it after the
8056       // last phi node.
8057       if (isa<PHINode>(I))
8058         Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt());
8059       else
8060         Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
8061     }
8062     auto BundleWidth = VectorizableTree[0]->Scalars.size();
8063     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
8064     auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
8065     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
8066     VectorizableTree[0]->VectorizedValue = Trunc;
8067   }
8068 
8069   LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
8070                     << " values .\n");
8071 
8072   // Extract all of the elements with the external uses.
8073   for (const auto &ExternalUse : ExternalUses) {
8074     Value *Scalar = ExternalUse.Scalar;
8075     llvm::User *User = ExternalUse.User;
8076 
8077     // Skip users that we already RAUW. This happens when one instruction
8078     // has multiple uses of the same value.
8079     if (User && !is_contained(Scalar->users(), User))
8080       continue;
8081     TreeEntry *E = getTreeEntry(Scalar);
8082     assert(E && "Invalid scalar");
8083     assert(E->State != TreeEntry::NeedToGather &&
8084            "Extracting from a gather list");
8085 
8086     Value *Vec = E->VectorizedValue;
8087     assert(Vec && "Can't find vectorizable value");
8088 
8089     Value *Lane = Builder.getInt32(ExternalUse.Lane);
8090     auto ExtractAndExtendIfNeeded = [&](Value *Vec) {
8091       if (Scalar->getType() != Vec->getType()) {
8092         Value *Ex;
8093         // "Reuse" the existing extract to improve final codegen.
8094         if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) {
8095           Ex = Builder.CreateExtractElement(ES->getOperand(0),
8096                                             ES->getOperand(1));
8097         } else {
8098           Ex = Builder.CreateExtractElement(Vec, Lane);
8099         }
8100         // If necessary, sign-extend or zero-extend ScalarRoot
8101         // to the larger type.
8102         if (!MinBWs.count(ScalarRoot))
8103           return Ex;
8104         if (MinBWs[ScalarRoot].second)
8105           return Builder.CreateSExt(Ex, Scalar->getType());
8106         return Builder.CreateZExt(Ex, Scalar->getType());
8107       }
8108       assert(isa<FixedVectorType>(Scalar->getType()) &&
8109              isa<InsertElementInst>(Scalar) &&
8110              "In-tree scalar of vector type is not insertelement?");
8111       return Vec;
8112     };
8113     // If User == nullptr, the Scalar is used as extra arg. Generate
8114     // ExtractElement instruction and update the record for this scalar in
8115     // ExternallyUsedValues.
8116     if (!User) {
8117       assert(ExternallyUsedValues.count(Scalar) &&
8118              "Scalar with nullptr as an external user must be registered in "
8119              "ExternallyUsedValues map");
8120       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
8121         Builder.SetInsertPoint(VecI->getParent(),
8122                                std::next(VecI->getIterator()));
8123       } else {
8124         Builder.SetInsertPoint(&F->getEntryBlock().front());
8125       }
8126       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
8127       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
8128       auto &NewInstLocs = ExternallyUsedValues[NewInst];
8129       auto It = ExternallyUsedValues.find(Scalar);
8130       assert(It != ExternallyUsedValues.end() &&
8131              "Externally used scalar is not found in ExternallyUsedValues");
8132       NewInstLocs.append(It->second);
8133       ExternallyUsedValues.erase(Scalar);
8134       // Required to update internally referenced instructions.
8135       Scalar->replaceAllUsesWith(NewInst);
8136       continue;
8137     }
8138 
8139     // Generate extracts for out-of-tree users.
8140     // Find the insertion point for the extractelement lane.
8141     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
8142       if (PHINode *PH = dyn_cast<PHINode>(User)) {
8143         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
8144           if (PH->getIncomingValue(i) == Scalar) {
8145             Instruction *IncomingTerminator =
8146                 PH->getIncomingBlock(i)->getTerminator();
8147             if (isa<CatchSwitchInst>(IncomingTerminator)) {
8148               Builder.SetInsertPoint(VecI->getParent(),
8149                                      std::next(VecI->getIterator()));
8150             } else {
8151               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
8152             }
8153             Value *NewInst = ExtractAndExtendIfNeeded(Vec);
8154             CSEBlocks.insert(PH->getIncomingBlock(i));
8155             PH->setOperand(i, NewInst);
8156           }
8157         }
8158       } else {
8159         Builder.SetInsertPoint(cast<Instruction>(User));
8160         Value *NewInst = ExtractAndExtendIfNeeded(Vec);
8161         CSEBlocks.insert(cast<Instruction>(User)->getParent());
8162         User->replaceUsesOfWith(Scalar, NewInst);
8163       }
8164     } else {
8165       Builder.SetInsertPoint(&F->getEntryBlock().front());
8166       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
8167       CSEBlocks.insert(&F->getEntryBlock());
8168       User->replaceUsesOfWith(Scalar, NewInst);
8169     }
8170 
8171     LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
8172   }
8173 
8174   // For each vectorized value:
8175   for (auto &TEPtr : VectorizableTree) {
8176     TreeEntry *Entry = TEPtr.get();
8177 
8178     // No need to handle users of gathered values.
8179     if (Entry->State == TreeEntry::NeedToGather)
8180       continue;
8181 
8182     assert(Entry->VectorizedValue && "Can't find vectorizable value");
8183 
8184     // For each lane:
8185     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
8186       Value *Scalar = Entry->Scalars[Lane];
8187 
8188 #ifndef NDEBUG
8189       Type *Ty = Scalar->getType();
8190       if (!Ty->isVoidTy()) {
8191         for (User *U : Scalar->users()) {
8192           LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
8193 
8194           // It is legal to delete users in the ignorelist.
8195           assert((getTreeEntry(U) || is_contained(UserIgnoreList, U) ||
8196                   (isa_and_nonnull<Instruction>(U) &&
8197                    isDeleted(cast<Instruction>(U)))) &&
8198                  "Deleting out-of-tree value");
8199         }
8200       }
8201 #endif
8202       LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
8203       eraseInstruction(cast<Instruction>(Scalar));
8204     }
8205   }
8206 
8207   Builder.ClearInsertionPoint();
8208   InstrElementSize.clear();
8209 
8210   return VectorizableTree[0]->VectorizedValue;
8211 }
8212 
8213 void BoUpSLP::optimizeGatherSequence() {
8214   LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleSeq.size()
8215                     << " gather sequences instructions.\n");
8216   // LICM InsertElementInst sequences.
8217   for (Instruction *I : GatherShuffleSeq) {
8218     if (isDeleted(I))
8219       continue;
8220 
8221     // Check if this block is inside a loop.
8222     Loop *L = LI->getLoopFor(I->getParent());
8223     if (!L)
8224       continue;
8225 
8226     // Check if it has a preheader.
8227     BasicBlock *PreHeader = L->getLoopPreheader();
8228     if (!PreHeader)
8229       continue;
8230 
8231     // If the vector or the element that we insert into it are
8232     // instructions that are defined in this basic block then we can't
8233     // hoist this instruction.
8234     if (any_of(I->operands(), [L](Value *V) {
8235           auto *OpI = dyn_cast<Instruction>(V);
8236           return OpI && L->contains(OpI);
8237         }))
8238       continue;
8239 
8240     // We can hoist this instruction. Move it to the pre-header.
8241     I->moveBefore(PreHeader->getTerminator());
8242   }
8243 
8244   // Make a list of all reachable blocks in our CSE queue.
8245   SmallVector<const DomTreeNode *, 8> CSEWorkList;
8246   CSEWorkList.reserve(CSEBlocks.size());
8247   for (BasicBlock *BB : CSEBlocks)
8248     if (DomTreeNode *N = DT->getNode(BB)) {
8249       assert(DT->isReachableFromEntry(N));
8250       CSEWorkList.push_back(N);
8251     }
8252 
8253   // Sort blocks by domination. This ensures we visit a block after all blocks
8254   // dominating it are visited.
8255   llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) {
8256     assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) &&
8257            "Different nodes should have different DFS numbers");
8258     return A->getDFSNumIn() < B->getDFSNumIn();
8259   });
8260 
8261   // Less defined shuffles can be replaced by the more defined copies.
8262   // Between two shuffles one is less defined if it has the same vector operands
8263   // and its mask indeces are the same as in the first one or undefs. E.g.
8264   // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0,
8265   // poison, <0, 0, 0, 0>.
8266   auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2,
8267                                            SmallVectorImpl<int> &NewMask) {
8268     if (I1->getType() != I2->getType())
8269       return false;
8270     auto *SI1 = dyn_cast<ShuffleVectorInst>(I1);
8271     auto *SI2 = dyn_cast<ShuffleVectorInst>(I2);
8272     if (!SI1 || !SI2)
8273       return I1->isIdenticalTo(I2);
8274     if (SI1->isIdenticalTo(SI2))
8275       return true;
8276     for (int I = 0, E = SI1->getNumOperands(); I < E; ++I)
8277       if (SI1->getOperand(I) != SI2->getOperand(I))
8278         return false;
8279     // Check if the second instruction is more defined than the first one.
8280     NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end());
8281     ArrayRef<int> SM1 = SI1->getShuffleMask();
8282     // Count trailing undefs in the mask to check the final number of used
8283     // registers.
8284     unsigned LastUndefsCnt = 0;
8285     for (int I = 0, E = NewMask.size(); I < E; ++I) {
8286       if (SM1[I] == UndefMaskElem)
8287         ++LastUndefsCnt;
8288       else
8289         LastUndefsCnt = 0;
8290       if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem &&
8291           NewMask[I] != SM1[I])
8292         return false;
8293       if (NewMask[I] == UndefMaskElem)
8294         NewMask[I] = SM1[I];
8295     }
8296     // Check if the last undefs actually change the final number of used vector
8297     // registers.
8298     return SM1.size() - LastUndefsCnt > 1 &&
8299            TTI->getNumberOfParts(SI1->getType()) ==
8300                TTI->getNumberOfParts(
8301                    FixedVectorType::get(SI1->getType()->getElementType(),
8302                                         SM1.size() - LastUndefsCnt));
8303   };
8304   // Perform O(N^2) search over the gather/shuffle sequences and merge identical
8305   // instructions. TODO: We can further optimize this scan if we split the
8306   // instructions into different buckets based on the insert lane.
8307   SmallVector<Instruction *, 16> Visited;
8308   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
8309     assert(*I &&
8310            (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
8311            "Worklist not sorted properly!");
8312     BasicBlock *BB = (*I)->getBlock();
8313     // For all instructions in blocks containing gather sequences:
8314     for (Instruction &In : llvm::make_early_inc_range(*BB)) {
8315       if (isDeleted(&In))
8316         continue;
8317       if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) &&
8318           !isa<ShuffleVectorInst>(&In) && !GatherShuffleSeq.contains(&In))
8319         continue;
8320 
8321       // Check if we can replace this instruction with any of the
8322       // visited instructions.
8323       bool Replaced = false;
8324       for (Instruction *&V : Visited) {
8325         SmallVector<int> NewMask;
8326         if (IsIdenticalOrLessDefined(&In, V, NewMask) &&
8327             DT->dominates(V->getParent(), In.getParent())) {
8328           In.replaceAllUsesWith(V);
8329           eraseInstruction(&In);
8330           if (auto *SI = dyn_cast<ShuffleVectorInst>(V))
8331             if (!NewMask.empty())
8332               SI->setShuffleMask(NewMask);
8333           Replaced = true;
8334           break;
8335         }
8336         if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) &&
8337             GatherShuffleSeq.contains(V) &&
8338             IsIdenticalOrLessDefined(V, &In, NewMask) &&
8339             DT->dominates(In.getParent(), V->getParent())) {
8340           In.moveAfter(V);
8341           V->replaceAllUsesWith(&In);
8342           eraseInstruction(V);
8343           if (auto *SI = dyn_cast<ShuffleVectorInst>(&In))
8344             if (!NewMask.empty())
8345               SI->setShuffleMask(NewMask);
8346           V = &In;
8347           Replaced = true;
8348           break;
8349         }
8350       }
8351       if (!Replaced) {
8352         assert(!is_contained(Visited, &In));
8353         Visited.push_back(&In);
8354       }
8355     }
8356   }
8357   CSEBlocks.clear();
8358   GatherShuffleSeq.clear();
8359 }
8360 
8361 BoUpSLP::ScheduleData *
8362 BoUpSLP::BlockScheduling::buildBundle(ArrayRef<Value *> VL) {
8363   ScheduleData *Bundle = nullptr;
8364   ScheduleData *PrevInBundle = nullptr;
8365   for (Value *V : VL) {
8366     if (doesNotNeedToBeScheduled(V))
8367       continue;
8368     ScheduleData *BundleMember = getScheduleData(V);
8369     assert(BundleMember &&
8370            "no ScheduleData for bundle member "
8371            "(maybe not in same basic block)");
8372     assert(BundleMember->isSchedulingEntity() &&
8373            "bundle member already part of other bundle");
8374     if (PrevInBundle) {
8375       PrevInBundle->NextInBundle = BundleMember;
8376     } else {
8377       Bundle = BundleMember;
8378     }
8379 
8380     // Group the instructions to a bundle.
8381     BundleMember->FirstInBundle = Bundle;
8382     PrevInBundle = BundleMember;
8383   }
8384   assert(Bundle && "Failed to find schedule bundle");
8385   return Bundle;
8386 }
8387 
8388 // Groups the instructions to a bundle (which is then a single scheduling entity)
8389 // and schedules instructions until the bundle gets ready.
8390 Optional<BoUpSLP::ScheduleData *>
8391 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
8392                                             const InstructionsState &S) {
8393   // No need to schedule PHIs, insertelement, extractelement and extractvalue
8394   // instructions.
8395   if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue) ||
8396       doesNotNeedToSchedule(VL))
8397     return nullptr;
8398 
8399   // Initialize the instruction bundle.
8400   Instruction *OldScheduleEnd = ScheduleEnd;
8401   LLVM_DEBUG(dbgs() << "SLP:  bundle: " << *S.OpValue << "\n");
8402 
8403   auto TryScheduleBundleImpl = [this, OldScheduleEnd, SLP](bool ReSchedule,
8404                                                          ScheduleData *Bundle) {
8405     // The scheduling region got new instructions at the lower end (or it is a
8406     // new region for the first bundle). This makes it necessary to
8407     // recalculate all dependencies.
8408     // It is seldom that this needs to be done a second time after adding the
8409     // initial bundle to the region.
8410     if (ScheduleEnd != OldScheduleEnd) {
8411       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode())
8412         doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); });
8413       ReSchedule = true;
8414     }
8415     if (Bundle) {
8416       LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle
8417                         << " in block " << BB->getName() << "\n");
8418       calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP);
8419     }
8420 
8421     if (ReSchedule) {
8422       resetSchedule();
8423       initialFillReadyList(ReadyInsts);
8424     }
8425 
8426     // Now try to schedule the new bundle or (if no bundle) just calculate
8427     // dependencies. As soon as the bundle is "ready" it means that there are no
8428     // cyclic dependencies and we can schedule it. Note that's important that we
8429     // don't "schedule" the bundle yet (see cancelScheduling).
8430     while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) &&
8431            !ReadyInsts.empty()) {
8432       ScheduleData *Picked = ReadyInsts.pop_back_val();
8433       assert(Picked->isSchedulingEntity() && Picked->isReady() &&
8434              "must be ready to schedule");
8435       schedule(Picked, ReadyInsts);
8436     }
8437   };
8438 
8439   // Make sure that the scheduling region contains all
8440   // instructions of the bundle.
8441   for (Value *V : VL) {
8442     if (doesNotNeedToBeScheduled(V))
8443       continue;
8444     if (!extendSchedulingRegion(V, S)) {
8445       // If the scheduling region got new instructions at the lower end (or it
8446       // is a new region for the first bundle). This makes it necessary to
8447       // recalculate all dependencies.
8448       // Otherwise the compiler may crash trying to incorrectly calculate
8449       // dependencies and emit instruction in the wrong order at the actual
8450       // scheduling.
8451       TryScheduleBundleImpl(/*ReSchedule=*/false, nullptr);
8452       return None;
8453     }
8454   }
8455 
8456   bool ReSchedule = false;
8457   for (Value *V : VL) {
8458     if (doesNotNeedToBeScheduled(V))
8459       continue;
8460     ScheduleData *BundleMember = getScheduleData(V);
8461     assert(BundleMember &&
8462            "no ScheduleData for bundle member (maybe not in same basic block)");
8463 
8464     // Make sure we don't leave the pieces of the bundle in the ready list when
8465     // whole bundle might not be ready.
8466     ReadyInsts.remove(BundleMember);
8467 
8468     if (!BundleMember->IsScheduled)
8469       continue;
8470     // A bundle member was scheduled as single instruction before and now
8471     // needs to be scheduled as part of the bundle. We just get rid of the
8472     // existing schedule.
8473     LLVM_DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
8474                       << " was already scheduled\n");
8475     ReSchedule = true;
8476   }
8477 
8478   auto *Bundle = buildBundle(VL);
8479   TryScheduleBundleImpl(ReSchedule, Bundle);
8480   if (!Bundle->isReady()) {
8481     cancelScheduling(VL, S.OpValue);
8482     return None;
8483   }
8484   return Bundle;
8485 }
8486 
8487 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
8488                                                 Value *OpValue) {
8489   if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue) ||
8490       doesNotNeedToSchedule(VL))
8491     return;
8492 
8493   if (doesNotNeedToBeScheduled(OpValue))
8494     OpValue = *find_if_not(VL, doesNotNeedToBeScheduled);
8495   ScheduleData *Bundle = getScheduleData(OpValue);
8496   LLVM_DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
8497   assert(!Bundle->IsScheduled &&
8498          "Can't cancel bundle which is already scheduled");
8499   assert(Bundle->isSchedulingEntity() &&
8500          (Bundle->isPartOfBundle() || needToScheduleSingleInstruction(VL)) &&
8501          "tried to unbundle something which is not a bundle");
8502 
8503   // Remove the bundle from the ready list.
8504   if (Bundle->isReady())
8505     ReadyInsts.remove(Bundle);
8506 
8507   // Un-bundle: make single instructions out of the bundle.
8508   ScheduleData *BundleMember = Bundle;
8509   while (BundleMember) {
8510     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
8511     BundleMember->FirstInBundle = BundleMember;
8512     ScheduleData *Next = BundleMember->NextInBundle;
8513     BundleMember->NextInBundle = nullptr;
8514     BundleMember->TE = nullptr;
8515     if (BundleMember->unscheduledDepsInBundle() == 0) {
8516       ReadyInsts.insert(BundleMember);
8517     }
8518     BundleMember = Next;
8519   }
8520 }
8521 
8522 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
8523   // Allocate a new ScheduleData for the instruction.
8524   if (ChunkPos >= ChunkSize) {
8525     ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
8526     ChunkPos = 0;
8527   }
8528   return &(ScheduleDataChunks.back()[ChunkPos++]);
8529 }
8530 
8531 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
8532                                                       const InstructionsState &S) {
8533   if (getScheduleData(V, isOneOf(S, V)))
8534     return true;
8535   Instruction *I = dyn_cast<Instruction>(V);
8536   assert(I && "bundle member must be an instruction");
8537   assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) &&
8538          !doesNotNeedToBeScheduled(I) &&
8539          "phi nodes/insertelements/extractelements/extractvalues don't need to "
8540          "be scheduled");
8541   auto &&CheckScheduleForI = [this, &S](Instruction *I) -> bool {
8542     ScheduleData *ISD = getScheduleData(I);
8543     if (!ISD)
8544       return false;
8545     assert(isInSchedulingRegion(ISD) &&
8546            "ScheduleData not in scheduling region");
8547     ScheduleData *SD = allocateScheduleDataChunks();
8548     SD->Inst = I;
8549     SD->init(SchedulingRegionID, S.OpValue);
8550     ExtraScheduleDataMap[I][S.OpValue] = SD;
8551     return true;
8552   };
8553   if (CheckScheduleForI(I))
8554     return true;
8555   if (!ScheduleStart) {
8556     // It's the first instruction in the new region.
8557     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
8558     ScheduleStart = I;
8559     ScheduleEnd = I->getNextNode();
8560     if (isOneOf(S, I) != I)
8561       CheckScheduleForI(I);
8562     assert(ScheduleEnd && "tried to vectorize a terminator?");
8563     LLVM_DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
8564     return true;
8565   }
8566   // Search up and down at the same time, because we don't know if the new
8567   // instruction is above or below the existing scheduling region.
8568   BasicBlock::reverse_iterator UpIter =
8569       ++ScheduleStart->getIterator().getReverse();
8570   BasicBlock::reverse_iterator UpperEnd = BB->rend();
8571   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
8572   BasicBlock::iterator LowerEnd = BB->end();
8573   while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I &&
8574          &*DownIter != I) {
8575     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
8576       LLVM_DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
8577       return false;
8578     }
8579 
8580     ++UpIter;
8581     ++DownIter;
8582   }
8583   if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) {
8584     assert(I->getParent() == ScheduleStart->getParent() &&
8585            "Instruction is in wrong basic block.");
8586     initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
8587     ScheduleStart = I;
8588     if (isOneOf(S, I) != I)
8589       CheckScheduleForI(I);
8590     LLVM_DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I
8591                       << "\n");
8592     return true;
8593   }
8594   assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) &&
8595          "Expected to reach top of the basic block or instruction down the "
8596          "lower end.");
8597   assert(I->getParent() == ScheduleEnd->getParent() &&
8598          "Instruction is in wrong basic block.");
8599   initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
8600                    nullptr);
8601   ScheduleEnd = I->getNextNode();
8602   if (isOneOf(S, I) != I)
8603     CheckScheduleForI(I);
8604   assert(ScheduleEnd && "tried to vectorize a terminator?");
8605   LLVM_DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
8606   return true;
8607 }
8608 
8609 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
8610                                                 Instruction *ToI,
8611                                                 ScheduleData *PrevLoadStore,
8612                                                 ScheduleData *NextLoadStore) {
8613   ScheduleData *CurrentLoadStore = PrevLoadStore;
8614   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
8615     // No need to allocate data for non-schedulable instructions.
8616     if (doesNotNeedToBeScheduled(I))
8617       continue;
8618     ScheduleData *SD = ScheduleDataMap.lookup(I);
8619     if (!SD) {
8620       SD = allocateScheduleDataChunks();
8621       ScheduleDataMap[I] = SD;
8622       SD->Inst = I;
8623     }
8624     assert(!isInSchedulingRegion(SD) &&
8625            "new ScheduleData already in scheduling region");
8626     SD->init(SchedulingRegionID, I);
8627 
8628     if (I->mayReadOrWriteMemory() &&
8629         (!isa<IntrinsicInst>(I) ||
8630          (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect &&
8631           cast<IntrinsicInst>(I)->getIntrinsicID() !=
8632               Intrinsic::pseudoprobe))) {
8633       // Update the linked list of memory accessing instructions.
8634       if (CurrentLoadStore) {
8635         CurrentLoadStore->NextLoadStore = SD;
8636       } else {
8637         FirstLoadStoreInRegion = SD;
8638       }
8639       CurrentLoadStore = SD;
8640     }
8641 
8642     if (match(I, m_Intrinsic<Intrinsic::stacksave>()) ||
8643         match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8644       RegionHasStackSave = true;
8645   }
8646   if (NextLoadStore) {
8647     if (CurrentLoadStore)
8648       CurrentLoadStore->NextLoadStore = NextLoadStore;
8649   } else {
8650     LastLoadStoreInRegion = CurrentLoadStore;
8651   }
8652 }
8653 
8654 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
8655                                                      bool InsertInReadyList,
8656                                                      BoUpSLP *SLP) {
8657   assert(SD->isSchedulingEntity());
8658 
8659   SmallVector<ScheduleData *, 10> WorkList;
8660   WorkList.push_back(SD);
8661 
8662   while (!WorkList.empty()) {
8663     ScheduleData *SD = WorkList.pop_back_val();
8664     for (ScheduleData *BundleMember = SD; BundleMember;
8665          BundleMember = BundleMember->NextInBundle) {
8666       assert(isInSchedulingRegion(BundleMember));
8667       if (BundleMember->hasValidDependencies())
8668         continue;
8669 
8670       LLVM_DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember
8671                  << "\n");
8672       BundleMember->Dependencies = 0;
8673       BundleMember->resetUnscheduledDeps();
8674 
8675       // Handle def-use chain dependencies.
8676       if (BundleMember->OpValue != BundleMember->Inst) {
8677         if (ScheduleData *UseSD = getScheduleData(BundleMember->Inst)) {
8678           BundleMember->Dependencies++;
8679           ScheduleData *DestBundle = UseSD->FirstInBundle;
8680           if (!DestBundle->IsScheduled)
8681             BundleMember->incrementUnscheduledDeps(1);
8682           if (!DestBundle->hasValidDependencies())
8683             WorkList.push_back(DestBundle);
8684         }
8685       } else {
8686         for (User *U : BundleMember->Inst->users()) {
8687           if (ScheduleData *UseSD = getScheduleData(cast<Instruction>(U))) {
8688             BundleMember->Dependencies++;
8689             ScheduleData *DestBundle = UseSD->FirstInBundle;
8690             if (!DestBundle->IsScheduled)
8691               BundleMember->incrementUnscheduledDeps(1);
8692             if (!DestBundle->hasValidDependencies())
8693               WorkList.push_back(DestBundle);
8694           }
8695         }
8696       }
8697 
8698       auto makeControlDependent = [&](Instruction *I) {
8699         auto *DepDest = getScheduleData(I);
8700         assert(DepDest && "must be in schedule window");
8701         DepDest->ControlDependencies.push_back(BundleMember);
8702         BundleMember->Dependencies++;
8703         ScheduleData *DestBundle = DepDest->FirstInBundle;
8704         if (!DestBundle->IsScheduled)
8705           BundleMember->incrementUnscheduledDeps(1);
8706         if (!DestBundle->hasValidDependencies())
8707           WorkList.push_back(DestBundle);
8708       };
8709 
8710       // Any instruction which isn't safe to speculate at the begining of the
8711       // block is control dependend on any early exit or non-willreturn call
8712       // which proceeds it.
8713       if (!isGuaranteedToTransferExecutionToSuccessor(BundleMember->Inst)) {
8714         for (Instruction *I = BundleMember->Inst->getNextNode();
8715              I != ScheduleEnd; I = I->getNextNode()) {
8716           if (isSafeToSpeculativelyExecute(I, &*BB->begin()))
8717             continue;
8718 
8719           // Add the dependency
8720           makeControlDependent(I);
8721 
8722           if (!isGuaranteedToTransferExecutionToSuccessor(I))
8723             // Everything past here must be control dependent on I.
8724             break;
8725         }
8726       }
8727 
8728       if (RegionHasStackSave) {
8729         // If we have an inalloc alloca instruction, it needs to be scheduled
8730         // after any preceeding stacksave.  We also need to prevent any alloca
8731         // from reordering above a preceeding stackrestore.
8732         if (match(BundleMember->Inst, m_Intrinsic<Intrinsic::stacksave>()) ||
8733             match(BundleMember->Inst, m_Intrinsic<Intrinsic::stackrestore>())) {
8734           for (Instruction *I = BundleMember->Inst->getNextNode();
8735                I != ScheduleEnd; I = I->getNextNode()) {
8736             if (match(I, m_Intrinsic<Intrinsic::stacksave>()) ||
8737                 match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8738               // Any allocas past here must be control dependent on I, and I
8739               // must be memory dependend on BundleMember->Inst.
8740               break;
8741 
8742             if (!isa<AllocaInst>(I))
8743               continue;
8744 
8745             // Add the dependency
8746             makeControlDependent(I);
8747           }
8748         }
8749 
8750         // In addition to the cases handle just above, we need to prevent
8751         // allocas from moving below a stacksave.  The stackrestore case
8752         // is currently thought to be conservatism.
8753         if (isa<AllocaInst>(BundleMember->Inst)) {
8754           for (Instruction *I = BundleMember->Inst->getNextNode();
8755                I != ScheduleEnd; I = I->getNextNode()) {
8756             if (!match(I, m_Intrinsic<Intrinsic::stacksave>()) &&
8757                 !match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8758               continue;
8759 
8760             // Add the dependency
8761             makeControlDependent(I);
8762             break;
8763           }
8764         }
8765       }
8766 
8767       // Handle the memory dependencies (if any).
8768       ScheduleData *DepDest = BundleMember->NextLoadStore;
8769       if (!DepDest)
8770         continue;
8771       Instruction *SrcInst = BundleMember->Inst;
8772       assert(SrcInst->mayReadOrWriteMemory() &&
8773              "NextLoadStore list for non memory effecting bundle?");
8774       MemoryLocation SrcLoc = getLocation(SrcInst);
8775       bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
8776       unsigned numAliased = 0;
8777       unsigned DistToSrc = 1;
8778 
8779       for ( ; DepDest; DepDest = DepDest->NextLoadStore) {
8780         assert(isInSchedulingRegion(DepDest));
8781 
8782         // We have two limits to reduce the complexity:
8783         // 1) AliasedCheckLimit: It's a small limit to reduce calls to
8784         //    SLP->isAliased (which is the expensive part in this loop).
8785         // 2) MaxMemDepDistance: It's for very large blocks and it aborts
8786         //    the whole loop (even if the loop is fast, it's quadratic).
8787         //    It's important for the loop break condition (see below) to
8788         //    check this limit even between two read-only instructions.
8789         if (DistToSrc >= MaxMemDepDistance ||
8790             ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
8791              (numAliased >= AliasedCheckLimit ||
8792               SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
8793 
8794           // We increment the counter only if the locations are aliased
8795           // (instead of counting all alias checks). This gives a better
8796           // balance between reduced runtime and accurate dependencies.
8797           numAliased++;
8798 
8799           DepDest->MemoryDependencies.push_back(BundleMember);
8800           BundleMember->Dependencies++;
8801           ScheduleData *DestBundle = DepDest->FirstInBundle;
8802           if (!DestBundle->IsScheduled) {
8803             BundleMember->incrementUnscheduledDeps(1);
8804           }
8805           if (!DestBundle->hasValidDependencies()) {
8806             WorkList.push_back(DestBundle);
8807           }
8808         }
8809 
8810         // Example, explaining the loop break condition: Let's assume our
8811         // starting instruction is i0 and MaxMemDepDistance = 3.
8812         //
8813         //                      +--------v--v--v
8814         //             i0,i1,i2,i3,i4,i5,i6,i7,i8
8815         //             +--------^--^--^
8816         //
8817         // MaxMemDepDistance let us stop alias-checking at i3 and we add
8818         // dependencies from i0 to i3,i4,.. (even if they are not aliased).
8819         // Previously we already added dependencies from i3 to i6,i7,i8
8820         // (because of MaxMemDepDistance). As we added a dependency from
8821         // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
8822         // and we can abort this loop at i6.
8823         if (DistToSrc >= 2 * MaxMemDepDistance)
8824           break;
8825         DistToSrc++;
8826       }
8827     }
8828     if (InsertInReadyList && SD->isReady()) {
8829       ReadyInsts.insert(SD);
8830       LLVM_DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst
8831                         << "\n");
8832     }
8833   }
8834 }
8835 
8836 void BoUpSLP::BlockScheduling::resetSchedule() {
8837   assert(ScheduleStart &&
8838          "tried to reset schedule on block which has not been scheduled");
8839   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
8840     doForAllOpcodes(I, [&](ScheduleData *SD) {
8841       assert(isInSchedulingRegion(SD) &&
8842              "ScheduleData not in scheduling region");
8843       SD->IsScheduled = false;
8844       SD->resetUnscheduledDeps();
8845     });
8846   }
8847   ReadyInsts.clear();
8848 }
8849 
8850 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
8851   if (!BS->ScheduleStart)
8852     return;
8853 
8854   LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
8855 
8856   // A key point - if we got here, pre-scheduling was able to find a valid
8857   // scheduling of the sub-graph of the scheduling window which consists
8858   // of all vector bundles and their transitive users.  As such, we do not
8859   // need to reschedule anything *outside of* that subgraph.
8860 
8861   BS->resetSchedule();
8862 
8863   // For the real scheduling we use a more sophisticated ready-list: it is
8864   // sorted by the original instruction location. This lets the final schedule
8865   // be as  close as possible to the original instruction order.
8866   // WARNING: If changing this order causes a correctness issue, that means
8867   // there is some missing dependence edge in the schedule data graph.
8868   struct ScheduleDataCompare {
8869     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
8870       return SD2->SchedulingPriority < SD1->SchedulingPriority;
8871     }
8872   };
8873   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
8874 
8875   // Ensure that all dependency data is updated (for nodes in the sub-graph)
8876   // and fill the ready-list with initial instructions.
8877   int Idx = 0;
8878   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
8879        I = I->getNextNode()) {
8880     BS->doForAllOpcodes(I, [this, &Idx, BS](ScheduleData *SD) {
8881       TreeEntry *SDTE = getTreeEntry(SD->Inst);
8882       (void)SDTE;
8883       assert((isVectorLikeInstWithConstOps(SD->Inst) ||
8884               SD->isPartOfBundle() ==
8885                   (SDTE && !doesNotNeedToSchedule(SDTE->Scalars))) &&
8886              "scheduler and vectorizer bundle mismatch");
8887       SD->FirstInBundle->SchedulingPriority = Idx++;
8888 
8889       if (SD->isSchedulingEntity() && SD->isPartOfBundle())
8890         BS->calculateDependencies(SD, false, this);
8891     });
8892   }
8893   BS->initialFillReadyList(ReadyInsts);
8894 
8895   Instruction *LastScheduledInst = BS->ScheduleEnd;
8896 
8897   // Do the "real" scheduling.
8898   while (!ReadyInsts.empty()) {
8899     ScheduleData *picked = *ReadyInsts.begin();
8900     ReadyInsts.erase(ReadyInsts.begin());
8901 
8902     // Move the scheduled instruction(s) to their dedicated places, if not
8903     // there yet.
8904     for (ScheduleData *BundleMember = picked; BundleMember;
8905          BundleMember = BundleMember->NextInBundle) {
8906       Instruction *pickedInst = BundleMember->Inst;
8907       if (pickedInst->getNextNode() != LastScheduledInst)
8908         pickedInst->moveBefore(LastScheduledInst);
8909       LastScheduledInst = pickedInst;
8910     }
8911 
8912     BS->schedule(picked, ReadyInsts);
8913   }
8914 
8915   // Check that we didn't break any of our invariants.
8916 #ifdef EXPENSIVE_CHECKS
8917   BS->verify();
8918 #endif
8919 
8920 #if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS)
8921   // Check that all schedulable entities got scheduled
8922   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; I = I->getNextNode()) {
8923     BS->doForAllOpcodes(I, [&](ScheduleData *SD) {
8924       if (SD->isSchedulingEntity() && SD->hasValidDependencies()) {
8925         assert(SD->IsScheduled && "must be scheduled at this point");
8926       }
8927     });
8928   }
8929 #endif
8930 
8931   // Avoid duplicate scheduling of the block.
8932   BS->ScheduleStart = nullptr;
8933 }
8934 
8935 unsigned BoUpSLP::getVectorElementSize(Value *V) {
8936   // If V is a store, just return the width of the stored value (or value
8937   // truncated just before storing) without traversing the expression tree.
8938   // This is the common case.
8939   if (auto *Store = dyn_cast<StoreInst>(V))
8940     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
8941 
8942   if (auto *IEI = dyn_cast<InsertElementInst>(V))
8943     return getVectorElementSize(IEI->getOperand(1));
8944 
8945   auto E = InstrElementSize.find(V);
8946   if (E != InstrElementSize.end())
8947     return E->second;
8948 
8949   // If V is not a store, we can traverse the expression tree to find loads
8950   // that feed it. The type of the loaded value may indicate a more suitable
8951   // width than V's type. We want to base the vector element size on the width
8952   // of memory operations where possible.
8953   SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist;
8954   SmallPtrSet<Instruction *, 16> Visited;
8955   if (auto *I = dyn_cast<Instruction>(V)) {
8956     Worklist.emplace_back(I, I->getParent());
8957     Visited.insert(I);
8958   }
8959 
8960   // Traverse the expression tree in bottom-up order looking for loads. If we
8961   // encounter an instruction we don't yet handle, we give up.
8962   auto Width = 0u;
8963   while (!Worklist.empty()) {
8964     Instruction *I;
8965     BasicBlock *Parent;
8966     std::tie(I, Parent) = Worklist.pop_back_val();
8967 
8968     // We should only be looking at scalar instructions here. If the current
8969     // instruction has a vector type, skip.
8970     auto *Ty = I->getType();
8971     if (isa<VectorType>(Ty))
8972       continue;
8973 
8974     // If the current instruction is a load, update MaxWidth to reflect the
8975     // width of the loaded value.
8976     if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) ||
8977         isa<ExtractValueInst>(I))
8978       Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty));
8979 
8980     // Otherwise, we need to visit the operands of the instruction. We only
8981     // handle the interesting cases from buildTree here. If an operand is an
8982     // instruction we haven't yet visited and from the same basic block as the
8983     // user or the use is a PHI node, we add it to the worklist.
8984     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
8985              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) ||
8986              isa<UnaryOperator>(I)) {
8987       for (Use &U : I->operands())
8988         if (auto *J = dyn_cast<Instruction>(U.get()))
8989           if (Visited.insert(J).second &&
8990               (isa<PHINode>(I) || J->getParent() == Parent))
8991             Worklist.emplace_back(J, J->getParent());
8992     } else {
8993       break;
8994     }
8995   }
8996 
8997   // If we didn't encounter a memory access in the expression tree, or if we
8998   // gave up for some reason, just return the width of V. Otherwise, return the
8999   // maximum width we found.
9000   if (!Width) {
9001     if (auto *CI = dyn_cast<CmpInst>(V))
9002       V = CI->getOperand(0);
9003     Width = DL->getTypeSizeInBits(V->getType());
9004   }
9005 
9006   for (Instruction *I : Visited)
9007     InstrElementSize[I] = Width;
9008 
9009   return Width;
9010 }
9011 
9012 // Determine if a value V in a vectorizable expression Expr can be demoted to a
9013 // smaller type with a truncation. We collect the values that will be demoted
9014 // in ToDemote and additional roots that require investigating in Roots.
9015 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
9016                                   SmallVectorImpl<Value *> &ToDemote,
9017                                   SmallVectorImpl<Value *> &Roots) {
9018   // We can always demote constants.
9019   if (isa<Constant>(V)) {
9020     ToDemote.push_back(V);
9021     return true;
9022   }
9023 
9024   // If the value is not an instruction in the expression with only one use, it
9025   // cannot be demoted.
9026   auto *I = dyn_cast<Instruction>(V);
9027   if (!I || !I->hasOneUse() || !Expr.count(I))
9028     return false;
9029 
9030   switch (I->getOpcode()) {
9031 
9032   // We can always demote truncations and extensions. Since truncations can
9033   // seed additional demotion, we save the truncated value.
9034   case Instruction::Trunc:
9035     Roots.push_back(I->getOperand(0));
9036     break;
9037   case Instruction::ZExt:
9038   case Instruction::SExt:
9039     if (isa<ExtractElementInst>(I->getOperand(0)) ||
9040         isa<InsertElementInst>(I->getOperand(0)))
9041       return false;
9042     break;
9043 
9044   // We can demote certain binary operations if we can demote both of their
9045   // operands.
9046   case Instruction::Add:
9047   case Instruction::Sub:
9048   case Instruction::Mul:
9049   case Instruction::And:
9050   case Instruction::Or:
9051   case Instruction::Xor:
9052     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
9053         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
9054       return false;
9055     break;
9056 
9057   // We can demote selects if we can demote their true and false values.
9058   case Instruction::Select: {
9059     SelectInst *SI = cast<SelectInst>(I);
9060     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
9061         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
9062       return false;
9063     break;
9064   }
9065 
9066   // We can demote phis if we can demote all their incoming operands. Note that
9067   // we don't need to worry about cycles since we ensure single use above.
9068   case Instruction::PHI: {
9069     PHINode *PN = cast<PHINode>(I);
9070     for (Value *IncValue : PN->incoming_values())
9071       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
9072         return false;
9073     break;
9074   }
9075 
9076   // Otherwise, conservatively give up.
9077   default:
9078     return false;
9079   }
9080 
9081   // Record the value that we can demote.
9082   ToDemote.push_back(V);
9083   return true;
9084 }
9085 
9086 void BoUpSLP::computeMinimumValueSizes() {
9087   // If there are no external uses, the expression tree must be rooted by a
9088   // store. We can't demote in-memory values, so there is nothing to do here.
9089   if (ExternalUses.empty())
9090     return;
9091 
9092   // We only attempt to truncate integer expressions.
9093   auto &TreeRoot = VectorizableTree[0]->Scalars;
9094   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
9095   if (!TreeRootIT)
9096     return;
9097 
9098   // If the expression is not rooted by a store, these roots should have
9099   // external uses. We will rely on InstCombine to rewrite the expression in
9100   // the narrower type. However, InstCombine only rewrites single-use values.
9101   // This means that if a tree entry other than a root is used externally, it
9102   // must have multiple uses and InstCombine will not rewrite it. The code
9103   // below ensures that only the roots are used externally.
9104   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
9105   for (auto &EU : ExternalUses)
9106     if (!Expr.erase(EU.Scalar))
9107       return;
9108   if (!Expr.empty())
9109     return;
9110 
9111   // Collect the scalar values of the vectorizable expression. We will use this
9112   // context to determine which values can be demoted. If we see a truncation,
9113   // we mark it as seeding another demotion.
9114   for (auto &EntryPtr : VectorizableTree)
9115     Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
9116 
9117   // Ensure the roots of the vectorizable tree don't form a cycle. They must
9118   // have a single external user that is not in the vectorizable tree.
9119   for (auto *Root : TreeRoot)
9120     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
9121       return;
9122 
9123   // Conservatively determine if we can actually truncate the roots of the
9124   // expression. Collect the values that can be demoted in ToDemote and
9125   // additional roots that require investigating in Roots.
9126   SmallVector<Value *, 32> ToDemote;
9127   SmallVector<Value *, 4> Roots;
9128   for (auto *Root : TreeRoot)
9129     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
9130       return;
9131 
9132   // The maximum bit width required to represent all the values that can be
9133   // demoted without loss of precision. It would be safe to truncate the roots
9134   // of the expression to this width.
9135   auto MaxBitWidth = 8u;
9136 
9137   // We first check if all the bits of the roots are demanded. If they're not,
9138   // we can truncate the roots to this narrower type.
9139   for (auto *Root : TreeRoot) {
9140     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
9141     MaxBitWidth = std::max<unsigned>(
9142         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
9143   }
9144 
9145   // True if the roots can be zero-extended back to their original type, rather
9146   // than sign-extended. We know that if the leading bits are not demanded, we
9147   // can safely zero-extend. So we initialize IsKnownPositive to True.
9148   bool IsKnownPositive = true;
9149 
9150   // If all the bits of the roots are demanded, we can try a little harder to
9151   // compute a narrower type. This can happen, for example, if the roots are
9152   // getelementptr indices. InstCombine promotes these indices to the pointer
9153   // width. Thus, all their bits are technically demanded even though the
9154   // address computation might be vectorized in a smaller type.
9155   //
9156   // We start by looking at each entry that can be demoted. We compute the
9157   // maximum bit width required to store the scalar by using ValueTracking to
9158   // compute the number of high-order bits we can truncate.
9159   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
9160       llvm::all_of(TreeRoot, [](Value *R) {
9161         assert(R->hasOneUse() && "Root should have only one use!");
9162         return isa<GetElementPtrInst>(R->user_back());
9163       })) {
9164     MaxBitWidth = 8u;
9165 
9166     // Determine if the sign bit of all the roots is known to be zero. If not,
9167     // IsKnownPositive is set to False.
9168     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
9169       KnownBits Known = computeKnownBits(R, *DL);
9170       return Known.isNonNegative();
9171     });
9172 
9173     // Determine the maximum number of bits required to store the scalar
9174     // values.
9175     for (auto *Scalar : ToDemote) {
9176       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
9177       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
9178       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
9179     }
9180 
9181     // If we can't prove that the sign bit is zero, we must add one to the
9182     // maximum bit width to account for the unknown sign bit. This preserves
9183     // the existing sign bit so we can safely sign-extend the root back to the
9184     // original type. Otherwise, if we know the sign bit is zero, we will
9185     // zero-extend the root instead.
9186     //
9187     // FIXME: This is somewhat suboptimal, as there will be cases where adding
9188     //        one to the maximum bit width will yield a larger-than-necessary
9189     //        type. In general, we need to add an extra bit only if we can't
9190     //        prove that the upper bit of the original type is equal to the
9191     //        upper bit of the proposed smaller type. If these two bits are the
9192     //        same (either zero or one) we know that sign-extending from the
9193     //        smaller type will result in the same value. Here, since we can't
9194     //        yet prove this, we are just making the proposed smaller type
9195     //        larger to ensure correctness.
9196     if (!IsKnownPositive)
9197       ++MaxBitWidth;
9198   }
9199 
9200   // Round MaxBitWidth up to the next power-of-two.
9201   if (!isPowerOf2_64(MaxBitWidth))
9202     MaxBitWidth = NextPowerOf2(MaxBitWidth);
9203 
9204   // If the maximum bit width we compute is less than the with of the roots'
9205   // type, we can proceed with the narrowing. Otherwise, do nothing.
9206   if (MaxBitWidth >= TreeRootIT->getBitWidth())
9207     return;
9208 
9209   // If we can truncate the root, we must collect additional values that might
9210   // be demoted as a result. That is, those seeded by truncations we will
9211   // modify.
9212   while (!Roots.empty())
9213     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
9214 
9215   // Finally, map the values we can demote to the maximum bit with we computed.
9216   for (auto *Scalar : ToDemote)
9217     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
9218 }
9219 
9220 namespace {
9221 
9222 /// The SLPVectorizer Pass.
9223 struct SLPVectorizer : public FunctionPass {
9224   SLPVectorizerPass Impl;
9225 
9226   /// Pass identification, replacement for typeid
9227   static char ID;
9228 
9229   explicit SLPVectorizer() : FunctionPass(ID) {
9230     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
9231   }
9232 
9233   bool doInitialization(Module &M) override { return false; }
9234 
9235   bool runOnFunction(Function &F) override {
9236     if (skipFunction(F))
9237       return false;
9238 
9239     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
9240     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
9241     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
9242     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
9243     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
9244     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
9245     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
9246     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
9247     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
9248     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
9249 
9250     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
9251   }
9252 
9253   void getAnalysisUsage(AnalysisUsage &AU) const override {
9254     FunctionPass::getAnalysisUsage(AU);
9255     AU.addRequired<AssumptionCacheTracker>();
9256     AU.addRequired<ScalarEvolutionWrapperPass>();
9257     AU.addRequired<AAResultsWrapperPass>();
9258     AU.addRequired<TargetTransformInfoWrapperPass>();
9259     AU.addRequired<LoopInfoWrapperPass>();
9260     AU.addRequired<DominatorTreeWrapperPass>();
9261     AU.addRequired<DemandedBitsWrapperPass>();
9262     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
9263     AU.addRequired<InjectTLIMappingsLegacy>();
9264     AU.addPreserved<LoopInfoWrapperPass>();
9265     AU.addPreserved<DominatorTreeWrapperPass>();
9266     AU.addPreserved<AAResultsWrapperPass>();
9267     AU.addPreserved<GlobalsAAWrapperPass>();
9268     AU.setPreservesCFG();
9269   }
9270 };
9271 
9272 } // end anonymous namespace
9273 
9274 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
9275   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
9276   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
9277   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
9278   auto *AA = &AM.getResult<AAManager>(F);
9279   auto *LI = &AM.getResult<LoopAnalysis>(F);
9280   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
9281   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
9282   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
9283   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
9284 
9285   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
9286   if (!Changed)
9287     return PreservedAnalyses::all();
9288 
9289   PreservedAnalyses PA;
9290   PA.preserveSet<CFGAnalyses>();
9291   return PA;
9292 }
9293 
9294 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
9295                                 TargetTransformInfo *TTI_,
9296                                 TargetLibraryInfo *TLI_, AAResults *AA_,
9297                                 LoopInfo *LI_, DominatorTree *DT_,
9298                                 AssumptionCache *AC_, DemandedBits *DB_,
9299                                 OptimizationRemarkEmitter *ORE_) {
9300   if (!RunSLPVectorization)
9301     return false;
9302   SE = SE_;
9303   TTI = TTI_;
9304   TLI = TLI_;
9305   AA = AA_;
9306   LI = LI_;
9307   DT = DT_;
9308   AC = AC_;
9309   DB = DB_;
9310   DL = &F.getParent()->getDataLayout();
9311 
9312   Stores.clear();
9313   GEPs.clear();
9314   bool Changed = false;
9315 
9316   // If the target claims to have no vector registers don't attempt
9317   // vectorization.
9318   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true))) {
9319     LLVM_DEBUG(
9320         dbgs() << "SLP: Didn't find any vector registers for target, abort.\n");
9321     return false;
9322   }
9323 
9324   // Don't vectorize when the attribute NoImplicitFloat is used.
9325   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
9326     return false;
9327 
9328   LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
9329 
9330   // Use the bottom up slp vectorizer to construct chains that start with
9331   // store instructions.
9332   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
9333 
9334   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
9335   // delete instructions.
9336 
9337   // Update DFS numbers now so that we can use them for ordering.
9338   DT->updateDFSNumbers();
9339 
9340   // Scan the blocks in the function in post order.
9341   for (auto BB : post_order(&F.getEntryBlock())) {
9342     // Start new block - clear the list of reduction roots.
9343     R.clearReductionData();
9344     collectSeedInstructions(BB);
9345 
9346     // Vectorize trees that end at stores.
9347     if (!Stores.empty()) {
9348       LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
9349                         << " underlying objects.\n");
9350       Changed |= vectorizeStoreChains(R);
9351     }
9352 
9353     // Vectorize trees that end at reductions.
9354     Changed |= vectorizeChainsInBlock(BB, R);
9355 
9356     // Vectorize the index computations of getelementptr instructions. This
9357     // is primarily intended to catch gather-like idioms ending at
9358     // non-consecutive loads.
9359     if (!GEPs.empty()) {
9360       LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
9361                         << " underlying objects.\n");
9362       Changed |= vectorizeGEPIndices(BB, R);
9363     }
9364   }
9365 
9366   if (Changed) {
9367     R.optimizeGatherSequence();
9368     LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
9369   }
9370   return Changed;
9371 }
9372 
9373 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
9374                                             unsigned Idx, unsigned MinVF) {
9375   LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()
9376                     << "\n");
9377   const unsigned Sz = R.getVectorElementSize(Chain[0]);
9378   unsigned VF = Chain.size();
9379 
9380   if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
9381     return false;
9382 
9383   LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx
9384                     << "\n");
9385 
9386   R.buildTree(Chain);
9387   if (R.isTreeTinyAndNotFullyVectorizable())
9388     return false;
9389   if (R.isLoadCombineCandidate())
9390     return false;
9391   R.reorderTopToBottom();
9392   R.reorderBottomToTop();
9393   R.buildExternalUses();
9394 
9395   R.computeMinimumValueSizes();
9396 
9397   InstructionCost Cost = R.getTreeCost();
9398 
9399   LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n");
9400   if (Cost < -SLPCostThreshold) {
9401     LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n");
9402 
9403     using namespace ore;
9404 
9405     R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
9406                                         cast<StoreInst>(Chain[0]))
9407                      << "Stores SLP vectorized with cost " << NV("Cost", Cost)
9408                      << " and with tree size "
9409                      << NV("TreeSize", R.getTreeSize()));
9410 
9411     R.vectorizeTree();
9412     return true;
9413   }
9414 
9415   return false;
9416 }
9417 
9418 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
9419                                         BoUpSLP &R) {
9420   // We may run into multiple chains that merge into a single chain. We mark the
9421   // stores that we vectorized so that we don't visit the same store twice.
9422   BoUpSLP::ValueSet VectorizedStores;
9423   bool Changed = false;
9424 
9425   int E = Stores.size();
9426   SmallBitVector Tails(E, false);
9427   int MaxIter = MaxStoreLookup.getValue();
9428   SmallVector<std::pair<int, int>, 16> ConsecutiveChain(
9429       E, std::make_pair(E, INT_MAX));
9430   SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false));
9431   int IterCnt;
9432   auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
9433                                   &CheckedPairs,
9434                                   &ConsecutiveChain](int K, int Idx) {
9435     if (IterCnt >= MaxIter)
9436       return true;
9437     if (CheckedPairs[Idx].test(K))
9438       return ConsecutiveChain[K].second == 1 &&
9439              ConsecutiveChain[K].first == Idx;
9440     ++IterCnt;
9441     CheckedPairs[Idx].set(K);
9442     CheckedPairs[K].set(Idx);
9443     Optional<int> Diff = getPointersDiff(
9444         Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(),
9445         Stores[Idx]->getValueOperand()->getType(),
9446         Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true);
9447     if (!Diff || *Diff == 0)
9448       return false;
9449     int Val = *Diff;
9450     if (Val < 0) {
9451       if (ConsecutiveChain[Idx].second > -Val) {
9452         Tails.set(K);
9453         ConsecutiveChain[Idx] = std::make_pair(K, -Val);
9454       }
9455       return false;
9456     }
9457     if (ConsecutiveChain[K].second <= Val)
9458       return false;
9459 
9460     Tails.set(Idx);
9461     ConsecutiveChain[K] = std::make_pair(Idx, Val);
9462     return Val == 1;
9463   };
9464   // Do a quadratic search on all of the given stores in reverse order and find
9465   // all of the pairs of stores that follow each other.
9466   for (int Idx = E - 1; Idx >= 0; --Idx) {
9467     // If a store has multiple consecutive store candidates, search according
9468     // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
9469     // This is because usually pairing with immediate succeeding or preceding
9470     // candidate create the best chance to find slp vectorization opportunity.
9471     const int MaxLookDepth = std::max(E - Idx, Idx + 1);
9472     IterCnt = 0;
9473     for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
9474       if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
9475           (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
9476         break;
9477   }
9478 
9479   // Tracks if we tried to vectorize stores starting from the given tail
9480   // already.
9481   SmallBitVector TriedTails(E, false);
9482   // For stores that start but don't end a link in the chain:
9483   for (int Cnt = E; Cnt > 0; --Cnt) {
9484     int I = Cnt - 1;
9485     if (ConsecutiveChain[I].first == E || Tails.test(I))
9486       continue;
9487     // We found a store instr that starts a chain. Now follow the chain and try
9488     // to vectorize it.
9489     BoUpSLP::ValueList Operands;
9490     // Collect the chain into a list.
9491     while (I != E && !VectorizedStores.count(Stores[I])) {
9492       Operands.push_back(Stores[I]);
9493       Tails.set(I);
9494       if (ConsecutiveChain[I].second != 1) {
9495         // Mark the new end in the chain and go back, if required. It might be
9496         // required if the original stores come in reversed order, for example.
9497         if (ConsecutiveChain[I].first != E &&
9498             Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) &&
9499             !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) {
9500           TriedTails.set(I);
9501           Tails.reset(ConsecutiveChain[I].first);
9502           if (Cnt < ConsecutiveChain[I].first + 2)
9503             Cnt = ConsecutiveChain[I].first + 2;
9504         }
9505         break;
9506       }
9507       // Move to the next value in the chain.
9508       I = ConsecutiveChain[I].first;
9509     }
9510     assert(!Operands.empty() && "Expected non-empty list of stores.");
9511 
9512     unsigned MaxVecRegSize = R.getMaxVecRegSize();
9513     unsigned EltSize = R.getVectorElementSize(Operands[0]);
9514     unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize);
9515 
9516     unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store),
9517                               MaxElts);
9518     auto *Store = cast<StoreInst>(Operands[0]);
9519     Type *StoreTy = Store->getValueOperand()->getType();
9520     Type *ValueTy = StoreTy;
9521     if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand()))
9522       ValueTy = Trunc->getSrcTy();
9523     unsigned MinVF = TTI->getStoreMinimumVF(
9524         R.getMinVF(DL->getTypeSizeInBits(ValueTy)), StoreTy, ValueTy);
9525 
9526     // FIXME: Is division-by-2 the correct step? Should we assert that the
9527     // register size is a power-of-2?
9528     unsigned StartIdx = 0;
9529     for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) {
9530       for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
9531         ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size);
9532         if (!VectorizedStores.count(Slice.front()) &&
9533             !VectorizedStores.count(Slice.back()) &&
9534             vectorizeStoreChain(Slice, R, Cnt, MinVF)) {
9535           // Mark the vectorized stores so that we don't vectorize them again.
9536           VectorizedStores.insert(Slice.begin(), Slice.end());
9537           Changed = true;
9538           // If we vectorized initial block, no need to try to vectorize it
9539           // again.
9540           if (Cnt == StartIdx)
9541             StartIdx += Size;
9542           Cnt += Size;
9543           continue;
9544         }
9545         ++Cnt;
9546       }
9547       // Check if the whole array was vectorized already - exit.
9548       if (StartIdx >= Operands.size())
9549         break;
9550     }
9551   }
9552 
9553   return Changed;
9554 }
9555 
9556 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
9557   // Initialize the collections. We will make a single pass over the block.
9558   Stores.clear();
9559   GEPs.clear();
9560 
9561   // Visit the store and getelementptr instructions in BB and organize them in
9562   // Stores and GEPs according to the underlying objects of their pointer
9563   // operands.
9564   for (Instruction &I : *BB) {
9565     // Ignore store instructions that are volatile or have a pointer operand
9566     // that doesn't point to a scalar type.
9567     if (auto *SI = dyn_cast<StoreInst>(&I)) {
9568       if (!SI->isSimple())
9569         continue;
9570       if (!isValidElementType(SI->getValueOperand()->getType()))
9571         continue;
9572       Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI);
9573     }
9574 
9575     // Ignore getelementptr instructions that have more than one index, a
9576     // constant index, or a pointer operand that doesn't point to a scalar
9577     // type.
9578     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
9579       auto Idx = GEP->idx_begin()->get();
9580       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
9581         continue;
9582       if (!isValidElementType(Idx->getType()))
9583         continue;
9584       if (GEP->getType()->isVectorTy())
9585         continue;
9586       GEPs[GEP->getPointerOperand()].push_back(GEP);
9587     }
9588   }
9589 }
9590 
9591 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
9592   if (!A || !B)
9593     return false;
9594   if (isa<InsertElementInst>(A) || isa<InsertElementInst>(B))
9595     return false;
9596   Value *VL[] = {A, B};
9597   return tryToVectorizeList(VL, R);
9598 }
9599 
9600 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
9601                                            bool LimitForRegisterSize) {
9602   if (VL.size() < 2)
9603     return false;
9604 
9605   LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
9606                     << VL.size() << ".\n");
9607 
9608   // Check that all of the parts are instructions of the same type,
9609   // we permit an alternate opcode via InstructionsState.
9610   InstructionsState S = getSameOpcode(VL);
9611   if (!S.getOpcode())
9612     return false;
9613 
9614   Instruction *I0 = cast<Instruction>(S.OpValue);
9615   // Make sure invalid types (including vector type) are rejected before
9616   // determining vectorization factor for scalar instructions.
9617   for (Value *V : VL) {
9618     Type *Ty = V->getType();
9619     if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) {
9620       // NOTE: the following will give user internal llvm type name, which may
9621       // not be useful.
9622       R.getORE()->emit([&]() {
9623         std::string type_str;
9624         llvm::raw_string_ostream rso(type_str);
9625         Ty->print(rso);
9626         return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
9627                << "Cannot SLP vectorize list: type "
9628                << rso.str() + " is unsupported by vectorizer";
9629       });
9630       return false;
9631     }
9632   }
9633 
9634   unsigned Sz = R.getVectorElementSize(I0);
9635   unsigned MinVF = R.getMinVF(Sz);
9636   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
9637   MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF);
9638   if (MaxVF < 2) {
9639     R.getORE()->emit([&]() {
9640       return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
9641              << "Cannot SLP vectorize list: vectorization factor "
9642              << "less than 2 is not supported";
9643     });
9644     return false;
9645   }
9646 
9647   bool Changed = false;
9648   bool CandidateFound = false;
9649   InstructionCost MinCost = SLPCostThreshold.getValue();
9650   Type *ScalarTy = VL[0]->getType();
9651   if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
9652     ScalarTy = IE->getOperand(1)->getType();
9653 
9654   unsigned NextInst = 0, MaxInst = VL.size();
9655   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
9656     // No actual vectorization should happen, if number of parts is the same as
9657     // provided vectorization factor (i.e. the scalar type is used for vector
9658     // code during codegen).
9659     auto *VecTy = FixedVectorType::get(ScalarTy, VF);
9660     if (TTI->getNumberOfParts(VecTy) == VF)
9661       continue;
9662     for (unsigned I = NextInst; I < MaxInst; ++I) {
9663       unsigned OpsWidth = 0;
9664 
9665       if (I + VF > MaxInst)
9666         OpsWidth = MaxInst - I;
9667       else
9668         OpsWidth = VF;
9669 
9670       if (!isPowerOf2_32(OpsWidth))
9671         continue;
9672 
9673       if ((LimitForRegisterSize && OpsWidth < MaxVF) ||
9674           (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2))
9675         break;
9676 
9677       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
9678       // Check that a previous iteration of this loop did not delete the Value.
9679       if (llvm::any_of(Ops, [&R](Value *V) {
9680             auto *I = dyn_cast<Instruction>(V);
9681             return I && R.isDeleted(I);
9682           }))
9683         continue;
9684 
9685       LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
9686                         << "\n");
9687 
9688       R.buildTree(Ops);
9689       if (R.isTreeTinyAndNotFullyVectorizable())
9690         continue;
9691       R.reorderTopToBottom();
9692       R.reorderBottomToTop(!isa<InsertElementInst>(Ops.front()));
9693       R.buildExternalUses();
9694 
9695       R.computeMinimumValueSizes();
9696       InstructionCost Cost = R.getTreeCost();
9697       CandidateFound = true;
9698       MinCost = std::min(MinCost, Cost);
9699 
9700       if (Cost < -SLPCostThreshold) {
9701         LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
9702         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
9703                                                     cast<Instruction>(Ops[0]))
9704                                  << "SLP vectorized with cost " << ore::NV("Cost", Cost)
9705                                  << " and with tree size "
9706                                  << ore::NV("TreeSize", R.getTreeSize()));
9707 
9708         R.vectorizeTree();
9709         // Move to the next bundle.
9710         I += VF - 1;
9711         NextInst = I + 1;
9712         Changed = true;
9713       }
9714     }
9715   }
9716 
9717   if (!Changed && CandidateFound) {
9718     R.getORE()->emit([&]() {
9719       return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
9720              << "List vectorization was possible but not beneficial with cost "
9721              << ore::NV("Cost", MinCost) << " >= "
9722              << ore::NV("Treshold", -SLPCostThreshold);
9723     });
9724   } else if (!Changed) {
9725     R.getORE()->emit([&]() {
9726       return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
9727              << "Cannot SLP vectorize list: vectorization was impossible"
9728              << " with available vectorization factors";
9729     });
9730   }
9731   return Changed;
9732 }
9733 
9734 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
9735   if (!I)
9736     return false;
9737 
9738   if ((!isa<BinaryOperator>(I) && !isa<CmpInst>(I)) ||
9739       isa<VectorType>(I->getType()))
9740     return false;
9741 
9742   Value *P = I->getParent();
9743 
9744   // Vectorize in current basic block only.
9745   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
9746   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
9747   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
9748     return false;
9749 
9750   // First collect all possible candidates
9751   SmallVector<std::pair<Value *, Value *>, 4> Candidates;
9752   Candidates.emplace_back(Op0, Op1);
9753 
9754   auto *A = dyn_cast<BinaryOperator>(Op0);
9755   auto *B = dyn_cast<BinaryOperator>(Op1);
9756   // Try to skip B.
9757   if (A && B && B->hasOneUse()) {
9758     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
9759     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
9760     if (B0 && B0->getParent() == P)
9761       Candidates.emplace_back(A, B0);
9762     if (B1 && B1->getParent() == P)
9763       Candidates.emplace_back(A, B1);
9764   }
9765   // Try to skip A.
9766   if (B && A && A->hasOneUse()) {
9767     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
9768     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
9769     if (A0 && A0->getParent() == P)
9770       Candidates.emplace_back(A0, B);
9771     if (A1 && A1->getParent() == P)
9772       Candidates.emplace_back(A1, B);
9773   }
9774 
9775   if (Candidates.size() == 1)
9776     return tryToVectorizePair(Op0, Op1, R);
9777 
9778   // We have multiple options. Try to pick the single best.
9779   Optional<int> BestCandidate = R.findBestRootPair(Candidates);
9780   if (!BestCandidate)
9781     return false;
9782   return tryToVectorizePair(Candidates[*BestCandidate].first,
9783                             Candidates[*BestCandidate].second, R);
9784 }
9785 
9786 namespace {
9787 
9788 /// Model horizontal reductions.
9789 ///
9790 /// A horizontal reduction is a tree of reduction instructions that has values
9791 /// that can be put into a vector as its leaves. For example:
9792 ///
9793 /// mul mul mul mul
9794 ///  \  /    \  /
9795 ///   +       +
9796 ///    \     /
9797 ///       +
9798 /// This tree has "mul" as its leaf values and "+" as its reduction
9799 /// instructions. A reduction can feed into a store or a binary operation
9800 /// feeding a phi.
9801 ///    ...
9802 ///    \  /
9803 ///     +
9804 ///     |
9805 ///  phi +=
9806 ///
9807 ///  Or:
9808 ///    ...
9809 ///    \  /
9810 ///     +
9811 ///     |
9812 ///   *p =
9813 ///
9814 class HorizontalReduction {
9815   using ReductionOpsType = SmallVector<Value *, 16>;
9816   using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
9817   ReductionOpsListType ReductionOps;
9818   /// List of possibly reduced values.
9819   SmallVector<SmallVector<Value *>> ReducedVals;
9820   /// Maps reduced value to the corresponding reduction operation.
9821   DenseMap<Value *, SmallVector<Instruction *>> ReducedValsToOps;
9822   // Use map vector to make stable output.
9823   MapVector<Instruction *, Value *> ExtraArgs;
9824   WeakTrackingVH ReductionRoot;
9825   /// The type of reduction operation.
9826   RecurKind RdxKind;
9827 
9828   static bool isCmpSelMinMax(Instruction *I) {
9829     return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) &&
9830            RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I));
9831   }
9832 
9833   // And/or are potentially poison-safe logical patterns like:
9834   // select x, y, false
9835   // select x, true, y
9836   static bool isBoolLogicOp(Instruction *I) {
9837     return match(I, m_LogicalAnd(m_Value(), m_Value())) ||
9838            match(I, m_LogicalOr(m_Value(), m_Value()));
9839   }
9840 
9841   /// Checks if instruction is associative and can be vectorized.
9842   static bool isVectorizable(RecurKind Kind, Instruction *I) {
9843     if (Kind == RecurKind::None)
9844       return false;
9845 
9846     // Integer ops that map to select instructions or intrinsics are fine.
9847     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) ||
9848         isBoolLogicOp(I))
9849       return true;
9850 
9851     if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) {
9852       // FP min/max are associative except for NaN and -0.0. We do not
9853       // have to rule out -0.0 here because the intrinsic semantics do not
9854       // specify a fixed result for it.
9855       return I->getFastMathFlags().noNaNs();
9856     }
9857 
9858     return I->isAssociative();
9859   }
9860 
9861   static Value *getRdxOperand(Instruction *I, unsigned Index) {
9862     // Poison-safe 'or' takes the form: select X, true, Y
9863     // To make that work with the normal operand processing, we skip the
9864     // true value operand.
9865     // TODO: Change the code and data structures to handle this without a hack.
9866     if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1)
9867       return I->getOperand(2);
9868     return I->getOperand(Index);
9869   }
9870 
9871   /// Creates reduction operation with the current opcode.
9872   static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS,
9873                          Value *RHS, const Twine &Name, bool UseSelect) {
9874     unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind);
9875     switch (Kind) {
9876     case RecurKind::Or:
9877       if (UseSelect &&
9878           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9879         return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name);
9880       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9881                                  Name);
9882     case RecurKind::And:
9883       if (UseSelect &&
9884           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9885         return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name);
9886       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9887                                  Name);
9888     case RecurKind::Add:
9889     case RecurKind::Mul:
9890     case RecurKind::Xor:
9891     case RecurKind::FAdd:
9892     case RecurKind::FMul:
9893       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9894                                  Name);
9895     case RecurKind::FMax:
9896       return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS);
9897     case RecurKind::FMin:
9898       return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS);
9899     case RecurKind::SMax:
9900       if (UseSelect) {
9901         Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name);
9902         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9903       }
9904       return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS);
9905     case RecurKind::SMin:
9906       if (UseSelect) {
9907         Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name);
9908         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9909       }
9910       return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS);
9911     case RecurKind::UMax:
9912       if (UseSelect) {
9913         Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name);
9914         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9915       }
9916       return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS);
9917     case RecurKind::UMin:
9918       if (UseSelect) {
9919         Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name);
9920         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9921       }
9922       return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS);
9923     default:
9924       llvm_unreachable("Unknown reduction operation.");
9925     }
9926   }
9927 
9928   /// Creates reduction operation with the current opcode with the IR flags
9929   /// from \p ReductionOps.
9930   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9931                          Value *RHS, const Twine &Name,
9932                          const ReductionOpsListType &ReductionOps) {
9933     bool UseSelect = ReductionOps.size() == 2 ||
9934                      // Logical or/and.
9935                      (ReductionOps.size() == 1 &&
9936                       isa<SelectInst>(ReductionOps.front().front()));
9937     assert((!UseSelect || ReductionOps.size() != 2 ||
9938             isa<SelectInst>(ReductionOps[1][0])) &&
9939            "Expected cmp + select pairs for reduction");
9940     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect);
9941     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9942       if (auto *Sel = dyn_cast<SelectInst>(Op)) {
9943         propagateIRFlags(Sel->getCondition(), ReductionOps[0]);
9944         propagateIRFlags(Op, ReductionOps[1]);
9945         return Op;
9946       }
9947     }
9948     propagateIRFlags(Op, ReductionOps[0]);
9949     return Op;
9950   }
9951 
9952   /// Creates reduction operation with the current opcode with the IR flags
9953   /// from \p I.
9954   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9955                          Value *RHS, const Twine &Name, Value *I) {
9956     auto *SelI = dyn_cast<SelectInst>(I);
9957     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, SelI != nullptr);
9958     if (SelI && RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9959       if (auto *Sel = dyn_cast<SelectInst>(Op))
9960         propagateIRFlags(Sel->getCondition(), SelI->getCondition());
9961     }
9962     propagateIRFlags(Op, I);
9963     return Op;
9964   }
9965 
9966   static RecurKind getRdxKind(Value *V) {
9967     auto *I = dyn_cast<Instruction>(V);
9968     if (!I)
9969       return RecurKind::None;
9970     if (match(I, m_Add(m_Value(), m_Value())))
9971       return RecurKind::Add;
9972     if (match(I, m_Mul(m_Value(), m_Value())))
9973       return RecurKind::Mul;
9974     if (match(I, m_And(m_Value(), m_Value())) ||
9975         match(I, m_LogicalAnd(m_Value(), m_Value())))
9976       return RecurKind::And;
9977     if (match(I, m_Or(m_Value(), m_Value())) ||
9978         match(I, m_LogicalOr(m_Value(), m_Value())))
9979       return RecurKind::Or;
9980     if (match(I, m_Xor(m_Value(), m_Value())))
9981       return RecurKind::Xor;
9982     if (match(I, m_FAdd(m_Value(), m_Value())))
9983       return RecurKind::FAdd;
9984     if (match(I, m_FMul(m_Value(), m_Value())))
9985       return RecurKind::FMul;
9986 
9987     if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value())))
9988       return RecurKind::FMax;
9989     if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value())))
9990       return RecurKind::FMin;
9991 
9992     // This matches either cmp+select or intrinsics. SLP is expected to handle
9993     // either form.
9994     // TODO: If we are canonicalizing to intrinsics, we can remove several
9995     //       special-case paths that deal with selects.
9996     if (match(I, m_SMax(m_Value(), m_Value())))
9997       return RecurKind::SMax;
9998     if (match(I, m_SMin(m_Value(), m_Value())))
9999       return RecurKind::SMin;
10000     if (match(I, m_UMax(m_Value(), m_Value())))
10001       return RecurKind::UMax;
10002     if (match(I, m_UMin(m_Value(), m_Value())))
10003       return RecurKind::UMin;
10004 
10005     if (auto *Select = dyn_cast<SelectInst>(I)) {
10006       // Try harder: look for min/max pattern based on instructions producing
10007       // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
10008       // During the intermediate stages of SLP, it's very common to have
10009       // pattern like this (since optimizeGatherSequence is run only once
10010       // at the end):
10011       // %1 = extractelement <2 x i32> %a, i32 0
10012       // %2 = extractelement <2 x i32> %a, i32 1
10013       // %cond = icmp sgt i32 %1, %2
10014       // %3 = extractelement <2 x i32> %a, i32 0
10015       // %4 = extractelement <2 x i32> %a, i32 1
10016       // %select = select i1 %cond, i32 %3, i32 %4
10017       CmpInst::Predicate Pred;
10018       Instruction *L1;
10019       Instruction *L2;
10020 
10021       Value *LHS = Select->getTrueValue();
10022       Value *RHS = Select->getFalseValue();
10023       Value *Cond = Select->getCondition();
10024 
10025       // TODO: Support inverse predicates.
10026       if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
10027         if (!isa<ExtractElementInst>(RHS) ||
10028             !L2->isIdenticalTo(cast<Instruction>(RHS)))
10029           return RecurKind::None;
10030       } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
10031         if (!isa<ExtractElementInst>(LHS) ||
10032             !L1->isIdenticalTo(cast<Instruction>(LHS)))
10033           return RecurKind::None;
10034       } else {
10035         if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
10036           return RecurKind::None;
10037         if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
10038             !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
10039             !L2->isIdenticalTo(cast<Instruction>(RHS)))
10040           return RecurKind::None;
10041       }
10042 
10043       switch (Pred) {
10044       default:
10045         return RecurKind::None;
10046       case CmpInst::ICMP_SGT:
10047       case CmpInst::ICMP_SGE:
10048         return RecurKind::SMax;
10049       case CmpInst::ICMP_SLT:
10050       case CmpInst::ICMP_SLE:
10051         return RecurKind::SMin;
10052       case CmpInst::ICMP_UGT:
10053       case CmpInst::ICMP_UGE:
10054         return RecurKind::UMax;
10055       case CmpInst::ICMP_ULT:
10056       case CmpInst::ICMP_ULE:
10057         return RecurKind::UMin;
10058       }
10059     }
10060     return RecurKind::None;
10061   }
10062 
10063   /// Get the index of the first operand.
10064   static unsigned getFirstOperandIndex(Instruction *I) {
10065     return isCmpSelMinMax(I) ? 1 : 0;
10066   }
10067 
10068   /// Total number of operands in the reduction operation.
10069   static unsigned getNumberOfOperands(Instruction *I) {
10070     return isCmpSelMinMax(I) ? 3 : 2;
10071   }
10072 
10073   /// Checks if the instruction is in basic block \p BB.
10074   /// For a cmp+sel min/max reduction check that both ops are in \p BB.
10075   static bool hasSameParent(Instruction *I, BasicBlock *BB) {
10076     if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) {
10077       auto *Sel = cast<SelectInst>(I);
10078       auto *Cmp = dyn_cast<Instruction>(Sel->getCondition());
10079       return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB;
10080     }
10081     return I->getParent() == BB;
10082   }
10083 
10084   /// Expected number of uses for reduction operations/reduced values.
10085   static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) {
10086     if (IsCmpSelMinMax) {
10087       // SelectInst must be used twice while the condition op must have single
10088       // use only.
10089       if (auto *Sel = dyn_cast<SelectInst>(I))
10090         return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse();
10091       return I->hasNUses(2);
10092     }
10093 
10094     // Arithmetic reduction operation must be used once only.
10095     return I->hasOneUse();
10096   }
10097 
10098   /// Initializes the list of reduction operations.
10099   void initReductionOps(Instruction *I) {
10100     if (isCmpSelMinMax(I))
10101       ReductionOps.assign(2, ReductionOpsType());
10102     else
10103       ReductionOps.assign(1, ReductionOpsType());
10104   }
10105 
10106   /// Add all reduction operations for the reduction instruction \p I.
10107   void addReductionOps(Instruction *I) {
10108     if (isCmpSelMinMax(I)) {
10109       ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
10110       ReductionOps[1].emplace_back(I);
10111     } else {
10112       ReductionOps[0].emplace_back(I);
10113     }
10114   }
10115 
10116   static Value *getLHS(RecurKind Kind, Instruction *I) {
10117     if (Kind == RecurKind::None)
10118       return nullptr;
10119     return I->getOperand(getFirstOperandIndex(I));
10120   }
10121   static Value *getRHS(RecurKind Kind, Instruction *I) {
10122     if (Kind == RecurKind::None)
10123       return nullptr;
10124     return I->getOperand(getFirstOperandIndex(I) + 1);
10125   }
10126 
10127 public:
10128   HorizontalReduction() = default;
10129 
10130   /// Try to find a reduction tree.
10131   bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst,
10132                                  ScalarEvolution &SE, const DataLayout &DL,
10133                                  const TargetLibraryInfo &TLI) {
10134     assert((!Phi || is_contained(Phi->operands(), Inst)) &&
10135            "Phi needs to use the binary operator");
10136     assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) ||
10137             isa<IntrinsicInst>(Inst)) &&
10138            "Expected binop, select, or intrinsic for reduction matching");
10139     RdxKind = getRdxKind(Inst);
10140 
10141     // We could have a initial reductions that is not an add.
10142     //  r *= v1 + v2 + v3 + v4
10143     // In such a case start looking for a tree rooted in the first '+'.
10144     if (Phi) {
10145       if (getLHS(RdxKind, Inst) == Phi) {
10146         Phi = nullptr;
10147         Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst));
10148         if (!Inst)
10149           return false;
10150         RdxKind = getRdxKind(Inst);
10151       } else if (getRHS(RdxKind, Inst) == Phi) {
10152         Phi = nullptr;
10153         Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst));
10154         if (!Inst)
10155           return false;
10156         RdxKind = getRdxKind(Inst);
10157       }
10158     }
10159 
10160     if (!isVectorizable(RdxKind, Inst))
10161       return false;
10162 
10163     // Analyze "regular" integer/FP types for reductions - no target-specific
10164     // types or pointers.
10165     Type *Ty = Inst->getType();
10166     if (!isValidElementType(Ty) || Ty->isPointerTy())
10167       return false;
10168 
10169     // Though the ultimate reduction may have multiple uses, its condition must
10170     // have only single use.
10171     if (auto *Sel = dyn_cast<SelectInst>(Inst))
10172       if (!Sel->getCondition()->hasOneUse())
10173         return false;
10174 
10175     ReductionRoot = Inst;
10176 
10177     // Iterate through all the operands of the possible reduction tree and
10178     // gather all the reduced values, sorting them by their value id.
10179     BasicBlock *BB = Inst->getParent();
10180     bool IsCmpSelMinMax = isCmpSelMinMax(Inst);
10181     SmallVector<Instruction *> Worklist(1, Inst);
10182     // Checks if the operands of the \p TreeN instruction are also reduction
10183     // operations or should be treated as reduced values or an extra argument,
10184     // which is not part of the reduction.
10185     auto &&CheckOperands = [this, IsCmpSelMinMax,
10186                             BB](Instruction *TreeN,
10187                                 SmallVectorImpl<Value *> &ExtraArgs,
10188                                 SmallVectorImpl<Value *> &PossibleReducedVals,
10189                                 SmallVectorImpl<Instruction *> &ReductionOps) {
10190       for (int I = getFirstOperandIndex(TreeN),
10191                End = getNumberOfOperands(TreeN);
10192            I < End; ++I) {
10193         Value *EdgeVal = getRdxOperand(TreeN, I);
10194         ReducedValsToOps[EdgeVal].push_back(TreeN);
10195         auto *EdgeInst = dyn_cast<Instruction>(EdgeVal);
10196         // Edge has wrong parent - mark as an extra argument.
10197         if (EdgeInst && !isVectorLikeInstWithConstOps(EdgeInst) &&
10198             !hasSameParent(EdgeInst, BB)) {
10199           ExtraArgs.push_back(EdgeVal);
10200           continue;
10201         }
10202         // If the edge is not an instruction, or it is different from the main
10203         // reduction opcode or has too many uses - possible reduced value.
10204         if (!EdgeInst || getRdxKind(EdgeInst) != RdxKind ||
10205             !hasRequiredNumberOfUses(IsCmpSelMinMax, EdgeInst) ||
10206             !isVectorizable(getRdxKind(EdgeInst), EdgeInst)) {
10207           PossibleReducedVals.push_back(EdgeVal);
10208           continue;
10209         }
10210         ReductionOps.push_back(EdgeInst);
10211       }
10212     };
10213     // Try to regroup reduced values so that it gets more profitable to try to
10214     // reduce them. Values are grouped by their value ids, instructions - by
10215     // instruction op id and/or alternate op id, plus do extra analysis for
10216     // loads (grouping them by the distabce between pointers) and cmp
10217     // instructions (grouping them by the predicate).
10218     MapVector<size_t, MapVector<size_t, MapVector<Value *, unsigned>>>
10219         PossibleReducedVals;
10220     initReductionOps(Inst);
10221     while (!Worklist.empty()) {
10222       Instruction *TreeN = Worklist.pop_back_val();
10223       SmallVector<Value *> Args;
10224       SmallVector<Value *> PossibleRedVals;
10225       SmallVector<Instruction *> PossibleReductionOps;
10226       CheckOperands(TreeN, Args, PossibleRedVals, PossibleReductionOps);
10227       // If too many extra args - mark the instruction itself as a reduction
10228       // value, not a reduction operation.
10229       if (Args.size() < 2) {
10230         addReductionOps(TreeN);
10231         // Add extra args.
10232         if (!Args.empty()) {
10233           assert(Args.size() == 1 && "Expected only single argument.");
10234           ExtraArgs[TreeN] = Args.front();
10235         }
10236         // Add reduction values. The values are sorted for better vectorization
10237         // results.
10238         for (Value *V : PossibleRedVals) {
10239           size_t Key, Idx;
10240           std::tie(Key, Idx) = generateKeySubkey(
10241               V, &TLI,
10242               [&PossibleReducedVals, &DL, &SE](size_t Key, LoadInst *LI) {
10243                 for (const auto &LoadData : PossibleReducedVals[Key]) {
10244                   auto *RLI = cast<LoadInst>(LoadData.second.front().first);
10245                   if (getPointersDiff(RLI->getType(), RLI->getPointerOperand(),
10246                                       LI->getType(), LI->getPointerOperand(),
10247                                       DL, SE, /*StrictCheck=*/true))
10248                     return hash_value(RLI->getPointerOperand());
10249                 }
10250                 return hash_value(LI->getPointerOperand());
10251               },
10252               /*AllowAlternate=*/false);
10253           ++PossibleReducedVals[Key][Idx]
10254                 .insert(std::make_pair(V, 0))
10255                 .first->second;
10256         }
10257         Worklist.append(PossibleReductionOps.rbegin(),
10258                         PossibleReductionOps.rend());
10259       } else {
10260         size_t Key, Idx;
10261         std::tie(Key, Idx) = generateKeySubkey(
10262             TreeN, &TLI,
10263             [&PossibleReducedVals, &DL, &SE](size_t Key, LoadInst *LI) {
10264               for (const auto &LoadData : PossibleReducedVals[Key]) {
10265                 auto *RLI = cast<LoadInst>(LoadData.second.front().first);
10266                 if (getPointersDiff(RLI->getType(), RLI->getPointerOperand(),
10267                                     LI->getType(), LI->getPointerOperand(), DL,
10268                                     SE, /*StrictCheck=*/true))
10269                   return hash_value(RLI->getPointerOperand());
10270               }
10271               return hash_value(LI->getPointerOperand());
10272             },
10273             /*AllowAlternate=*/false);
10274         ++PossibleReducedVals[Key][Idx]
10275               .insert(std::make_pair(TreeN, 0))
10276               .first->second;
10277       }
10278     }
10279     auto PossibleReducedValsVect = PossibleReducedVals.takeVector();
10280     // Sort values by the total number of values kinds to start the reduction
10281     // from the longest possible reduced values sequences.
10282     for (auto &PossibleReducedVals : PossibleReducedValsVect) {
10283       auto PossibleRedVals = PossibleReducedVals.second.takeVector();
10284       SmallVector<SmallVector<Value *>> PossibleRedValsVect;
10285       for (auto It = PossibleRedVals.begin(), E = PossibleRedVals.end();
10286            It != E; ++It) {
10287         PossibleRedValsVect.emplace_back();
10288         auto RedValsVect = It->second.takeVector();
10289         stable_sort(RedValsVect, [](const auto &P1, const auto &P2) {
10290           return P1.second < P2.second;
10291         });
10292         for (const std::pair<Value *, unsigned> &Data : RedValsVect)
10293           PossibleRedValsVect.back().append(Data.second, Data.first);
10294       }
10295       stable_sort(PossibleRedValsVect, [](const auto &P1, const auto &P2) {
10296         return P1.size() > P2.size();
10297       });
10298       ReducedVals.emplace_back();
10299       for (ArrayRef<Value *> Data : PossibleRedValsVect)
10300         ReducedVals.back().append(Data.rbegin(), Data.rend());
10301     }
10302     // Sort the reduced values by number of same/alternate opcode and/or pointer
10303     // operand.
10304     stable_sort(ReducedVals, [](ArrayRef<Value *> P1, ArrayRef<Value *> P2) {
10305       return P1.size() > P2.size();
10306     });
10307     return true;
10308   }
10309 
10310   /// Attempt to vectorize the tree found by matchAssociativeReduction.
10311   Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
10312     constexpr int ReductionLimit = 4;
10313     // If there are a sufficient number of reduction values, reduce
10314     // to a nearby power-of-2. We can safely generate oversized
10315     // vectors and rely on the backend to split them to legal sizes.
10316     unsigned NumReducedVals = std::accumulate(
10317         ReducedVals.begin(), ReducedVals.end(), 0,
10318         [](int Num, ArrayRef<Value *> Vals) { return Num + Vals.size(); });
10319     if (NumReducedVals < ReductionLimit)
10320       return nullptr;
10321 
10322     IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
10323 
10324     // Track the reduced values in case if they are replaced by extractelement
10325     // because of the vectorization.
10326     DenseMap<Value *, WeakTrackingVH> TrackedVals;
10327     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
10328     // The same extra argument may be used several times, so log each attempt
10329     // to use it.
10330     for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) {
10331       assert(Pair.first && "DebugLoc must be set.");
10332       ExternallyUsedValues[Pair.second].push_back(Pair.first);
10333       TrackedVals.try_emplace(Pair.second, Pair.second);
10334     }
10335 
10336     // The compare instruction of a min/max is the insertion point for new
10337     // instructions and may be replaced with a new compare instruction.
10338     auto &&GetCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
10339       assert(isa<SelectInst>(RdxRootInst) &&
10340              "Expected min/max reduction to have select root instruction");
10341       Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
10342       assert(isa<Instruction>(ScalarCond) &&
10343              "Expected min/max reduction to have compare condition");
10344       return cast<Instruction>(ScalarCond);
10345     };
10346 
10347     // The reduction root is used as the insertion point for new instructions,
10348     // so set it as externally used to prevent it from being deleted.
10349     ExternallyUsedValues[ReductionRoot];
10350     SmallVector<Value *> IgnoreList;
10351     for (ReductionOpsType &RdxOps : ReductionOps)
10352       for (Value *RdxOp : RdxOps) {
10353         if (!RdxOp)
10354           continue;
10355         IgnoreList.push_back(RdxOp);
10356       }
10357     bool IsCmpSelMinMax = isCmpSelMinMax(cast<Instruction>(ReductionRoot));
10358 
10359     // Need to track reduced vals, they may be changed during vectorization of
10360     // subvectors.
10361     for (ArrayRef<Value *> Candidates : ReducedVals)
10362       for (Value *V : Candidates)
10363         TrackedVals.try_emplace(V, V);
10364 
10365     DenseMap<Value *, unsigned> VectorizedVals;
10366     Value *VectorizedTree = nullptr;
10367     bool CheckForReusedReductionOps = false;
10368     // Try to vectorize elements based on their type.
10369     for (unsigned I = 0, E = ReducedVals.size(); I < E; ++I) {
10370       ArrayRef<Value *> OrigReducedVals = ReducedVals[I];
10371       InstructionsState S = getSameOpcode(OrigReducedVals);
10372       SmallVector<Value *> Candidates;
10373       DenseMap<Value *, Value *> TrackedToOrig;
10374       for (unsigned Cnt = 0, Sz = OrigReducedVals.size(); Cnt < Sz; ++Cnt) {
10375         Value *RdxVal = TrackedVals.find(OrigReducedVals[Cnt])->second;
10376         // Check if the reduction value was not overriden by the extractelement
10377         // instruction because of the vectorization and exclude it, if it is not
10378         // compatible with other values.
10379         if (auto *Inst = dyn_cast<Instruction>(RdxVal))
10380           if (isVectorLikeInstWithConstOps(Inst) &&
10381               (!S.getOpcode() || !S.isOpcodeOrAlt(Inst)))
10382             continue;
10383         Candidates.push_back(RdxVal);
10384         TrackedToOrig.try_emplace(RdxVal, OrigReducedVals[Cnt]);
10385       }
10386       bool ShuffledExtracts = false;
10387       // Try to handle shuffled extractelements.
10388       if (S.getOpcode() == Instruction::ExtractElement && !S.isAltShuffle() &&
10389           I + 1 < E) {
10390         InstructionsState NextS = getSameOpcode(ReducedVals[I + 1]);
10391         if (NextS.getOpcode() == Instruction::ExtractElement &&
10392             !NextS.isAltShuffle()) {
10393           SmallVector<Value *> CommonCandidates(Candidates);
10394           for (Value *RV : ReducedVals[I + 1]) {
10395             Value *RdxVal = TrackedVals.find(RV)->second;
10396             // Check if the reduction value was not overriden by the
10397             // extractelement instruction because of the vectorization and
10398             // exclude it, if it is not compatible with other values.
10399             if (auto *Inst = dyn_cast<Instruction>(RdxVal))
10400               if (!NextS.getOpcode() || !NextS.isOpcodeOrAlt(Inst))
10401                 continue;
10402             CommonCandidates.push_back(RdxVal);
10403             TrackedToOrig.try_emplace(RdxVal, RV);
10404           }
10405           SmallVector<int> Mask;
10406           if (isFixedVectorShuffle(CommonCandidates, Mask)) {
10407             ++I;
10408             Candidates.swap(CommonCandidates);
10409             ShuffledExtracts = true;
10410           }
10411         }
10412       }
10413       unsigned NumReducedVals = Candidates.size();
10414       if (NumReducedVals < ReductionLimit)
10415         continue;
10416 
10417       unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
10418       unsigned Start = 0;
10419       unsigned Pos = Start;
10420       // Restarts vectorization attempt with lower vector factor.
10421       unsigned PrevReduxWidth = ReduxWidth;
10422       bool CheckForReusedReductionOpsLocal = false;
10423       auto &&AdjustReducedVals = [&Pos, &Start, &ReduxWidth, NumReducedVals,
10424                                   &CheckForReusedReductionOpsLocal,
10425                                   &PrevReduxWidth, &V,
10426                                   &IgnoreList](bool IgnoreVL = false) {
10427         bool IsAnyRedOpGathered =
10428             !IgnoreVL && any_of(IgnoreList, [&V](Value *RedOp) {
10429               return V.isGathered(RedOp);
10430             });
10431         if (!CheckForReusedReductionOpsLocal && PrevReduxWidth == ReduxWidth) {
10432           // Check if any of the reduction ops are gathered. If so, worth
10433           // trying again with less number of reduction ops.
10434           CheckForReusedReductionOpsLocal |= IsAnyRedOpGathered;
10435         }
10436         ++Pos;
10437         if (Pos < NumReducedVals - ReduxWidth + 1)
10438           return IsAnyRedOpGathered;
10439         Pos = Start;
10440         ReduxWidth /= 2;
10441         return IsAnyRedOpGathered;
10442       };
10443       while (Pos < NumReducedVals - ReduxWidth + 1 &&
10444              ReduxWidth >= ReductionLimit) {
10445         // Dependency in tree of the reduction ops - drop this attempt, try
10446         // later.
10447         if (CheckForReusedReductionOpsLocal && PrevReduxWidth != ReduxWidth &&
10448             Start == 0) {
10449           CheckForReusedReductionOps = true;
10450           break;
10451         }
10452         PrevReduxWidth = ReduxWidth;
10453         ArrayRef<Value *> VL(std::next(Candidates.begin(), Pos), ReduxWidth);
10454         // Beeing analyzed already - skip.
10455         if (V.areAnalyzedReductionVals(VL)) {
10456           (void)AdjustReducedVals(/*IgnoreVL=*/true);
10457           continue;
10458         }
10459         // Early exit if any of the reduction values were deleted during
10460         // previous vectorization attempts.
10461         if (any_of(VL, [&V](Value *RedVal) {
10462               auto *RedValI = dyn_cast<Instruction>(RedVal);
10463               if (!RedValI)
10464                 return false;
10465               return V.isDeleted(RedValI);
10466             }))
10467           break;
10468         V.buildTree(VL, IgnoreList);
10469         if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true)) {
10470           if (!AdjustReducedVals())
10471             V.analyzedReductionVals(VL);
10472           continue;
10473         }
10474         if (V.isLoadCombineReductionCandidate(RdxKind)) {
10475           if (!AdjustReducedVals())
10476             V.analyzedReductionVals(VL);
10477           continue;
10478         }
10479         V.reorderTopToBottom();
10480         // No need to reorder the root node at all.
10481         V.reorderBottomToTop(/*IgnoreReorder=*/true);
10482         // Keep extracted other reduction values, if they are used in the
10483         // vectorization trees.
10484         BoUpSLP::ExtraValueToDebugLocsMap LocalExternallyUsedValues(
10485             ExternallyUsedValues);
10486         for (unsigned Cnt = 0, Sz = ReducedVals.size(); Cnt < Sz; ++Cnt) {
10487           if (Cnt == I || (ShuffledExtracts && Cnt == I - 1))
10488             continue;
10489           for_each(ReducedVals[Cnt],
10490                    [&LocalExternallyUsedValues, &TrackedVals](Value *V) {
10491                      if (isa<Instruction>(V))
10492                        LocalExternallyUsedValues[TrackedVals[V]];
10493                    });
10494         }
10495         for (unsigned Cnt = 0; Cnt < NumReducedVals; ++Cnt) {
10496           if (Cnt >= Pos && Cnt < Pos + ReduxWidth)
10497             continue;
10498           unsigned NumOps = VectorizedVals.lookup(Candidates[Cnt]) +
10499                             std::count(VL.begin(), VL.end(), Candidates[Cnt]);
10500           if (NumOps != ReducedValsToOps.find(Candidates[Cnt])->second.size())
10501             LocalExternallyUsedValues[Candidates[Cnt]];
10502         }
10503         V.buildExternalUses(LocalExternallyUsedValues);
10504 
10505         V.computeMinimumValueSizes();
10506 
10507         // Intersect the fast-math-flags from all reduction operations.
10508         FastMathFlags RdxFMF;
10509         RdxFMF.set();
10510         for (Value *U : IgnoreList)
10511           if (auto *FPMO = dyn_cast<FPMathOperator>(U))
10512             RdxFMF &= FPMO->getFastMathFlags();
10513         // Estimate cost.
10514         InstructionCost TreeCost = V.getTreeCost(VL);
10515         InstructionCost ReductionCost =
10516             getReductionCost(TTI, VL[0], ReduxWidth, RdxFMF);
10517         InstructionCost Cost = TreeCost + ReductionCost;
10518         if (!Cost.isValid()) {
10519           LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n");
10520           return nullptr;
10521         }
10522         if (Cost >= -SLPCostThreshold) {
10523           V.getORE()->emit([&]() {
10524             return OptimizationRemarkMissed(
10525                        SV_NAME, "HorSLPNotBeneficial",
10526                        ReducedValsToOps.find(VL[0])->second.front())
10527                    << "Vectorizing horizontal reduction is possible"
10528                    << "but not beneficial with cost " << ore::NV("Cost", Cost)
10529                    << " and threshold "
10530                    << ore::NV("Threshold", -SLPCostThreshold);
10531           });
10532           if (!AdjustReducedVals())
10533             V.analyzedReductionVals(VL);
10534           continue;
10535         }
10536 
10537         LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
10538                           << Cost << ". (HorRdx)\n");
10539         V.getORE()->emit([&]() {
10540           return OptimizationRemark(
10541                      SV_NAME, "VectorizedHorizontalReduction",
10542                      ReducedValsToOps.find(VL[0])->second.front())
10543                  << "Vectorized horizontal reduction with cost "
10544                  << ore::NV("Cost", Cost) << " and with tree size "
10545                  << ore::NV("TreeSize", V.getTreeSize());
10546         });
10547 
10548         Builder.setFastMathFlags(RdxFMF);
10549 
10550         // Vectorize a tree.
10551         Value *VectorizedRoot = V.vectorizeTree(LocalExternallyUsedValues);
10552 
10553         // Emit a reduction. If the root is a select (min/max idiom), the insert
10554         // point is the compare condition of that select.
10555         Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
10556         if (IsCmpSelMinMax)
10557           Builder.SetInsertPoint(GetCmpForMinMaxReduction(RdxRootInst));
10558         else
10559           Builder.SetInsertPoint(RdxRootInst);
10560 
10561         // To prevent poison from leaking across what used to be sequential,
10562         // safe, scalar boolean logic operations, the reduction operand must be
10563         // frozen.
10564         if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst))
10565           VectorizedRoot = Builder.CreateFreeze(VectorizedRoot);
10566 
10567         Value *ReducedSubTree =
10568             emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
10569 
10570         if (!VectorizedTree) {
10571           // Initialize the final value in the reduction.
10572           VectorizedTree = ReducedSubTree;
10573         } else {
10574           // Update the final value in the reduction.
10575           Builder.SetCurrentDebugLocation(
10576               cast<Instruction>(ReductionOps.front().front())->getDebugLoc());
10577           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
10578                                     ReducedSubTree, "op.rdx", ReductionOps);
10579         }
10580         // Count vectorized reduced values to exclude them from final reduction.
10581         for (Value *V : VL)
10582           ++VectorizedVals.try_emplace(TrackedToOrig.find(V)->second, 0)
10583                 .first->getSecond();
10584         Pos += ReduxWidth;
10585         Start = Pos;
10586         ReduxWidth = PowerOf2Floor(NumReducedVals - Pos);
10587       }
10588     }
10589     if (VectorizedTree) {
10590       // Finish the reduction.
10591       // Need to add extra arguments and not vectorized possible reduction
10592       // values.
10593       SmallPtrSet<Value *, 8> Visited;
10594       for (unsigned I = 0, E = ReducedVals.size(); I < E; ++I) {
10595         ArrayRef<Value *> Candidates = ReducedVals[I];
10596         for (Value *RdxVal : Candidates) {
10597           if (!Visited.insert(RdxVal).second)
10598             continue;
10599           Value *StableRdxVal = RdxVal;
10600           auto TVIt = TrackedVals.find(RdxVal);
10601           if (TVIt != TrackedVals.end())
10602             StableRdxVal = TVIt->second;
10603           unsigned NumOps = VectorizedVals.lookup(RdxVal);
10604           for (Instruction *RedOp :
10605                makeArrayRef(ReducedValsToOps.find(RdxVal)->second)
10606                    .drop_back(NumOps)) {
10607             Builder.SetCurrentDebugLocation(RedOp->getDebugLoc());
10608             ReductionOpsListType Ops;
10609             if (auto *Sel = dyn_cast<SelectInst>(RedOp))
10610               Ops.emplace_back().push_back(Sel->getCondition());
10611             Ops.emplace_back().push_back(RedOp);
10612             VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
10613                                       StableRdxVal, "op.rdx", Ops);
10614           }
10615         }
10616       }
10617       for (auto &Pair : ExternallyUsedValues) {
10618         // Add each externally used value to the final reduction.
10619         for (auto *I : Pair.second) {
10620           Builder.SetCurrentDebugLocation(I->getDebugLoc());
10621           ReductionOpsListType Ops;
10622           if (auto *Sel = dyn_cast<SelectInst>(I))
10623             Ops.emplace_back().push_back(Sel->getCondition());
10624           Ops.emplace_back().push_back(I);
10625           Value *StableRdxVal = Pair.first;
10626           auto TVIt = TrackedVals.find(Pair.first);
10627           if (TVIt != TrackedVals.end())
10628             StableRdxVal = TVIt->second;
10629           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
10630                                     StableRdxVal, "op.rdx", Ops);
10631         }
10632       }
10633 
10634       ReductionRoot->replaceAllUsesWith(VectorizedTree);
10635 
10636       // The original scalar reduction is expected to have no remaining
10637       // uses outside the reduction tree itself.  Assert that we got this
10638       // correct, replace internal uses with undef, and mark for eventual
10639       // deletion.
10640 #ifndef NDEBUG
10641       SmallSet<Value *, 4> IgnoreSet;
10642       for (ArrayRef<Value *> RdxOps : ReductionOps)
10643         IgnoreSet.insert(RdxOps.begin(), RdxOps.end());
10644 #endif
10645       for (ArrayRef<Value *> RdxOps : ReductionOps) {
10646         for (Value *Ignore : RdxOps) {
10647           if (!Ignore)
10648             continue;
10649 #ifndef NDEBUG
10650           for (auto *U : Ignore->users()) {
10651             assert(IgnoreSet.count(U) &&
10652                    "All users must be either in the reduction ops list.");
10653           }
10654 #endif
10655           if (!Ignore->use_empty()) {
10656             Value *Undef = UndefValue::get(Ignore->getType());
10657             Ignore->replaceAllUsesWith(Undef);
10658           }
10659           V.eraseInstruction(cast<Instruction>(Ignore));
10660         }
10661       }
10662     } else if (!CheckForReusedReductionOps) {
10663       for (ReductionOpsType &RdxOps : ReductionOps)
10664         for (Value *RdxOp : RdxOps)
10665           V.analyzedReductionRoot(cast<Instruction>(RdxOp));
10666     }
10667     return VectorizedTree;
10668   }
10669 
10670 private:
10671   /// Calculate the cost of a reduction.
10672   InstructionCost getReductionCost(TargetTransformInfo *TTI,
10673                                    Value *FirstReducedVal, unsigned ReduxWidth,
10674                                    FastMathFlags FMF) {
10675     TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
10676     Type *ScalarTy = FirstReducedVal->getType();
10677     FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth);
10678     InstructionCost VectorCost, ScalarCost;
10679     switch (RdxKind) {
10680     case RecurKind::Add:
10681     case RecurKind::Mul:
10682     case RecurKind::Or:
10683     case RecurKind::And:
10684     case RecurKind::Xor:
10685     case RecurKind::FAdd:
10686     case RecurKind::FMul: {
10687       unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind);
10688       VectorCost =
10689           TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind);
10690       ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind);
10691       break;
10692     }
10693     case RecurKind::FMax:
10694     case RecurKind::FMin: {
10695       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
10696       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
10697       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
10698                                                /*IsUnsigned=*/false, CostKind);
10699       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
10700       ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy,
10701                                            SclCondTy, RdxPred, CostKind) +
10702                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
10703                                            SclCondTy, RdxPred, CostKind);
10704       break;
10705     }
10706     case RecurKind::SMax:
10707     case RecurKind::SMin:
10708     case RecurKind::UMax:
10709     case RecurKind::UMin: {
10710       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
10711       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
10712       bool IsUnsigned =
10713           RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin;
10714       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, IsUnsigned,
10715                                                CostKind);
10716       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
10717       ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
10718                                            SclCondTy, RdxPred, CostKind) +
10719                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
10720                                            SclCondTy, RdxPred, CostKind);
10721       break;
10722     }
10723     default:
10724       llvm_unreachable("Expected arithmetic or min/max reduction operation");
10725     }
10726 
10727     // Scalar cost is repeated for N-1 elements.
10728     ScalarCost *= (ReduxWidth - 1);
10729     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost
10730                       << " for reduction that starts with " << *FirstReducedVal
10731                       << " (It is a splitting reduction)\n");
10732     return VectorCost - ScalarCost;
10733   }
10734 
10735   /// Emit a horizontal reduction of the vectorized value.
10736   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
10737                        unsigned ReduxWidth, const TargetTransformInfo *TTI) {
10738     assert(VectorizedValue && "Need to have a vectorized tree node");
10739     assert(isPowerOf2_32(ReduxWidth) &&
10740            "We only handle power-of-two reductions for now");
10741     assert(RdxKind != RecurKind::FMulAdd &&
10742            "A call to the llvm.fmuladd intrinsic is not handled yet");
10743 
10744     ++NumVectorInstructions;
10745     return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind);
10746   }
10747 };
10748 
10749 } // end anonymous namespace
10750 
10751 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) {
10752   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
10753     return cast<FixedVectorType>(IE->getType())->getNumElements();
10754 
10755   unsigned AggregateSize = 1;
10756   auto *IV = cast<InsertValueInst>(InsertInst);
10757   Type *CurrentType = IV->getType();
10758   do {
10759     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
10760       for (auto *Elt : ST->elements())
10761         if (Elt != ST->getElementType(0)) // check homogeneity
10762           return None;
10763       AggregateSize *= ST->getNumElements();
10764       CurrentType = ST->getElementType(0);
10765     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
10766       AggregateSize *= AT->getNumElements();
10767       CurrentType = AT->getElementType();
10768     } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
10769       AggregateSize *= VT->getNumElements();
10770       return AggregateSize;
10771     } else if (CurrentType->isSingleValueType()) {
10772       return AggregateSize;
10773     } else {
10774       return None;
10775     }
10776   } while (true);
10777 }
10778 
10779 static void findBuildAggregate_rec(Instruction *LastInsertInst,
10780                                    TargetTransformInfo *TTI,
10781                                    SmallVectorImpl<Value *> &BuildVectorOpds,
10782                                    SmallVectorImpl<Value *> &InsertElts,
10783                                    unsigned OperandOffset) {
10784   do {
10785     Value *InsertedOperand = LastInsertInst->getOperand(1);
10786     Optional<unsigned> OperandIndex =
10787         getInsertIndex(LastInsertInst, OperandOffset);
10788     if (!OperandIndex)
10789       return;
10790     if (isa<InsertElementInst>(InsertedOperand) ||
10791         isa<InsertValueInst>(InsertedOperand)) {
10792       findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI,
10793                              BuildVectorOpds, InsertElts, *OperandIndex);
10794 
10795     } else {
10796       BuildVectorOpds[*OperandIndex] = InsertedOperand;
10797       InsertElts[*OperandIndex] = LastInsertInst;
10798     }
10799     LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0));
10800   } while (LastInsertInst != nullptr &&
10801            (isa<InsertValueInst>(LastInsertInst) ||
10802             isa<InsertElementInst>(LastInsertInst)) &&
10803            LastInsertInst->hasOneUse());
10804 }
10805 
10806 /// Recognize construction of vectors like
10807 ///  %ra = insertelement <4 x float> poison, float %s0, i32 0
10808 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
10809 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
10810 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
10811 ///  starting from the last insertelement or insertvalue instruction.
10812 ///
10813 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>},
10814 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
10815 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
10816 ///
10817 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
10818 ///
10819 /// \return true if it matches.
10820 static bool findBuildAggregate(Instruction *LastInsertInst,
10821                                TargetTransformInfo *TTI,
10822                                SmallVectorImpl<Value *> &BuildVectorOpds,
10823                                SmallVectorImpl<Value *> &InsertElts) {
10824 
10825   assert((isa<InsertElementInst>(LastInsertInst) ||
10826           isa<InsertValueInst>(LastInsertInst)) &&
10827          "Expected insertelement or insertvalue instruction!");
10828 
10829   assert((BuildVectorOpds.empty() && InsertElts.empty()) &&
10830          "Expected empty result vectors!");
10831 
10832   Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst);
10833   if (!AggregateSize)
10834     return false;
10835   BuildVectorOpds.resize(*AggregateSize);
10836   InsertElts.resize(*AggregateSize);
10837 
10838   findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts, 0);
10839   llvm::erase_value(BuildVectorOpds, nullptr);
10840   llvm::erase_value(InsertElts, nullptr);
10841   if (BuildVectorOpds.size() >= 2)
10842     return true;
10843 
10844   return false;
10845 }
10846 
10847 /// Try and get a reduction value from a phi node.
10848 ///
10849 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
10850 /// if they come from either \p ParentBB or a containing loop latch.
10851 ///
10852 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
10853 /// if not possible.
10854 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
10855                                 BasicBlock *ParentBB, LoopInfo *LI) {
10856   // There are situations where the reduction value is not dominated by the
10857   // reduction phi. Vectorizing such cases has been reported to cause
10858   // miscompiles. See PR25787.
10859   auto DominatedReduxValue = [&](Value *R) {
10860     return isa<Instruction>(R) &&
10861            DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
10862   };
10863 
10864   Value *Rdx = nullptr;
10865 
10866   // Return the incoming value if it comes from the same BB as the phi node.
10867   if (P->getIncomingBlock(0) == ParentBB) {
10868     Rdx = P->getIncomingValue(0);
10869   } else if (P->getIncomingBlock(1) == ParentBB) {
10870     Rdx = P->getIncomingValue(1);
10871   }
10872 
10873   if (Rdx && DominatedReduxValue(Rdx))
10874     return Rdx;
10875 
10876   // Otherwise, check whether we have a loop latch to look at.
10877   Loop *BBL = LI->getLoopFor(ParentBB);
10878   if (!BBL)
10879     return nullptr;
10880   BasicBlock *BBLatch = BBL->getLoopLatch();
10881   if (!BBLatch)
10882     return nullptr;
10883 
10884   // There is a loop latch, return the incoming value if it comes from
10885   // that. This reduction pattern occasionally turns up.
10886   if (P->getIncomingBlock(0) == BBLatch) {
10887     Rdx = P->getIncomingValue(0);
10888   } else if (P->getIncomingBlock(1) == BBLatch) {
10889     Rdx = P->getIncomingValue(1);
10890   }
10891 
10892   if (Rdx && DominatedReduxValue(Rdx))
10893     return Rdx;
10894 
10895   return nullptr;
10896 }
10897 
10898 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) {
10899   if (match(I, m_BinOp(m_Value(V0), m_Value(V1))))
10900     return true;
10901   if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1))))
10902     return true;
10903   if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1))))
10904     return true;
10905   if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1))))
10906     return true;
10907   if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1))))
10908     return true;
10909   if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1))))
10910     return true;
10911   if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1))))
10912     return true;
10913   return false;
10914 }
10915 
10916 /// Attempt to reduce a horizontal reduction.
10917 /// If it is legal to match a horizontal reduction feeding the phi node \a P
10918 /// with reduction operators \a Root (or one of its operands) in a basic block
10919 /// \a BB, then check if it can be done. If horizontal reduction is not found
10920 /// and root instruction is a binary operation, vectorization of the operands is
10921 /// attempted.
10922 /// \returns true if a horizontal reduction was matched and reduced or operands
10923 /// of one of the binary instruction were vectorized.
10924 /// \returns false if a horizontal reduction was not matched (or not possible)
10925 /// or no vectorization of any binary operation feeding \a Root instruction was
10926 /// performed.
10927 static bool tryToVectorizeHorReductionOrInstOperands(
10928     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
10929     TargetTransformInfo *TTI, ScalarEvolution &SE, const DataLayout &DL,
10930     const TargetLibraryInfo &TLI,
10931     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
10932   if (!ShouldVectorizeHor)
10933     return false;
10934 
10935   if (!Root)
10936     return false;
10937 
10938   if (Root->getParent() != BB || isa<PHINode>(Root))
10939     return false;
10940   // Start analysis starting from Root instruction. If horizontal reduction is
10941   // found, try to vectorize it. If it is not a horizontal reduction or
10942   // vectorization is not possible or not effective, and currently analyzed
10943   // instruction is a binary operation, try to vectorize the operands, using
10944   // pre-order DFS traversal order. If the operands were not vectorized, repeat
10945   // the same procedure considering each operand as a possible root of the
10946   // horizontal reduction.
10947   // Interrupt the process if the Root instruction itself was vectorized or all
10948   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
10949   // Skip the analysis of CmpInsts. Compiler implements postanalysis of the
10950   // CmpInsts so we can skip extra attempts in
10951   // tryToVectorizeHorReductionOrInstOperands and save compile time.
10952   std::queue<std::pair<Instruction *, unsigned>> Stack;
10953   Stack.emplace(Root, 0);
10954   SmallPtrSet<Value *, 8> VisitedInstrs;
10955   SmallVector<WeakTrackingVH> PostponedInsts;
10956   bool Res = false;
10957   auto &&TryToReduce = [TTI, &SE, &DL, &P, &R, &TLI](Instruction *Inst,
10958                                                      Value *&B0,
10959                                                      Value *&B1) -> Value * {
10960     if (R.isAnalizedReductionRoot(Inst))
10961       return nullptr;
10962     bool IsBinop = matchRdxBop(Inst, B0, B1);
10963     bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value()));
10964     if (IsBinop || IsSelect) {
10965       HorizontalReduction HorRdx;
10966       if (HorRdx.matchAssociativeReduction(P, Inst, SE, DL, TLI))
10967         return HorRdx.tryToReduce(R, TTI);
10968     }
10969     return nullptr;
10970   };
10971   while (!Stack.empty()) {
10972     Instruction *Inst;
10973     unsigned Level;
10974     std::tie(Inst, Level) = Stack.front();
10975     Stack.pop();
10976     // Do not try to analyze instruction that has already been vectorized.
10977     // This may happen when we vectorize instruction operands on a previous
10978     // iteration while stack was populated before that happened.
10979     if (R.isDeleted(Inst))
10980       continue;
10981     Value *B0 = nullptr, *B1 = nullptr;
10982     if (Value *V = TryToReduce(Inst, B0, B1)) {
10983       Res = true;
10984       // Set P to nullptr to avoid re-analysis of phi node in
10985       // matchAssociativeReduction function unless this is the root node.
10986       P = nullptr;
10987       if (auto *I = dyn_cast<Instruction>(V)) {
10988         // Try to find another reduction.
10989         Stack.emplace(I, Level);
10990         continue;
10991       }
10992     } else {
10993       bool IsBinop = B0 && B1;
10994       if (P && IsBinop) {
10995         Inst = dyn_cast<Instruction>(B0);
10996         if (Inst == P)
10997           Inst = dyn_cast<Instruction>(B1);
10998         if (!Inst) {
10999           // Set P to nullptr to avoid re-analysis of phi node in
11000           // matchAssociativeReduction function unless this is the root node.
11001           P = nullptr;
11002           continue;
11003         }
11004       }
11005       // Set P to nullptr to avoid re-analysis of phi node in
11006       // matchAssociativeReduction function unless this is the root node.
11007       P = nullptr;
11008       // Do not try to vectorize CmpInst operands, this is done separately.
11009       // Final attempt for binop args vectorization should happen after the loop
11010       // to try to find reductions.
11011       if (!isa<CmpInst, InsertElementInst, InsertValueInst>(Inst))
11012         PostponedInsts.push_back(Inst);
11013     }
11014 
11015     // Try to vectorize operands.
11016     // Continue analysis for the instruction from the same basic block only to
11017     // save compile time.
11018     if (++Level < RecursionMaxDepth)
11019       for (auto *Op : Inst->operand_values())
11020         if (VisitedInstrs.insert(Op).second)
11021           if (auto *I = dyn_cast<Instruction>(Op))
11022             // Do not try to vectorize CmpInst operands,  this is done
11023             // separately.
11024             if (!isa<PHINode, CmpInst, InsertElementInst, InsertValueInst>(I) &&
11025                 !R.isDeleted(I) && I->getParent() == BB)
11026               Stack.emplace(I, Level);
11027   }
11028   // Try to vectorized binops where reductions were not found.
11029   for (Value *V : PostponedInsts)
11030     if (auto *Inst = dyn_cast<Instruction>(V))
11031       if (!R.isDeleted(Inst))
11032         Res |= Vectorize(Inst, R);
11033   return Res;
11034 }
11035 
11036 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
11037                                                  BasicBlock *BB, BoUpSLP &R,
11038                                                  TargetTransformInfo *TTI) {
11039   auto *I = dyn_cast_or_null<Instruction>(V);
11040   if (!I)
11041     return false;
11042 
11043   if (!isa<BinaryOperator>(I))
11044     P = nullptr;
11045   // Try to match and vectorize a horizontal reduction.
11046   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
11047     return tryToVectorize(I, R);
11048   };
11049   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI, *SE, *DL,
11050                                                   *TLI, ExtraVectorization);
11051 }
11052 
11053 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
11054                                                  BasicBlock *BB, BoUpSLP &R) {
11055   const DataLayout &DL = BB->getModule()->getDataLayout();
11056   if (!R.canMapToVector(IVI->getType(), DL))
11057     return false;
11058 
11059   SmallVector<Value *, 16> BuildVectorOpds;
11060   SmallVector<Value *, 16> BuildVectorInsts;
11061   if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts))
11062     return false;
11063 
11064   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
11065   // Aggregate value is unlikely to be processed in vector register.
11066   return tryToVectorizeList(BuildVectorOpds, R);
11067 }
11068 
11069 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
11070                                                    BasicBlock *BB, BoUpSLP &R) {
11071   SmallVector<Value *, 16> BuildVectorInsts;
11072   SmallVector<Value *, 16> BuildVectorOpds;
11073   SmallVector<int> Mask;
11074   if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
11075       (llvm::all_of(
11076            BuildVectorOpds,
11077            [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) &&
11078        isFixedVectorShuffle(BuildVectorOpds, Mask)))
11079     return false;
11080 
11081   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n");
11082   return tryToVectorizeList(BuildVectorInsts, R);
11083 }
11084 
11085 template <typename T>
11086 static bool
11087 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming,
11088                        function_ref<unsigned(T *)> Limit,
11089                        function_ref<bool(T *, T *)> Comparator,
11090                        function_ref<bool(T *, T *)> AreCompatible,
11091                        function_ref<bool(ArrayRef<T *>, bool)> TryToVectorizeHelper,
11092                        bool LimitForRegisterSize) {
11093   bool Changed = false;
11094   // Sort by type, parent, operands.
11095   stable_sort(Incoming, Comparator);
11096 
11097   // Try to vectorize elements base on their type.
11098   SmallVector<T *> Candidates;
11099   for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) {
11100     // Look for the next elements with the same type, parent and operand
11101     // kinds.
11102     auto *SameTypeIt = IncIt;
11103     while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt))
11104       ++SameTypeIt;
11105 
11106     // Try to vectorize them.
11107     unsigned NumElts = (SameTypeIt - IncIt);
11108     LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes ("
11109                       << NumElts << ")\n");
11110     // The vectorization is a 3-state attempt:
11111     // 1. Try to vectorize instructions with the same/alternate opcodes with the
11112     // size of maximal register at first.
11113     // 2. Try to vectorize remaining instructions with the same type, if
11114     // possible. This may result in the better vectorization results rather than
11115     // if we try just to vectorize instructions with the same/alternate opcodes.
11116     // 3. Final attempt to try to vectorize all instructions with the
11117     // same/alternate ops only, this may result in some extra final
11118     // vectorization.
11119     if (NumElts > 1 &&
11120         TryToVectorizeHelper(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) {
11121       // Success start over because instructions might have been changed.
11122       Changed = true;
11123     } else if (NumElts < Limit(*IncIt) &&
11124                (Candidates.empty() ||
11125                 Candidates.front()->getType() == (*IncIt)->getType())) {
11126       Candidates.append(IncIt, std::next(IncIt, NumElts));
11127     }
11128     // Final attempt to vectorize instructions with the same types.
11129     if (Candidates.size() > 1 &&
11130         (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) {
11131       if (TryToVectorizeHelper(Candidates, /*LimitForRegisterSize=*/false)) {
11132         // Success start over because instructions might have been changed.
11133         Changed = true;
11134       } else if (LimitForRegisterSize) {
11135         // Try to vectorize using small vectors.
11136         for (auto *It = Candidates.begin(), *End = Candidates.end();
11137              It != End;) {
11138           auto *SameTypeIt = It;
11139           while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It))
11140             ++SameTypeIt;
11141           unsigned NumElts = (SameTypeIt - It);
11142           if (NumElts > 1 && TryToVectorizeHelper(makeArrayRef(It, NumElts),
11143                                             /*LimitForRegisterSize=*/false))
11144             Changed = true;
11145           It = SameTypeIt;
11146         }
11147       }
11148       Candidates.clear();
11149     }
11150 
11151     // Start over at the next instruction of a different type (or the end).
11152     IncIt = SameTypeIt;
11153   }
11154   return Changed;
11155 }
11156 
11157 /// Compare two cmp instructions. If IsCompatibility is true, function returns
11158 /// true if 2 cmps have same/swapped predicates and mos compatible corresponding
11159 /// operands. If IsCompatibility is false, function implements strict weak
11160 /// ordering relation between two cmp instructions, returning true if the first
11161 /// instruction is "less" than the second, i.e. its predicate is less than the
11162 /// predicate of the second or the operands IDs are less than the operands IDs
11163 /// of the second cmp instruction.
11164 template <bool IsCompatibility>
11165 static bool compareCmp(Value *V, Value *V2,
11166                        function_ref<bool(Instruction *)> IsDeleted) {
11167   auto *CI1 = cast<CmpInst>(V);
11168   auto *CI2 = cast<CmpInst>(V2);
11169   if (IsDeleted(CI2) || !isValidElementType(CI2->getType()))
11170     return false;
11171   if (CI1->getOperand(0)->getType()->getTypeID() <
11172       CI2->getOperand(0)->getType()->getTypeID())
11173     return !IsCompatibility;
11174   if (CI1->getOperand(0)->getType()->getTypeID() >
11175       CI2->getOperand(0)->getType()->getTypeID())
11176     return false;
11177   CmpInst::Predicate Pred1 = CI1->getPredicate();
11178   CmpInst::Predicate Pred2 = CI2->getPredicate();
11179   CmpInst::Predicate SwapPred1 = CmpInst::getSwappedPredicate(Pred1);
11180   CmpInst::Predicate SwapPred2 = CmpInst::getSwappedPredicate(Pred2);
11181   CmpInst::Predicate BasePred1 = std::min(Pred1, SwapPred1);
11182   CmpInst::Predicate BasePred2 = std::min(Pred2, SwapPred2);
11183   if (BasePred1 < BasePred2)
11184     return !IsCompatibility;
11185   if (BasePred1 > BasePred2)
11186     return false;
11187   // Compare operands.
11188   bool LEPreds = Pred1 <= Pred2;
11189   bool GEPreds = Pred1 >= Pred2;
11190   for (int I = 0, E = CI1->getNumOperands(); I < E; ++I) {
11191     auto *Op1 = CI1->getOperand(LEPreds ? I : E - I - 1);
11192     auto *Op2 = CI2->getOperand(GEPreds ? I : E - I - 1);
11193     if (Op1->getValueID() < Op2->getValueID())
11194       return !IsCompatibility;
11195     if (Op1->getValueID() > Op2->getValueID())
11196       return false;
11197     if (auto *I1 = dyn_cast<Instruction>(Op1))
11198       if (auto *I2 = dyn_cast<Instruction>(Op2)) {
11199         if (I1->getParent() != I2->getParent())
11200           return false;
11201         InstructionsState S = getSameOpcode({I1, I2});
11202         if (S.getOpcode())
11203           continue;
11204         return false;
11205       }
11206   }
11207   return IsCompatibility;
11208 }
11209 
11210 bool SLPVectorizerPass::vectorizeSimpleInstructions(
11211     SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R,
11212     bool AtTerminator) {
11213   bool OpsChanged = false;
11214   SmallVector<Instruction *, 4> PostponedCmps;
11215   for (auto *I : reverse(Instructions)) {
11216     if (R.isDeleted(I))
11217       continue;
11218     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I)) {
11219       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
11220     } else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I)) {
11221       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
11222     } else if (isa<CmpInst>(I)) {
11223       PostponedCmps.push_back(I);
11224       continue;
11225     }
11226     // Try to find reductions in buildvector sequnces.
11227     OpsChanged |= vectorizeRootInstruction(nullptr, I, BB, R, TTI);
11228   }
11229   if (AtTerminator) {
11230     // Try to find reductions first.
11231     for (Instruction *I : PostponedCmps) {
11232       if (R.isDeleted(I))
11233         continue;
11234       for (Value *Op : I->operands())
11235         OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI);
11236     }
11237     // Try to vectorize operands as vector bundles.
11238     for (Instruction *I : PostponedCmps) {
11239       if (R.isDeleted(I))
11240         continue;
11241       OpsChanged |= tryToVectorize(I, R);
11242     }
11243     // Try to vectorize list of compares.
11244     // Sort by type, compare predicate, etc.
11245     auto &&CompareSorter = [&R](Value *V, Value *V2) {
11246       return compareCmp<false>(V, V2,
11247                                [&R](Instruction *I) { return R.isDeleted(I); });
11248     };
11249 
11250     auto &&AreCompatibleCompares = [&R](Value *V1, Value *V2) {
11251       if (V1 == V2)
11252         return true;
11253       return compareCmp<true>(V1, V2,
11254                               [&R](Instruction *I) { return R.isDeleted(I); });
11255     };
11256     auto Limit = [&R](Value *V) {
11257       unsigned EltSize = R.getVectorElementSize(V);
11258       return std::max(2U, R.getMaxVecRegSize() / EltSize);
11259     };
11260 
11261     SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end());
11262     OpsChanged |= tryToVectorizeSequence<Value>(
11263         Vals, Limit, CompareSorter, AreCompatibleCompares,
11264         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
11265           // Exclude possible reductions from other blocks.
11266           bool ArePossiblyReducedInOtherBlock =
11267               any_of(Candidates, [](Value *V) {
11268                 return any_of(V->users(), [V](User *U) {
11269                   return isa<SelectInst>(U) &&
11270                          cast<SelectInst>(U)->getParent() !=
11271                              cast<Instruction>(V)->getParent();
11272                 });
11273               });
11274           if (ArePossiblyReducedInOtherBlock)
11275             return false;
11276           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
11277         },
11278         /*LimitForRegisterSize=*/true);
11279     Instructions.clear();
11280   } else {
11281     // Insert in reverse order since the PostponedCmps vector was filled in
11282     // reverse order.
11283     Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend());
11284   }
11285   return OpsChanged;
11286 }
11287 
11288 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
11289   bool Changed = false;
11290   SmallVector<Value *, 4> Incoming;
11291   SmallPtrSet<Value *, 16> VisitedInstrs;
11292   // Maps phi nodes to the non-phi nodes found in the use tree for each phi
11293   // node. Allows better to identify the chains that can be vectorized in the
11294   // better way.
11295   DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes;
11296   auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) {
11297     assert(isValidElementType(V1->getType()) &&
11298            isValidElementType(V2->getType()) &&
11299            "Expected vectorizable types only.");
11300     // It is fine to compare type IDs here, since we expect only vectorizable
11301     // types, like ints, floats and pointers, we don't care about other type.
11302     if (V1->getType()->getTypeID() < V2->getType()->getTypeID())
11303       return true;
11304     if (V1->getType()->getTypeID() > V2->getType()->getTypeID())
11305       return false;
11306     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
11307     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
11308     if (Opcodes1.size() < Opcodes2.size())
11309       return true;
11310     if (Opcodes1.size() > Opcodes2.size())
11311       return false;
11312     Optional<bool> ConstOrder;
11313     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
11314       // Undefs are compatible with any other value.
11315       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) {
11316         if (!ConstOrder)
11317           ConstOrder =
11318               !isa<UndefValue>(Opcodes1[I]) && isa<UndefValue>(Opcodes2[I]);
11319         continue;
11320       }
11321       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
11322         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
11323           DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent());
11324           DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent());
11325           if (!NodeI1)
11326             return NodeI2 != nullptr;
11327           if (!NodeI2)
11328             return false;
11329           assert((NodeI1 == NodeI2) ==
11330                      (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
11331                  "Different nodes should have different DFS numbers");
11332           if (NodeI1 != NodeI2)
11333             return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
11334           InstructionsState S = getSameOpcode({I1, I2});
11335           if (S.getOpcode())
11336             continue;
11337           return I1->getOpcode() < I2->getOpcode();
11338         }
11339       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) {
11340         if (!ConstOrder)
11341           ConstOrder = Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID();
11342         continue;
11343       }
11344       if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID())
11345         return true;
11346       if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID())
11347         return false;
11348     }
11349     return ConstOrder && *ConstOrder;
11350   };
11351   auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) {
11352     if (V1 == V2)
11353       return true;
11354     if (V1->getType() != V2->getType())
11355       return false;
11356     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
11357     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
11358     if (Opcodes1.size() != Opcodes2.size())
11359       return false;
11360     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
11361       // Undefs are compatible with any other value.
11362       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
11363         continue;
11364       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
11365         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
11366           if (I1->getParent() != I2->getParent())
11367             return false;
11368           InstructionsState S = getSameOpcode({I1, I2});
11369           if (S.getOpcode())
11370             continue;
11371           return false;
11372         }
11373       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
11374         continue;
11375       if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID())
11376         return false;
11377     }
11378     return true;
11379   };
11380   auto Limit = [&R](Value *V) {
11381     unsigned EltSize = R.getVectorElementSize(V);
11382     return std::max(2U, R.getMaxVecRegSize() / EltSize);
11383   };
11384 
11385   bool HaveVectorizedPhiNodes = false;
11386   do {
11387     // Collect the incoming values from the PHIs.
11388     Incoming.clear();
11389     for (Instruction &I : *BB) {
11390       PHINode *P = dyn_cast<PHINode>(&I);
11391       if (!P)
11392         break;
11393 
11394       // No need to analyze deleted, vectorized and non-vectorizable
11395       // instructions.
11396       if (!VisitedInstrs.count(P) && !R.isDeleted(P) &&
11397           isValidElementType(P->getType()))
11398         Incoming.push_back(P);
11399     }
11400 
11401     // Find the corresponding non-phi nodes for better matching when trying to
11402     // build the tree.
11403     for (Value *V : Incoming) {
11404       SmallVectorImpl<Value *> &Opcodes =
11405           PHIToOpcodes.try_emplace(V).first->getSecond();
11406       if (!Opcodes.empty())
11407         continue;
11408       SmallVector<Value *, 4> Nodes(1, V);
11409       SmallPtrSet<Value *, 4> Visited;
11410       while (!Nodes.empty()) {
11411         auto *PHI = cast<PHINode>(Nodes.pop_back_val());
11412         if (!Visited.insert(PHI).second)
11413           continue;
11414         for (Value *V : PHI->incoming_values()) {
11415           if (auto *PHI1 = dyn_cast<PHINode>((V))) {
11416             Nodes.push_back(PHI1);
11417             continue;
11418           }
11419           Opcodes.emplace_back(V);
11420         }
11421       }
11422     }
11423 
11424     HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>(
11425         Incoming, Limit, PHICompare, AreCompatiblePHIs,
11426         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
11427           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
11428         },
11429         /*LimitForRegisterSize=*/true);
11430     Changed |= HaveVectorizedPhiNodes;
11431     VisitedInstrs.insert(Incoming.begin(), Incoming.end());
11432   } while (HaveVectorizedPhiNodes);
11433 
11434   VisitedInstrs.clear();
11435 
11436   SmallVector<Instruction *, 8> PostProcessInstructions;
11437   SmallDenseSet<Instruction *, 4> KeyNodes;
11438   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
11439     // Skip instructions with scalable type. The num of elements is unknown at
11440     // compile-time for scalable type.
11441     if (isa<ScalableVectorType>(it->getType()))
11442       continue;
11443 
11444     // Skip instructions marked for the deletion.
11445     if (R.isDeleted(&*it))
11446       continue;
11447     // We may go through BB multiple times so skip the one we have checked.
11448     if (!VisitedInstrs.insert(&*it).second) {
11449       if (it->use_empty() && KeyNodes.contains(&*it) &&
11450           vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
11451                                       it->isTerminator())) {
11452         // We would like to start over since some instructions are deleted
11453         // and the iterator may become invalid value.
11454         Changed = true;
11455         it = BB->begin();
11456         e = BB->end();
11457       }
11458       continue;
11459     }
11460 
11461     if (isa<DbgInfoIntrinsic>(it))
11462       continue;
11463 
11464     // Try to vectorize reductions that use PHINodes.
11465     if (PHINode *P = dyn_cast<PHINode>(it)) {
11466       // Check that the PHI is a reduction PHI.
11467       if (P->getNumIncomingValues() == 2) {
11468         // Try to match and vectorize a horizontal reduction.
11469         if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
11470                                      TTI)) {
11471           Changed = true;
11472           it = BB->begin();
11473           e = BB->end();
11474           continue;
11475         }
11476       }
11477       // Try to vectorize the incoming values of the PHI, to catch reductions
11478       // that feed into PHIs.
11479       for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) {
11480         // Skip if the incoming block is the current BB for now. Also, bypass
11481         // unreachable IR for efficiency and to avoid crashing.
11482         // TODO: Collect the skipped incoming values and try to vectorize them
11483         // after processing BB.
11484         if (BB == P->getIncomingBlock(I) ||
11485             !DT->isReachableFromEntry(P->getIncomingBlock(I)))
11486           continue;
11487 
11488         Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I),
11489                                             P->getIncomingBlock(I), R, TTI);
11490       }
11491       continue;
11492     }
11493 
11494     // Ran into an instruction without users, like terminator, or function call
11495     // with ignored return value, store. Ignore unused instructions (basing on
11496     // instruction type, except for CallInst and InvokeInst).
11497     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
11498                             isa<InvokeInst>(it))) {
11499       KeyNodes.insert(&*it);
11500       bool OpsChanged = false;
11501       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
11502         for (auto *V : it->operand_values()) {
11503           // Try to match and vectorize a horizontal reduction.
11504           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
11505         }
11506       }
11507       // Start vectorization of post-process list of instructions from the
11508       // top-tree instructions to try to vectorize as many instructions as
11509       // possible.
11510       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
11511                                                 it->isTerminator());
11512       if (OpsChanged) {
11513         // We would like to start over since some instructions are deleted
11514         // and the iterator may become invalid value.
11515         Changed = true;
11516         it = BB->begin();
11517         e = BB->end();
11518         continue;
11519       }
11520     }
11521 
11522     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
11523         isa<InsertValueInst>(it))
11524       PostProcessInstructions.push_back(&*it);
11525   }
11526 
11527   return Changed;
11528 }
11529 
11530 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
11531   auto Changed = false;
11532   for (auto &Entry : GEPs) {
11533     // If the getelementptr list has fewer than two elements, there's nothing
11534     // to do.
11535     if (Entry.second.size() < 2)
11536       continue;
11537 
11538     LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
11539                       << Entry.second.size() << ".\n");
11540 
11541     // Process the GEP list in chunks suitable for the target's supported
11542     // vector size. If a vector register can't hold 1 element, we are done. We
11543     // are trying to vectorize the index computations, so the maximum number of
11544     // elements is based on the size of the index expression, rather than the
11545     // size of the GEP itself (the target's pointer size).
11546     unsigned MaxVecRegSize = R.getMaxVecRegSize();
11547     unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin());
11548     if (MaxVecRegSize < EltSize)
11549       continue;
11550 
11551     unsigned MaxElts = MaxVecRegSize / EltSize;
11552     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
11553       auto Len = std::min<unsigned>(BE - BI, MaxElts);
11554       ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len);
11555 
11556       // Initialize a set a candidate getelementptrs. Note that we use a
11557       // SetVector here to preserve program order. If the index computations
11558       // are vectorizable and begin with loads, we want to minimize the chance
11559       // of having to reorder them later.
11560       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
11561 
11562       // Some of the candidates may have already been vectorized after we
11563       // initially collected them. If so, they are marked as deleted, so remove
11564       // them from the set of candidates.
11565       Candidates.remove_if(
11566           [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
11567 
11568       // Remove from the set of candidates all pairs of getelementptrs with
11569       // constant differences. Such getelementptrs are likely not good
11570       // candidates for vectorization in a bottom-up phase since one can be
11571       // computed from the other. We also ensure all candidate getelementptr
11572       // indices are unique.
11573       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
11574         auto *GEPI = GEPList[I];
11575         if (!Candidates.count(GEPI))
11576           continue;
11577         auto *SCEVI = SE->getSCEV(GEPList[I]);
11578         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
11579           auto *GEPJ = GEPList[J];
11580           auto *SCEVJ = SE->getSCEV(GEPList[J]);
11581           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
11582             Candidates.remove(GEPI);
11583             Candidates.remove(GEPJ);
11584           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
11585             Candidates.remove(GEPJ);
11586           }
11587         }
11588       }
11589 
11590       // We break out of the above computation as soon as we know there are
11591       // fewer than two candidates remaining.
11592       if (Candidates.size() < 2)
11593         continue;
11594 
11595       // Add the single, non-constant index of each candidate to the bundle. We
11596       // ensured the indices met these constraints when we originally collected
11597       // the getelementptrs.
11598       SmallVector<Value *, 16> Bundle(Candidates.size());
11599       auto BundleIndex = 0u;
11600       for (auto *V : Candidates) {
11601         auto *GEP = cast<GetElementPtrInst>(V);
11602         auto *GEPIdx = GEP->idx_begin()->get();
11603         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
11604         Bundle[BundleIndex++] = GEPIdx;
11605       }
11606 
11607       // Try and vectorize the indices. We are currently only interested in
11608       // gather-like cases of the form:
11609       //
11610       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
11611       //
11612       // where the loads of "a", the loads of "b", and the subtractions can be
11613       // performed in parallel. It's likely that detecting this pattern in a
11614       // bottom-up phase will be simpler and less costly than building a
11615       // full-blown top-down phase beginning at the consecutive loads.
11616       Changed |= tryToVectorizeList(Bundle, R);
11617     }
11618   }
11619   return Changed;
11620 }
11621 
11622 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
11623   bool Changed = false;
11624   // Sort by type, base pointers and values operand. Value operands must be
11625   // compatible (have the same opcode, same parent), otherwise it is
11626   // definitely not profitable to try to vectorize them.
11627   auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) {
11628     if (V->getPointerOperandType()->getTypeID() <
11629         V2->getPointerOperandType()->getTypeID())
11630       return true;
11631     if (V->getPointerOperandType()->getTypeID() >
11632         V2->getPointerOperandType()->getTypeID())
11633       return false;
11634     // UndefValues are compatible with all other values.
11635     if (isa<UndefValue>(V->getValueOperand()) ||
11636         isa<UndefValue>(V2->getValueOperand()))
11637       return false;
11638     if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand()))
11639       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
11640         DomTreeNodeBase<llvm::BasicBlock> *NodeI1 =
11641             DT->getNode(I1->getParent());
11642         DomTreeNodeBase<llvm::BasicBlock> *NodeI2 =
11643             DT->getNode(I2->getParent());
11644         assert(NodeI1 && "Should only process reachable instructions");
11645         assert(NodeI2 && "Should only process reachable instructions");
11646         assert((NodeI1 == NodeI2) ==
11647                    (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
11648                "Different nodes should have different DFS numbers");
11649         if (NodeI1 != NodeI2)
11650           return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
11651         InstructionsState S = getSameOpcode({I1, I2});
11652         if (S.getOpcode())
11653           return false;
11654         return I1->getOpcode() < I2->getOpcode();
11655       }
11656     if (isa<Constant>(V->getValueOperand()) &&
11657         isa<Constant>(V2->getValueOperand()))
11658       return false;
11659     return V->getValueOperand()->getValueID() <
11660            V2->getValueOperand()->getValueID();
11661   };
11662 
11663   auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) {
11664     if (V1 == V2)
11665       return true;
11666     if (V1->getPointerOperandType() != V2->getPointerOperandType())
11667       return false;
11668     // Undefs are compatible with any other value.
11669     if (isa<UndefValue>(V1->getValueOperand()) ||
11670         isa<UndefValue>(V2->getValueOperand()))
11671       return true;
11672     if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand()))
11673       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
11674         if (I1->getParent() != I2->getParent())
11675           return false;
11676         InstructionsState S = getSameOpcode({I1, I2});
11677         return S.getOpcode() > 0;
11678       }
11679     if (isa<Constant>(V1->getValueOperand()) &&
11680         isa<Constant>(V2->getValueOperand()))
11681       return true;
11682     return V1->getValueOperand()->getValueID() ==
11683            V2->getValueOperand()->getValueID();
11684   };
11685   auto Limit = [&R, this](StoreInst *SI) {
11686     unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
11687     return R.getMinVF(EltSize);
11688   };
11689 
11690   // Attempt to sort and vectorize each of the store-groups.
11691   for (auto &Pair : Stores) {
11692     if (Pair.second.size() < 2)
11693       continue;
11694 
11695     LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
11696                       << Pair.second.size() << ".\n");
11697 
11698     if (!isValidElementType(Pair.second.front()->getValueOperand()->getType()))
11699       continue;
11700 
11701     Changed |= tryToVectorizeSequence<StoreInst>(
11702         Pair.second, Limit, StoreSorter, AreCompatibleStores,
11703         [this, &R](ArrayRef<StoreInst *> Candidates, bool) {
11704           return vectorizeStores(Candidates, R);
11705         },
11706         /*LimitForRegisterSize=*/false);
11707   }
11708   return Changed;
11709 }
11710 
11711 char SLPVectorizer::ID = 0;
11712 
11713 static const char lv_name[] = "SLP Vectorizer";
11714 
11715 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
11716 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
11717 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
11718 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
11719 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
11720 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
11721 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
11722 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
11723 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
11724 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
11725 
11726 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
11727