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/DebugLoc.h"
57 #include "llvm/IR/DerivedTypes.h"
58 #include "llvm/IR/Dominators.h"
59 #include "llvm/IR/Function.h"
60 #include "llvm/IR/IRBuilder.h"
61 #include "llvm/IR/InstrTypes.h"
62 #include "llvm/IR/Instruction.h"
63 #include "llvm/IR/Instructions.h"
64 #include "llvm/IR/IntrinsicInst.h"
65 #include "llvm/IR/Intrinsics.h"
66 #include "llvm/IR/Module.h"
67 #include "llvm/IR/NoFolder.h"
68 #include "llvm/IR/Operator.h"
69 #include "llvm/IR/PatternMatch.h"
70 #include "llvm/IR/Type.h"
71 #include "llvm/IR/Use.h"
72 #include "llvm/IR/User.h"
73 #include "llvm/IR/Value.h"
74 #include "llvm/IR/ValueHandle.h"
75 #include "llvm/IR/Verifier.h"
76 #include "llvm/InitializePasses.h"
77 #include "llvm/Pass.h"
78 #include "llvm/Support/Casting.h"
79 #include "llvm/Support/CommandLine.h"
80 #include "llvm/Support/Compiler.h"
81 #include "llvm/Support/DOTGraphTraits.h"
82 #include "llvm/Support/Debug.h"
83 #include "llvm/Support/ErrorHandling.h"
84 #include "llvm/Support/GraphWriter.h"
85 #include "llvm/Support/InstructionCost.h"
86 #include "llvm/Support/KnownBits.h"
87 #include "llvm/Support/MathExtras.h"
88 #include "llvm/Support/raw_ostream.h"
89 #include "llvm/Transforms/Utils/InjectTLIMappings.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 static cl::opt<bool>
168     ViewSLPTree("view-slp-tree", cl::Hidden,
169                 cl::desc("Display the SLP trees with Graphviz"));
170 
171 // Limit the number of alias checks. The limit is chosen so that
172 // it has no negative effect on the llvm benchmarks.
173 static const unsigned AliasedCheckLimit = 10;
174 
175 // Another limit for the alias checks: The maximum distance between load/store
176 // instructions where alias checks are done.
177 // This limit is useful for very large basic blocks.
178 static const unsigned MaxMemDepDistance = 160;
179 
180 /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
181 /// regions to be handled.
182 static const int MinScheduleRegionSize = 16;
183 
184 /// Predicate for the element types that the SLP vectorizer supports.
185 ///
186 /// The most important thing to filter here are types which are invalid in LLVM
187 /// vectors. We also filter target specific types which have absolutely no
188 /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
189 /// avoids spending time checking the cost model and realizing that they will
190 /// be inevitably scalarized.
191 static bool isValidElementType(Type *Ty) {
192   return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() &&
193          !Ty->isPPC_FP128Ty();
194 }
195 
196 /// \returns True if the value is a constant (but not globals/constant
197 /// expressions).
198 static bool isConstant(Value *V) {
199   return isa<Constant>(V) && !isa<ConstantExpr>(V) && !isa<GlobalValue>(V);
200 }
201 
202 /// Checks if \p V is one of vector-like instructions, i.e. undef,
203 /// insertelement/extractelement with constant indices for fixed vector type or
204 /// extractvalue instruction.
205 static bool isVectorLikeInstWithConstOps(Value *V) {
206   if (!isa<InsertElementInst, ExtractElementInst>(V) &&
207       !isa<ExtractValueInst, UndefValue>(V))
208     return false;
209   auto *I = dyn_cast<Instruction>(V);
210   if (!I || isa<ExtractValueInst>(I))
211     return true;
212   if (!isa<FixedVectorType>(I->getOperand(0)->getType()))
213     return false;
214   if (isa<ExtractElementInst>(I))
215     return isConstant(I->getOperand(1));
216   assert(isa<InsertElementInst>(V) && "Expected only insertelement.");
217   return isConstant(I->getOperand(2));
218 }
219 
220 /// \returns true if all of the instructions in \p VL are in the same block or
221 /// false otherwise.
222 static bool allSameBlock(ArrayRef<Value *> VL) {
223   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
224   if (!I0)
225     return false;
226   if (all_of(VL, isVectorLikeInstWithConstOps))
227     return true;
228 
229   BasicBlock *BB = I0->getParent();
230   for (int I = 1, E = VL.size(); I < E; I++) {
231     auto *II = dyn_cast<Instruction>(VL[I]);
232     if (!II)
233       return false;
234 
235     if (BB != II->getParent())
236       return false;
237   }
238   return true;
239 }
240 
241 /// \returns True if all of the values in \p VL are constants (but not
242 /// globals/constant expressions).
243 static bool allConstant(ArrayRef<Value *> VL) {
244   // Constant expressions and globals can't be vectorized like normal integer/FP
245   // constants.
246   return all_of(VL, isConstant);
247 }
248 
249 /// \returns True if all of the values in \p VL are identical or some of them
250 /// are UndefValue.
251 static bool isSplat(ArrayRef<Value *> VL) {
252   Value *FirstNonUndef = nullptr;
253   for (Value *V : VL) {
254     if (isa<UndefValue>(V))
255       continue;
256     if (!FirstNonUndef) {
257       FirstNonUndef = V;
258       continue;
259     }
260     if (V != FirstNonUndef)
261       return false;
262   }
263   return FirstNonUndef != nullptr;
264 }
265 
266 /// \returns True if \p I is commutative, handles CmpInst and BinaryOperator.
267 static bool isCommutative(Instruction *I) {
268   if (auto *Cmp = dyn_cast<CmpInst>(I))
269     return Cmp->isCommutative();
270   if (auto *BO = dyn_cast<BinaryOperator>(I))
271     return BO->isCommutative();
272   // TODO: This should check for generic Instruction::isCommutative(), but
273   //       we need to confirm that the caller code correctly handles Intrinsics
274   //       for example (does not have 2 operands).
275   return false;
276 }
277 
278 /// Checks if the given value is actually an undefined constant vector.
279 static bool isUndefVector(const Value *V) {
280   if (isa<UndefValue>(V))
281     return true;
282   auto *C = dyn_cast<Constant>(V);
283   if (!C)
284     return false;
285   if (!C->containsUndefOrPoisonElement())
286     return false;
287   auto *VecTy = dyn_cast<FixedVectorType>(C->getType());
288   if (!VecTy)
289     return false;
290   for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
291     if (Constant *Elem = C->getAggregateElement(I))
292       if (!isa<UndefValue>(Elem))
293         return false;
294   }
295   return true;
296 }
297 
298 /// Checks if the vector of instructions can be represented as a shuffle, like:
299 /// %x0 = extractelement <4 x i8> %x, i32 0
300 /// %x3 = extractelement <4 x i8> %x, i32 3
301 /// %y1 = extractelement <4 x i8> %y, i32 1
302 /// %y2 = extractelement <4 x i8> %y, i32 2
303 /// %x0x0 = mul i8 %x0, %x0
304 /// %x3x3 = mul i8 %x3, %x3
305 /// %y1y1 = mul i8 %y1, %y1
306 /// %y2y2 = mul i8 %y2, %y2
307 /// %ins1 = insertelement <4 x i8> poison, i8 %x0x0, i32 0
308 /// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1
309 /// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2
310 /// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3
311 /// ret <4 x i8> %ins4
312 /// can be transformed into:
313 /// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5,
314 ///                                                         i32 6>
315 /// %2 = mul <4 x i8> %1, %1
316 /// ret <4 x i8> %2
317 /// We convert this initially to something like:
318 /// %x0 = extractelement <4 x i8> %x, i32 0
319 /// %x3 = extractelement <4 x i8> %x, i32 3
320 /// %y1 = extractelement <4 x i8> %y, i32 1
321 /// %y2 = extractelement <4 x i8> %y, i32 2
322 /// %1 = insertelement <4 x i8> poison, i8 %x0, i32 0
323 /// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1
324 /// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2
325 /// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3
326 /// %5 = mul <4 x i8> %4, %4
327 /// %6 = extractelement <4 x i8> %5, i32 0
328 /// %ins1 = insertelement <4 x i8> poison, i8 %6, i32 0
329 /// %7 = extractelement <4 x i8> %5, i32 1
330 /// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1
331 /// %8 = extractelement <4 x i8> %5, i32 2
332 /// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2
333 /// %9 = extractelement <4 x i8> %5, i32 3
334 /// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3
335 /// ret <4 x i8> %ins4
336 /// InstCombiner transforms this into a shuffle and vector mul
337 /// Mask will return the Shuffle Mask equivalent to the extracted elements.
338 /// TODO: Can we split off and reuse the shuffle mask detection from
339 /// TargetTransformInfo::getInstructionThroughput?
340 static Optional<TargetTransformInfo::ShuffleKind>
341 isFixedVectorShuffle(ArrayRef<Value *> VL, SmallVectorImpl<int> &Mask) {
342   const auto *It =
343       find_if(VL, [](Value *V) { return isa<ExtractElementInst>(V); });
344   if (It == VL.end())
345     return None;
346   auto *EI0 = cast<ExtractElementInst>(*It);
347   if (isa<ScalableVectorType>(EI0->getVectorOperandType()))
348     return None;
349   unsigned Size =
350       cast<FixedVectorType>(EI0->getVectorOperandType())->getNumElements();
351   Value *Vec1 = nullptr;
352   Value *Vec2 = nullptr;
353   enum ShuffleMode { Unknown, Select, Permute };
354   ShuffleMode CommonShuffleMode = Unknown;
355   Mask.assign(VL.size(), UndefMaskElem);
356   for (unsigned I = 0, E = VL.size(); I < E; ++I) {
357     // Undef can be represented as an undef element in a vector.
358     if (isa<UndefValue>(VL[I]))
359       continue;
360     auto *EI = cast<ExtractElementInst>(VL[I]);
361     if (isa<ScalableVectorType>(EI->getVectorOperandType()))
362       return None;
363     auto *Vec = EI->getVectorOperand();
364     // We can extractelement from undef or poison vector.
365     if (isUndefVector(Vec))
366       continue;
367     // All vector operands must have the same number of vector elements.
368     if (cast<FixedVectorType>(Vec->getType())->getNumElements() != Size)
369       return None;
370     if (isa<UndefValue>(EI->getIndexOperand()))
371       continue;
372     auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand());
373     if (!Idx)
374       return None;
375     // Undefined behavior if Idx is negative or >= Size.
376     if (Idx->getValue().uge(Size))
377       continue;
378     unsigned IntIdx = Idx->getValue().getZExtValue();
379     Mask[I] = IntIdx;
380     // For correct shuffling we have to have at most 2 different vector operands
381     // in all extractelement instructions.
382     if (!Vec1 || Vec1 == Vec) {
383       Vec1 = Vec;
384     } else if (!Vec2 || Vec2 == Vec) {
385       Vec2 = Vec;
386       Mask[I] += Size;
387     } else {
388       return None;
389     }
390     if (CommonShuffleMode == Permute)
391       continue;
392     // If the extract index is not the same as the operation number, it is a
393     // permutation.
394     if (IntIdx != I) {
395       CommonShuffleMode = Permute;
396       continue;
397     }
398     CommonShuffleMode = Select;
399   }
400   // If we're not crossing lanes in different vectors, consider it as blending.
401   if (CommonShuffleMode == Select && Vec2)
402     return TargetTransformInfo::SK_Select;
403   // If Vec2 was never used, we have a permutation of a single vector, otherwise
404   // we have permutation of 2 vectors.
405   return Vec2 ? TargetTransformInfo::SK_PermuteTwoSrc
406               : TargetTransformInfo::SK_PermuteSingleSrc;
407 }
408 
409 namespace {
410 
411 /// Main data required for vectorization of instructions.
412 struct InstructionsState {
413   /// The very first instruction in the list with the main opcode.
414   Value *OpValue = nullptr;
415 
416   /// The main/alternate instruction.
417   Instruction *MainOp = nullptr;
418   Instruction *AltOp = nullptr;
419 
420   /// The main/alternate opcodes for the list of instructions.
421   unsigned getOpcode() const {
422     return MainOp ? MainOp->getOpcode() : 0;
423   }
424 
425   unsigned getAltOpcode() const {
426     return AltOp ? AltOp->getOpcode() : 0;
427   }
428 
429   /// Some of the instructions in the list have alternate opcodes.
430   bool isAltShuffle() const { return AltOp != MainOp; }
431 
432   bool isOpcodeOrAlt(Instruction *I) const {
433     unsigned CheckedOpcode = I->getOpcode();
434     return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode;
435   }
436 
437   InstructionsState() = delete;
438   InstructionsState(Value *OpValue, Instruction *MainOp, Instruction *AltOp)
439       : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {}
440 };
441 
442 } // end anonymous namespace
443 
444 /// Chooses the correct key for scheduling data. If \p Op has the same (or
445 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p
446 /// OpValue.
447 static Value *isOneOf(const InstructionsState &S, Value *Op) {
448   auto *I = dyn_cast<Instruction>(Op);
449   if (I && S.isOpcodeOrAlt(I))
450     return Op;
451   return S.OpValue;
452 }
453 
454 /// \returns true if \p Opcode is allowed as part of of the main/alternate
455 /// instruction for SLP vectorization.
456 ///
457 /// Example of unsupported opcode is SDIV that can potentially cause UB if the
458 /// "shuffled out" lane would result in division by zero.
459 static bool isValidForAlternation(unsigned Opcode) {
460   if (Instruction::isIntDivRem(Opcode))
461     return false;
462 
463   return true;
464 }
465 
466 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
467                                        unsigned BaseIndex = 0);
468 
469 /// Checks if the provided operands of 2 cmp instructions are compatible, i.e.
470 /// compatible instructions or constants, or just some other regular values.
471 static bool areCompatibleCmpOps(Value *BaseOp0, Value *BaseOp1, Value *Op0,
472                                 Value *Op1) {
473   return (isConstant(BaseOp0) && isConstant(Op0)) ||
474          (isConstant(BaseOp1) && isConstant(Op1)) ||
475          (!isa<Instruction>(BaseOp0) && !isa<Instruction>(Op0) &&
476           !isa<Instruction>(BaseOp1) && !isa<Instruction>(Op1)) ||
477          getSameOpcode({BaseOp0, Op0}).getOpcode() ||
478          getSameOpcode({BaseOp1, Op1}).getOpcode();
479 }
480 
481 /// \returns analysis of the Instructions in \p VL described in
482 /// InstructionsState, the Opcode that we suppose the whole list
483 /// could be vectorized even if its structure is diverse.
484 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
485                                        unsigned BaseIndex) {
486   // Make sure these are all Instructions.
487   if (llvm::any_of(VL, [](Value *V) { return !isa<Instruction>(V); }))
488     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
489 
490   bool IsCastOp = isa<CastInst>(VL[BaseIndex]);
491   bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]);
492   bool IsCmpOp = isa<CmpInst>(VL[BaseIndex]);
493   CmpInst::Predicate BasePred =
494       IsCmpOp ? cast<CmpInst>(VL[BaseIndex])->getPredicate()
495               : CmpInst::BAD_ICMP_PREDICATE;
496   unsigned Opcode = cast<Instruction>(VL[BaseIndex])->getOpcode();
497   unsigned AltOpcode = Opcode;
498   unsigned AltIndex = BaseIndex;
499 
500   // Check for one alternate opcode from another BinaryOperator.
501   // TODO - generalize to support all operators (types, calls etc.).
502   for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) {
503     unsigned InstOpcode = cast<Instruction>(VL[Cnt])->getOpcode();
504     if (IsBinOp && isa<BinaryOperator>(VL[Cnt])) {
505       if (InstOpcode == Opcode || InstOpcode == AltOpcode)
506         continue;
507       if (Opcode == AltOpcode && isValidForAlternation(InstOpcode) &&
508           isValidForAlternation(Opcode)) {
509         AltOpcode = InstOpcode;
510         AltIndex = Cnt;
511         continue;
512       }
513     } else if (IsCastOp && isa<CastInst>(VL[Cnt])) {
514       Type *Ty0 = cast<Instruction>(VL[BaseIndex])->getOperand(0)->getType();
515       Type *Ty1 = cast<Instruction>(VL[Cnt])->getOperand(0)->getType();
516       if (Ty0 == Ty1) {
517         if (InstOpcode == Opcode || InstOpcode == AltOpcode)
518           continue;
519         if (Opcode == AltOpcode) {
520           assert(isValidForAlternation(Opcode) &&
521                  isValidForAlternation(InstOpcode) &&
522                  "Cast isn't safe for alternation, logic needs to be updated!");
523           AltOpcode = InstOpcode;
524           AltIndex = Cnt;
525           continue;
526         }
527       }
528     } else if (IsCmpOp && isa<CmpInst>(VL[Cnt])) {
529       auto *BaseInst = cast<Instruction>(VL[BaseIndex]);
530       auto *Inst = cast<Instruction>(VL[Cnt]);
531       Type *Ty0 = BaseInst->getOperand(0)->getType();
532       Type *Ty1 = Inst->getOperand(0)->getType();
533       if (Ty0 == Ty1) {
534         Value *BaseOp0 = BaseInst->getOperand(0);
535         Value *BaseOp1 = BaseInst->getOperand(1);
536         Value *Op0 = Inst->getOperand(0);
537         Value *Op1 = Inst->getOperand(1);
538         CmpInst::Predicate CurrentPred =
539             cast<CmpInst>(VL[Cnt])->getPredicate();
540         CmpInst::Predicate SwappedCurrentPred =
541             CmpInst::getSwappedPredicate(CurrentPred);
542         // Check for compatible operands. If the corresponding operands are not
543         // compatible - need to perform alternate vectorization.
544         if (InstOpcode == Opcode) {
545           if (BasePred == CurrentPred &&
546               areCompatibleCmpOps(BaseOp0, BaseOp1, Op0, Op1))
547             continue;
548           if (BasePred == SwappedCurrentPred &&
549               areCompatibleCmpOps(BaseOp0, BaseOp1, Op1, Op0))
550             continue;
551           if (E == 2 &&
552               (BasePred == CurrentPred || BasePred == SwappedCurrentPred))
553             continue;
554           auto *AltInst = cast<CmpInst>(VL[AltIndex]);
555           CmpInst::Predicate AltPred = AltInst->getPredicate();
556           Value *AltOp0 = AltInst->getOperand(0);
557           Value *AltOp1 = AltInst->getOperand(1);
558           // Check if operands are compatible with alternate operands.
559           if (AltPred == CurrentPred &&
560               areCompatibleCmpOps(AltOp0, AltOp1, Op0, Op1))
561             continue;
562           if (AltPred == SwappedCurrentPred &&
563               areCompatibleCmpOps(AltOp0, AltOp1, Op1, Op0))
564             continue;
565         }
566         if (BaseIndex == AltIndex && BasePred != CurrentPred) {
567           assert(isValidForAlternation(Opcode) &&
568                  isValidForAlternation(InstOpcode) &&
569                  "Cast isn't safe for alternation, logic needs to be updated!");
570           AltIndex = Cnt;
571           continue;
572         }
573         auto *AltInst = cast<CmpInst>(VL[AltIndex]);
574         CmpInst::Predicate AltPred = AltInst->getPredicate();
575         if (BasePred == CurrentPred || BasePred == SwappedCurrentPred ||
576             AltPred == CurrentPred || AltPred == SwappedCurrentPred)
577           continue;
578       }
579     } else if (InstOpcode == Opcode || InstOpcode == AltOpcode)
580       continue;
581     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
582   }
583 
584   return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]),
585                            cast<Instruction>(VL[AltIndex]));
586 }
587 
588 /// \returns true if all of the values in \p VL have the same type or false
589 /// otherwise.
590 static bool allSameType(ArrayRef<Value *> VL) {
591   Type *Ty = VL[0]->getType();
592   for (int i = 1, e = VL.size(); i < e; i++)
593     if (VL[i]->getType() != Ty)
594       return false;
595 
596   return true;
597 }
598 
599 /// \returns True if Extract{Value,Element} instruction extracts element Idx.
600 static Optional<unsigned> getExtractIndex(Instruction *E) {
601   unsigned Opcode = E->getOpcode();
602   assert((Opcode == Instruction::ExtractElement ||
603           Opcode == Instruction::ExtractValue) &&
604          "Expected extractelement or extractvalue instruction.");
605   if (Opcode == Instruction::ExtractElement) {
606     auto *CI = dyn_cast<ConstantInt>(E->getOperand(1));
607     if (!CI)
608       return None;
609     return CI->getZExtValue();
610   }
611   ExtractValueInst *EI = cast<ExtractValueInst>(E);
612   if (EI->getNumIndices() != 1)
613     return None;
614   return *EI->idx_begin();
615 }
616 
617 /// \returns True if in-tree use also needs extract. This refers to
618 /// possible scalar operand in vectorized instruction.
619 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
620                                     TargetLibraryInfo *TLI) {
621   unsigned Opcode = UserInst->getOpcode();
622   switch (Opcode) {
623   case Instruction::Load: {
624     LoadInst *LI = cast<LoadInst>(UserInst);
625     return (LI->getPointerOperand() == Scalar);
626   }
627   case Instruction::Store: {
628     StoreInst *SI = cast<StoreInst>(UserInst);
629     return (SI->getPointerOperand() == Scalar);
630   }
631   case Instruction::Call: {
632     CallInst *CI = cast<CallInst>(UserInst);
633     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
634     for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
635       if (hasVectorInstrinsicScalarOpd(ID, i))
636         return (CI->getArgOperand(i) == Scalar);
637     }
638     LLVM_FALLTHROUGH;
639   }
640   default:
641     return false;
642   }
643 }
644 
645 /// \returns the AA location that is being access by the instruction.
646 static MemoryLocation getLocation(Instruction *I) {
647   if (StoreInst *SI = dyn_cast<StoreInst>(I))
648     return MemoryLocation::get(SI);
649   if (LoadInst *LI = dyn_cast<LoadInst>(I))
650     return MemoryLocation::get(LI);
651   return MemoryLocation();
652 }
653 
654 /// \returns True if the instruction is not a volatile or atomic load/store.
655 static bool isSimple(Instruction *I) {
656   if (LoadInst *LI = dyn_cast<LoadInst>(I))
657     return LI->isSimple();
658   if (StoreInst *SI = dyn_cast<StoreInst>(I))
659     return SI->isSimple();
660   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
661     return !MI->isVolatile();
662   return true;
663 }
664 
665 /// Shuffles \p Mask in accordance with the given \p SubMask.
666 static void addMask(SmallVectorImpl<int> &Mask, ArrayRef<int> SubMask) {
667   if (SubMask.empty())
668     return;
669   if (Mask.empty()) {
670     Mask.append(SubMask.begin(), SubMask.end());
671     return;
672   }
673   SmallVector<int> NewMask(SubMask.size(), UndefMaskElem);
674   int TermValue = std::min(Mask.size(), SubMask.size());
675   for (int I = 0, E = SubMask.size(); I < E; ++I) {
676     if (SubMask[I] >= TermValue || SubMask[I] == UndefMaskElem ||
677         Mask[SubMask[I]] >= TermValue)
678       continue;
679     NewMask[I] = Mask[SubMask[I]];
680   }
681   Mask.swap(NewMask);
682 }
683 
684 /// Order may have elements assigned special value (size) which is out of
685 /// bounds. Such indices only appear on places which correspond to undef values
686 /// (see canReuseExtract for details) and used in order to avoid undef values
687 /// have effect on operands ordering.
688 /// The first loop below simply finds all unused indices and then the next loop
689 /// nest assigns these indices for undef values positions.
690 /// As an example below Order has two undef positions and they have assigned
691 /// values 3 and 7 respectively:
692 /// before:  6 9 5 4 9 2 1 0
693 /// after:   6 3 5 4 7 2 1 0
694 static void fixupOrderingIndices(SmallVectorImpl<unsigned> &Order) {
695   const unsigned Sz = Order.size();
696   SmallBitVector UnusedIndices(Sz, /*t=*/true);
697   SmallBitVector MaskedIndices(Sz);
698   for (unsigned I = 0; I < Sz; ++I) {
699     if (Order[I] < Sz)
700       UnusedIndices.reset(Order[I]);
701     else
702       MaskedIndices.set(I);
703   }
704   if (MaskedIndices.none())
705     return;
706   assert(UnusedIndices.count() == MaskedIndices.count() &&
707          "Non-synced masked/available indices.");
708   int Idx = UnusedIndices.find_first();
709   int MIdx = MaskedIndices.find_first();
710   while (MIdx >= 0) {
711     assert(Idx >= 0 && "Indices must be synced.");
712     Order[MIdx] = Idx;
713     Idx = UnusedIndices.find_next(Idx);
714     MIdx = MaskedIndices.find_next(MIdx);
715   }
716 }
717 
718 namespace llvm {
719 
720 static void inversePermutation(ArrayRef<unsigned> Indices,
721                                SmallVectorImpl<int> &Mask) {
722   Mask.clear();
723   const unsigned E = Indices.size();
724   Mask.resize(E, UndefMaskElem);
725   for (unsigned I = 0; I < E; ++I)
726     Mask[Indices[I]] = I;
727 }
728 
729 /// \returns inserting index of InsertElement or InsertValue instruction,
730 /// using Offset as base offset for index.
731 static Optional<unsigned> getInsertIndex(Value *InsertInst,
732                                          unsigned Offset = 0) {
733   int Index = Offset;
734   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst)) {
735     if (auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2))) {
736       auto *VT = cast<FixedVectorType>(IE->getType());
737       if (CI->getValue().uge(VT->getNumElements()))
738         return None;
739       Index *= VT->getNumElements();
740       Index += CI->getZExtValue();
741       return Index;
742     }
743     return None;
744   }
745 
746   auto *IV = cast<InsertValueInst>(InsertInst);
747   Type *CurrentType = IV->getType();
748   for (unsigned I : IV->indices()) {
749     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
750       Index *= ST->getNumElements();
751       CurrentType = ST->getElementType(I);
752     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
753       Index *= AT->getNumElements();
754       CurrentType = AT->getElementType();
755     } else {
756       return None;
757     }
758     Index += I;
759   }
760   return Index;
761 }
762 
763 /// Reorders the list of scalars in accordance with the given \p Mask.
764 static void reorderScalars(SmallVectorImpl<Value *> &Scalars,
765                            ArrayRef<int> Mask) {
766   assert(!Mask.empty() && "Expected non-empty mask.");
767   SmallVector<Value *> Prev(Scalars.size(),
768                             UndefValue::get(Scalars.front()->getType()));
769   Prev.swap(Scalars);
770   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
771     if (Mask[I] != UndefMaskElem)
772       Scalars[Mask[I]] = Prev[I];
773 }
774 
775 namespace slpvectorizer {
776 
777 /// Bottom Up SLP Vectorizer.
778 class BoUpSLP {
779   struct TreeEntry;
780   struct ScheduleData;
781 
782 public:
783   using ValueList = SmallVector<Value *, 8>;
784   using InstrList = SmallVector<Instruction *, 16>;
785   using ValueSet = SmallPtrSet<Value *, 16>;
786   using StoreList = SmallVector<StoreInst *, 8>;
787   using ExtraValueToDebugLocsMap =
788       MapVector<Value *, SmallVector<Instruction *, 2>>;
789   using OrdersType = SmallVector<unsigned, 4>;
790 
791   BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
792           TargetLibraryInfo *TLi, AAResults *Aa, LoopInfo *Li,
793           DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB,
794           const DataLayout *DL, OptimizationRemarkEmitter *ORE)
795       : F(Func), SE(Se), TTI(Tti), TLI(TLi), AA(Aa), LI(Li), DT(Dt), AC(AC),
796         DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) {
797     CodeMetrics::collectEphemeralValues(F, AC, EphValues);
798     // Use the vector register size specified by the target unless overridden
799     // by a command-line option.
800     // TODO: It would be better to limit the vectorization factor based on
801     //       data type rather than just register size. For example, x86 AVX has
802     //       256-bit registers, but it does not support integer operations
803     //       at that width (that requires AVX2).
804     if (MaxVectorRegSizeOption.getNumOccurrences())
805       MaxVecRegSize = MaxVectorRegSizeOption;
806     else
807       MaxVecRegSize =
808           TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
809               .getFixedSize();
810 
811     if (MinVectorRegSizeOption.getNumOccurrences())
812       MinVecRegSize = MinVectorRegSizeOption;
813     else
814       MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
815   }
816 
817   /// Vectorize the tree that starts with the elements in \p VL.
818   /// Returns the vectorized root.
819   Value *vectorizeTree();
820 
821   /// Vectorize the tree but with the list of externally used values \p
822   /// ExternallyUsedValues. Values in this MapVector can be replaced but the
823   /// generated extractvalue instructions.
824   Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues);
825 
826   /// \returns the cost incurred by unwanted spills and fills, caused by
827   /// holding live values over call sites.
828   InstructionCost getSpillCost() const;
829 
830   /// \returns the vectorization cost of the subtree that starts at \p VL.
831   /// A negative number means that this is profitable.
832   InstructionCost getTreeCost(ArrayRef<Value *> VectorizedVals = None);
833 
834   /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
835   /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
836   void buildTree(ArrayRef<Value *> Roots,
837                  ArrayRef<Value *> UserIgnoreLst = None);
838 
839   /// Builds external uses of the vectorized scalars, i.e. the list of
840   /// vectorized scalars to be extracted, their lanes and their scalar users. \p
841   /// ExternallyUsedValues contains additional list of external uses to handle
842   /// vectorization of reductions.
843   void
844   buildExternalUses(const ExtraValueToDebugLocsMap &ExternallyUsedValues = {});
845 
846   /// Clear the internal data structures that are created by 'buildTree'.
847   void deleteTree() {
848     VectorizableTree.clear();
849     ScalarToTreeEntry.clear();
850     MustGather.clear();
851     ExternalUses.clear();
852     for (auto &Iter : BlocksSchedules) {
853       BlockScheduling *BS = Iter.second.get();
854       BS->clear();
855     }
856     MinBWs.clear();
857     InstrElementSize.clear();
858   }
859 
860   unsigned getTreeSize() const { return VectorizableTree.size(); }
861 
862   /// Perform LICM and CSE on the newly generated gather sequences.
863   void optimizeGatherSequence();
864 
865   /// Checks if the specified gather tree entry \p TE can be represented as a
866   /// shuffled vector entry + (possibly) permutation with other gathers. It
867   /// implements the checks only for possibly ordered scalars (Loads,
868   /// ExtractElement, ExtractValue), which can be part of the graph.
869   Optional<OrdersType> findReusedOrderedScalars(const TreeEntry &TE);
870 
871   /// Gets reordering data for the given tree entry. If the entry is vectorized
872   /// - just return ReorderIndices, otherwise check if the scalars can be
873   /// reordered and return the most optimal order.
874   /// \param TopToBottom If true, include the order of vectorized stores and
875   /// insertelement nodes, otherwise skip them.
876   Optional<OrdersType> getReorderingData(const TreeEntry &TE, bool TopToBottom);
877 
878   /// Reorders the current graph to the most profitable order starting from the
879   /// root node to the leaf nodes. The best order is chosen only from the nodes
880   /// of the same size (vectorization factor). Smaller nodes are considered
881   /// parts of subgraph with smaller VF and they are reordered independently. We
882   /// can make it because we still need to extend smaller nodes to the wider VF
883   /// and we can merge reordering shuffles with the widening shuffles.
884   void reorderTopToBottom();
885 
886   /// Reorders the current graph to the most profitable order starting from
887   /// leaves to the root. It allows to rotate small subgraphs and reduce the
888   /// number of reshuffles if the leaf nodes use the same order. In this case we
889   /// can merge the orders and just shuffle user node instead of shuffling its
890   /// operands. Plus, even the leaf nodes have different orders, it allows to
891   /// sink reordering in the graph closer to the root node and merge it later
892   /// during analysis.
893   void reorderBottomToTop(bool IgnoreReorder = false);
894 
895   /// \return The vector element size in bits to use when vectorizing the
896   /// expression tree ending at \p V. If V is a store, the size is the width of
897   /// the stored value. Otherwise, the size is the width of the largest loaded
898   /// value reaching V. This method is used by the vectorizer to calculate
899   /// vectorization factors.
900   unsigned getVectorElementSize(Value *V);
901 
902   /// Compute the minimum type sizes required to represent the entries in a
903   /// vectorizable tree.
904   void computeMinimumValueSizes();
905 
906   // \returns maximum vector register size as set by TTI or overridden by cl::opt.
907   unsigned getMaxVecRegSize() const {
908     return MaxVecRegSize;
909   }
910 
911   // \returns minimum vector register size as set by cl::opt.
912   unsigned getMinVecRegSize() const {
913     return MinVecRegSize;
914   }
915 
916   unsigned getMinVF(unsigned Sz) const {
917     return std::max(2U, getMinVecRegSize() / Sz);
918   }
919 
920   unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const {
921     unsigned MaxVF = MaxVFOption.getNumOccurrences() ?
922       MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode);
923     return MaxVF ? MaxVF : UINT_MAX;
924   }
925 
926   /// Check if homogeneous aggregate is isomorphic to some VectorType.
927   /// Accepts homogeneous multidimensional aggregate of scalars/vectors like
928   /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> },
929   /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on.
930   ///
931   /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
932   unsigned canMapToVector(Type *T, const DataLayout &DL) const;
933 
934   /// \returns True if the VectorizableTree is both tiny and not fully
935   /// vectorizable. We do not vectorize such trees.
936   bool isTreeTinyAndNotFullyVectorizable(bool ForReduction = false) const;
937 
938   /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values
939   /// can be load combined in the backend. Load combining may not be allowed in
940   /// the IR optimizer, so we do not want to alter the pattern. For example,
941   /// partially transforming a scalar bswap() pattern into vector code is
942   /// effectively impossible for the backend to undo.
943   /// TODO: If load combining is allowed in the IR optimizer, this analysis
944   ///       may not be necessary.
945   bool isLoadCombineReductionCandidate(RecurKind RdxKind) const;
946 
947   /// Assume that a vector of stores of bitwise-or/shifted/zexted loaded values
948   /// can be load combined in the backend. Load combining may not be allowed in
949   /// the IR optimizer, so we do not want to alter the pattern. For example,
950   /// partially transforming a scalar bswap() pattern into vector code is
951   /// effectively impossible for the backend to undo.
952   /// TODO: If load combining is allowed in the IR optimizer, this analysis
953   ///       may not be necessary.
954   bool isLoadCombineCandidate() const;
955 
956   OptimizationRemarkEmitter *getORE() { return ORE; }
957 
958   /// This structure holds any data we need about the edges being traversed
959   /// during buildTree_rec(). We keep track of:
960   /// (i) the user TreeEntry index, and
961   /// (ii) the index of the edge.
962   struct EdgeInfo {
963     EdgeInfo() = default;
964     EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx)
965         : UserTE(UserTE), EdgeIdx(EdgeIdx) {}
966     /// The user TreeEntry.
967     TreeEntry *UserTE = nullptr;
968     /// The operand index of the use.
969     unsigned EdgeIdx = UINT_MAX;
970 #ifndef NDEBUG
971     friend inline raw_ostream &operator<<(raw_ostream &OS,
972                                           const BoUpSLP::EdgeInfo &EI) {
973       EI.dump(OS);
974       return OS;
975     }
976     /// Debug print.
977     void dump(raw_ostream &OS) const {
978       OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null")
979          << " EdgeIdx:" << EdgeIdx << "}";
980     }
981     LLVM_DUMP_METHOD void dump() const { dump(dbgs()); }
982 #endif
983   };
984 
985   /// A helper data structure to hold the operands of a vector of instructions.
986   /// This supports a fixed vector length for all operand vectors.
987   class VLOperands {
988     /// For each operand we need (i) the value, and (ii) the opcode that it
989     /// would be attached to if the expression was in a left-linearized form.
990     /// This is required to avoid illegal operand reordering.
991     /// For example:
992     /// \verbatim
993     ///                         0 Op1
994     ///                         |/
995     /// Op1 Op2   Linearized    + Op2
996     ///   \ /     ---------->   |/
997     ///    -                    -
998     ///
999     /// Op1 - Op2            (0 + Op1) - Op2
1000     /// \endverbatim
1001     ///
1002     /// Value Op1 is attached to a '+' operation, and Op2 to a '-'.
1003     ///
1004     /// Another way to think of this is to track all the operations across the
1005     /// path from the operand all the way to the root of the tree and to
1006     /// calculate the operation that corresponds to this path. For example, the
1007     /// path from Op2 to the root crosses the RHS of the '-', therefore the
1008     /// corresponding operation is a '-' (which matches the one in the
1009     /// linearized tree, as shown above).
1010     ///
1011     /// For lack of a better term, we refer to this operation as Accumulated
1012     /// Path Operation (APO).
1013     struct OperandData {
1014       OperandData() = default;
1015       OperandData(Value *V, bool APO, bool IsUsed)
1016           : V(V), APO(APO), IsUsed(IsUsed) {}
1017       /// The operand value.
1018       Value *V = nullptr;
1019       /// TreeEntries only allow a single opcode, or an alternate sequence of
1020       /// them (e.g, +, -). Therefore, we can safely use a boolean value for the
1021       /// APO. It is set to 'true' if 'V' is attached to an inverse operation
1022       /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise
1023       /// (e.g., Add/Mul)
1024       bool APO = false;
1025       /// Helper data for the reordering function.
1026       bool IsUsed = false;
1027     };
1028 
1029     /// During operand reordering, we are trying to select the operand at lane
1030     /// that matches best with the operand at the neighboring lane. Our
1031     /// selection is based on the type of value we are looking for. For example,
1032     /// if the neighboring lane has a load, we need to look for a load that is
1033     /// accessing a consecutive address. These strategies are summarized in the
1034     /// 'ReorderingMode' enumerator.
1035     enum class ReorderingMode {
1036       Load,     ///< Matching loads to consecutive memory addresses
1037       Opcode,   ///< Matching instructions based on opcode (same or alternate)
1038       Constant, ///< Matching constants
1039       Splat,    ///< Matching the same instruction multiple times (broadcast)
1040       Failed,   ///< We failed to create a vectorizable group
1041     };
1042 
1043     using OperandDataVec = SmallVector<OperandData, 2>;
1044 
1045     /// A vector of operand vectors.
1046     SmallVector<OperandDataVec, 4> OpsVec;
1047 
1048     const DataLayout &DL;
1049     ScalarEvolution &SE;
1050     const BoUpSLP &R;
1051 
1052     /// \returns the operand data at \p OpIdx and \p Lane.
1053     OperandData &getData(unsigned OpIdx, unsigned Lane) {
1054       return OpsVec[OpIdx][Lane];
1055     }
1056 
1057     /// \returns the operand data at \p OpIdx and \p Lane. Const version.
1058     const OperandData &getData(unsigned OpIdx, unsigned Lane) const {
1059       return OpsVec[OpIdx][Lane];
1060     }
1061 
1062     /// Clears the used flag for all entries.
1063     void clearUsed() {
1064       for (unsigned OpIdx = 0, NumOperands = getNumOperands();
1065            OpIdx != NumOperands; ++OpIdx)
1066         for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
1067              ++Lane)
1068           OpsVec[OpIdx][Lane].IsUsed = false;
1069     }
1070 
1071     /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2.
1072     void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) {
1073       std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]);
1074     }
1075 
1076     // The hard-coded scores listed here are not very important, though it shall
1077     // be higher for better matches to improve the resulting cost. When
1078     // computing the scores of matching one sub-tree with another, we are
1079     // basically counting the number of values that are matching. So even if all
1080     // scores are set to 1, we would still get a decent matching result.
1081     // However, sometimes we have to break ties. For example we may have to
1082     // choose between matching loads vs matching opcodes. This is what these
1083     // scores are helping us with: they provide the order of preference. Also,
1084     // this is important if the scalar is externally used or used in another
1085     // tree entry node in the different lane.
1086 
1087     /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]).
1088     static const int ScoreConsecutiveLoads = 4;
1089     /// Loads from reversed memory addresses, e.g. load(A[i+1]), load(A[i]).
1090     static const int ScoreReversedLoads = 3;
1091     /// ExtractElementInst from same vector and consecutive indexes.
1092     static const int ScoreConsecutiveExtracts = 4;
1093     /// ExtractElementInst from same vector and reversed indices.
1094     static const int ScoreReversedExtracts = 3;
1095     /// Constants.
1096     static const int ScoreConstants = 2;
1097     /// Instructions with the same opcode.
1098     static const int ScoreSameOpcode = 2;
1099     /// Instructions with alt opcodes (e.g, add + sub).
1100     static const int ScoreAltOpcodes = 1;
1101     /// Identical instructions (a.k.a. splat or broadcast).
1102     static const int ScoreSplat = 1;
1103     /// Matching with an undef is preferable to failing.
1104     static const int ScoreUndef = 1;
1105     /// Score for failing to find a decent match.
1106     static const int ScoreFail = 0;
1107     /// Score if all users are vectorized.
1108     static const int ScoreAllUserVectorized = 1;
1109 
1110     /// \returns the score of placing \p V1 and \p V2 in consecutive lanes.
1111     /// Also, checks if \p V1 and \p V2 are compatible with instructions in \p
1112     /// MainAltOps.
1113     static int getShallowScore(Value *V1, Value *V2, const DataLayout &DL,
1114                                ScalarEvolution &SE, int NumLanes,
1115                                ArrayRef<Value *> MainAltOps) {
1116       if (V1 == V2)
1117         return VLOperands::ScoreSplat;
1118 
1119       auto *LI1 = dyn_cast<LoadInst>(V1);
1120       auto *LI2 = dyn_cast<LoadInst>(V2);
1121       if (LI1 && LI2) {
1122         if (LI1->getParent() != LI2->getParent())
1123           return VLOperands::ScoreFail;
1124 
1125         Optional<int> Dist = getPointersDiff(
1126             LI1->getType(), LI1->getPointerOperand(), LI2->getType(),
1127             LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true);
1128         if (!Dist || *Dist == 0)
1129           return VLOperands::ScoreFail;
1130         // The distance is too large - still may be profitable to use masked
1131         // loads/gathers.
1132         if (std::abs(*Dist) > NumLanes / 2)
1133           return VLOperands::ScoreAltOpcodes;
1134         // This still will detect consecutive loads, but we might have "holes"
1135         // in some cases. It is ok for non-power-2 vectorization and may produce
1136         // better results. It should not affect current vectorization.
1137         return (*Dist > 0) ? VLOperands::ScoreConsecutiveLoads
1138                            : VLOperands::ScoreReversedLoads;
1139       }
1140 
1141       auto *C1 = dyn_cast<Constant>(V1);
1142       auto *C2 = dyn_cast<Constant>(V2);
1143       if (C1 && C2)
1144         return VLOperands::ScoreConstants;
1145 
1146       // Extracts from consecutive indexes of the same vector better score as
1147       // the extracts could be optimized away.
1148       Value *EV1;
1149       ConstantInt *Ex1Idx;
1150       if (match(V1, m_ExtractElt(m_Value(EV1), m_ConstantInt(Ex1Idx)))) {
1151         // Undefs are always profitable for extractelements.
1152         if (isa<UndefValue>(V2))
1153           return VLOperands::ScoreConsecutiveExtracts;
1154         Value *EV2 = nullptr;
1155         ConstantInt *Ex2Idx = nullptr;
1156         if (match(V2,
1157                   m_ExtractElt(m_Value(EV2), m_CombineOr(m_ConstantInt(Ex2Idx),
1158                                                          m_Undef())))) {
1159           // Undefs are always profitable for extractelements.
1160           if (!Ex2Idx)
1161             return VLOperands::ScoreConsecutiveExtracts;
1162           if (isUndefVector(EV2) && EV2->getType() == EV1->getType())
1163             return VLOperands::ScoreConsecutiveExtracts;
1164           if (EV2 == EV1) {
1165             int Idx1 = Ex1Idx->getZExtValue();
1166             int Idx2 = Ex2Idx->getZExtValue();
1167             int Dist = Idx2 - Idx1;
1168             // The distance is too large - still may be profitable to use
1169             // shuffles.
1170             if (std::abs(Dist) == 0)
1171               return VLOperands::ScoreSplat;
1172             if (std::abs(Dist) > NumLanes / 2)
1173               return VLOperands::ScoreSameOpcode;
1174             return (Dist > 0) ? VLOperands::ScoreConsecutiveExtracts
1175                               : VLOperands::ScoreReversedExtracts;
1176           }
1177           return VLOperands::ScoreAltOpcodes;
1178         }
1179         return VLOperands::ScoreFail;
1180       }
1181 
1182       auto *I1 = dyn_cast<Instruction>(V1);
1183       auto *I2 = dyn_cast<Instruction>(V2);
1184       if (I1 && I2) {
1185         if (I1->getParent() != I2->getParent())
1186           return VLOperands::ScoreFail;
1187         SmallVector<Value *, 4> Ops(MainAltOps.begin(), MainAltOps.end());
1188         Ops.push_back(I1);
1189         Ops.push_back(I2);
1190         InstructionsState S = getSameOpcode(Ops);
1191         // Note: Only consider instructions with <= 2 operands to avoid
1192         // complexity explosion.
1193         if (S.getOpcode() &&
1194             (S.MainOp->getNumOperands() <= 2 || !MainAltOps.empty() ||
1195              !S.isAltShuffle()) &&
1196             all_of(Ops, [&S](Value *V) {
1197               return cast<Instruction>(V)->getNumOperands() ==
1198                      S.MainOp->getNumOperands();
1199             }))
1200           return S.isAltShuffle() ? VLOperands::ScoreAltOpcodes
1201                                   : VLOperands::ScoreSameOpcode;
1202       }
1203 
1204       if (isa<UndefValue>(V2))
1205         return VLOperands::ScoreUndef;
1206 
1207       return VLOperands::ScoreFail;
1208     }
1209 
1210     /// \param Lane lane of the operands under analysis.
1211     /// \param OpIdx operand index in \p Lane lane we're looking the best
1212     /// candidate for.
1213     /// \param Idx operand index of the current candidate value.
1214     /// \returns The additional score due to possible broadcasting of the
1215     /// elements in the lane. It is more profitable to have power-of-2 unique
1216     /// elements in the lane, it will be vectorized with higher probability
1217     /// after removing duplicates. Currently the SLP vectorizer supports only
1218     /// vectorization of the power-of-2 number of unique scalars.
1219     int getSplatScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1220       Value *IdxLaneV = getData(Idx, Lane).V;
1221       if (!isa<Instruction>(IdxLaneV) || IdxLaneV == getData(OpIdx, Lane).V)
1222         return 0;
1223       SmallPtrSet<Value *, 4> Uniques;
1224       for (unsigned Ln = 0, E = getNumLanes(); Ln < E; ++Ln) {
1225         if (Ln == Lane)
1226           continue;
1227         Value *OpIdxLnV = getData(OpIdx, Ln).V;
1228         if (!isa<Instruction>(OpIdxLnV))
1229           return 0;
1230         Uniques.insert(OpIdxLnV);
1231       }
1232       int UniquesCount = Uniques.size();
1233       int UniquesCntWithIdxLaneV =
1234           Uniques.contains(IdxLaneV) ? UniquesCount : UniquesCount + 1;
1235       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1236       int UniquesCntWithOpIdxLaneV =
1237           Uniques.contains(OpIdxLaneV) ? UniquesCount : UniquesCount + 1;
1238       if (UniquesCntWithIdxLaneV == UniquesCntWithOpIdxLaneV)
1239         return 0;
1240       return (PowerOf2Ceil(UniquesCntWithOpIdxLaneV) -
1241               UniquesCntWithOpIdxLaneV) -
1242              (PowerOf2Ceil(UniquesCntWithIdxLaneV) - UniquesCntWithIdxLaneV);
1243     }
1244 
1245     /// \param Lane lane of the operands under analysis.
1246     /// \param OpIdx operand index in \p Lane lane we're looking the best
1247     /// candidate for.
1248     /// \param Idx operand index of the current candidate value.
1249     /// \returns The additional score for the scalar which users are all
1250     /// vectorized.
1251     int getExternalUseScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1252       Value *IdxLaneV = getData(Idx, Lane).V;
1253       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1254       // Do not care about number of uses for vector-like instructions
1255       // (extractelement/extractvalue with constant indices), they are extracts
1256       // themselves and already externally used. Vectorization of such
1257       // instructions does not add extra extractelement instruction, just may
1258       // remove it.
1259       if (isVectorLikeInstWithConstOps(IdxLaneV) &&
1260           isVectorLikeInstWithConstOps(OpIdxLaneV))
1261         return VLOperands::ScoreAllUserVectorized;
1262       auto *IdxLaneI = dyn_cast<Instruction>(IdxLaneV);
1263       if (!IdxLaneI || !isa<Instruction>(OpIdxLaneV))
1264         return 0;
1265       return R.areAllUsersVectorized(IdxLaneI, None)
1266                  ? VLOperands::ScoreAllUserVectorized
1267                  : 0;
1268     }
1269 
1270     /// Go through the operands of \p LHS and \p RHS recursively until \p
1271     /// MaxLevel, and return the cummulative score. For example:
1272     /// \verbatim
1273     ///  A[0]  B[0]  A[1]  B[1]  C[0] D[0]  B[1] A[1]
1274     ///     \ /         \ /         \ /        \ /
1275     ///      +           +           +          +
1276     ///     G1          G2          G3         G4
1277     /// \endverbatim
1278     /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at
1279     /// each level recursively, accumulating the score. It starts from matching
1280     /// the additions at level 0, then moves on to the loads (level 1). The
1281     /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and
1282     /// {B[0],B[1]} match with VLOperands::ScoreConsecutiveLoads, while
1283     /// {A[0],C[0]} has a score of VLOperands::ScoreFail.
1284     /// Please note that the order of the operands does not matter, as we
1285     /// evaluate the score of all profitable combinations of operands. In
1286     /// other words the score of G1 and G4 is the same as G1 and G2. This
1287     /// heuristic is based on ideas described in:
1288     ///   Look-ahead SLP: Auto-vectorization in the presence of commutative
1289     ///   operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha,
1290     ///   Luís F. W. Góes
1291     int getScoreAtLevelRec(Value *LHS, Value *RHS, int CurrLevel, int MaxLevel,
1292                            ArrayRef<Value *> MainAltOps) {
1293 
1294       // Get the shallow score of V1 and V2.
1295       int ShallowScoreAtThisLevel =
1296           getShallowScore(LHS, RHS, DL, SE, getNumLanes(), MainAltOps);
1297 
1298       // If reached MaxLevel,
1299       //  or if V1 and V2 are not instructions,
1300       //  or if they are SPLAT,
1301       //  or if they are not consecutive,
1302       //  or if profitable to vectorize loads or extractelements, early return
1303       //  the current cost.
1304       auto *I1 = dyn_cast<Instruction>(LHS);
1305       auto *I2 = dyn_cast<Instruction>(RHS);
1306       if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 ||
1307           ShallowScoreAtThisLevel == VLOperands::ScoreFail ||
1308           (((isa<LoadInst>(I1) && isa<LoadInst>(I2)) ||
1309             (I1->getNumOperands() > 2 && I2->getNumOperands() > 2) ||
1310             (isa<ExtractElementInst>(I1) && isa<ExtractElementInst>(I2))) &&
1311            ShallowScoreAtThisLevel))
1312         return ShallowScoreAtThisLevel;
1313       assert(I1 && I2 && "Should have early exited.");
1314 
1315       // Contains the I2 operand indexes that got matched with I1 operands.
1316       SmallSet<unsigned, 4> Op2Used;
1317 
1318       // Recursion towards the operands of I1 and I2. We are trying all possible
1319       // operand pairs, and keeping track of the best score.
1320       for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands();
1321            OpIdx1 != NumOperands1; ++OpIdx1) {
1322         // Try to pair op1I with the best operand of I2.
1323         int MaxTmpScore = 0;
1324         unsigned MaxOpIdx2 = 0;
1325         bool FoundBest = false;
1326         // If I2 is commutative try all combinations.
1327         unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1;
1328         unsigned ToIdx = isCommutative(I2)
1329                              ? I2->getNumOperands()
1330                              : std::min(I2->getNumOperands(), OpIdx1 + 1);
1331         assert(FromIdx <= ToIdx && "Bad index");
1332         for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) {
1333           // Skip operands already paired with OpIdx1.
1334           if (Op2Used.count(OpIdx2))
1335             continue;
1336           // Recursively calculate the cost at each level
1337           int TmpScore =
1338               getScoreAtLevelRec(I1->getOperand(OpIdx1), I2->getOperand(OpIdx2),
1339                                  CurrLevel + 1, MaxLevel, None);
1340           // Look for the best score.
1341           if (TmpScore > VLOperands::ScoreFail && TmpScore > MaxTmpScore) {
1342             MaxTmpScore = TmpScore;
1343             MaxOpIdx2 = OpIdx2;
1344             FoundBest = true;
1345           }
1346         }
1347         if (FoundBest) {
1348           // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it.
1349           Op2Used.insert(MaxOpIdx2);
1350           ShallowScoreAtThisLevel += MaxTmpScore;
1351         }
1352       }
1353       return ShallowScoreAtThisLevel;
1354     }
1355 
1356     /// Score scaling factor for fully compatible instructions but with
1357     /// different number of external uses. Allows better selection of the
1358     /// instructions with less external uses.
1359     static const int ScoreScaleFactor = 10;
1360 
1361     /// \Returns the look-ahead score, which tells us how much the sub-trees
1362     /// rooted at \p LHS and \p RHS match, the more they match the higher the
1363     /// score. This helps break ties in an informed way when we cannot decide on
1364     /// the order of the operands by just considering the immediate
1365     /// predecessors.
1366     int getLookAheadScore(Value *LHS, Value *RHS, ArrayRef<Value *> MainAltOps,
1367                           int Lane, unsigned OpIdx, unsigned Idx,
1368                           bool &IsUsed) {
1369       int Score =
1370           getScoreAtLevelRec(LHS, RHS, 1, LookAheadMaxDepth, MainAltOps);
1371       if (Score) {
1372         int SplatScore = getSplatScore(Lane, OpIdx, Idx);
1373         if (Score <= -SplatScore) {
1374           // Set the minimum score for splat-like sequence to avoid setting
1375           // failed state.
1376           Score = 1;
1377         } else {
1378           Score += SplatScore;
1379           // Scale score to see the difference between different operands
1380           // and similar operands but all vectorized/not all vectorized
1381           // uses. It does not affect actual selection of the best
1382           // compatible operand in general, just allows to select the
1383           // operand with all vectorized uses.
1384           Score *= ScoreScaleFactor;
1385           Score += getExternalUseScore(Lane, OpIdx, Idx);
1386           IsUsed = true;
1387         }
1388       }
1389       return Score;
1390     }
1391 
1392     /// Best defined scores per lanes between the passes. Used to choose the
1393     /// best operand (with the highest score) between the passes.
1394     /// The key - {Operand Index, Lane}.
1395     /// The value - the best score between the passes for the lane and the
1396     /// operand.
1397     SmallDenseMap<std::pair<unsigned, unsigned>, unsigned, 8>
1398         BestScoresPerLanes;
1399 
1400     // Search all operands in Ops[*][Lane] for the one that matches best
1401     // Ops[OpIdx][LastLane] and return its opreand index.
1402     // If no good match can be found, return None.
1403     Optional<unsigned> getBestOperand(unsigned OpIdx, int Lane, int LastLane,
1404                                       ArrayRef<ReorderingMode> ReorderingModes,
1405                                       ArrayRef<Value *> MainAltOps) {
1406       unsigned NumOperands = getNumOperands();
1407 
1408       // The operand of the previous lane at OpIdx.
1409       Value *OpLastLane = getData(OpIdx, LastLane).V;
1410 
1411       // Our strategy mode for OpIdx.
1412       ReorderingMode RMode = ReorderingModes[OpIdx];
1413       if (RMode == ReorderingMode::Failed)
1414         return None;
1415 
1416       // The linearized opcode of the operand at OpIdx, Lane.
1417       bool OpIdxAPO = getData(OpIdx, Lane).APO;
1418 
1419       // The best operand index and its score.
1420       // Sometimes we have more than one option (e.g., Opcode and Undefs), so we
1421       // are using the score to differentiate between the two.
1422       struct BestOpData {
1423         Optional<unsigned> Idx = None;
1424         unsigned Score = 0;
1425       } BestOp;
1426       BestOp.Score =
1427           BestScoresPerLanes.try_emplace(std::make_pair(OpIdx, Lane), 0)
1428               .first->second;
1429 
1430       // Track if the operand must be marked as used. If the operand is set to
1431       // Score 1 explicitly (because of non power-of-2 unique scalars, we may
1432       // want to reestimate the operands again on the following iterations).
1433       bool IsUsed =
1434           RMode == ReorderingMode::Splat || RMode == ReorderingMode::Constant;
1435       // Iterate through all unused operands and look for the best.
1436       for (unsigned Idx = 0; Idx != NumOperands; ++Idx) {
1437         // Get the operand at Idx and Lane.
1438         OperandData &OpData = getData(Idx, Lane);
1439         Value *Op = OpData.V;
1440         bool OpAPO = OpData.APO;
1441 
1442         // Skip already selected operands.
1443         if (OpData.IsUsed)
1444           continue;
1445 
1446         // Skip if we are trying to move the operand to a position with a
1447         // different opcode in the linearized tree form. This would break the
1448         // semantics.
1449         if (OpAPO != OpIdxAPO)
1450           continue;
1451 
1452         // Look for an operand that matches the current mode.
1453         switch (RMode) {
1454         case ReorderingMode::Load:
1455         case ReorderingMode::Constant:
1456         case ReorderingMode::Opcode: {
1457           bool LeftToRight = Lane > LastLane;
1458           Value *OpLeft = (LeftToRight) ? OpLastLane : Op;
1459           Value *OpRight = (LeftToRight) ? Op : OpLastLane;
1460           int Score = getLookAheadScore(OpLeft, OpRight, MainAltOps, Lane,
1461                                         OpIdx, Idx, IsUsed);
1462           if (Score > static_cast<int>(BestOp.Score)) {
1463             BestOp.Idx = Idx;
1464             BestOp.Score = Score;
1465             BestScoresPerLanes[std::make_pair(OpIdx, Lane)] = Score;
1466           }
1467           break;
1468         }
1469         case ReorderingMode::Splat:
1470           if (Op == OpLastLane)
1471             BestOp.Idx = Idx;
1472           break;
1473         case ReorderingMode::Failed:
1474           llvm_unreachable("Not expected Failed reordering mode.");
1475         }
1476       }
1477 
1478       if (BestOp.Idx) {
1479         getData(BestOp.Idx.getValue(), Lane).IsUsed = IsUsed;
1480         return BestOp.Idx;
1481       }
1482       // If we could not find a good match return None.
1483       return None;
1484     }
1485 
1486     /// Helper for reorderOperandVecs.
1487     /// \returns the lane that we should start reordering from. This is the one
1488     /// which has the least number of operands that can freely move about or
1489     /// less profitable because it already has the most optimal set of operands.
1490     unsigned getBestLaneToStartReordering() const {
1491       unsigned Min = UINT_MAX;
1492       unsigned SameOpNumber = 0;
1493       // std::pair<unsigned, unsigned> is used to implement a simple voting
1494       // algorithm and choose the lane with the least number of operands that
1495       // can freely move about or less profitable because it already has the
1496       // most optimal set of operands. The first unsigned is a counter for
1497       // voting, the second unsigned is the counter of lanes with instructions
1498       // with same/alternate opcodes and same parent basic block.
1499       MapVector<unsigned, std::pair<unsigned, unsigned>> HashMap;
1500       // Try to be closer to the original results, if we have multiple lanes
1501       // with same cost. If 2 lanes have the same cost, use the one with the
1502       // lowest index.
1503       for (int I = getNumLanes(); I > 0; --I) {
1504         unsigned Lane = I - 1;
1505         OperandsOrderData NumFreeOpsHash =
1506             getMaxNumOperandsThatCanBeReordered(Lane);
1507         // Compare the number of operands that can move and choose the one with
1508         // the least number.
1509         if (NumFreeOpsHash.NumOfAPOs < Min) {
1510           Min = NumFreeOpsHash.NumOfAPOs;
1511           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1512           HashMap.clear();
1513           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1514         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1515                    NumFreeOpsHash.NumOpsWithSameOpcodeParent < SameOpNumber) {
1516           // Select the most optimal lane in terms of number of operands that
1517           // should be moved around.
1518           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1519           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1520         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1521                    NumFreeOpsHash.NumOpsWithSameOpcodeParent == SameOpNumber) {
1522           auto It = HashMap.find(NumFreeOpsHash.Hash);
1523           if (It == HashMap.end())
1524             HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1525           else
1526             ++It->second.first;
1527         }
1528       }
1529       // Select the lane with the minimum counter.
1530       unsigned BestLane = 0;
1531       unsigned CntMin = UINT_MAX;
1532       for (const auto &Data : reverse(HashMap)) {
1533         if (Data.second.first < CntMin) {
1534           CntMin = Data.second.first;
1535           BestLane = Data.second.second;
1536         }
1537       }
1538       return BestLane;
1539     }
1540 
1541     /// Data structure that helps to reorder operands.
1542     struct OperandsOrderData {
1543       /// The best number of operands with the same APOs, which can be
1544       /// reordered.
1545       unsigned NumOfAPOs = UINT_MAX;
1546       /// Number of operands with the same/alternate instruction opcode and
1547       /// parent.
1548       unsigned NumOpsWithSameOpcodeParent = 0;
1549       /// Hash for the actual operands ordering.
1550       /// Used to count operands, actually their position id and opcode
1551       /// value. It is used in the voting mechanism to find the lane with the
1552       /// least number of operands that can freely move about or less profitable
1553       /// because it already has the most optimal set of operands. Can be
1554       /// replaced with SmallVector<unsigned> instead but hash code is faster
1555       /// and requires less memory.
1556       unsigned Hash = 0;
1557     };
1558     /// \returns the maximum number of operands that are allowed to be reordered
1559     /// for \p Lane and the number of compatible instructions(with the same
1560     /// parent/opcode). This is used as a heuristic for selecting the first lane
1561     /// to start operand reordering.
1562     OperandsOrderData getMaxNumOperandsThatCanBeReordered(unsigned Lane) const {
1563       unsigned CntTrue = 0;
1564       unsigned NumOperands = getNumOperands();
1565       // Operands with the same APO can be reordered. We therefore need to count
1566       // how many of them we have for each APO, like this: Cnt[APO] = x.
1567       // Since we only have two APOs, namely true and false, we can avoid using
1568       // a map. Instead we can simply count the number of operands that
1569       // correspond to one of them (in this case the 'true' APO), and calculate
1570       // the other by subtracting it from the total number of operands.
1571       // Operands with the same instruction opcode and parent are more
1572       // profitable since we don't need to move them in many cases, with a high
1573       // probability such lane already can be vectorized effectively.
1574       bool AllUndefs = true;
1575       unsigned NumOpsWithSameOpcodeParent = 0;
1576       Instruction *OpcodeI = nullptr;
1577       BasicBlock *Parent = nullptr;
1578       unsigned Hash = 0;
1579       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1580         const OperandData &OpData = getData(OpIdx, Lane);
1581         if (OpData.APO)
1582           ++CntTrue;
1583         // Use Boyer-Moore majority voting for finding the majority opcode and
1584         // the number of times it occurs.
1585         if (auto *I = dyn_cast<Instruction>(OpData.V)) {
1586           if (!OpcodeI || !getSameOpcode({OpcodeI, I}).getOpcode() ||
1587               I->getParent() != Parent) {
1588             if (NumOpsWithSameOpcodeParent == 0) {
1589               NumOpsWithSameOpcodeParent = 1;
1590               OpcodeI = I;
1591               Parent = I->getParent();
1592             } else {
1593               --NumOpsWithSameOpcodeParent;
1594             }
1595           } else {
1596             ++NumOpsWithSameOpcodeParent;
1597           }
1598         }
1599         Hash = hash_combine(
1600             Hash, hash_value((OpIdx + 1) * (OpData.V->getValueID() + 1)));
1601         AllUndefs = AllUndefs && isa<UndefValue>(OpData.V);
1602       }
1603       if (AllUndefs)
1604         return {};
1605       OperandsOrderData Data;
1606       Data.NumOfAPOs = std::max(CntTrue, NumOperands - CntTrue);
1607       Data.NumOpsWithSameOpcodeParent = NumOpsWithSameOpcodeParent;
1608       Data.Hash = Hash;
1609       return Data;
1610     }
1611 
1612     /// Go through the instructions in VL and append their operands.
1613     void appendOperandsOfVL(ArrayRef<Value *> VL) {
1614       assert(!VL.empty() && "Bad VL");
1615       assert((empty() || VL.size() == getNumLanes()) &&
1616              "Expected same number of lanes");
1617       assert(isa<Instruction>(VL[0]) && "Expected instruction");
1618       unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands();
1619       OpsVec.resize(NumOperands);
1620       unsigned NumLanes = VL.size();
1621       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1622         OpsVec[OpIdx].resize(NumLanes);
1623         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1624           assert(isa<Instruction>(VL[Lane]) && "Expected instruction");
1625           // Our tree has just 3 nodes: the root and two operands.
1626           // It is therefore trivial to get the APO. We only need to check the
1627           // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or
1628           // RHS operand. The LHS operand of both add and sub is never attached
1629           // to an inversese operation in the linearized form, therefore its APO
1630           // is false. The RHS is true only if VL[Lane] is an inverse operation.
1631 
1632           // Since operand reordering is performed on groups of commutative
1633           // operations or alternating sequences (e.g., +, -), we can safely
1634           // tell the inverse operations by checking commutativity.
1635           bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane]));
1636           bool APO = (OpIdx == 0) ? false : IsInverseOperation;
1637           OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx),
1638                                  APO, false};
1639         }
1640       }
1641     }
1642 
1643     /// \returns the number of operands.
1644     unsigned getNumOperands() const { return OpsVec.size(); }
1645 
1646     /// \returns the number of lanes.
1647     unsigned getNumLanes() const { return OpsVec[0].size(); }
1648 
1649     /// \returns the operand value at \p OpIdx and \p Lane.
1650     Value *getValue(unsigned OpIdx, unsigned Lane) const {
1651       return getData(OpIdx, Lane).V;
1652     }
1653 
1654     /// \returns true if the data structure is empty.
1655     bool empty() const { return OpsVec.empty(); }
1656 
1657     /// Clears the data.
1658     void clear() { OpsVec.clear(); }
1659 
1660     /// \Returns true if there are enough operands identical to \p Op to fill
1661     /// the whole vector.
1662     /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow.
1663     bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) {
1664       bool OpAPO = getData(OpIdx, Lane).APO;
1665       for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) {
1666         if (Ln == Lane)
1667           continue;
1668         // This is set to true if we found a candidate for broadcast at Lane.
1669         bool FoundCandidate = false;
1670         for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) {
1671           OperandData &Data = getData(OpI, Ln);
1672           if (Data.APO != OpAPO || Data.IsUsed)
1673             continue;
1674           if (Data.V == Op) {
1675             FoundCandidate = true;
1676             Data.IsUsed = true;
1677             break;
1678           }
1679         }
1680         if (!FoundCandidate)
1681           return false;
1682       }
1683       return true;
1684     }
1685 
1686   public:
1687     /// Initialize with all the operands of the instruction vector \p RootVL.
1688     VLOperands(ArrayRef<Value *> RootVL, const DataLayout &DL,
1689                ScalarEvolution &SE, const BoUpSLP &R)
1690         : DL(DL), SE(SE), R(R) {
1691       // Append all the operands of RootVL.
1692       appendOperandsOfVL(RootVL);
1693     }
1694 
1695     /// \Returns a value vector with the operands across all lanes for the
1696     /// opearnd at \p OpIdx.
1697     ValueList getVL(unsigned OpIdx) const {
1698       ValueList OpVL(OpsVec[OpIdx].size());
1699       assert(OpsVec[OpIdx].size() == getNumLanes() &&
1700              "Expected same num of lanes across all operands");
1701       for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane)
1702         OpVL[Lane] = OpsVec[OpIdx][Lane].V;
1703       return OpVL;
1704     }
1705 
1706     // Performs operand reordering for 2 or more operands.
1707     // The original operands are in OrigOps[OpIdx][Lane].
1708     // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'.
1709     void reorder() {
1710       unsigned NumOperands = getNumOperands();
1711       unsigned NumLanes = getNumLanes();
1712       // Each operand has its own mode. We are using this mode to help us select
1713       // the instructions for each lane, so that they match best with the ones
1714       // we have selected so far.
1715       SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands);
1716 
1717       // This is a greedy single-pass algorithm. We are going over each lane
1718       // once and deciding on the best order right away with no back-tracking.
1719       // However, in order to increase its effectiveness, we start with the lane
1720       // that has operands that can move the least. For example, given the
1721       // following lanes:
1722       //  Lane 0 : A[0] = B[0] + C[0]   // Visited 3rd
1723       //  Lane 1 : A[1] = C[1] - B[1]   // Visited 1st
1724       //  Lane 2 : A[2] = B[2] + C[2]   // Visited 2nd
1725       //  Lane 3 : A[3] = C[3] - B[3]   // Visited 4th
1726       // we will start at Lane 1, since the operands of the subtraction cannot
1727       // be reordered. Then we will visit the rest of the lanes in a circular
1728       // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3.
1729 
1730       // Find the first lane that we will start our search from.
1731       unsigned FirstLane = getBestLaneToStartReordering();
1732 
1733       // Initialize the modes.
1734       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1735         Value *OpLane0 = getValue(OpIdx, FirstLane);
1736         // Keep track if we have instructions with all the same opcode on one
1737         // side.
1738         if (isa<LoadInst>(OpLane0))
1739           ReorderingModes[OpIdx] = ReorderingMode::Load;
1740         else if (isa<Instruction>(OpLane0)) {
1741           // Check if OpLane0 should be broadcast.
1742           if (shouldBroadcast(OpLane0, OpIdx, FirstLane))
1743             ReorderingModes[OpIdx] = ReorderingMode::Splat;
1744           else
1745             ReorderingModes[OpIdx] = ReorderingMode::Opcode;
1746         }
1747         else if (isa<Constant>(OpLane0))
1748           ReorderingModes[OpIdx] = ReorderingMode::Constant;
1749         else if (isa<Argument>(OpLane0))
1750           // Our best hope is a Splat. It may save some cost in some cases.
1751           ReorderingModes[OpIdx] = ReorderingMode::Splat;
1752         else
1753           // NOTE: This should be unreachable.
1754           ReorderingModes[OpIdx] = ReorderingMode::Failed;
1755       }
1756 
1757       // Check that we don't have same operands. No need to reorder if operands
1758       // are just perfect diamond or shuffled diamond match. Do not do it only
1759       // for possible broadcasts or non-power of 2 number of scalars (just for
1760       // now).
1761       auto &&SkipReordering = [this]() {
1762         SmallPtrSet<Value *, 4> UniqueValues;
1763         ArrayRef<OperandData> Op0 = OpsVec.front();
1764         for (const OperandData &Data : Op0)
1765           UniqueValues.insert(Data.V);
1766         for (ArrayRef<OperandData> Op : drop_begin(OpsVec, 1)) {
1767           if (any_of(Op, [&UniqueValues](const OperandData &Data) {
1768                 return !UniqueValues.contains(Data.V);
1769               }))
1770             return false;
1771         }
1772         // TODO: Check if we can remove a check for non-power-2 number of
1773         // scalars after full support of non-power-2 vectorization.
1774         return UniqueValues.size() != 2 && isPowerOf2_32(UniqueValues.size());
1775       };
1776 
1777       // If the initial strategy fails for any of the operand indexes, then we
1778       // perform reordering again in a second pass. This helps avoid assigning
1779       // high priority to the failed strategy, and should improve reordering for
1780       // the non-failed operand indexes.
1781       for (int Pass = 0; Pass != 2; ++Pass) {
1782         // Check if no need to reorder operands since they're are perfect or
1783         // shuffled diamond match.
1784         // Need to to do it to avoid extra external use cost counting for
1785         // shuffled matches, which may cause regressions.
1786         if (SkipReordering())
1787           break;
1788         // Skip the second pass if the first pass did not fail.
1789         bool StrategyFailed = false;
1790         // Mark all operand data as free to use.
1791         clearUsed();
1792         // We keep the original operand order for the FirstLane, so reorder the
1793         // rest of the lanes. We are visiting the nodes in a circular fashion,
1794         // using FirstLane as the center point and increasing the radius
1795         // distance.
1796         SmallVector<SmallVector<Value *, 2>> MainAltOps(NumOperands);
1797         for (unsigned I = 0; I < NumOperands; ++I)
1798           MainAltOps[I].push_back(getData(I, FirstLane).V);
1799 
1800         for (unsigned Distance = 1; Distance != NumLanes; ++Distance) {
1801           // Visit the lane on the right and then the lane on the left.
1802           for (int Direction : {+1, -1}) {
1803             int Lane = FirstLane + Direction * Distance;
1804             if (Lane < 0 || Lane >= (int)NumLanes)
1805               continue;
1806             int LastLane = Lane - Direction;
1807             assert(LastLane >= 0 && LastLane < (int)NumLanes &&
1808                    "Out of bounds");
1809             // Look for a good match for each operand.
1810             for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1811               // Search for the operand that matches SortedOps[OpIdx][Lane-1].
1812               Optional<unsigned> BestIdx = getBestOperand(
1813                   OpIdx, Lane, LastLane, ReorderingModes, MainAltOps[OpIdx]);
1814               // By not selecting a value, we allow the operands that follow to
1815               // select a better matching value. We will get a non-null value in
1816               // the next run of getBestOperand().
1817               if (BestIdx) {
1818                 // Swap the current operand with the one returned by
1819                 // getBestOperand().
1820                 swap(OpIdx, BestIdx.getValue(), Lane);
1821               } else {
1822                 // We failed to find a best operand, set mode to 'Failed'.
1823                 ReorderingModes[OpIdx] = ReorderingMode::Failed;
1824                 // Enable the second pass.
1825                 StrategyFailed = true;
1826               }
1827               // Try to get the alternate opcode and follow it during analysis.
1828               if (MainAltOps[OpIdx].size() != 2) {
1829                 OperandData &AltOp = getData(OpIdx, Lane);
1830                 InstructionsState OpS =
1831                     getSameOpcode({MainAltOps[OpIdx].front(), AltOp.V});
1832                 if (OpS.getOpcode() && OpS.isAltShuffle())
1833                   MainAltOps[OpIdx].push_back(AltOp.V);
1834               }
1835             }
1836           }
1837         }
1838         // Skip second pass if the strategy did not fail.
1839         if (!StrategyFailed)
1840           break;
1841       }
1842     }
1843 
1844 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1845     LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) {
1846       switch (RMode) {
1847       case ReorderingMode::Load:
1848         return "Load";
1849       case ReorderingMode::Opcode:
1850         return "Opcode";
1851       case ReorderingMode::Constant:
1852         return "Constant";
1853       case ReorderingMode::Splat:
1854         return "Splat";
1855       case ReorderingMode::Failed:
1856         return "Failed";
1857       }
1858       llvm_unreachable("Unimplemented Reordering Type");
1859     }
1860 
1861     LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode,
1862                                                    raw_ostream &OS) {
1863       return OS << getModeStr(RMode);
1864     }
1865 
1866     /// Debug print.
1867     LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) {
1868       printMode(RMode, dbgs());
1869     }
1870 
1871     friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) {
1872       return printMode(RMode, OS);
1873     }
1874 
1875     LLVM_DUMP_METHOD raw_ostream &print(raw_ostream &OS) const {
1876       const unsigned Indent = 2;
1877       unsigned Cnt = 0;
1878       for (const OperandDataVec &OpDataVec : OpsVec) {
1879         OS << "Operand " << Cnt++ << "\n";
1880         for (const OperandData &OpData : OpDataVec) {
1881           OS.indent(Indent) << "{";
1882           if (Value *V = OpData.V)
1883             OS << *V;
1884           else
1885             OS << "null";
1886           OS << ", APO:" << OpData.APO << "}\n";
1887         }
1888         OS << "\n";
1889       }
1890       return OS;
1891     }
1892 
1893     /// Debug print.
1894     LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
1895 #endif
1896   };
1897 
1898   /// Checks if the instruction is marked for deletion.
1899   bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); }
1900 
1901   /// Marks values operands for later deletion by replacing them with Undefs.
1902   void eraseInstructions(ArrayRef<Value *> AV);
1903 
1904   ~BoUpSLP();
1905 
1906 private:
1907   /// Checks if all users of \p I are the part of the vectorization tree.
1908   bool areAllUsersVectorized(Instruction *I,
1909                              ArrayRef<Value *> VectorizedVals) const;
1910 
1911   /// \returns the cost of the vectorizable entry.
1912   InstructionCost getEntryCost(const TreeEntry *E,
1913                                ArrayRef<Value *> VectorizedVals);
1914 
1915   /// This is the recursive part of buildTree.
1916   void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth,
1917                      const EdgeInfo &EI);
1918 
1919   /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
1920   /// be vectorized to use the original vector (or aggregate "bitcast" to a
1921   /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
1922   /// returns false, setting \p CurrentOrder to either an empty vector or a
1923   /// non-identity permutation that allows to reuse extract instructions.
1924   bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
1925                        SmallVectorImpl<unsigned> &CurrentOrder) const;
1926 
1927   /// Vectorize a single entry in the tree.
1928   Value *vectorizeTree(TreeEntry *E);
1929 
1930   /// Vectorize a single entry in the tree, starting in \p VL.
1931   Value *vectorizeTree(ArrayRef<Value *> VL);
1932 
1933   /// \returns the scalarization cost for this type. Scalarization in this
1934   /// context means the creation of vectors from a group of scalars. If \p
1935   /// NeedToShuffle is true, need to add a cost of reshuffling some of the
1936   /// vector elements.
1937   InstructionCost getGatherCost(FixedVectorType *Ty,
1938                                 const APInt &ShuffledIndices,
1939                                 bool NeedToShuffle) const;
1940 
1941   /// Checks if the gathered \p VL can be represented as shuffle(s) of previous
1942   /// tree entries.
1943   /// \returns ShuffleKind, if gathered values can be represented as shuffles of
1944   /// previous tree entries. \p Mask is filled with the shuffle mask.
1945   Optional<TargetTransformInfo::ShuffleKind>
1946   isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
1947                         SmallVectorImpl<const TreeEntry *> &Entries);
1948 
1949   /// \returns the scalarization cost for this list of values. Assuming that
1950   /// this subtree gets vectorized, we may need to extract the values from the
1951   /// roots. This method calculates the cost of extracting the values.
1952   InstructionCost getGatherCost(ArrayRef<Value *> VL) const;
1953 
1954   /// Set the Builder insert point to one after the last instruction in
1955   /// the bundle
1956   void setInsertPointAfterBundle(const TreeEntry *E);
1957 
1958   /// \returns a vector from a collection of scalars in \p VL.
1959   Value *gather(ArrayRef<Value *> VL);
1960 
1961   /// \returns whether the VectorizableTree is fully vectorizable and will
1962   /// be beneficial even the tree height is tiny.
1963   bool isFullyVectorizableTinyTree(bool ForReduction) const;
1964 
1965   /// Reorder commutative or alt operands to get better probability of
1966   /// generating vectorized code.
1967   static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
1968                                              SmallVectorImpl<Value *> &Left,
1969                                              SmallVectorImpl<Value *> &Right,
1970                                              const DataLayout &DL,
1971                                              ScalarEvolution &SE,
1972                                              const BoUpSLP &R);
1973   struct TreeEntry {
1974     using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>;
1975     TreeEntry(VecTreeTy &Container) : Container(Container) {}
1976 
1977     /// \returns true if the scalars in VL are equal to this entry.
1978     bool isSame(ArrayRef<Value *> VL) const {
1979       auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) {
1980         if (Mask.size() != VL.size() && VL.size() == Scalars.size())
1981           return std::equal(VL.begin(), VL.end(), Scalars.begin());
1982         return VL.size() == Mask.size() &&
1983                std::equal(VL.begin(), VL.end(), Mask.begin(),
1984                           [Scalars](Value *V, int Idx) {
1985                             return (isa<UndefValue>(V) &&
1986                                     Idx == UndefMaskElem) ||
1987                                    (Idx != UndefMaskElem && V == Scalars[Idx]);
1988                           });
1989       };
1990       if (!ReorderIndices.empty()) {
1991         // TODO: implement matching if the nodes are just reordered, still can
1992         // treat the vector as the same if the list of scalars matches VL
1993         // directly, without reordering.
1994         SmallVector<int> Mask;
1995         inversePermutation(ReorderIndices, Mask);
1996         if (VL.size() == Scalars.size())
1997           return IsSame(Scalars, Mask);
1998         if (VL.size() == ReuseShuffleIndices.size()) {
1999           ::addMask(Mask, ReuseShuffleIndices);
2000           return IsSame(Scalars, Mask);
2001         }
2002         return false;
2003       }
2004       return IsSame(Scalars, ReuseShuffleIndices);
2005     }
2006 
2007     /// \returns true if current entry has same operands as \p TE.
2008     bool hasEqualOperands(const TreeEntry &TE) const {
2009       if (TE.getNumOperands() != getNumOperands())
2010         return false;
2011       SmallBitVector Used(getNumOperands());
2012       for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
2013         unsigned PrevCount = Used.count();
2014         for (unsigned K = 0; K < E; ++K) {
2015           if (Used.test(K))
2016             continue;
2017           if (getOperand(K) == TE.getOperand(I)) {
2018             Used.set(K);
2019             break;
2020           }
2021         }
2022         // Check if we actually found the matching operand.
2023         if (PrevCount == Used.count())
2024           return false;
2025       }
2026       return true;
2027     }
2028 
2029     /// \return Final vectorization factor for the node. Defined by the total
2030     /// number of vectorized scalars, including those, used several times in the
2031     /// entry and counted in the \a ReuseShuffleIndices, if any.
2032     unsigned getVectorFactor() const {
2033       if (!ReuseShuffleIndices.empty())
2034         return ReuseShuffleIndices.size();
2035       return Scalars.size();
2036     };
2037 
2038     /// A vector of scalars.
2039     ValueList Scalars;
2040 
2041     /// The Scalars are vectorized into this value. It is initialized to Null.
2042     Value *VectorizedValue = nullptr;
2043 
2044     /// Do we need to gather this sequence or vectorize it
2045     /// (either with vector instruction or with scatter/gather
2046     /// intrinsics for store/load)?
2047     enum EntryState { Vectorize, ScatterVectorize, NeedToGather };
2048     EntryState State;
2049 
2050     /// Does this sequence require some shuffling?
2051     SmallVector<int, 4> ReuseShuffleIndices;
2052 
2053     /// Does this entry require reordering?
2054     SmallVector<unsigned, 4> ReorderIndices;
2055 
2056     /// Points back to the VectorizableTree.
2057     ///
2058     /// Only used for Graphviz right now.  Unfortunately GraphTrait::NodeRef has
2059     /// to be a pointer and needs to be able to initialize the child iterator.
2060     /// Thus we need a reference back to the container to translate the indices
2061     /// to entries.
2062     VecTreeTy &Container;
2063 
2064     /// The TreeEntry index containing the user of this entry.  We can actually
2065     /// have multiple users so the data structure is not truly a tree.
2066     SmallVector<EdgeInfo, 1> UserTreeIndices;
2067 
2068     /// The index of this treeEntry in VectorizableTree.
2069     int Idx = -1;
2070 
2071   private:
2072     /// The operands of each instruction in each lane Operands[op_index][lane].
2073     /// Note: This helps avoid the replication of the code that performs the
2074     /// reordering of operands during buildTree_rec() and vectorizeTree().
2075     SmallVector<ValueList, 2> Operands;
2076 
2077     /// The main/alternate instruction.
2078     Instruction *MainOp = nullptr;
2079     Instruction *AltOp = nullptr;
2080 
2081   public:
2082     /// Set this bundle's \p OpIdx'th operand to \p OpVL.
2083     void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) {
2084       if (Operands.size() < OpIdx + 1)
2085         Operands.resize(OpIdx + 1);
2086       assert(Operands[OpIdx].empty() && "Already resized?");
2087       assert(OpVL.size() <= Scalars.size() &&
2088              "Number of operands is greater than the number of scalars.");
2089       Operands[OpIdx].resize(OpVL.size());
2090       copy(OpVL, Operands[OpIdx].begin());
2091     }
2092 
2093     /// Set the operands of this bundle in their original order.
2094     void setOperandsInOrder() {
2095       assert(Operands.empty() && "Already initialized?");
2096       auto *I0 = cast<Instruction>(Scalars[0]);
2097       Operands.resize(I0->getNumOperands());
2098       unsigned NumLanes = Scalars.size();
2099       for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands();
2100            OpIdx != NumOperands; ++OpIdx) {
2101         Operands[OpIdx].resize(NumLanes);
2102         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
2103           auto *I = cast<Instruction>(Scalars[Lane]);
2104           assert(I->getNumOperands() == NumOperands &&
2105                  "Expected same number of operands");
2106           Operands[OpIdx][Lane] = I->getOperand(OpIdx);
2107         }
2108       }
2109     }
2110 
2111     /// Reorders operands of the node to the given mask \p Mask.
2112     void reorderOperands(ArrayRef<int> Mask) {
2113       for (ValueList &Operand : Operands)
2114         reorderScalars(Operand, Mask);
2115     }
2116 
2117     /// \returns the \p OpIdx operand of this TreeEntry.
2118     ValueList &getOperand(unsigned OpIdx) {
2119       assert(OpIdx < Operands.size() && "Off bounds");
2120       return Operands[OpIdx];
2121     }
2122 
2123     /// \returns the \p OpIdx operand of this TreeEntry.
2124     ArrayRef<Value *> getOperand(unsigned OpIdx) const {
2125       assert(OpIdx < Operands.size() && "Off bounds");
2126       return Operands[OpIdx];
2127     }
2128 
2129     /// \returns the number of operands.
2130     unsigned getNumOperands() const { return Operands.size(); }
2131 
2132     /// \return the single \p OpIdx operand.
2133     Value *getSingleOperand(unsigned OpIdx) const {
2134       assert(OpIdx < Operands.size() && "Off bounds");
2135       assert(!Operands[OpIdx].empty() && "No operand available");
2136       return Operands[OpIdx][0];
2137     }
2138 
2139     /// Some of the instructions in the list have alternate opcodes.
2140     bool isAltShuffle() const { return MainOp != AltOp; }
2141 
2142     bool isOpcodeOrAlt(Instruction *I) const {
2143       unsigned CheckedOpcode = I->getOpcode();
2144       return (getOpcode() == CheckedOpcode ||
2145               getAltOpcode() == CheckedOpcode);
2146     }
2147 
2148     /// Chooses the correct key for scheduling data. If \p Op has the same (or
2149     /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is
2150     /// \p OpValue.
2151     Value *isOneOf(Value *Op) const {
2152       auto *I = dyn_cast<Instruction>(Op);
2153       if (I && isOpcodeOrAlt(I))
2154         return Op;
2155       return MainOp;
2156     }
2157 
2158     void setOperations(const InstructionsState &S) {
2159       MainOp = S.MainOp;
2160       AltOp = S.AltOp;
2161     }
2162 
2163     Instruction *getMainOp() const {
2164       return MainOp;
2165     }
2166 
2167     Instruction *getAltOp() const {
2168       return AltOp;
2169     }
2170 
2171     /// The main/alternate opcodes for the list of instructions.
2172     unsigned getOpcode() const {
2173       return MainOp ? MainOp->getOpcode() : 0;
2174     }
2175 
2176     unsigned getAltOpcode() const {
2177       return AltOp ? AltOp->getOpcode() : 0;
2178     }
2179 
2180     /// When ReuseReorderShuffleIndices is empty it just returns position of \p
2181     /// V within vector of Scalars. Otherwise, try to remap on its reuse index.
2182     int findLaneForValue(Value *V) const {
2183       unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V));
2184       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2185       if (!ReorderIndices.empty())
2186         FoundLane = ReorderIndices[FoundLane];
2187       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2188       if (!ReuseShuffleIndices.empty()) {
2189         FoundLane = std::distance(ReuseShuffleIndices.begin(),
2190                                   find(ReuseShuffleIndices, FoundLane));
2191       }
2192       return FoundLane;
2193     }
2194 
2195 #ifndef NDEBUG
2196     /// Debug printer.
2197     LLVM_DUMP_METHOD void dump() const {
2198       dbgs() << Idx << ".\n";
2199       for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) {
2200         dbgs() << "Operand " << OpI << ":\n";
2201         for (const Value *V : Operands[OpI])
2202           dbgs().indent(2) << *V << "\n";
2203       }
2204       dbgs() << "Scalars: \n";
2205       for (Value *V : Scalars)
2206         dbgs().indent(2) << *V << "\n";
2207       dbgs() << "State: ";
2208       switch (State) {
2209       case Vectorize:
2210         dbgs() << "Vectorize\n";
2211         break;
2212       case ScatterVectorize:
2213         dbgs() << "ScatterVectorize\n";
2214         break;
2215       case NeedToGather:
2216         dbgs() << "NeedToGather\n";
2217         break;
2218       }
2219       dbgs() << "MainOp: ";
2220       if (MainOp)
2221         dbgs() << *MainOp << "\n";
2222       else
2223         dbgs() << "NULL\n";
2224       dbgs() << "AltOp: ";
2225       if (AltOp)
2226         dbgs() << *AltOp << "\n";
2227       else
2228         dbgs() << "NULL\n";
2229       dbgs() << "VectorizedValue: ";
2230       if (VectorizedValue)
2231         dbgs() << *VectorizedValue << "\n";
2232       else
2233         dbgs() << "NULL\n";
2234       dbgs() << "ReuseShuffleIndices: ";
2235       if (ReuseShuffleIndices.empty())
2236         dbgs() << "Empty";
2237       else
2238         for (int ReuseIdx : ReuseShuffleIndices)
2239           dbgs() << ReuseIdx << ", ";
2240       dbgs() << "\n";
2241       dbgs() << "ReorderIndices: ";
2242       for (unsigned ReorderIdx : ReorderIndices)
2243         dbgs() << ReorderIdx << ", ";
2244       dbgs() << "\n";
2245       dbgs() << "UserTreeIndices: ";
2246       for (const auto &EInfo : UserTreeIndices)
2247         dbgs() << EInfo << ", ";
2248       dbgs() << "\n";
2249     }
2250 #endif
2251   };
2252 
2253 #ifndef NDEBUG
2254   void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost,
2255                      InstructionCost VecCost,
2256                      InstructionCost ScalarCost) const {
2257     dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump();
2258     dbgs() << "SLP: Costs:\n";
2259     dbgs() << "SLP:     ReuseShuffleCost = " << ReuseShuffleCost << "\n";
2260     dbgs() << "SLP:     VectorCost = " << VecCost << "\n";
2261     dbgs() << "SLP:     ScalarCost = " << ScalarCost << "\n";
2262     dbgs() << "SLP:     ReuseShuffleCost + VecCost - ScalarCost = " <<
2263                ReuseShuffleCost + VecCost - ScalarCost << "\n";
2264   }
2265 #endif
2266 
2267   /// Create a new VectorizableTree entry.
2268   TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle,
2269                           const InstructionsState &S,
2270                           const EdgeInfo &UserTreeIdx,
2271                           ArrayRef<int> ReuseShuffleIndices = None,
2272                           ArrayRef<unsigned> ReorderIndices = None) {
2273     TreeEntry::EntryState EntryState =
2274         Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather;
2275     return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx,
2276                         ReuseShuffleIndices, ReorderIndices);
2277   }
2278 
2279   TreeEntry *newTreeEntry(ArrayRef<Value *> VL,
2280                           TreeEntry::EntryState EntryState,
2281                           Optional<ScheduleData *> Bundle,
2282                           const InstructionsState &S,
2283                           const EdgeInfo &UserTreeIdx,
2284                           ArrayRef<int> ReuseShuffleIndices = None,
2285                           ArrayRef<unsigned> ReorderIndices = None) {
2286     assert(((!Bundle && EntryState == TreeEntry::NeedToGather) ||
2287             (Bundle && EntryState != TreeEntry::NeedToGather)) &&
2288            "Need to vectorize gather entry?");
2289     VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree));
2290     TreeEntry *Last = VectorizableTree.back().get();
2291     Last->Idx = VectorizableTree.size() - 1;
2292     Last->State = EntryState;
2293     Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
2294                                      ReuseShuffleIndices.end());
2295     if (ReorderIndices.empty()) {
2296       Last->Scalars.assign(VL.begin(), VL.end());
2297       Last->setOperations(S);
2298     } else {
2299       // Reorder scalars and build final mask.
2300       Last->Scalars.assign(VL.size(), nullptr);
2301       transform(ReorderIndices, Last->Scalars.begin(),
2302                 [VL](unsigned Idx) -> Value * {
2303                   if (Idx >= VL.size())
2304                     return UndefValue::get(VL.front()->getType());
2305                   return VL[Idx];
2306                 });
2307       InstructionsState S = getSameOpcode(Last->Scalars);
2308       Last->setOperations(S);
2309       Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end());
2310     }
2311     if (Last->State != TreeEntry::NeedToGather) {
2312       for (Value *V : VL) {
2313         assert(!getTreeEntry(V) && "Scalar already in tree!");
2314         ScalarToTreeEntry[V] = Last;
2315       }
2316       // Update the scheduler bundle to point to this TreeEntry.
2317       unsigned Lane = 0;
2318       for (ScheduleData *BundleMember = Bundle.getValue(); BundleMember;
2319            BundleMember = BundleMember->NextInBundle) {
2320         BundleMember->TE = Last;
2321         BundleMember->Lane = Lane;
2322         ++Lane;
2323       }
2324       assert((!Bundle.getValue() || Lane == VL.size()) &&
2325              "Bundle and VL out of sync");
2326     } else {
2327       MustGather.insert(VL.begin(), VL.end());
2328     }
2329 
2330     if (UserTreeIdx.UserTE)
2331       Last->UserTreeIndices.push_back(UserTreeIdx);
2332 
2333     return Last;
2334   }
2335 
2336   /// -- Vectorization State --
2337   /// Holds all of the tree entries.
2338   TreeEntry::VecTreeTy VectorizableTree;
2339 
2340 #ifndef NDEBUG
2341   /// Debug printer.
2342   LLVM_DUMP_METHOD void dumpVectorizableTree() const {
2343     for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) {
2344       VectorizableTree[Id]->dump();
2345       dbgs() << "\n";
2346     }
2347   }
2348 #endif
2349 
2350   TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); }
2351 
2352   const TreeEntry *getTreeEntry(Value *V) const {
2353     return ScalarToTreeEntry.lookup(V);
2354   }
2355 
2356   /// Maps a specific scalar to its tree entry.
2357   SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry;
2358 
2359   /// Maps a value to the proposed vectorizable size.
2360   SmallDenseMap<Value *, unsigned> InstrElementSize;
2361 
2362   /// A list of scalars that we found that we need to keep as scalars.
2363   ValueSet MustGather;
2364 
2365   /// This POD struct describes one external user in the vectorized tree.
2366   struct ExternalUser {
2367     ExternalUser(Value *S, llvm::User *U, int L)
2368         : Scalar(S), User(U), Lane(L) {}
2369 
2370     // Which scalar in our function.
2371     Value *Scalar;
2372 
2373     // Which user that uses the scalar.
2374     llvm::User *User;
2375 
2376     // Which lane does the scalar belong to.
2377     int Lane;
2378   };
2379   using UserList = SmallVector<ExternalUser, 16>;
2380 
2381   /// Checks if two instructions may access the same memory.
2382   ///
2383   /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
2384   /// is invariant in the calling loop.
2385   bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
2386                  Instruction *Inst2) {
2387     // First check if the result is already in the cache.
2388     AliasCacheKey key = std::make_pair(Inst1, Inst2);
2389     Optional<bool> &result = AliasCache[key];
2390     if (result.hasValue()) {
2391       return result.getValue();
2392     }
2393     bool aliased = true;
2394     if (Loc1.Ptr && isSimple(Inst1))
2395       aliased = isModOrRefSet(AA->getModRefInfo(Inst2, Loc1));
2396     // Store the result in the cache.
2397     result = aliased;
2398     return aliased;
2399   }
2400 
2401   using AliasCacheKey = std::pair<Instruction *, Instruction *>;
2402 
2403   /// Cache for alias results.
2404   /// TODO: consider moving this to the AliasAnalysis itself.
2405   DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
2406 
2407   /// Removes an instruction from its block and eventually deletes it.
2408   /// It's like Instruction::eraseFromParent() except that the actual deletion
2409   /// is delayed until BoUpSLP is destructed.
2410   /// This is required to ensure that there are no incorrect collisions in the
2411   /// AliasCache, which can happen if a new instruction is allocated at the
2412   /// same address as a previously deleted instruction.
2413   void eraseInstruction(Instruction *I, bool ReplaceOpsWithUndef = false) {
2414     auto It = DeletedInstructions.try_emplace(I, ReplaceOpsWithUndef).first;
2415     It->getSecond() = It->getSecond() && ReplaceOpsWithUndef;
2416   }
2417 
2418   /// Temporary store for deleted instructions. Instructions will be deleted
2419   /// eventually when the BoUpSLP is destructed.
2420   DenseMap<Instruction *, bool> DeletedInstructions;
2421 
2422   /// A list of values that need to extracted out of the tree.
2423   /// This list holds pairs of (Internal Scalar : External User). External User
2424   /// can be nullptr, it means that this Internal Scalar will be used later,
2425   /// after vectorization.
2426   UserList ExternalUses;
2427 
2428   /// Values used only by @llvm.assume calls.
2429   SmallPtrSet<const Value *, 32> EphValues;
2430 
2431   /// Holds all of the instructions that we gathered.
2432   SetVector<Instruction *> GatherShuffleSeq;
2433 
2434   /// A list of blocks that we are going to CSE.
2435   SetVector<BasicBlock *> CSEBlocks;
2436 
2437   /// Contains all scheduling relevant data for an instruction.
2438   /// A ScheduleData either represents a single instruction or a member of an
2439   /// instruction bundle (= a group of instructions which is combined into a
2440   /// vector instruction).
2441   struct ScheduleData {
2442     // The initial value for the dependency counters. It means that the
2443     // dependencies are not calculated yet.
2444     enum { InvalidDeps = -1 };
2445 
2446     ScheduleData() = default;
2447 
2448     void init(int BlockSchedulingRegionID, Value *OpVal) {
2449       FirstInBundle = this;
2450       NextInBundle = nullptr;
2451       NextLoadStore = nullptr;
2452       IsScheduled = false;
2453       SchedulingRegionID = BlockSchedulingRegionID;
2454       clearDependencies();
2455       OpValue = OpVal;
2456       TE = nullptr;
2457       Lane = -1;
2458     }
2459 
2460     /// Verify basic self consistency properties
2461     void verify() {
2462       if (hasValidDependencies()) {
2463         assert(UnscheduledDeps <= Dependencies && "invariant");
2464       } else {
2465         assert(UnscheduledDeps == Dependencies && "invariant");
2466       }
2467 
2468       if (IsScheduled) {
2469         assert(isSchedulingEntity() &&
2470                 "unexpected scheduled state");
2471         for (const ScheduleData *BundleMember = this; BundleMember;
2472              BundleMember = BundleMember->NextInBundle) {
2473           assert(BundleMember->hasValidDependencies() &&
2474                  BundleMember->UnscheduledDeps == 0 &&
2475                  "unexpected scheduled state");
2476           assert((BundleMember == this || !BundleMember->IsScheduled) &&
2477                  "only bundle is marked scheduled");
2478         }
2479       }
2480     }
2481 
2482     /// Returns true if the dependency information has been calculated.
2483     /// Note that depenendency validity can vary between instructions within
2484     /// a single bundle.
2485     bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
2486 
2487     /// Returns true for single instructions and for bundle representatives
2488     /// (= the head of a bundle).
2489     bool isSchedulingEntity() const { return FirstInBundle == this; }
2490 
2491     /// Returns true if it represents an instruction bundle and not only a
2492     /// single instruction.
2493     bool isPartOfBundle() const {
2494       return NextInBundle != nullptr || FirstInBundle != this;
2495     }
2496 
2497     /// Returns true if it is ready for scheduling, i.e. it has no more
2498     /// unscheduled depending instructions/bundles.
2499     bool isReady() const {
2500       assert(isSchedulingEntity() &&
2501              "can't consider non-scheduling entity for ready list");
2502       return unscheduledDepsInBundle() == 0 && !IsScheduled;
2503     }
2504 
2505     /// Modifies the number of unscheduled dependencies for this instruction,
2506     /// and returns the number of remaining dependencies for the containing
2507     /// bundle.
2508     int incrementUnscheduledDeps(int Incr) {
2509       assert(hasValidDependencies() &&
2510              "increment of unscheduled deps would be meaningless");
2511       UnscheduledDeps += Incr;
2512       return FirstInBundle->unscheduledDepsInBundle();
2513     }
2514 
2515     /// Sets the number of unscheduled dependencies to the number of
2516     /// dependencies.
2517     void resetUnscheduledDeps() {
2518       UnscheduledDeps = Dependencies;
2519     }
2520 
2521     /// Clears all dependency information.
2522     void clearDependencies() {
2523       Dependencies = InvalidDeps;
2524       resetUnscheduledDeps();
2525       MemoryDependencies.clear();
2526     }
2527 
2528     int unscheduledDepsInBundle() const {
2529       assert(isSchedulingEntity() && "only meaningful on the bundle");
2530       int Sum = 0;
2531       for (const ScheduleData *BundleMember = this; BundleMember;
2532            BundleMember = BundleMember->NextInBundle) {
2533         if (BundleMember->UnscheduledDeps == InvalidDeps)
2534           return InvalidDeps;
2535         Sum += BundleMember->UnscheduledDeps;
2536       }
2537       return Sum;
2538     }
2539 
2540     void dump(raw_ostream &os) const {
2541       if (!isSchedulingEntity()) {
2542         os << "/ " << *Inst;
2543       } else if (NextInBundle) {
2544         os << '[' << *Inst;
2545         ScheduleData *SD = NextInBundle;
2546         while (SD) {
2547           os << ';' << *SD->Inst;
2548           SD = SD->NextInBundle;
2549         }
2550         os << ']';
2551       } else {
2552         os << *Inst;
2553       }
2554     }
2555 
2556     Instruction *Inst = nullptr;
2557 
2558     /// Points to the head in an instruction bundle (and always to this for
2559     /// single instructions).
2560     ScheduleData *FirstInBundle = nullptr;
2561 
2562     /// Single linked list of all instructions in a bundle. Null if it is a
2563     /// single instruction.
2564     ScheduleData *NextInBundle = nullptr;
2565 
2566     /// Single linked list of all memory instructions (e.g. load, store, call)
2567     /// in the block - until the end of the scheduling region.
2568     ScheduleData *NextLoadStore = nullptr;
2569 
2570     /// The dependent memory instructions.
2571     /// This list is derived on demand in calculateDependencies().
2572     SmallVector<ScheduleData *, 4> MemoryDependencies;
2573 
2574     /// This ScheduleData is in the current scheduling region if this matches
2575     /// the current SchedulingRegionID of BlockScheduling.
2576     int SchedulingRegionID = 0;
2577 
2578     /// Used for getting a "good" final ordering of instructions.
2579     int SchedulingPriority = 0;
2580 
2581     /// The number of dependencies. Constitutes of the number of users of the
2582     /// instruction plus the number of dependent memory instructions (if any).
2583     /// This value is calculated on demand.
2584     /// If InvalidDeps, the number of dependencies is not calculated yet.
2585     int Dependencies = InvalidDeps;
2586 
2587     /// The number of dependencies minus the number of dependencies of scheduled
2588     /// instructions. As soon as this is zero, the instruction/bundle gets ready
2589     /// for scheduling.
2590     /// Note that this is negative as long as Dependencies is not calculated.
2591     int UnscheduledDeps = InvalidDeps;
2592 
2593     /// True if this instruction is scheduled (or considered as scheduled in the
2594     /// dry-run).
2595     bool IsScheduled = false;
2596 
2597     /// Opcode of the current instruction in the schedule data.
2598     Value *OpValue = nullptr;
2599 
2600     /// The TreeEntry that this instruction corresponds to.
2601     TreeEntry *TE = nullptr;
2602 
2603     /// The lane of this node in the TreeEntry.
2604     int Lane = -1;
2605   };
2606 
2607 #ifndef NDEBUG
2608   friend inline raw_ostream &operator<<(raw_ostream &os,
2609                                         const BoUpSLP::ScheduleData &SD) {
2610     SD.dump(os);
2611     return os;
2612   }
2613 #endif
2614 
2615   friend struct GraphTraits<BoUpSLP *>;
2616   friend struct DOTGraphTraits<BoUpSLP *>;
2617 
2618   /// Contains all scheduling data for a basic block.
2619   struct BlockScheduling {
2620     BlockScheduling(BasicBlock *BB)
2621         : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
2622 
2623     void clear() {
2624       ReadyInsts.clear();
2625       ScheduleStart = nullptr;
2626       ScheduleEnd = nullptr;
2627       FirstLoadStoreInRegion = nullptr;
2628       LastLoadStoreInRegion = nullptr;
2629 
2630       // Reduce the maximum schedule region size by the size of the
2631       // previous scheduling run.
2632       ScheduleRegionSizeLimit -= ScheduleRegionSize;
2633       if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
2634         ScheduleRegionSizeLimit = MinScheduleRegionSize;
2635       ScheduleRegionSize = 0;
2636 
2637       // Make a new scheduling region, i.e. all existing ScheduleData is not
2638       // in the new region yet.
2639       ++SchedulingRegionID;
2640     }
2641 
2642     ScheduleData *getScheduleData(Value *V) {
2643       ScheduleData *SD = ScheduleDataMap[V];
2644       if (SD && SD->SchedulingRegionID == SchedulingRegionID)
2645         return SD;
2646       return nullptr;
2647     }
2648 
2649     ScheduleData *getScheduleData(Value *V, Value *Key) {
2650       if (V == Key)
2651         return getScheduleData(V);
2652       auto I = ExtraScheduleDataMap.find(V);
2653       if (I != ExtraScheduleDataMap.end()) {
2654         ScheduleData *SD = I->second[Key];
2655         if (SD && SD->SchedulingRegionID == SchedulingRegionID)
2656           return SD;
2657       }
2658       return nullptr;
2659     }
2660 
2661     bool isInSchedulingRegion(ScheduleData *SD) const {
2662       return SD->SchedulingRegionID == SchedulingRegionID;
2663     }
2664 
2665     /// Marks an instruction as scheduled and puts all dependent ready
2666     /// instructions into the ready-list.
2667     template <typename ReadyListType>
2668     void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
2669       SD->IsScheduled = true;
2670       LLVM_DEBUG(dbgs() << "SLP:   schedule " << *SD << "\n");
2671 
2672       for (ScheduleData *BundleMember = SD; BundleMember;
2673            BundleMember = BundleMember->NextInBundle) {
2674         if (BundleMember->Inst != BundleMember->OpValue)
2675           continue;
2676 
2677         // Handle the def-use chain dependencies.
2678 
2679         // Decrement the unscheduled counter and insert to ready list if ready.
2680         auto &&DecrUnsched = [this, &ReadyList](Instruction *I) {
2681           doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
2682             if (OpDef && OpDef->hasValidDependencies() &&
2683                 OpDef->incrementUnscheduledDeps(-1) == 0) {
2684               // There are no more unscheduled dependencies after
2685               // decrementing, so we can put the dependent instruction
2686               // into the ready list.
2687               ScheduleData *DepBundle = OpDef->FirstInBundle;
2688               assert(!DepBundle->IsScheduled &&
2689                      "already scheduled bundle gets ready");
2690               ReadyList.insert(DepBundle);
2691               LLVM_DEBUG(dbgs()
2692                          << "SLP:    gets ready (def): " << *DepBundle << "\n");
2693             }
2694           });
2695         };
2696 
2697         // If BundleMember is a vector bundle, its operands may have been
2698         // reordered during buildTree(). We therefore need to get its operands
2699         // through the TreeEntry.
2700         if (TreeEntry *TE = BundleMember->TE) {
2701           int Lane = BundleMember->Lane;
2702           assert(Lane >= 0 && "Lane not set");
2703 
2704           // Since vectorization tree is being built recursively this assertion
2705           // ensures that the tree entry has all operands set before reaching
2706           // this code. Couple of exceptions known at the moment are extracts
2707           // where their second (immediate) operand is not added. Since
2708           // immediates do not affect scheduler behavior this is considered
2709           // okay.
2710           auto *In = TE->getMainOp();
2711           assert(In &&
2712                  (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) ||
2713                   In->getNumOperands() == TE->getNumOperands()) &&
2714                  "Missed TreeEntry operands?");
2715           (void)In; // fake use to avoid build failure when assertions disabled
2716 
2717           for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands();
2718                OpIdx != NumOperands; ++OpIdx)
2719             if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane]))
2720               DecrUnsched(I);
2721         } else {
2722           // If BundleMember is a stand-alone instruction, no operand reordering
2723           // has taken place, so we directly access its operands.
2724           for (Use &U : BundleMember->Inst->operands())
2725             if (auto *I = dyn_cast<Instruction>(U.get()))
2726               DecrUnsched(I);
2727         }
2728         // Handle the memory dependencies.
2729         for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
2730           if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
2731             // There are no more unscheduled dependencies after decrementing,
2732             // so we can put the dependent instruction into the ready list.
2733             ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
2734             assert(!DepBundle->IsScheduled &&
2735                    "already scheduled bundle gets ready");
2736             ReadyList.insert(DepBundle);
2737             LLVM_DEBUG(dbgs()
2738                        << "SLP:    gets ready (mem): " << *DepBundle << "\n");
2739           }
2740         }
2741       }
2742     }
2743 
2744     /// Verify basic self consistency properties of the data structure.
2745     void verify() {
2746       if (!ScheduleStart)
2747         return;
2748 
2749       assert(ScheduleStart->getParent() == ScheduleEnd->getParent() &&
2750              ScheduleStart->comesBefore(ScheduleEnd) &&
2751              "Not a valid scheduling region?");
2752 
2753       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2754         auto *SD = getScheduleData(I);
2755         assert(SD && "primary scheduledata must exist in window");
2756         assert(isInSchedulingRegion(SD) &&
2757                "primary schedule data not in window?");
2758         (void)SD;
2759         doForAllOpcodes(I, [](ScheduleData *SD) { SD->verify(); });
2760       }
2761 
2762       for (auto *SD : ReadyInsts) {
2763         assert(SD->isSchedulingEntity() && SD->isReady() &&
2764                "item in ready list not ready?");
2765         (void)SD;
2766       }
2767     }
2768 
2769     void doForAllOpcodes(Value *V,
2770                          function_ref<void(ScheduleData *SD)> Action) {
2771       if (ScheduleData *SD = getScheduleData(V))
2772         Action(SD);
2773       auto I = ExtraScheduleDataMap.find(V);
2774       if (I != ExtraScheduleDataMap.end())
2775         for (auto &P : I->second)
2776           if (P.second->SchedulingRegionID == SchedulingRegionID)
2777             Action(P.second);
2778     }
2779 
2780     /// Put all instructions into the ReadyList which are ready for scheduling.
2781     template <typename ReadyListType>
2782     void initialFillReadyList(ReadyListType &ReadyList) {
2783       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2784         doForAllOpcodes(I, [&](ScheduleData *SD) {
2785           if (SD->isSchedulingEntity() && SD->isReady()) {
2786             ReadyList.insert(SD);
2787             LLVM_DEBUG(dbgs()
2788                        << "SLP:    initially in ready list: " << *SD << "\n");
2789           }
2790         });
2791       }
2792     }
2793 
2794     /// Build a bundle from the ScheduleData nodes corresponding to the
2795     /// scalar instruction for each lane.
2796     ScheduleData *buildBundle(ArrayRef<Value *> VL);
2797 
2798     /// Checks if a bundle of instructions can be scheduled, i.e. has no
2799     /// cyclic dependencies. This is only a dry-run, no instructions are
2800     /// actually moved at this stage.
2801     /// \returns the scheduling bundle. The returned Optional value is non-None
2802     /// if \p VL is allowed to be scheduled.
2803     Optional<ScheduleData *>
2804     tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
2805                       const InstructionsState &S);
2806 
2807     /// Un-bundles a group of instructions.
2808     void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
2809 
2810     /// Allocates schedule data chunk.
2811     ScheduleData *allocateScheduleDataChunks();
2812 
2813     /// Extends the scheduling region so that V is inside the region.
2814     /// \returns true if the region size is within the limit.
2815     bool extendSchedulingRegion(Value *V, const InstructionsState &S);
2816 
2817     /// Initialize the ScheduleData structures for new instructions in the
2818     /// scheduling region.
2819     void initScheduleData(Instruction *FromI, Instruction *ToI,
2820                           ScheduleData *PrevLoadStore,
2821                           ScheduleData *NextLoadStore);
2822 
2823     /// Updates the dependency information of a bundle and of all instructions/
2824     /// bundles which depend on the original bundle.
2825     void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
2826                                BoUpSLP *SLP);
2827 
2828     /// Sets all instruction in the scheduling region to un-scheduled.
2829     void resetSchedule();
2830 
2831     BasicBlock *BB;
2832 
2833     /// Simple memory allocation for ScheduleData.
2834     std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
2835 
2836     /// The size of a ScheduleData array in ScheduleDataChunks.
2837     int ChunkSize;
2838 
2839     /// The allocator position in the current chunk, which is the last entry
2840     /// of ScheduleDataChunks.
2841     int ChunkPos;
2842 
2843     /// Attaches ScheduleData to Instruction.
2844     /// Note that the mapping survives during all vectorization iterations, i.e.
2845     /// ScheduleData structures are recycled.
2846     DenseMap<Value *, ScheduleData *> ScheduleDataMap;
2847 
2848     /// Attaches ScheduleData to Instruction with the leading key.
2849     DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
2850         ExtraScheduleDataMap;
2851 
2852     /// The ready-list for scheduling (only used for the dry-run).
2853     SetVector<ScheduleData *> ReadyInsts;
2854 
2855     /// The first instruction of the scheduling region.
2856     Instruction *ScheduleStart = nullptr;
2857 
2858     /// The first instruction _after_ the scheduling region.
2859     Instruction *ScheduleEnd = nullptr;
2860 
2861     /// The first memory accessing instruction in the scheduling region
2862     /// (can be null).
2863     ScheduleData *FirstLoadStoreInRegion = nullptr;
2864 
2865     /// The last memory accessing instruction in the scheduling region
2866     /// (can be null).
2867     ScheduleData *LastLoadStoreInRegion = nullptr;
2868 
2869     /// The current size of the scheduling region.
2870     int ScheduleRegionSize = 0;
2871 
2872     /// The maximum size allowed for the scheduling region.
2873     int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
2874 
2875     /// The ID of the scheduling region. For a new vectorization iteration this
2876     /// is incremented which "removes" all ScheduleData from the region.
2877     // Make sure that the initial SchedulingRegionID is greater than the
2878     // initial SchedulingRegionID in ScheduleData (which is 0).
2879     int SchedulingRegionID = 1;
2880   };
2881 
2882   /// Attaches the BlockScheduling structures to basic blocks.
2883   MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
2884 
2885   /// Performs the "real" scheduling. Done before vectorization is actually
2886   /// performed in a basic block.
2887   void scheduleBlock(BlockScheduling *BS);
2888 
2889   /// List of users to ignore during scheduling and that don't need extracting.
2890   ArrayRef<Value *> UserIgnoreList;
2891 
2892   /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
2893   /// sorted SmallVectors of unsigned.
2894   struct OrdersTypeDenseMapInfo {
2895     static OrdersType getEmptyKey() {
2896       OrdersType V;
2897       V.push_back(~1U);
2898       return V;
2899     }
2900 
2901     static OrdersType getTombstoneKey() {
2902       OrdersType V;
2903       V.push_back(~2U);
2904       return V;
2905     }
2906 
2907     static unsigned getHashValue(const OrdersType &V) {
2908       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
2909     }
2910 
2911     static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
2912       return LHS == RHS;
2913     }
2914   };
2915 
2916   // Analysis and block reference.
2917   Function *F;
2918   ScalarEvolution *SE;
2919   TargetTransformInfo *TTI;
2920   TargetLibraryInfo *TLI;
2921   AAResults *AA;
2922   LoopInfo *LI;
2923   DominatorTree *DT;
2924   AssumptionCache *AC;
2925   DemandedBits *DB;
2926   const DataLayout *DL;
2927   OptimizationRemarkEmitter *ORE;
2928 
2929   unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
2930   unsigned MinVecRegSize; // Set by cl::opt (default: 128).
2931 
2932   /// Instruction builder to construct the vectorized tree.
2933   IRBuilder<> Builder;
2934 
2935   /// A map of scalar integer values to the smallest bit width with which they
2936   /// can legally be represented. The values map to (width, signed) pairs,
2937   /// where "width" indicates the minimum bit width and "signed" is True if the
2938   /// value must be signed-extended, rather than zero-extended, back to its
2939   /// original width.
2940   MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
2941 };
2942 
2943 } // end namespace slpvectorizer
2944 
2945 template <> struct GraphTraits<BoUpSLP *> {
2946   using TreeEntry = BoUpSLP::TreeEntry;
2947 
2948   /// NodeRef has to be a pointer per the GraphWriter.
2949   using NodeRef = TreeEntry *;
2950 
2951   using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy;
2952 
2953   /// Add the VectorizableTree to the index iterator to be able to return
2954   /// TreeEntry pointers.
2955   struct ChildIteratorType
2956       : public iterator_adaptor_base<
2957             ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
2958     ContainerTy &VectorizableTree;
2959 
2960     ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W,
2961                       ContainerTy &VT)
2962         : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
2963 
2964     NodeRef operator*() { return I->UserTE; }
2965   };
2966 
2967   static NodeRef getEntryNode(BoUpSLP &R) {
2968     return R.VectorizableTree[0].get();
2969   }
2970 
2971   static ChildIteratorType child_begin(NodeRef N) {
2972     return {N->UserTreeIndices.begin(), N->Container};
2973   }
2974 
2975   static ChildIteratorType child_end(NodeRef N) {
2976     return {N->UserTreeIndices.end(), N->Container};
2977   }
2978 
2979   /// For the node iterator we just need to turn the TreeEntry iterator into a
2980   /// TreeEntry* iterator so that it dereferences to NodeRef.
2981   class nodes_iterator {
2982     using ItTy = ContainerTy::iterator;
2983     ItTy It;
2984 
2985   public:
2986     nodes_iterator(const ItTy &It2) : It(It2) {}
2987     NodeRef operator*() { return It->get(); }
2988     nodes_iterator operator++() {
2989       ++It;
2990       return *this;
2991     }
2992     bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
2993   };
2994 
2995   static nodes_iterator nodes_begin(BoUpSLP *R) {
2996     return nodes_iterator(R->VectorizableTree.begin());
2997   }
2998 
2999   static nodes_iterator nodes_end(BoUpSLP *R) {
3000     return nodes_iterator(R->VectorizableTree.end());
3001   }
3002 
3003   static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
3004 };
3005 
3006 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
3007   using TreeEntry = BoUpSLP::TreeEntry;
3008 
3009   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
3010 
3011   std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
3012     std::string Str;
3013     raw_string_ostream OS(Str);
3014     if (isSplat(Entry->Scalars))
3015       OS << "<splat> ";
3016     for (auto V : Entry->Scalars) {
3017       OS << *V;
3018       if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) {
3019             return EU.Scalar == V;
3020           }))
3021         OS << " <extract>";
3022       OS << "\n";
3023     }
3024     return Str;
3025   }
3026 
3027   static std::string getNodeAttributes(const TreeEntry *Entry,
3028                                        const BoUpSLP *) {
3029     if (Entry->State == TreeEntry::NeedToGather)
3030       return "color=red";
3031     return "";
3032   }
3033 };
3034 
3035 } // end namespace llvm
3036 
3037 BoUpSLP::~BoUpSLP() {
3038   for (const auto &Pair : DeletedInstructions) {
3039     // Replace operands of ignored instructions with Undefs in case if they were
3040     // marked for deletion.
3041     if (Pair.getSecond()) {
3042       Value *Undef = UndefValue::get(Pair.getFirst()->getType());
3043       Pair.getFirst()->replaceAllUsesWith(Undef);
3044     }
3045     Pair.getFirst()->dropAllReferences();
3046   }
3047   for (const auto &Pair : DeletedInstructions) {
3048     assert(Pair.getFirst()->use_empty() &&
3049            "trying to erase instruction with users.");
3050     Pair.getFirst()->eraseFromParent();
3051   }
3052 #ifdef EXPENSIVE_CHECKS
3053   // If we could guarantee that this call is not extremely slow, we could
3054   // remove the ifdef limitation (see PR47712).
3055   assert(!verifyFunction(*F, &dbgs()));
3056 #endif
3057 }
3058 
3059 void BoUpSLP::eraseInstructions(ArrayRef<Value *> AV) {
3060   for (auto *V : AV) {
3061     if (auto *I = dyn_cast<Instruction>(V))
3062       eraseInstruction(I, /*ReplaceOpsWithUndef=*/true);
3063   };
3064 }
3065 
3066 /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses
3067 /// contains original mask for the scalars reused in the node. Procedure
3068 /// transform this mask in accordance with the given \p Mask.
3069 static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) {
3070   assert(!Mask.empty() && Reuses.size() == Mask.size() &&
3071          "Expected non-empty mask.");
3072   SmallVector<int> Prev(Reuses.begin(), Reuses.end());
3073   Prev.swap(Reuses);
3074   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
3075     if (Mask[I] != UndefMaskElem)
3076       Reuses[Mask[I]] = Prev[I];
3077 }
3078 
3079 /// Reorders the given \p Order according to the given \p Mask. \p Order - is
3080 /// the original order of the scalars. Procedure transforms the provided order
3081 /// in accordance with the given \p Mask. If the resulting \p Order is just an
3082 /// identity order, \p Order is cleared.
3083 static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) {
3084   assert(!Mask.empty() && "Expected non-empty mask.");
3085   SmallVector<int> MaskOrder;
3086   if (Order.empty()) {
3087     MaskOrder.resize(Mask.size());
3088     std::iota(MaskOrder.begin(), MaskOrder.end(), 0);
3089   } else {
3090     inversePermutation(Order, MaskOrder);
3091   }
3092   reorderReuses(MaskOrder, Mask);
3093   if (ShuffleVectorInst::isIdentityMask(MaskOrder)) {
3094     Order.clear();
3095     return;
3096   }
3097   Order.assign(Mask.size(), Mask.size());
3098   for (unsigned I = 0, E = Mask.size(); I < E; ++I)
3099     if (MaskOrder[I] != UndefMaskElem)
3100       Order[MaskOrder[I]] = I;
3101   fixupOrderingIndices(Order);
3102 }
3103 
3104 Optional<BoUpSLP::OrdersType>
3105 BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) {
3106   assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
3107   unsigned NumScalars = TE.Scalars.size();
3108   OrdersType CurrentOrder(NumScalars, NumScalars);
3109   SmallVector<int> Positions;
3110   SmallBitVector UsedPositions(NumScalars);
3111   const TreeEntry *STE = nullptr;
3112   // Try to find all gathered scalars that are gets vectorized in other
3113   // vectorize node. Here we can have only one single tree vector node to
3114   // correctly identify order of the gathered scalars.
3115   for (unsigned I = 0; I < NumScalars; ++I) {
3116     Value *V = TE.Scalars[I];
3117     if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V))
3118       continue;
3119     if (const auto *LocalSTE = getTreeEntry(V)) {
3120       if (!STE)
3121         STE = LocalSTE;
3122       else if (STE != LocalSTE)
3123         // Take the order only from the single vector node.
3124         return None;
3125       unsigned Lane =
3126           std::distance(STE->Scalars.begin(), find(STE->Scalars, V));
3127       if (Lane >= NumScalars)
3128         return None;
3129       if (CurrentOrder[Lane] != NumScalars) {
3130         if (Lane != I)
3131           continue;
3132         UsedPositions.reset(CurrentOrder[Lane]);
3133       }
3134       // The partial identity (where only some elements of the gather node are
3135       // in the identity order) is good.
3136       CurrentOrder[Lane] = I;
3137       UsedPositions.set(I);
3138     }
3139   }
3140   // Need to keep the order if we have a vector entry and at least 2 scalars or
3141   // the vectorized entry has just 2 scalars.
3142   if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) {
3143     auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) {
3144       for (unsigned I = 0; I < NumScalars; ++I)
3145         if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars)
3146           return false;
3147       return true;
3148     };
3149     if (IsIdentityOrder(CurrentOrder)) {
3150       CurrentOrder.clear();
3151       return CurrentOrder;
3152     }
3153     auto *It = CurrentOrder.begin();
3154     for (unsigned I = 0; I < NumScalars;) {
3155       if (UsedPositions.test(I)) {
3156         ++I;
3157         continue;
3158       }
3159       if (*It == NumScalars) {
3160         *It = I;
3161         ++I;
3162       }
3163       ++It;
3164     }
3165     return CurrentOrder;
3166   }
3167   return None;
3168 }
3169 
3170 Optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE,
3171                                                          bool TopToBottom) {
3172   // No need to reorder if need to shuffle reuses, still need to shuffle the
3173   // node.
3174   if (!TE.ReuseShuffleIndices.empty())
3175     return None;
3176   if (TE.State == TreeEntry::Vectorize &&
3177       (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) ||
3178        (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) &&
3179       !TE.isAltShuffle())
3180     return TE.ReorderIndices;
3181   if (TE.State == TreeEntry::NeedToGather) {
3182     // TODO: add analysis of other gather nodes with extractelement
3183     // instructions and other values/instructions, not only undefs.
3184     if (((TE.getOpcode() == Instruction::ExtractElement &&
3185           !TE.isAltShuffle()) ||
3186          (all_of(TE.Scalars,
3187                  [](Value *V) {
3188                    return isa<UndefValue, ExtractElementInst>(V);
3189                  }) &&
3190           any_of(TE.Scalars,
3191                  [](Value *V) { return isa<ExtractElementInst>(V); }))) &&
3192         all_of(TE.Scalars,
3193                [](Value *V) {
3194                  auto *EE = dyn_cast<ExtractElementInst>(V);
3195                  return !EE || isa<FixedVectorType>(EE->getVectorOperandType());
3196                }) &&
3197         allSameType(TE.Scalars)) {
3198       // Check that gather of extractelements can be represented as
3199       // just a shuffle of a single vector.
3200       OrdersType CurrentOrder;
3201       bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder);
3202       if (Reuse || !CurrentOrder.empty()) {
3203         if (!CurrentOrder.empty())
3204           fixupOrderingIndices(CurrentOrder);
3205         return CurrentOrder;
3206       }
3207     }
3208     if (Optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE))
3209       return CurrentOrder;
3210   }
3211   return None;
3212 }
3213 
3214 void BoUpSLP::reorderTopToBottom() {
3215   // Maps VF to the graph nodes.
3216   DenseMap<unsigned, SetVector<TreeEntry *>> VFToOrderedEntries;
3217   // ExtractElement gather nodes which can be vectorized and need to handle
3218   // their ordering.
3219   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3220   // Find all reorderable nodes with the given VF.
3221   // Currently the are vectorized stores,loads,extracts + some gathering of
3222   // extracts.
3223   for_each(VectorizableTree, [this, &VFToOrderedEntries, &GathersToOrders](
3224                                  const std::unique_ptr<TreeEntry> &TE) {
3225     if (Optional<OrdersType> CurrentOrder =
3226             getReorderingData(*TE.get(), /*TopToBottom=*/true)) {
3227       // Do not include ordering for nodes used in the alt opcode vectorization,
3228       // better to reorder them during bottom-to-top stage. If follow the order
3229       // here, it causes reordering of the whole graph though actually it is
3230       // profitable just to reorder the subgraph that starts from the alternate
3231       // opcode vectorization node. Such nodes already end-up with the shuffle
3232       // instruction and it is just enough to change this shuffle rather than
3233       // rotate the scalars for the whole graph.
3234       unsigned Cnt = 0;
3235       const TreeEntry *UserTE = TE.get();
3236       while (UserTE && Cnt < RecursionMaxDepth) {
3237         if (UserTE->UserTreeIndices.size() != 1)
3238           break;
3239         if (all_of(UserTE->UserTreeIndices, [](const EdgeInfo &EI) {
3240               return EI.UserTE->State == TreeEntry::Vectorize &&
3241                      EI.UserTE->isAltShuffle() && EI.UserTE->Idx != 0;
3242             }))
3243           return;
3244         if (UserTE->UserTreeIndices.empty())
3245           UserTE = nullptr;
3246         else
3247           UserTE = UserTE->UserTreeIndices.back().UserTE;
3248         ++Cnt;
3249       }
3250       VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
3251       if (TE->State != TreeEntry::Vectorize)
3252         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3253     }
3254   });
3255 
3256   // Reorder the graph nodes according to their vectorization factor.
3257   for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1;
3258        VF /= 2) {
3259     auto It = VFToOrderedEntries.find(VF);
3260     if (It == VFToOrderedEntries.end())
3261       continue;
3262     // Try to find the most profitable order. We just are looking for the most
3263     // used order and reorder scalar elements in the nodes according to this
3264     // mostly used order.
3265     ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef();
3266     // All operands are reordered and used only in this node - propagate the
3267     // most used order to the user node.
3268     MapVector<OrdersType, unsigned,
3269               DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3270         OrdersUses;
3271     SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3272     for (const TreeEntry *OpTE : OrderedEntries) {
3273       // No need to reorder this nodes, still need to extend and to use shuffle,
3274       // just need to merge reordering shuffle and the reuse shuffle.
3275       if (!OpTE->ReuseShuffleIndices.empty())
3276         continue;
3277       // Count number of orders uses.
3278       const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3279         if (OpTE->State == TreeEntry::NeedToGather)
3280           return GathersToOrders.find(OpTE)->second;
3281         return OpTE->ReorderIndices;
3282       }();
3283       // Stores actually store the mask, not the order, need to invert.
3284       if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3285           OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3286         SmallVector<int> Mask;
3287         inversePermutation(Order, Mask);
3288         unsigned E = Order.size();
3289         OrdersType CurrentOrder(E, E);
3290         transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3291           return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3292         });
3293         fixupOrderingIndices(CurrentOrder);
3294         ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
3295       } else {
3296         ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
3297       }
3298     }
3299     // Set order of the user node.
3300     if (OrdersUses.empty())
3301       continue;
3302     // Choose the most used order.
3303     ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3304     unsigned Cnt = OrdersUses.front().second;
3305     for (const auto &Pair : drop_begin(OrdersUses)) {
3306       if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3307         BestOrder = Pair.first;
3308         Cnt = Pair.second;
3309       }
3310     }
3311     // Set order of the user node.
3312     if (BestOrder.empty())
3313       continue;
3314     SmallVector<int> Mask;
3315     inversePermutation(BestOrder, Mask);
3316     SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3317     unsigned E = BestOrder.size();
3318     transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3319       return I < E ? static_cast<int>(I) : UndefMaskElem;
3320     });
3321     // Do an actual reordering, if profitable.
3322     for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
3323       // Just do the reordering for the nodes with the given VF.
3324       if (TE->Scalars.size() != VF) {
3325         if (TE->ReuseShuffleIndices.size() == VF) {
3326           // Need to reorder the reuses masks of the operands with smaller VF to
3327           // be able to find the match between the graph nodes and scalar
3328           // operands of the given node during vectorization/cost estimation.
3329           assert(all_of(TE->UserTreeIndices,
3330                         [VF, &TE](const EdgeInfo &EI) {
3331                           return EI.UserTE->Scalars.size() == VF ||
3332                                  EI.UserTE->Scalars.size() ==
3333                                      TE->Scalars.size();
3334                         }) &&
3335                  "All users must be of VF size.");
3336           // Update ordering of the operands with the smaller VF than the given
3337           // one.
3338           reorderReuses(TE->ReuseShuffleIndices, Mask);
3339         }
3340         continue;
3341       }
3342       if (TE->State == TreeEntry::Vectorize &&
3343           isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst,
3344               InsertElementInst>(TE->getMainOp()) &&
3345           !TE->isAltShuffle()) {
3346         // Build correct orders for extract{element,value}, loads and
3347         // stores.
3348         reorderOrder(TE->ReorderIndices, Mask);
3349         if (isa<InsertElementInst, StoreInst>(TE->getMainOp()))
3350           TE->reorderOperands(Mask);
3351       } else {
3352         // Reorder the node and its operands.
3353         TE->reorderOperands(Mask);
3354         assert(TE->ReorderIndices.empty() &&
3355                "Expected empty reorder sequence.");
3356         reorderScalars(TE->Scalars, Mask);
3357       }
3358       if (!TE->ReuseShuffleIndices.empty()) {
3359         // Apply reversed order to keep the original ordering of the reused
3360         // elements to avoid extra reorder indices shuffling.
3361         OrdersType CurrentOrder;
3362         reorderOrder(CurrentOrder, MaskOrder);
3363         SmallVector<int> NewReuses;
3364         inversePermutation(CurrentOrder, NewReuses);
3365         addMask(NewReuses, TE->ReuseShuffleIndices);
3366         TE->ReuseShuffleIndices.swap(NewReuses);
3367       }
3368     }
3369   }
3370 }
3371 
3372 void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) {
3373   SetVector<TreeEntry *> OrderedEntries;
3374   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3375   // Find all reorderable leaf nodes with the given VF.
3376   // Currently the are vectorized loads,extracts without alternate operands +
3377   // some gathering of extracts.
3378   SmallVector<TreeEntry *> NonVectorized;
3379   for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders,
3380                               &NonVectorized](
3381                                  const std::unique_ptr<TreeEntry> &TE) {
3382     if (TE->State != TreeEntry::Vectorize)
3383       NonVectorized.push_back(TE.get());
3384     if (Optional<OrdersType> CurrentOrder =
3385             getReorderingData(*TE.get(), /*TopToBottom=*/false)) {
3386       OrderedEntries.insert(TE.get());
3387       if (TE->State != TreeEntry::Vectorize)
3388         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3389     }
3390   });
3391 
3392   // Checks if the operands of the users are reordarable and have only single
3393   // use.
3394   auto &&CheckOperands =
3395       [this, &NonVectorized](const auto &Data,
3396                              SmallVectorImpl<TreeEntry *> &GatherOps) {
3397         for (unsigned I = 0, E = Data.first->getNumOperands(); I < E; ++I) {
3398           if (any_of(Data.second,
3399                      [I](const std::pair<unsigned, TreeEntry *> &OpData) {
3400                        return OpData.first == I &&
3401                               OpData.second->State == TreeEntry::Vectorize;
3402                      }))
3403             continue;
3404           ArrayRef<Value *> VL = Data.first->getOperand(I);
3405           const TreeEntry *TE = nullptr;
3406           const auto *It = find_if(VL, [this, &TE](Value *V) {
3407             TE = getTreeEntry(V);
3408             return TE;
3409           });
3410           if (It != VL.end() && TE->isSame(VL))
3411             return false;
3412           TreeEntry *Gather = nullptr;
3413           if (count_if(NonVectorized, [VL, &Gather](TreeEntry *TE) {
3414                 assert(TE->State != TreeEntry::Vectorize &&
3415                        "Only non-vectorized nodes are expected.");
3416                 if (TE->isSame(VL)) {
3417                   Gather = TE;
3418                   return true;
3419                 }
3420                 return false;
3421               }) > 1)
3422             return false;
3423           if (Gather)
3424             GatherOps.push_back(Gather);
3425         }
3426         return true;
3427       };
3428   // 1. Propagate order to the graph nodes, which use only reordered nodes.
3429   // I.e., if the node has operands, that are reordered, try to make at least
3430   // one operand order in the natural order and reorder others + reorder the
3431   // user node itself.
3432   SmallPtrSet<const TreeEntry *, 4> Visited;
3433   while (!OrderedEntries.empty()) {
3434     // 1. Filter out only reordered nodes.
3435     // 2. If the entry has multiple uses - skip it and jump to the next node.
3436     MapVector<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users;
3437     SmallVector<TreeEntry *> Filtered;
3438     for (TreeEntry *TE : OrderedEntries) {
3439       if (!(TE->State == TreeEntry::Vectorize ||
3440             (TE->State == TreeEntry::NeedToGather &&
3441              GathersToOrders.count(TE))) ||
3442           TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3443           !all_of(drop_begin(TE->UserTreeIndices),
3444                   [TE](const EdgeInfo &EI) {
3445                     return EI.UserTE == TE->UserTreeIndices.front().UserTE;
3446                   }) ||
3447           !Visited.insert(TE).second) {
3448         Filtered.push_back(TE);
3449         continue;
3450       }
3451       // Build a map between user nodes and their operands order to speedup
3452       // search. The graph currently does not provide this dependency directly.
3453       for (EdgeInfo &EI : TE->UserTreeIndices) {
3454         TreeEntry *UserTE = EI.UserTE;
3455         auto It = Users.find(UserTE);
3456         if (It == Users.end())
3457           It = Users.insert({UserTE, {}}).first;
3458         It->second.emplace_back(EI.EdgeIdx, TE);
3459       }
3460     }
3461     // Erase filtered entries.
3462     for_each(Filtered,
3463              [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); });
3464     for (const auto &Data : Users) {
3465       // Check that operands are used only in the User node.
3466       SmallVector<TreeEntry *> GatherOps;
3467       if (!CheckOperands(Data, GatherOps)) {
3468         for_each(Data.second,
3469                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3470                    OrderedEntries.remove(Op.second);
3471                  });
3472         continue;
3473       }
3474       // All operands are reordered and used only in this node - propagate the
3475       // most used order to the user node.
3476       MapVector<OrdersType, unsigned,
3477                 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3478           OrdersUses;
3479       // Do the analysis for each tree entry only once, otherwise the order of
3480       // the same node my be considered several times, though might be not
3481       // profitable.
3482       SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3483       for (const auto &Op : Data.second) {
3484         TreeEntry *OpTE = Op.second;
3485         if (!VisitedOps.insert(OpTE).second)
3486           continue;
3487         if (!OpTE->ReuseShuffleIndices.empty() ||
3488             (IgnoreReorder && OpTE == VectorizableTree.front().get()))
3489           continue;
3490         const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3491           if (OpTE->State == TreeEntry::NeedToGather)
3492             return GathersToOrders.find(OpTE)->second;
3493           return OpTE->ReorderIndices;
3494         }();
3495         // Stores actually store the mask, not the order, need to invert.
3496         if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3497             OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3498           SmallVector<int> Mask;
3499           inversePermutation(Order, Mask);
3500           unsigned E = Order.size();
3501           OrdersType CurrentOrder(E, E);
3502           transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3503             return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3504           });
3505           fixupOrderingIndices(CurrentOrder);
3506           ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
3507         } else {
3508           ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
3509         }
3510         OrdersUses.insert(std::make_pair(OrdersType(), 0)).first->second +=
3511             OpTE->UserTreeIndices.size();
3512         assert(OrdersUses[{}] > 0 && "Counter cannot be less than 0.");
3513         --OrdersUses[{}];
3514       }
3515       // If no orders - skip current nodes and jump to the next one, if any.
3516       if (OrdersUses.empty()) {
3517         for_each(Data.second,
3518                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3519                    OrderedEntries.remove(Op.second);
3520                  });
3521         continue;
3522       }
3523       // Choose the best order.
3524       ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3525       unsigned Cnt = OrdersUses.front().second;
3526       for (const auto &Pair : drop_begin(OrdersUses)) {
3527         if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3528           BestOrder = Pair.first;
3529           Cnt = Pair.second;
3530         }
3531       }
3532       // Set order of the user node (reordering of operands and user nodes).
3533       if (BestOrder.empty()) {
3534         for_each(Data.second,
3535                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3536                    OrderedEntries.remove(Op.second);
3537                  });
3538         continue;
3539       }
3540       // Erase operands from OrderedEntries list and adjust their orders.
3541       VisitedOps.clear();
3542       SmallVector<int> Mask;
3543       inversePermutation(BestOrder, Mask);
3544       SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3545       unsigned E = BestOrder.size();
3546       transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3547         return I < E ? static_cast<int>(I) : UndefMaskElem;
3548       });
3549       for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) {
3550         TreeEntry *TE = Op.second;
3551         OrderedEntries.remove(TE);
3552         if (!VisitedOps.insert(TE).second)
3553           continue;
3554         if (!TE->ReuseShuffleIndices.empty() && TE->ReorderIndices.empty()) {
3555           // Just reorder reuses indices.
3556           reorderReuses(TE->ReuseShuffleIndices, Mask);
3557           continue;
3558         }
3559         // Gathers are processed separately.
3560         if (TE->State != TreeEntry::Vectorize)
3561           continue;
3562         assert((BestOrder.size() == TE->ReorderIndices.size() ||
3563                 TE->ReorderIndices.empty()) &&
3564                "Non-matching sizes of user/operand entries.");
3565         reorderOrder(TE->ReorderIndices, Mask);
3566       }
3567       // For gathers just need to reorder its scalars.
3568       for (TreeEntry *Gather : GatherOps) {
3569         assert(Gather->ReorderIndices.empty() &&
3570                "Unexpected reordering of gathers.");
3571         if (!Gather->ReuseShuffleIndices.empty()) {
3572           // Just reorder reuses indices.
3573           reorderReuses(Gather->ReuseShuffleIndices, Mask);
3574           continue;
3575         }
3576         reorderScalars(Gather->Scalars, Mask);
3577         OrderedEntries.remove(Gather);
3578       }
3579       // Reorder operands of the user node and set the ordering for the user
3580       // node itself.
3581       if (Data.first->State != TreeEntry::Vectorize ||
3582           !isa<ExtractElementInst, ExtractValueInst, LoadInst>(
3583               Data.first->getMainOp()) ||
3584           Data.first->isAltShuffle())
3585         Data.first->reorderOperands(Mask);
3586       if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) ||
3587           Data.first->isAltShuffle()) {
3588         reorderScalars(Data.first->Scalars, Mask);
3589         reorderOrder(Data.first->ReorderIndices, MaskOrder);
3590         if (Data.first->ReuseShuffleIndices.empty() &&
3591             !Data.first->ReorderIndices.empty() &&
3592             !Data.first->isAltShuffle()) {
3593           // Insert user node to the list to try to sink reordering deeper in
3594           // the graph.
3595           OrderedEntries.insert(Data.first);
3596         }
3597       } else {
3598         reorderOrder(Data.first->ReorderIndices, Mask);
3599       }
3600     }
3601   }
3602   // If the reordering is unnecessary, just remove the reorder.
3603   if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() &&
3604       VectorizableTree.front()->ReuseShuffleIndices.empty())
3605     VectorizableTree.front()->ReorderIndices.clear();
3606 }
3607 
3608 void BoUpSLP::buildExternalUses(
3609     const ExtraValueToDebugLocsMap &ExternallyUsedValues) {
3610   // Collect the values that we need to extract from the tree.
3611   for (auto &TEPtr : VectorizableTree) {
3612     TreeEntry *Entry = TEPtr.get();
3613 
3614     // No need to handle users of gathered values.
3615     if (Entry->State == TreeEntry::NeedToGather)
3616       continue;
3617 
3618     // For each lane:
3619     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
3620       Value *Scalar = Entry->Scalars[Lane];
3621       int FoundLane = Entry->findLaneForValue(Scalar);
3622 
3623       // Check if the scalar is externally used as an extra arg.
3624       auto ExtI = ExternallyUsedValues.find(Scalar);
3625       if (ExtI != ExternallyUsedValues.end()) {
3626         LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
3627                           << Lane << " from " << *Scalar << ".\n");
3628         ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
3629       }
3630       for (User *U : Scalar->users()) {
3631         LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
3632 
3633         Instruction *UserInst = dyn_cast<Instruction>(U);
3634         if (!UserInst)
3635           continue;
3636 
3637         if (isDeleted(UserInst))
3638           continue;
3639 
3640         // Skip in-tree scalars that become vectors
3641         if (TreeEntry *UseEntry = getTreeEntry(U)) {
3642           Value *UseScalar = UseEntry->Scalars[0];
3643           // Some in-tree scalars will remain as scalar in vectorized
3644           // instructions. If that is the case, the one in Lane 0 will
3645           // be used.
3646           if (UseScalar != U ||
3647               UseEntry->State == TreeEntry::ScatterVectorize ||
3648               !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
3649             LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
3650                               << ".\n");
3651             assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state");
3652             continue;
3653           }
3654         }
3655 
3656         // Ignore users in the user ignore list.
3657         if (is_contained(UserIgnoreList, UserInst))
3658           continue;
3659 
3660         LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
3661                           << Lane << " from " << *Scalar << ".\n");
3662         ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
3663       }
3664     }
3665   }
3666 }
3667 
3668 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
3669                         ArrayRef<Value *> UserIgnoreLst) {
3670   deleteTree();
3671   UserIgnoreList = UserIgnoreLst;
3672   if (!allSameType(Roots))
3673     return;
3674   buildTree_rec(Roots, 0, EdgeInfo());
3675 }
3676 
3677 namespace {
3678 /// Tracks the state we can represent the loads in the given sequence.
3679 enum class LoadsState { Gather, Vectorize, ScatterVectorize };
3680 } // anonymous namespace
3681 
3682 /// Checks if the given array of loads can be represented as a vectorized,
3683 /// scatter or just simple gather.
3684 static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0,
3685                                     const TargetTransformInfo &TTI,
3686                                     const DataLayout &DL, ScalarEvolution &SE,
3687                                     SmallVectorImpl<unsigned> &Order,
3688                                     SmallVectorImpl<Value *> &PointerOps) {
3689   // Check that a vectorized load would load the same memory as a scalar
3690   // load. For example, we don't want to vectorize loads that are smaller
3691   // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
3692   // treats loading/storing it as an i8 struct. If we vectorize loads/stores
3693   // from such a struct, we read/write packed bits disagreeing with the
3694   // unvectorized version.
3695   Type *ScalarTy = VL0->getType();
3696 
3697   if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy))
3698     return LoadsState::Gather;
3699 
3700   // Make sure all loads in the bundle are simple - we can't vectorize
3701   // atomic or volatile loads.
3702   PointerOps.clear();
3703   PointerOps.resize(VL.size());
3704   auto *POIter = PointerOps.begin();
3705   for (Value *V : VL) {
3706     auto *L = cast<LoadInst>(V);
3707     if (!L->isSimple())
3708       return LoadsState::Gather;
3709     *POIter = L->getPointerOperand();
3710     ++POIter;
3711   }
3712 
3713   Order.clear();
3714   // Check the order of pointer operands.
3715   if (llvm::sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order)) {
3716     Value *Ptr0;
3717     Value *PtrN;
3718     if (Order.empty()) {
3719       Ptr0 = PointerOps.front();
3720       PtrN = PointerOps.back();
3721     } else {
3722       Ptr0 = PointerOps[Order.front()];
3723       PtrN = PointerOps[Order.back()];
3724     }
3725     Optional<int> Diff =
3726         getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE);
3727     // Check that the sorted loads are consecutive.
3728     if (static_cast<unsigned>(*Diff) == VL.size() - 1)
3729       return LoadsState::Vectorize;
3730     Align CommonAlignment = cast<LoadInst>(VL0)->getAlign();
3731     for (Value *V : VL)
3732       CommonAlignment =
3733           commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
3734     if (TTI.isLegalMaskedGather(FixedVectorType::get(ScalarTy, VL.size()),
3735                                 CommonAlignment))
3736       return LoadsState::ScatterVectorize;
3737   }
3738 
3739   return LoadsState::Gather;
3740 }
3741 
3742 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
3743                             const EdgeInfo &UserTreeIdx) {
3744   assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
3745 
3746   SmallVector<int> ReuseShuffleIndicies;
3747   SmallVector<Value *> UniqueValues;
3748   auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues,
3749                                 &UserTreeIdx,
3750                                 this](const InstructionsState &S) {
3751     // Check that every instruction appears once in this bundle.
3752     DenseMap<Value *, unsigned> UniquePositions;
3753     for (Value *V : VL) {
3754       if (isConstant(V)) {
3755         ReuseShuffleIndicies.emplace_back(
3756             isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size());
3757         UniqueValues.emplace_back(V);
3758         continue;
3759       }
3760       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
3761       ReuseShuffleIndicies.emplace_back(Res.first->second);
3762       if (Res.second)
3763         UniqueValues.emplace_back(V);
3764     }
3765     size_t NumUniqueScalarValues = UniqueValues.size();
3766     if (NumUniqueScalarValues == VL.size()) {
3767       ReuseShuffleIndicies.clear();
3768     } else {
3769       LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
3770       if (NumUniqueScalarValues <= 1 ||
3771           (UniquePositions.size() == 1 && all_of(UniqueValues,
3772                                                  [](Value *V) {
3773                                                    return isa<UndefValue>(V) ||
3774                                                           !isConstant(V);
3775                                                  })) ||
3776           !llvm::isPowerOf2_32(NumUniqueScalarValues)) {
3777         LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
3778         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3779         return false;
3780       }
3781       VL = UniqueValues;
3782     }
3783     return true;
3784   };
3785 
3786   InstructionsState S = getSameOpcode(VL);
3787   if (Depth == RecursionMaxDepth) {
3788     LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
3789     if (TryToFindDuplicates(S))
3790       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3791                    ReuseShuffleIndicies);
3792     return;
3793   }
3794 
3795   // Don't handle scalable vectors
3796   if (S.getOpcode() == Instruction::ExtractElement &&
3797       isa<ScalableVectorType>(
3798           cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) {
3799     LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n");
3800     if (TryToFindDuplicates(S))
3801       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3802                    ReuseShuffleIndicies);
3803     return;
3804   }
3805 
3806   // Don't handle vectors.
3807   if (S.OpValue->getType()->isVectorTy() &&
3808       !isa<InsertElementInst>(S.OpValue)) {
3809     LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
3810     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3811     return;
3812   }
3813 
3814   if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
3815     if (SI->getValueOperand()->getType()->isVectorTy()) {
3816       LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
3817       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3818       return;
3819     }
3820 
3821   // If all of the operands are identical or constant we have a simple solution.
3822   // If we deal with insert/extract instructions, they all must have constant
3823   // indices, otherwise we should gather them, not try to vectorize.
3824   if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode() ||
3825       (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(S.MainOp) &&
3826        !all_of(VL, isVectorLikeInstWithConstOps))) {
3827     LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
3828     if (TryToFindDuplicates(S))
3829       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3830                    ReuseShuffleIndicies);
3831     return;
3832   }
3833 
3834   // We now know that this is a vector of instructions of the same type from
3835   // the same block.
3836 
3837   // Don't vectorize ephemeral values.
3838   for (Value *V : VL) {
3839     if (EphValues.count(V)) {
3840       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
3841                         << ") is ephemeral.\n");
3842       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3843       return;
3844     }
3845   }
3846 
3847   // Check if this is a duplicate of another entry.
3848   if (TreeEntry *E = getTreeEntry(S.OpValue)) {
3849     LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n");
3850     if (!E->isSame(VL)) {
3851       LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
3852       if (TryToFindDuplicates(S))
3853         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3854                      ReuseShuffleIndicies);
3855       return;
3856     }
3857     // Record the reuse of the tree node.  FIXME, currently this is only used to
3858     // properly draw the graph rather than for the actual vectorization.
3859     E->UserTreeIndices.push_back(UserTreeIdx);
3860     LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue
3861                       << ".\n");
3862     return;
3863   }
3864 
3865   // Check that none of the instructions in the bundle are already in the tree.
3866   for (Value *V : VL) {
3867     auto *I = dyn_cast<Instruction>(V);
3868     if (!I)
3869       continue;
3870     if (getTreeEntry(I)) {
3871       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
3872                         << ") is already in tree.\n");
3873       if (TryToFindDuplicates(S))
3874         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3875                      ReuseShuffleIndicies);
3876       return;
3877     }
3878   }
3879 
3880   // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
3881   for (Value *V : VL) {
3882     if (is_contained(UserIgnoreList, V)) {
3883       LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
3884       if (TryToFindDuplicates(S))
3885         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3886                      ReuseShuffleIndicies);
3887       return;
3888     }
3889   }
3890 
3891   // Check that all of the users of the scalars that we want to vectorize are
3892   // schedulable.
3893   auto *VL0 = cast<Instruction>(S.OpValue);
3894   BasicBlock *BB = VL0->getParent();
3895 
3896   if (!DT->isReachableFromEntry(BB)) {
3897     // Don't go into unreachable blocks. They may contain instructions with
3898     // dependency cycles which confuse the final scheduling.
3899     LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
3900     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3901     return;
3902   }
3903 
3904   // Check that every instruction appears once in this bundle.
3905   if (!TryToFindDuplicates(S))
3906     return;
3907 
3908   auto &BSRef = BlocksSchedules[BB];
3909   if (!BSRef)
3910     BSRef = std::make_unique<BlockScheduling>(BB);
3911 
3912   BlockScheduling &BS = *BSRef.get();
3913 
3914   Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S);
3915 #ifdef EXPENSIVE_CHECKS
3916   // Make sure we didn't break any internal invariants
3917   BS.verify();
3918 #endif
3919   if (!Bundle) {
3920     LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
3921     assert((!BS.getScheduleData(VL0) ||
3922             !BS.getScheduleData(VL0)->isPartOfBundle()) &&
3923            "tryScheduleBundle should cancelScheduling on failure");
3924     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3925                  ReuseShuffleIndicies);
3926     return;
3927   }
3928   LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
3929 
3930   unsigned ShuffleOrOp = S.isAltShuffle() ?
3931                 (unsigned) Instruction::ShuffleVector : S.getOpcode();
3932   switch (ShuffleOrOp) {
3933     case Instruction::PHI: {
3934       auto *PH = cast<PHINode>(VL0);
3935 
3936       // Check for terminator values (e.g. invoke).
3937       for (Value *V : VL)
3938         for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
3939           Instruction *Term = dyn_cast<Instruction>(
3940               cast<PHINode>(V)->getIncomingValueForBlock(
3941                   PH->getIncomingBlock(I)));
3942           if (Term && Term->isTerminator()) {
3943             LLVM_DEBUG(dbgs()
3944                        << "SLP: Need to swizzle PHINodes (terminator use).\n");
3945             BS.cancelScheduling(VL, VL0);
3946             newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3947                          ReuseShuffleIndicies);
3948             return;
3949           }
3950         }
3951 
3952       TreeEntry *TE =
3953           newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies);
3954       LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
3955 
3956       // Keeps the reordered operands to avoid code duplication.
3957       SmallVector<ValueList, 2> OperandsVec;
3958       for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
3959         if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) {
3960           ValueList Operands(VL.size(), PoisonValue::get(PH->getType()));
3961           TE->setOperand(I, Operands);
3962           OperandsVec.push_back(Operands);
3963           continue;
3964         }
3965         ValueList Operands;
3966         // Prepare the operand vector.
3967         for (Value *V : VL)
3968           Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(
3969               PH->getIncomingBlock(I)));
3970         TE->setOperand(I, Operands);
3971         OperandsVec.push_back(Operands);
3972       }
3973       for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx)
3974         buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx});
3975       return;
3976     }
3977     case Instruction::ExtractValue:
3978     case Instruction::ExtractElement: {
3979       OrdersType CurrentOrder;
3980       bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
3981       if (Reuse) {
3982         LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
3983         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3984                      ReuseShuffleIndicies);
3985         // This is a special case, as it does not gather, but at the same time
3986         // we are not extending buildTree_rec() towards the operands.
3987         ValueList Op0;
3988         Op0.assign(VL.size(), VL0->getOperand(0));
3989         VectorizableTree.back()->setOperand(0, Op0);
3990         return;
3991       }
3992       if (!CurrentOrder.empty()) {
3993         LLVM_DEBUG({
3994           dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
3995                     "with order";
3996           for (unsigned Idx : CurrentOrder)
3997             dbgs() << " " << Idx;
3998           dbgs() << "\n";
3999         });
4000         fixupOrderingIndices(CurrentOrder);
4001         // Insert new order with initial value 0, if it does not exist,
4002         // otherwise return the iterator to the existing one.
4003         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4004                      ReuseShuffleIndicies, CurrentOrder);
4005         // This is a special case, as it does not gather, but at the same time
4006         // we are not extending buildTree_rec() towards the operands.
4007         ValueList Op0;
4008         Op0.assign(VL.size(), VL0->getOperand(0));
4009         VectorizableTree.back()->setOperand(0, Op0);
4010         return;
4011       }
4012       LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
4013       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4014                    ReuseShuffleIndicies);
4015       BS.cancelScheduling(VL, VL0);
4016       return;
4017     }
4018     case Instruction::InsertElement: {
4019       assert(ReuseShuffleIndicies.empty() && "All inserts should be unique");
4020 
4021       // Check that we have a buildvector and not a shuffle of 2 or more
4022       // different vectors.
4023       ValueSet SourceVectors;
4024       for (Value *V : VL) {
4025         SourceVectors.insert(cast<Instruction>(V)->getOperand(0));
4026         assert(getInsertIndex(V) != None && "Non-constant or undef index?");
4027       }
4028 
4029       if (count_if(VL, [&SourceVectors](Value *V) {
4030             return !SourceVectors.contains(V);
4031           }) >= 2) {
4032         // Found 2nd source vector - cancel.
4033         LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with "
4034                              "different source vectors.\n");
4035         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4036         BS.cancelScheduling(VL, VL0);
4037         return;
4038       }
4039 
4040       auto OrdCompare = [](const std::pair<int, int> &P1,
4041                            const std::pair<int, int> &P2) {
4042         return P1.first > P2.first;
4043       };
4044       PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>,
4045                     decltype(OrdCompare)>
4046           Indices(OrdCompare);
4047       for (int I = 0, E = VL.size(); I < E; ++I) {
4048         unsigned Idx = *getInsertIndex(VL[I]);
4049         Indices.emplace(Idx, I);
4050       }
4051       OrdersType CurrentOrder(VL.size(), VL.size());
4052       bool IsIdentity = true;
4053       for (int I = 0, E = VL.size(); I < E; ++I) {
4054         CurrentOrder[Indices.top().second] = I;
4055         IsIdentity &= Indices.top().second == I;
4056         Indices.pop();
4057       }
4058       if (IsIdentity)
4059         CurrentOrder.clear();
4060       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4061                                    None, CurrentOrder);
4062       LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n");
4063 
4064       constexpr int NumOps = 2;
4065       ValueList VectorOperands[NumOps];
4066       for (int I = 0; I < NumOps; ++I) {
4067         for (Value *V : VL)
4068           VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I));
4069 
4070         TE->setOperand(I, VectorOperands[I]);
4071       }
4072       buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1});
4073       return;
4074     }
4075     case Instruction::Load: {
4076       // Check that a vectorized load would load the same memory as a scalar
4077       // load. For example, we don't want to vectorize loads that are smaller
4078       // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
4079       // treats loading/storing it as an i8 struct. If we vectorize loads/stores
4080       // from such a struct, we read/write packed bits disagreeing with the
4081       // unvectorized version.
4082       SmallVector<Value *> PointerOps;
4083       OrdersType CurrentOrder;
4084       TreeEntry *TE = nullptr;
4085       switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, CurrentOrder,
4086                                 PointerOps)) {
4087       case LoadsState::Vectorize:
4088         if (CurrentOrder.empty()) {
4089           // Original loads are consecutive and does not require reordering.
4090           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4091                             ReuseShuffleIndicies);
4092           LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
4093         } else {
4094           fixupOrderingIndices(CurrentOrder);
4095           // Need to reorder.
4096           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4097                             ReuseShuffleIndicies, CurrentOrder);
4098           LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
4099         }
4100         TE->setOperandsInOrder();
4101         break;
4102       case LoadsState::ScatterVectorize:
4103         // Vectorizing non-consecutive loads with `llvm.masked.gather`.
4104         TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S,
4105                           UserTreeIdx, ReuseShuffleIndicies);
4106         TE->setOperandsInOrder();
4107         buildTree_rec(PointerOps, Depth + 1, {TE, 0});
4108         LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n");
4109         break;
4110       case LoadsState::Gather:
4111         BS.cancelScheduling(VL, VL0);
4112         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4113                      ReuseShuffleIndicies);
4114 #ifndef NDEBUG
4115         Type *ScalarTy = VL0->getType();
4116         if (DL->getTypeSizeInBits(ScalarTy) !=
4117             DL->getTypeAllocSizeInBits(ScalarTy))
4118           LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
4119         else if (any_of(VL, [](Value *V) {
4120                    return !cast<LoadInst>(V)->isSimple();
4121                  }))
4122           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
4123         else
4124           LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
4125 #endif // NDEBUG
4126         break;
4127       }
4128       return;
4129     }
4130     case Instruction::ZExt:
4131     case Instruction::SExt:
4132     case Instruction::FPToUI:
4133     case Instruction::FPToSI:
4134     case Instruction::FPExt:
4135     case Instruction::PtrToInt:
4136     case Instruction::IntToPtr:
4137     case Instruction::SIToFP:
4138     case Instruction::UIToFP:
4139     case Instruction::Trunc:
4140     case Instruction::FPTrunc:
4141     case Instruction::BitCast: {
4142       Type *SrcTy = VL0->getOperand(0)->getType();
4143       for (Value *V : VL) {
4144         Type *Ty = cast<Instruction>(V)->getOperand(0)->getType();
4145         if (Ty != SrcTy || !isValidElementType(Ty)) {
4146           BS.cancelScheduling(VL, VL0);
4147           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4148                        ReuseShuffleIndicies);
4149           LLVM_DEBUG(dbgs()
4150                      << "SLP: Gathering casts with different src types.\n");
4151           return;
4152         }
4153       }
4154       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4155                                    ReuseShuffleIndicies);
4156       LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
4157 
4158       TE->setOperandsInOrder();
4159       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4160         ValueList Operands;
4161         // Prepare the operand vector.
4162         for (Value *V : VL)
4163           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4164 
4165         buildTree_rec(Operands, Depth + 1, {TE, i});
4166       }
4167       return;
4168     }
4169     case Instruction::ICmp:
4170     case Instruction::FCmp: {
4171       // Check that all of the compares have the same predicate.
4172       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
4173       CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0);
4174       Type *ComparedTy = VL0->getOperand(0)->getType();
4175       for (Value *V : VL) {
4176         CmpInst *Cmp = cast<CmpInst>(V);
4177         if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) ||
4178             Cmp->getOperand(0)->getType() != ComparedTy) {
4179           BS.cancelScheduling(VL, VL0);
4180           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4181                        ReuseShuffleIndicies);
4182           LLVM_DEBUG(dbgs()
4183                      << "SLP: Gathering cmp with different predicate.\n");
4184           return;
4185         }
4186       }
4187 
4188       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4189                                    ReuseShuffleIndicies);
4190       LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
4191 
4192       ValueList Left, Right;
4193       if (cast<CmpInst>(VL0)->isCommutative()) {
4194         // Commutative predicate - collect + sort operands of the instructions
4195         // so that each side is more likely to have the same opcode.
4196         assert(P0 == SwapP0 && "Commutative Predicate mismatch");
4197         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4198       } else {
4199         // Collect operands - commute if it uses the swapped predicate.
4200         for (Value *V : VL) {
4201           auto *Cmp = cast<CmpInst>(V);
4202           Value *LHS = Cmp->getOperand(0);
4203           Value *RHS = Cmp->getOperand(1);
4204           if (Cmp->getPredicate() != P0)
4205             std::swap(LHS, RHS);
4206           Left.push_back(LHS);
4207           Right.push_back(RHS);
4208         }
4209       }
4210       TE->setOperand(0, Left);
4211       TE->setOperand(1, Right);
4212       buildTree_rec(Left, Depth + 1, {TE, 0});
4213       buildTree_rec(Right, Depth + 1, {TE, 1});
4214       return;
4215     }
4216     case Instruction::Select:
4217     case Instruction::FNeg:
4218     case Instruction::Add:
4219     case Instruction::FAdd:
4220     case Instruction::Sub:
4221     case Instruction::FSub:
4222     case Instruction::Mul:
4223     case Instruction::FMul:
4224     case Instruction::UDiv:
4225     case Instruction::SDiv:
4226     case Instruction::FDiv:
4227     case Instruction::URem:
4228     case Instruction::SRem:
4229     case Instruction::FRem:
4230     case Instruction::Shl:
4231     case Instruction::LShr:
4232     case Instruction::AShr:
4233     case Instruction::And:
4234     case Instruction::Or:
4235     case Instruction::Xor: {
4236       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4237                                    ReuseShuffleIndicies);
4238       LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n");
4239 
4240       // Sort operands of the instructions so that each side is more likely to
4241       // have the same opcode.
4242       if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
4243         ValueList Left, Right;
4244         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4245         TE->setOperand(0, Left);
4246         TE->setOperand(1, Right);
4247         buildTree_rec(Left, Depth + 1, {TE, 0});
4248         buildTree_rec(Right, Depth + 1, {TE, 1});
4249         return;
4250       }
4251 
4252       TE->setOperandsInOrder();
4253       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4254         ValueList Operands;
4255         // Prepare the operand vector.
4256         for (Value *V : VL)
4257           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4258 
4259         buildTree_rec(Operands, Depth + 1, {TE, i});
4260       }
4261       return;
4262     }
4263     case Instruction::GetElementPtr: {
4264       // We don't combine GEPs with complicated (nested) indexing.
4265       for (Value *V : VL) {
4266         if (cast<Instruction>(V)->getNumOperands() != 2) {
4267           LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
4268           BS.cancelScheduling(VL, VL0);
4269           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4270                        ReuseShuffleIndicies);
4271           return;
4272         }
4273       }
4274 
4275       // We can't combine several GEPs into one vector if they operate on
4276       // different types.
4277       Type *Ty0 = VL0->getOperand(0)->getType();
4278       for (Value *V : VL) {
4279         Type *CurTy = cast<Instruction>(V)->getOperand(0)->getType();
4280         if (Ty0 != CurTy) {
4281           LLVM_DEBUG(dbgs()
4282                      << "SLP: not-vectorizable GEP (different types).\n");
4283           BS.cancelScheduling(VL, VL0);
4284           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4285                        ReuseShuffleIndicies);
4286           return;
4287         }
4288       }
4289 
4290       // We don't combine GEPs with non-constant indexes.
4291       Type *Ty1 = VL0->getOperand(1)->getType();
4292       for (Value *V : VL) {
4293         auto Op = cast<Instruction>(V)->getOperand(1);
4294         if (!isa<ConstantInt>(Op) ||
4295             (Op->getType() != Ty1 &&
4296              Op->getType()->getScalarSizeInBits() >
4297                  DL->getIndexSizeInBits(
4298                      V->getType()->getPointerAddressSpace()))) {
4299           LLVM_DEBUG(dbgs()
4300                      << "SLP: not-vectorizable GEP (non-constant indexes).\n");
4301           BS.cancelScheduling(VL, VL0);
4302           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4303                        ReuseShuffleIndicies);
4304           return;
4305         }
4306       }
4307 
4308       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4309                                    ReuseShuffleIndicies);
4310       LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
4311       SmallVector<ValueList, 2> Operands(2);
4312       // Prepare the operand vector for pointer operands.
4313       for (Value *V : VL)
4314         Operands.front().push_back(
4315             cast<GetElementPtrInst>(V)->getPointerOperand());
4316       TE->setOperand(0, Operands.front());
4317       // Need to cast all indices to the same type before vectorization to
4318       // avoid crash.
4319       // Required to be able to find correct matches between different gather
4320       // nodes and reuse the vectorized values rather than trying to gather them
4321       // again.
4322       int IndexIdx = 1;
4323       Type *VL0Ty = VL0->getOperand(IndexIdx)->getType();
4324       Type *Ty = all_of(VL,
4325                         [VL0Ty, IndexIdx](Value *V) {
4326                           return VL0Ty == cast<GetElementPtrInst>(V)
4327                                               ->getOperand(IndexIdx)
4328                                               ->getType();
4329                         })
4330                      ? VL0Ty
4331                      : DL->getIndexType(cast<GetElementPtrInst>(VL0)
4332                                             ->getPointerOperandType()
4333                                             ->getScalarType());
4334       // Prepare the operand vector.
4335       for (Value *V : VL) {
4336         auto *Op = cast<Instruction>(V)->getOperand(IndexIdx);
4337         auto *CI = cast<ConstantInt>(Op);
4338         Operands.back().push_back(ConstantExpr::getIntegerCast(
4339             CI, Ty, CI->getValue().isSignBitSet()));
4340       }
4341       TE->setOperand(IndexIdx, Operands.back());
4342 
4343       for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I)
4344         buildTree_rec(Operands[I], Depth + 1, {TE, I});
4345       return;
4346     }
4347     case Instruction::Store: {
4348       // Check if the stores are consecutive or if we need to swizzle them.
4349       llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType();
4350       // Avoid types that are padded when being allocated as scalars, while
4351       // being packed together in a vector (such as i1).
4352       if (DL->getTypeSizeInBits(ScalarTy) !=
4353           DL->getTypeAllocSizeInBits(ScalarTy)) {
4354         BS.cancelScheduling(VL, VL0);
4355         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4356                      ReuseShuffleIndicies);
4357         LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n");
4358         return;
4359       }
4360       // Make sure all stores in the bundle are simple - we can't vectorize
4361       // atomic or volatile stores.
4362       SmallVector<Value *, 4> PointerOps(VL.size());
4363       ValueList Operands(VL.size());
4364       auto POIter = PointerOps.begin();
4365       auto OIter = Operands.begin();
4366       for (Value *V : VL) {
4367         auto *SI = cast<StoreInst>(V);
4368         if (!SI->isSimple()) {
4369           BS.cancelScheduling(VL, VL0);
4370           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4371                        ReuseShuffleIndicies);
4372           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n");
4373           return;
4374         }
4375         *POIter = SI->getPointerOperand();
4376         *OIter = SI->getValueOperand();
4377         ++POIter;
4378         ++OIter;
4379       }
4380 
4381       OrdersType CurrentOrder;
4382       // Check the order of pointer operands.
4383       if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) {
4384         Value *Ptr0;
4385         Value *PtrN;
4386         if (CurrentOrder.empty()) {
4387           Ptr0 = PointerOps.front();
4388           PtrN = PointerOps.back();
4389         } else {
4390           Ptr0 = PointerOps[CurrentOrder.front()];
4391           PtrN = PointerOps[CurrentOrder.back()];
4392         }
4393         Optional<int> Dist =
4394             getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE);
4395         // Check that the sorted pointer operands are consecutive.
4396         if (static_cast<unsigned>(*Dist) == VL.size() - 1) {
4397           if (CurrentOrder.empty()) {
4398             // Original stores are consecutive and does not require reordering.
4399             TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
4400                                          UserTreeIdx, ReuseShuffleIndicies);
4401             TE->setOperandsInOrder();
4402             buildTree_rec(Operands, Depth + 1, {TE, 0});
4403             LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
4404           } else {
4405             fixupOrderingIndices(CurrentOrder);
4406             TreeEntry *TE =
4407                 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4408                              ReuseShuffleIndicies, CurrentOrder);
4409             TE->setOperandsInOrder();
4410             buildTree_rec(Operands, Depth + 1, {TE, 0});
4411             LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n");
4412           }
4413           return;
4414         }
4415       }
4416 
4417       BS.cancelScheduling(VL, VL0);
4418       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4419                    ReuseShuffleIndicies);
4420       LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
4421       return;
4422     }
4423     case Instruction::Call: {
4424       // Check if the calls are all to the same vectorizable intrinsic or
4425       // library function.
4426       CallInst *CI = cast<CallInst>(VL0);
4427       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4428 
4429       VFShape Shape = VFShape::get(
4430           *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())),
4431           false /*HasGlobalPred*/);
4432       Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4433 
4434       if (!VecFunc && !isTriviallyVectorizable(ID)) {
4435         BS.cancelScheduling(VL, VL0);
4436         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4437                      ReuseShuffleIndicies);
4438         LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
4439         return;
4440       }
4441       Function *F = CI->getCalledFunction();
4442       unsigned NumArgs = CI->arg_size();
4443       SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr);
4444       for (unsigned j = 0; j != NumArgs; ++j)
4445         if (hasVectorInstrinsicScalarOpd(ID, j))
4446           ScalarArgs[j] = CI->getArgOperand(j);
4447       for (Value *V : VL) {
4448         CallInst *CI2 = dyn_cast<CallInst>(V);
4449         if (!CI2 || CI2->getCalledFunction() != F ||
4450             getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
4451             (VecFunc &&
4452              VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) ||
4453             !CI->hasIdenticalOperandBundleSchema(*CI2)) {
4454           BS.cancelScheduling(VL, VL0);
4455           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4456                        ReuseShuffleIndicies);
4457           LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V
4458                             << "\n");
4459           return;
4460         }
4461         // Some intrinsics have scalar arguments and should be same in order for
4462         // them to be vectorized.
4463         for (unsigned j = 0; j != NumArgs; ++j) {
4464           if (hasVectorInstrinsicScalarOpd(ID, j)) {
4465             Value *A1J = CI2->getArgOperand(j);
4466             if (ScalarArgs[j] != A1J) {
4467               BS.cancelScheduling(VL, VL0);
4468               newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4469                            ReuseShuffleIndicies);
4470               LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
4471                                 << " argument " << ScalarArgs[j] << "!=" << A1J
4472                                 << "\n");
4473               return;
4474             }
4475           }
4476         }
4477         // Verify that the bundle operands are identical between the two calls.
4478         if (CI->hasOperandBundles() &&
4479             !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
4480                         CI->op_begin() + CI->getBundleOperandsEndIndex(),
4481                         CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
4482           BS.cancelScheduling(VL, VL0);
4483           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4484                        ReuseShuffleIndicies);
4485           LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
4486                             << *CI << "!=" << *V << '\n');
4487           return;
4488         }
4489       }
4490 
4491       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4492                                    ReuseShuffleIndicies);
4493       TE->setOperandsInOrder();
4494       for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
4495         // For scalar operands no need to to create an entry since no need to
4496         // vectorize it.
4497         if (hasVectorInstrinsicScalarOpd(ID, i))
4498           continue;
4499         ValueList Operands;
4500         // Prepare the operand vector.
4501         for (Value *V : VL) {
4502           auto *CI2 = cast<CallInst>(V);
4503           Operands.push_back(CI2->getArgOperand(i));
4504         }
4505         buildTree_rec(Operands, Depth + 1, {TE, i});
4506       }
4507       return;
4508     }
4509     case Instruction::ShuffleVector: {
4510       // If this is not an alternate sequence of opcode like add-sub
4511       // then do not vectorize this instruction.
4512       if (!S.isAltShuffle()) {
4513         BS.cancelScheduling(VL, VL0);
4514         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4515                      ReuseShuffleIndicies);
4516         LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
4517         return;
4518       }
4519       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4520                                    ReuseShuffleIndicies);
4521       LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
4522 
4523       // Reorder operands if reordering would enable vectorization.
4524       auto *CI = dyn_cast<CmpInst>(VL0);
4525       if (isa<BinaryOperator>(VL0) || CI) {
4526         ValueList Left, Right;
4527         if (!CI || all_of(VL, [](Value *V) {
4528               return cast<CmpInst>(V)->isCommutative();
4529             })) {
4530           reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4531         } else {
4532           CmpInst::Predicate P0 = CI->getPredicate();
4533           CmpInst::Predicate AltP0 = cast<CmpInst>(S.AltOp)->getPredicate();
4534           assert(P0 != AltP0 &&
4535                  "Expected different main/alternate predicates.");
4536           CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
4537           Value *BaseOp0 = VL0->getOperand(0);
4538           Value *BaseOp1 = VL0->getOperand(1);
4539           // Collect operands - commute if it uses the swapped predicate or
4540           // alternate operation.
4541           for (Value *V : VL) {
4542             auto *Cmp = cast<CmpInst>(V);
4543             Value *LHS = Cmp->getOperand(0);
4544             Value *RHS = Cmp->getOperand(1);
4545             CmpInst::Predicate CurrentPred = Cmp->getPredicate();
4546             if (P0 == AltP0Swapped) {
4547               if ((P0 == CurrentPred &&
4548                    !areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)) ||
4549                   (AltP0 == CurrentPred &&
4550                    areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)))
4551                 std::swap(LHS, RHS);
4552             } else if (P0 != CurrentPred && AltP0 != CurrentPred) {
4553               std::swap(LHS, RHS);
4554             }
4555             Left.push_back(LHS);
4556             Right.push_back(RHS);
4557           }
4558         }
4559         TE->setOperand(0, Left);
4560         TE->setOperand(1, Right);
4561         buildTree_rec(Left, Depth + 1, {TE, 0});
4562         buildTree_rec(Right, Depth + 1, {TE, 1});
4563         return;
4564       }
4565 
4566       TE->setOperandsInOrder();
4567       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4568         ValueList Operands;
4569         // Prepare the operand vector.
4570         for (Value *V : VL)
4571           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4572 
4573         buildTree_rec(Operands, Depth + 1, {TE, i});
4574       }
4575       return;
4576     }
4577     default:
4578       BS.cancelScheduling(VL, VL0);
4579       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4580                    ReuseShuffleIndicies);
4581       LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
4582       return;
4583   }
4584 }
4585 
4586 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
4587   unsigned N = 1;
4588   Type *EltTy = T;
4589 
4590   while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) ||
4591          isa<VectorType>(EltTy)) {
4592     if (auto *ST = dyn_cast<StructType>(EltTy)) {
4593       // Check that struct is homogeneous.
4594       for (const auto *Ty : ST->elements())
4595         if (Ty != *ST->element_begin())
4596           return 0;
4597       N *= ST->getNumElements();
4598       EltTy = *ST->element_begin();
4599     } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) {
4600       N *= AT->getNumElements();
4601       EltTy = AT->getElementType();
4602     } else {
4603       auto *VT = cast<FixedVectorType>(EltTy);
4604       N *= VT->getNumElements();
4605       EltTy = VT->getElementType();
4606     }
4607   }
4608 
4609   if (!isValidElementType(EltTy))
4610     return 0;
4611   uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N));
4612   if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
4613     return 0;
4614   return N;
4615 }
4616 
4617 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
4618                               SmallVectorImpl<unsigned> &CurrentOrder) const {
4619   const auto *It = find_if(VL, [](Value *V) {
4620     return isa<ExtractElementInst, ExtractValueInst>(V);
4621   });
4622   assert(It != VL.end() && "Expected at least one extract instruction.");
4623   auto *E0 = cast<Instruction>(*It);
4624   assert(all_of(VL,
4625                 [](Value *V) {
4626                   return isa<UndefValue, ExtractElementInst, ExtractValueInst>(
4627                       V);
4628                 }) &&
4629          "Invalid opcode");
4630   // Check if all of the extracts come from the same vector and from the
4631   // correct offset.
4632   Value *Vec = E0->getOperand(0);
4633 
4634   CurrentOrder.clear();
4635 
4636   // We have to extract from a vector/aggregate with the same number of elements.
4637   unsigned NElts;
4638   if (E0->getOpcode() == Instruction::ExtractValue) {
4639     const DataLayout &DL = E0->getModule()->getDataLayout();
4640     NElts = canMapToVector(Vec->getType(), DL);
4641     if (!NElts)
4642       return false;
4643     // Check if load can be rewritten as load of vector.
4644     LoadInst *LI = dyn_cast<LoadInst>(Vec);
4645     if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
4646       return false;
4647   } else {
4648     NElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
4649   }
4650 
4651   if (NElts != VL.size())
4652     return false;
4653 
4654   // Check that all of the indices extract from the correct offset.
4655   bool ShouldKeepOrder = true;
4656   unsigned E = VL.size();
4657   // Assign to all items the initial value E + 1 so we can check if the extract
4658   // instruction index was used already.
4659   // Also, later we can check that all the indices are used and we have a
4660   // consecutive access in the extract instructions, by checking that no
4661   // element of CurrentOrder still has value E + 1.
4662   CurrentOrder.assign(E, E);
4663   unsigned I = 0;
4664   for (; I < E; ++I) {
4665     auto *Inst = dyn_cast<Instruction>(VL[I]);
4666     if (!Inst)
4667       continue;
4668     if (Inst->getOperand(0) != Vec)
4669       break;
4670     if (auto *EE = dyn_cast<ExtractElementInst>(Inst))
4671       if (isa<UndefValue>(EE->getIndexOperand()))
4672         continue;
4673     Optional<unsigned> Idx = getExtractIndex(Inst);
4674     if (!Idx)
4675       break;
4676     const unsigned ExtIdx = *Idx;
4677     if (ExtIdx != I) {
4678       if (ExtIdx >= E || CurrentOrder[ExtIdx] != E)
4679         break;
4680       ShouldKeepOrder = false;
4681       CurrentOrder[ExtIdx] = I;
4682     } else {
4683       if (CurrentOrder[I] != E)
4684         break;
4685       CurrentOrder[I] = I;
4686     }
4687   }
4688   if (I < E) {
4689     CurrentOrder.clear();
4690     return false;
4691   }
4692   if (ShouldKeepOrder)
4693     CurrentOrder.clear();
4694 
4695   return ShouldKeepOrder;
4696 }
4697 
4698 bool BoUpSLP::areAllUsersVectorized(Instruction *I,
4699                                     ArrayRef<Value *> VectorizedVals) const {
4700   return (I->hasOneUse() && is_contained(VectorizedVals, I)) ||
4701          all_of(I->users(), [this](User *U) {
4702            return ScalarToTreeEntry.count(U) > 0 ||
4703                   isVectorLikeInstWithConstOps(U) ||
4704                   (isa<ExtractElementInst>(U) && MustGather.contains(U));
4705          });
4706 }
4707 
4708 static std::pair<InstructionCost, InstructionCost>
4709 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy,
4710                    TargetTransformInfo *TTI, TargetLibraryInfo *TLI) {
4711   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4712 
4713   // Calculate the cost of the scalar and vector calls.
4714   SmallVector<Type *, 4> VecTys;
4715   for (Use &Arg : CI->args())
4716     VecTys.push_back(
4717         FixedVectorType::get(Arg->getType(), VecTy->getNumElements()));
4718   FastMathFlags FMF;
4719   if (auto *FPCI = dyn_cast<FPMathOperator>(CI))
4720     FMF = FPCI->getFastMathFlags();
4721   SmallVector<const Value *> Arguments(CI->args());
4722   IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF,
4723                                     dyn_cast<IntrinsicInst>(CI));
4724   auto IntrinsicCost =
4725     TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput);
4726 
4727   auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
4728                                      VecTy->getNumElements())),
4729                             false /*HasGlobalPred*/);
4730   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4731   auto LibCost = IntrinsicCost;
4732   if (!CI->isNoBuiltin() && VecFunc) {
4733     // Calculate the cost of the vector library call.
4734     // If the corresponding vector call is cheaper, return its cost.
4735     LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys,
4736                                     TTI::TCK_RecipThroughput);
4737   }
4738   return {IntrinsicCost, LibCost};
4739 }
4740 
4741 /// Compute the cost of creating a vector of type \p VecTy containing the
4742 /// extracted values from \p VL.
4743 static InstructionCost
4744 computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy,
4745                    TargetTransformInfo::ShuffleKind ShuffleKind,
4746                    ArrayRef<int> Mask, TargetTransformInfo &TTI) {
4747   unsigned NumOfParts = TTI.getNumberOfParts(VecTy);
4748 
4749   if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts ||
4750       VecTy->getNumElements() < NumOfParts)
4751     return TTI.getShuffleCost(ShuffleKind, VecTy, Mask);
4752 
4753   bool AllConsecutive = true;
4754   unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts;
4755   unsigned Idx = -1;
4756   InstructionCost Cost = 0;
4757 
4758   // Process extracts in blocks of EltsPerVector to check if the source vector
4759   // operand can be re-used directly. If not, add the cost of creating a shuffle
4760   // to extract the values into a vector register.
4761   for (auto *V : VL) {
4762     ++Idx;
4763 
4764     // Need to exclude undefs from analysis.
4765     if (isa<UndefValue>(V) || Mask[Idx] == UndefMaskElem)
4766       continue;
4767 
4768     // Reached the start of a new vector registers.
4769     if (Idx % EltsPerVector == 0) {
4770       AllConsecutive = true;
4771       continue;
4772     }
4773 
4774     // Check all extracts for a vector register on the target directly
4775     // extract values in order.
4776     unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V));
4777     if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != UndefMaskElem) {
4778       unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1]));
4779       AllConsecutive &= PrevIdx + 1 == CurrentIdx &&
4780                         CurrentIdx % EltsPerVector == Idx % EltsPerVector;
4781     }
4782 
4783     if (AllConsecutive)
4784       continue;
4785 
4786     // Skip all indices, except for the last index per vector block.
4787     if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size())
4788       continue;
4789 
4790     // If we have a series of extracts which are not consecutive and hence
4791     // cannot re-use the source vector register directly, compute the shuffle
4792     // cost to extract the a vector with EltsPerVector elements.
4793     Cost += TTI.getShuffleCost(
4794         TargetTransformInfo::SK_PermuteSingleSrc,
4795         FixedVectorType::get(VecTy->getElementType(), EltsPerVector));
4796   }
4797   return Cost;
4798 }
4799 
4800 /// Build shuffle mask for shuffle graph entries and lists of main and alternate
4801 /// operations operands.
4802 static void
4803 buildSuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices,
4804                      ArrayRef<int> ReusesIndices,
4805                      const function_ref<bool(Instruction *)> IsAltOp,
4806                      SmallVectorImpl<int> &Mask,
4807                      SmallVectorImpl<Value *> *OpScalars = nullptr,
4808                      SmallVectorImpl<Value *> *AltScalars = nullptr) {
4809   unsigned Sz = VL.size();
4810   Mask.assign(Sz, UndefMaskElem);
4811   SmallVector<int> OrderMask;
4812   if (!ReorderIndices.empty())
4813     inversePermutation(ReorderIndices, OrderMask);
4814   for (unsigned I = 0; I < Sz; ++I) {
4815     unsigned Idx = I;
4816     if (!ReorderIndices.empty())
4817       Idx = OrderMask[I];
4818     auto *OpInst = cast<Instruction>(VL[Idx]);
4819     if (IsAltOp(OpInst)) {
4820       Mask[I] = Sz + Idx;
4821       if (AltScalars)
4822         AltScalars->push_back(OpInst);
4823     } else {
4824       Mask[I] = Idx;
4825       if (OpScalars)
4826         OpScalars->push_back(OpInst);
4827     }
4828   }
4829   if (!ReusesIndices.empty()) {
4830     SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem);
4831     transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) {
4832       return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem;
4833     });
4834     Mask.swap(NewMask);
4835   }
4836 }
4837 
4838 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E,
4839                                       ArrayRef<Value *> VectorizedVals) {
4840   ArrayRef<Value*> VL = E->Scalars;
4841 
4842   Type *ScalarTy = VL[0]->getType();
4843   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
4844     ScalarTy = SI->getValueOperand()->getType();
4845   else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
4846     ScalarTy = CI->getOperand(0)->getType();
4847   else if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
4848     ScalarTy = IE->getOperand(1)->getType();
4849   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
4850   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
4851 
4852   // If we have computed a smaller type for the expression, update VecTy so
4853   // that the costs will be accurate.
4854   if (MinBWs.count(VL[0]))
4855     VecTy = FixedVectorType::get(
4856         IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
4857   unsigned EntryVF = E->getVectorFactor();
4858   auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF);
4859 
4860   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
4861   // FIXME: it tries to fix a problem with MSVC buildbots.
4862   TargetTransformInfo &TTIRef = *TTI;
4863   auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy,
4864                                VectorizedVals, E](InstructionCost &Cost) {
4865     DenseMap<Value *, int> ExtractVectorsTys;
4866     SmallPtrSet<Value *, 4> CheckedExtracts;
4867     for (auto *V : VL) {
4868       if (isa<UndefValue>(V))
4869         continue;
4870       // If all users of instruction are going to be vectorized and this
4871       // instruction itself is not going to be vectorized, consider this
4872       // instruction as dead and remove its cost from the final cost of the
4873       // vectorized tree.
4874       // Also, avoid adjusting the cost for extractelements with multiple uses
4875       // in different graph entries.
4876       const TreeEntry *VE = getTreeEntry(V);
4877       if (!CheckedExtracts.insert(V).second ||
4878           !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) ||
4879           (VE && VE != E))
4880         continue;
4881       auto *EE = cast<ExtractElementInst>(V);
4882       Optional<unsigned> EEIdx = getExtractIndex(EE);
4883       if (!EEIdx)
4884         continue;
4885       unsigned Idx = *EEIdx;
4886       if (TTIRef.getNumberOfParts(VecTy) !=
4887           TTIRef.getNumberOfParts(EE->getVectorOperandType())) {
4888         auto It =
4889             ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first;
4890         It->getSecond() = std::min<int>(It->second, Idx);
4891       }
4892       // Take credit for instruction that will become dead.
4893       if (EE->hasOneUse()) {
4894         Instruction *Ext = EE->user_back();
4895         if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
4896             all_of(Ext->users(),
4897                    [](User *U) { return isa<GetElementPtrInst>(U); })) {
4898           // Use getExtractWithExtendCost() to calculate the cost of
4899           // extractelement/ext pair.
4900           Cost -=
4901               TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(),
4902                                               EE->getVectorOperandType(), Idx);
4903           // Add back the cost of s|zext which is subtracted separately.
4904           Cost += TTIRef.getCastInstrCost(
4905               Ext->getOpcode(), Ext->getType(), EE->getType(),
4906               TTI::getCastContextHint(Ext), CostKind, Ext);
4907           continue;
4908         }
4909       }
4910       Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement,
4911                                         EE->getVectorOperandType(), Idx);
4912     }
4913     // Add a cost for subvector extracts/inserts if required.
4914     for (const auto &Data : ExtractVectorsTys) {
4915       auto *EEVTy = cast<FixedVectorType>(Data.first->getType());
4916       unsigned NumElts = VecTy->getNumElements();
4917       if (Data.second % NumElts == 0)
4918         continue;
4919       if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) {
4920         unsigned Idx = (Data.second / NumElts) * NumElts;
4921         unsigned EENumElts = EEVTy->getNumElements();
4922         if (Idx + NumElts <= EENumElts) {
4923           Cost +=
4924               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
4925                                     EEVTy, None, Idx, VecTy);
4926         } else {
4927           // Need to round up the subvector type vectorization factor to avoid a
4928           // crash in cost model functions. Make SubVT so that Idx + VF of SubVT
4929           // <= EENumElts.
4930           auto *SubVT =
4931               FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx);
4932           Cost +=
4933               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
4934                                     EEVTy, None, Idx, SubVT);
4935         }
4936       } else {
4937         Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector,
4938                                       VecTy, None, 0, EEVTy);
4939       }
4940     }
4941   };
4942   if (E->State == TreeEntry::NeedToGather) {
4943     if (allConstant(VL))
4944       return 0;
4945     if (isa<InsertElementInst>(VL[0]))
4946       return InstructionCost::getInvalid();
4947     SmallVector<int> Mask;
4948     SmallVector<const TreeEntry *> Entries;
4949     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
4950         isGatherShuffledEntry(E, Mask, Entries);
4951     if (Shuffle.hasValue()) {
4952       InstructionCost GatherCost = 0;
4953       if (ShuffleVectorInst::isIdentityMask(Mask)) {
4954         // Perfect match in the graph, will reuse the previously vectorized
4955         // node. Cost is 0.
4956         LLVM_DEBUG(
4957             dbgs()
4958             << "SLP: perfect diamond match for gather bundle that starts with "
4959             << *VL.front() << ".\n");
4960         if (NeedToShuffleReuses)
4961           GatherCost =
4962               TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
4963                                   FinalVecTy, E->ReuseShuffleIndices);
4964       } else {
4965         LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size()
4966                           << " entries for bundle that starts with "
4967                           << *VL.front() << ".\n");
4968         // Detected that instead of gather we can emit a shuffle of single/two
4969         // previously vectorized nodes. Add the cost of the permutation rather
4970         // than gather.
4971         ::addMask(Mask, E->ReuseShuffleIndices);
4972         GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask);
4973       }
4974       return GatherCost;
4975     }
4976     if ((E->getOpcode() == Instruction::ExtractElement ||
4977          all_of(E->Scalars,
4978                 [](Value *V) {
4979                   return isa<ExtractElementInst, UndefValue>(V);
4980                 })) &&
4981         allSameType(VL)) {
4982       // Check that gather of extractelements can be represented as just a
4983       // shuffle of a single/two vectors the scalars are extracted from.
4984       SmallVector<int> Mask;
4985       Optional<TargetTransformInfo::ShuffleKind> ShuffleKind =
4986           isFixedVectorShuffle(VL, Mask);
4987       if (ShuffleKind.hasValue()) {
4988         // Found the bunch of extractelement instructions that must be gathered
4989         // into a vector and can be represented as a permutation elements in a
4990         // single input vector or of 2 input vectors.
4991         InstructionCost Cost =
4992             computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI);
4993         AdjustExtractsCost(Cost);
4994         if (NeedToShuffleReuses)
4995           Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
4996                                       FinalVecTy, E->ReuseShuffleIndices);
4997         return Cost;
4998       }
4999     }
5000     if (isSplat(VL)) {
5001       // Found the broadcasting of the single scalar, calculate the cost as the
5002       // broadcast.
5003       assert(VecTy == FinalVecTy &&
5004              "No reused scalars expected for broadcast.");
5005       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy);
5006     }
5007     InstructionCost ReuseShuffleCost = 0;
5008     if (NeedToShuffleReuses)
5009       ReuseShuffleCost = TTI->getShuffleCost(
5010           TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices);
5011     // Improve gather cost for gather of loads, if we can group some of the
5012     // loads into vector loads.
5013     if (VL.size() > 2 && E->getOpcode() == Instruction::Load &&
5014         !E->isAltShuffle()) {
5015       BoUpSLP::ValueSet VectorizedLoads;
5016       unsigned StartIdx = 0;
5017       unsigned VF = VL.size() / 2;
5018       unsigned VectorizedCnt = 0;
5019       unsigned ScatterVectorizeCnt = 0;
5020       const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType());
5021       for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) {
5022         for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End;
5023              Cnt += VF) {
5024           ArrayRef<Value *> Slice = VL.slice(Cnt, VF);
5025           if (!VectorizedLoads.count(Slice.front()) &&
5026               !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) {
5027             SmallVector<Value *> PointerOps;
5028             OrdersType CurrentOrder;
5029             LoadsState LS = canVectorizeLoads(Slice, Slice.front(), *TTI, *DL,
5030                                               *SE, CurrentOrder, PointerOps);
5031             switch (LS) {
5032             case LoadsState::Vectorize:
5033             case LoadsState::ScatterVectorize:
5034               // Mark the vectorized loads so that we don't vectorize them
5035               // again.
5036               if (LS == LoadsState::Vectorize)
5037                 ++VectorizedCnt;
5038               else
5039                 ++ScatterVectorizeCnt;
5040               VectorizedLoads.insert(Slice.begin(), Slice.end());
5041               // If we vectorized initial block, no need to try to vectorize it
5042               // again.
5043               if (Cnt == StartIdx)
5044                 StartIdx += VF;
5045               break;
5046             case LoadsState::Gather:
5047               break;
5048             }
5049           }
5050         }
5051         // Check if the whole array was vectorized already - exit.
5052         if (StartIdx >= VL.size())
5053           break;
5054         // Found vectorizable parts - exit.
5055         if (!VectorizedLoads.empty())
5056           break;
5057       }
5058       if (!VectorizedLoads.empty()) {
5059         InstructionCost GatherCost = 0;
5060         unsigned NumParts = TTI->getNumberOfParts(VecTy);
5061         bool NeedInsertSubvectorAnalysis =
5062             !NumParts || (VL.size() / VF) > NumParts;
5063         // Get the cost for gathered loads.
5064         for (unsigned I = 0, End = VL.size(); I < End; I += VF) {
5065           if (VectorizedLoads.contains(VL[I]))
5066             continue;
5067           GatherCost += getGatherCost(VL.slice(I, VF));
5068         }
5069         // The cost for vectorized loads.
5070         InstructionCost ScalarsCost = 0;
5071         for (Value *V : VectorizedLoads) {
5072           auto *LI = cast<LoadInst>(V);
5073           ScalarsCost += TTI->getMemoryOpCost(
5074               Instruction::Load, LI->getType(), LI->getAlign(),
5075               LI->getPointerAddressSpace(), CostKind, LI);
5076         }
5077         auto *LI = cast<LoadInst>(E->getMainOp());
5078         auto *LoadTy = FixedVectorType::get(LI->getType(), VF);
5079         Align Alignment = LI->getAlign();
5080         GatherCost +=
5081             VectorizedCnt *
5082             TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment,
5083                                  LI->getPointerAddressSpace(), CostKind, LI);
5084         GatherCost += ScatterVectorizeCnt *
5085                       TTI->getGatherScatterOpCost(
5086                           Instruction::Load, LoadTy, LI->getPointerOperand(),
5087                           /*VariableMask=*/false, Alignment, CostKind, LI);
5088         if (NeedInsertSubvectorAnalysis) {
5089           // Add the cost for the subvectors insert.
5090           for (int I = VF, E = VL.size(); I < E; I += VF)
5091             GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy,
5092                                               None, I, LoadTy);
5093         }
5094         return ReuseShuffleCost + GatherCost - ScalarsCost;
5095       }
5096     }
5097     return ReuseShuffleCost + getGatherCost(VL);
5098   }
5099   InstructionCost CommonCost = 0;
5100   SmallVector<int> Mask;
5101   if (!E->ReorderIndices.empty()) {
5102     SmallVector<int> NewMask;
5103     if (E->getOpcode() == Instruction::Store) {
5104       // For stores the order is actually a mask.
5105       NewMask.resize(E->ReorderIndices.size());
5106       copy(E->ReorderIndices, NewMask.begin());
5107     } else {
5108       inversePermutation(E->ReorderIndices, NewMask);
5109     }
5110     ::addMask(Mask, NewMask);
5111   }
5112   if (NeedToShuffleReuses)
5113     ::addMask(Mask, E->ReuseShuffleIndices);
5114   if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask))
5115     CommonCost =
5116         TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask);
5117   assert((E->State == TreeEntry::Vectorize ||
5118           E->State == TreeEntry::ScatterVectorize) &&
5119          "Unhandled state");
5120   assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
5121   Instruction *VL0 = E->getMainOp();
5122   unsigned ShuffleOrOp =
5123       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
5124   switch (ShuffleOrOp) {
5125     case Instruction::PHI:
5126       return 0;
5127 
5128     case Instruction::ExtractValue:
5129     case Instruction::ExtractElement: {
5130       // The common cost of removal ExtractElement/ExtractValue instructions +
5131       // the cost of shuffles, if required to resuffle the original vector.
5132       if (NeedToShuffleReuses) {
5133         unsigned Idx = 0;
5134         for (unsigned I : E->ReuseShuffleIndices) {
5135           if (ShuffleOrOp == Instruction::ExtractElement) {
5136             auto *EE = cast<ExtractElementInst>(VL[I]);
5137             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5138                                                   EE->getVectorOperandType(),
5139                                                   *getExtractIndex(EE));
5140           } else {
5141             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5142                                                   VecTy, Idx);
5143             ++Idx;
5144           }
5145         }
5146         Idx = EntryVF;
5147         for (Value *V : VL) {
5148           if (ShuffleOrOp == Instruction::ExtractElement) {
5149             auto *EE = cast<ExtractElementInst>(V);
5150             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5151                                                   EE->getVectorOperandType(),
5152                                                   *getExtractIndex(EE));
5153           } else {
5154             --Idx;
5155             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5156                                                   VecTy, Idx);
5157           }
5158         }
5159       }
5160       if (ShuffleOrOp == Instruction::ExtractValue) {
5161         for (unsigned I = 0, E = VL.size(); I < E; ++I) {
5162           auto *EI = cast<Instruction>(VL[I]);
5163           // Take credit for instruction that will become dead.
5164           if (EI->hasOneUse()) {
5165             Instruction *Ext = EI->user_back();
5166             if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5167                 all_of(Ext->users(),
5168                        [](User *U) { return isa<GetElementPtrInst>(U); })) {
5169               // Use getExtractWithExtendCost() to calculate the cost of
5170               // extractelement/ext pair.
5171               CommonCost -= TTI->getExtractWithExtendCost(
5172                   Ext->getOpcode(), Ext->getType(), VecTy, I);
5173               // Add back the cost of s|zext which is subtracted separately.
5174               CommonCost += TTI->getCastInstrCost(
5175                   Ext->getOpcode(), Ext->getType(), EI->getType(),
5176                   TTI::getCastContextHint(Ext), CostKind, Ext);
5177               continue;
5178             }
5179           }
5180           CommonCost -=
5181               TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I);
5182         }
5183       } else {
5184         AdjustExtractsCost(CommonCost);
5185       }
5186       return CommonCost;
5187     }
5188     case Instruction::InsertElement: {
5189       assert(E->ReuseShuffleIndices.empty() &&
5190              "Unique insertelements only are expected.");
5191       auto *SrcVecTy = cast<FixedVectorType>(VL0->getType());
5192 
5193       unsigned const NumElts = SrcVecTy->getNumElements();
5194       unsigned const NumScalars = VL.size();
5195       APInt DemandedElts = APInt::getZero(NumElts);
5196       // TODO: Add support for Instruction::InsertValue.
5197       SmallVector<int> Mask;
5198       if (!E->ReorderIndices.empty()) {
5199         inversePermutation(E->ReorderIndices, Mask);
5200         Mask.append(NumElts - NumScalars, UndefMaskElem);
5201       } else {
5202         Mask.assign(NumElts, UndefMaskElem);
5203         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
5204       }
5205       unsigned Offset = *getInsertIndex(VL0);
5206       bool IsIdentity = true;
5207       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
5208       Mask.swap(PrevMask);
5209       for (unsigned I = 0; I < NumScalars; ++I) {
5210         unsigned InsertIdx = *getInsertIndex(VL[PrevMask[I]]);
5211         DemandedElts.setBit(InsertIdx);
5212         IsIdentity &= InsertIdx - Offset == I;
5213         Mask[InsertIdx - Offset] = I;
5214       }
5215       assert(Offset < NumElts && "Failed to find vector index offset");
5216 
5217       InstructionCost Cost = 0;
5218       Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts,
5219                                             /*Insert*/ true, /*Extract*/ false);
5220 
5221       if (IsIdentity && NumElts != NumScalars && Offset % NumScalars != 0) {
5222         // FIXME: Replace with SK_InsertSubvector once it is properly supported.
5223         unsigned Sz = PowerOf2Ceil(Offset + NumScalars);
5224         Cost += TTI->getShuffleCost(
5225             TargetTransformInfo::SK_PermuteSingleSrc,
5226             FixedVectorType::get(SrcVecTy->getElementType(), Sz));
5227       } else if (!IsIdentity) {
5228         auto *FirstInsert =
5229             cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
5230               return !is_contained(E->Scalars,
5231                                    cast<Instruction>(V)->getOperand(0));
5232             }));
5233         if (isUndefVector(FirstInsert->getOperand(0))) {
5234           Cost += TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, SrcVecTy, Mask);
5235         } else {
5236           SmallVector<int> InsertMask(NumElts);
5237           std::iota(InsertMask.begin(), InsertMask.end(), 0);
5238           for (unsigned I = 0; I < NumElts; I++) {
5239             if (Mask[I] != UndefMaskElem)
5240               InsertMask[Offset + I] = NumElts + I;
5241           }
5242           Cost +=
5243               TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVecTy, InsertMask);
5244         }
5245       }
5246 
5247       return Cost;
5248     }
5249     case Instruction::ZExt:
5250     case Instruction::SExt:
5251     case Instruction::FPToUI:
5252     case Instruction::FPToSI:
5253     case Instruction::FPExt:
5254     case Instruction::PtrToInt:
5255     case Instruction::IntToPtr:
5256     case Instruction::SIToFP:
5257     case Instruction::UIToFP:
5258     case Instruction::Trunc:
5259     case Instruction::FPTrunc:
5260     case Instruction::BitCast: {
5261       Type *SrcTy = VL0->getOperand(0)->getType();
5262       InstructionCost ScalarEltCost =
5263           TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy,
5264                                 TTI::getCastContextHint(VL0), CostKind, VL0);
5265       if (NeedToShuffleReuses) {
5266         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5267       }
5268 
5269       // Calculate the cost of this instruction.
5270       InstructionCost ScalarCost = VL.size() * ScalarEltCost;
5271 
5272       auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size());
5273       InstructionCost VecCost = 0;
5274       // Check if the values are candidates to demote.
5275       if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
5276         VecCost = CommonCost + TTI->getCastInstrCost(
5277                                    E->getOpcode(), VecTy, SrcVecTy,
5278                                    TTI::getCastContextHint(VL0), CostKind, VL0);
5279       }
5280       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5281       return VecCost - ScalarCost;
5282     }
5283     case Instruction::FCmp:
5284     case Instruction::ICmp:
5285     case Instruction::Select: {
5286       // Calculate the cost of this instruction.
5287       InstructionCost ScalarEltCost =
5288           TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5289                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0);
5290       if (NeedToShuffleReuses) {
5291         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5292       }
5293       auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size());
5294       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5295 
5296       // Check if all entries in VL are either compares or selects with compares
5297       // as condition that have the same predicates.
5298       CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE;
5299       bool First = true;
5300       for (auto *V : VL) {
5301         CmpInst::Predicate CurrentPred;
5302         auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value());
5303         if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) &&
5304              !match(V, MatchCmp)) ||
5305             (!First && VecPred != CurrentPred)) {
5306           VecPred = CmpInst::BAD_ICMP_PREDICATE;
5307           break;
5308         }
5309         First = false;
5310         VecPred = CurrentPred;
5311       }
5312 
5313       InstructionCost VecCost = TTI->getCmpSelInstrCost(
5314           E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0);
5315       // Check if it is possible and profitable to use min/max for selects in
5316       // VL.
5317       //
5318       auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL);
5319       if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) {
5320         IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy,
5321                                           {VecTy, VecTy});
5322         InstructionCost IntrinsicCost =
5323             TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5324         // If the selects are the only uses of the compares, they will be dead
5325         // and we can adjust the cost by removing their cost.
5326         if (IntrinsicAndUse.second)
5327           IntrinsicCost -=
5328               TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy, MaskTy,
5329                                       CmpInst::BAD_ICMP_PREDICATE, CostKind);
5330         VecCost = std::min(VecCost, IntrinsicCost);
5331       }
5332       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5333       return CommonCost + VecCost - ScalarCost;
5334     }
5335     case Instruction::FNeg:
5336     case Instruction::Add:
5337     case Instruction::FAdd:
5338     case Instruction::Sub:
5339     case Instruction::FSub:
5340     case Instruction::Mul:
5341     case Instruction::FMul:
5342     case Instruction::UDiv:
5343     case Instruction::SDiv:
5344     case Instruction::FDiv:
5345     case Instruction::URem:
5346     case Instruction::SRem:
5347     case Instruction::FRem:
5348     case Instruction::Shl:
5349     case Instruction::LShr:
5350     case Instruction::AShr:
5351     case Instruction::And:
5352     case Instruction::Or:
5353     case Instruction::Xor: {
5354       // Certain instructions can be cheaper to vectorize if they have a
5355       // constant second vector operand.
5356       TargetTransformInfo::OperandValueKind Op1VK =
5357           TargetTransformInfo::OK_AnyValue;
5358       TargetTransformInfo::OperandValueKind Op2VK =
5359           TargetTransformInfo::OK_UniformConstantValue;
5360       TargetTransformInfo::OperandValueProperties Op1VP =
5361           TargetTransformInfo::OP_None;
5362       TargetTransformInfo::OperandValueProperties Op2VP =
5363           TargetTransformInfo::OP_PowerOf2;
5364 
5365       // If all operands are exactly the same ConstantInt then set the
5366       // operand kind to OK_UniformConstantValue.
5367       // If instead not all operands are constants, then set the operand kind
5368       // to OK_AnyValue. If all operands are constants but not the same,
5369       // then set the operand kind to OK_NonUniformConstantValue.
5370       ConstantInt *CInt0 = nullptr;
5371       for (unsigned i = 0, e = VL.size(); i < e; ++i) {
5372         const Instruction *I = cast<Instruction>(VL[i]);
5373         unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0;
5374         ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx));
5375         if (!CInt) {
5376           Op2VK = TargetTransformInfo::OK_AnyValue;
5377           Op2VP = TargetTransformInfo::OP_None;
5378           break;
5379         }
5380         if (Op2VP == TargetTransformInfo::OP_PowerOf2 &&
5381             !CInt->getValue().isPowerOf2())
5382           Op2VP = TargetTransformInfo::OP_None;
5383         if (i == 0) {
5384           CInt0 = CInt;
5385           continue;
5386         }
5387         if (CInt0 != CInt)
5388           Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5389       }
5390 
5391       SmallVector<const Value *, 4> Operands(VL0->operand_values());
5392       InstructionCost ScalarEltCost =
5393           TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK,
5394                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5395       if (NeedToShuffleReuses) {
5396         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5397       }
5398       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5399       InstructionCost VecCost =
5400           TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK,
5401                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5402       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5403       return CommonCost + VecCost - ScalarCost;
5404     }
5405     case Instruction::GetElementPtr: {
5406       TargetTransformInfo::OperandValueKind Op1VK =
5407           TargetTransformInfo::OK_AnyValue;
5408       TargetTransformInfo::OperandValueKind Op2VK =
5409           TargetTransformInfo::OK_UniformConstantValue;
5410 
5411       InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost(
5412           Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK);
5413       if (NeedToShuffleReuses) {
5414         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5415       }
5416       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5417       InstructionCost VecCost = TTI->getArithmeticInstrCost(
5418           Instruction::Add, VecTy, CostKind, Op1VK, Op2VK);
5419       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5420       return CommonCost + VecCost - ScalarCost;
5421     }
5422     case Instruction::Load: {
5423       // Cost of wide load - cost of scalar loads.
5424       Align Alignment = cast<LoadInst>(VL0)->getAlign();
5425       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5426           Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0);
5427       if (NeedToShuffleReuses) {
5428         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5429       }
5430       InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost;
5431       InstructionCost VecLdCost;
5432       if (E->State == TreeEntry::Vectorize) {
5433         VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0,
5434                                          CostKind, VL0);
5435       } else {
5436         assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState");
5437         Align CommonAlignment = Alignment;
5438         for (Value *V : VL)
5439           CommonAlignment =
5440               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
5441         VecLdCost = TTI->getGatherScatterOpCost(
5442             Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(),
5443             /*VariableMask=*/false, CommonAlignment, CostKind, VL0);
5444       }
5445       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost));
5446       return CommonCost + VecLdCost - ScalarLdCost;
5447     }
5448     case Instruction::Store: {
5449       // We know that we can merge the stores. Calculate the cost.
5450       bool IsReorder = !E->ReorderIndices.empty();
5451       auto *SI =
5452           cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0);
5453       Align Alignment = SI->getAlign();
5454       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5455           Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0);
5456       InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost;
5457       InstructionCost VecStCost = TTI->getMemoryOpCost(
5458           Instruction::Store, VecTy, Alignment, 0, CostKind, VL0);
5459       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost));
5460       return CommonCost + VecStCost - ScalarStCost;
5461     }
5462     case Instruction::Call: {
5463       CallInst *CI = cast<CallInst>(VL0);
5464       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5465 
5466       // Calculate the cost of the scalar and vector calls.
5467       IntrinsicCostAttributes CostAttrs(ID, *CI, 1);
5468       InstructionCost ScalarEltCost =
5469           TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5470       if (NeedToShuffleReuses) {
5471         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5472       }
5473       InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
5474 
5475       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
5476       InstructionCost VecCallCost =
5477           std::min(VecCallCosts.first, VecCallCosts.second);
5478 
5479       LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
5480                         << " (" << VecCallCost << "-" << ScalarCallCost << ")"
5481                         << " for " << *CI << "\n");
5482 
5483       return CommonCost + VecCallCost - ScalarCallCost;
5484     }
5485     case Instruction::ShuffleVector: {
5486       assert(E->isAltShuffle() &&
5487              ((Instruction::isBinaryOp(E->getOpcode()) &&
5488                Instruction::isBinaryOp(E->getAltOpcode())) ||
5489               (Instruction::isCast(E->getOpcode()) &&
5490                Instruction::isCast(E->getAltOpcode())) ||
5491               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
5492              "Invalid Shuffle Vector Operand");
5493       InstructionCost ScalarCost = 0;
5494       if (NeedToShuffleReuses) {
5495         for (unsigned Idx : E->ReuseShuffleIndices) {
5496           Instruction *I = cast<Instruction>(VL[Idx]);
5497           CommonCost -= TTI->getInstructionCost(I, CostKind);
5498         }
5499         for (Value *V : VL) {
5500           Instruction *I = cast<Instruction>(V);
5501           CommonCost += TTI->getInstructionCost(I, CostKind);
5502         }
5503       }
5504       for (Value *V : VL) {
5505         Instruction *I = cast<Instruction>(V);
5506         assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5507         ScalarCost += TTI->getInstructionCost(I, CostKind);
5508       }
5509       // VecCost is equal to sum of the cost of creating 2 vectors
5510       // and the cost of creating shuffle.
5511       InstructionCost VecCost = 0;
5512       // Try to find the previous shuffle node with the same operands and same
5513       // main/alternate ops.
5514       auto &&TryFindNodeWithEqualOperands = [this, E]() {
5515         for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
5516           if (TE.get() == E)
5517             break;
5518           if (TE->isAltShuffle() &&
5519               ((TE->getOpcode() == E->getOpcode() &&
5520                 TE->getAltOpcode() == E->getAltOpcode()) ||
5521                (TE->getOpcode() == E->getAltOpcode() &&
5522                 TE->getAltOpcode() == E->getOpcode())) &&
5523               TE->hasEqualOperands(*E))
5524             return true;
5525         }
5526         return false;
5527       };
5528       if (TryFindNodeWithEqualOperands()) {
5529         LLVM_DEBUG({
5530           dbgs() << "SLP: diamond match for alternate node found.\n";
5531           E->dump();
5532         });
5533         // No need to add new vector costs here since we're going to reuse
5534         // same main/alternate vector ops, just do different shuffling.
5535       } else if (Instruction::isBinaryOp(E->getOpcode())) {
5536         VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind);
5537         VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy,
5538                                                CostKind);
5539       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
5540         VecCost = TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy,
5541                                           Builder.getInt1Ty(),
5542                                           CI0->getPredicate(), CostKind, VL0);
5543         VecCost += TTI->getCmpSelInstrCost(
5544             E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5545             cast<CmpInst>(E->getAltOp())->getPredicate(), CostKind,
5546             E->getAltOp());
5547       } else {
5548         Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
5549         Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
5550         auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size());
5551         auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size());
5552         VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty,
5553                                         TTI::CastContextHint::None, CostKind);
5554         VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty,
5555                                          TTI::CastContextHint::None, CostKind);
5556       }
5557 
5558       SmallVector<int> Mask;
5559       buildSuffleEntryMask(
5560           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
5561           [E](Instruction *I) {
5562             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5563             if (auto *CI0 = dyn_cast<CmpInst>(E->getMainOp())) {
5564               auto *AltCI0 = cast<CmpInst>(E->getAltOp());
5565               auto *CI = cast<CmpInst>(I);
5566               CmpInst::Predicate P0 = CI0->getPredicate();
5567               CmpInst::Predicate AltP0 = AltCI0->getPredicate();
5568               assert(P0 != AltP0 &&
5569                      "Expected different main/alternate predicates.");
5570               CmpInst::Predicate AltP0Swapped =
5571                   CmpInst::getSwappedPredicate(AltP0);
5572               CmpInst::Predicate CurrentPred = CI->getPredicate();
5573               if (P0 == AltP0Swapped)
5574                 return (P0 == CurrentPred &&
5575                         !areCompatibleCmpOps(
5576                             CI0->getOperand(0), CI0->getOperand(1),
5577                             CI->getOperand(0), CI->getOperand(1))) ||
5578                        (AltP0 == CurrentPred &&
5579                         !areCompatibleCmpOps(
5580                             CI0->getOperand(0), CI0->getOperand(1),
5581                             CI->getOperand(1), CI->getOperand(0)));
5582               return AltP0 == CurrentPred || AltP0Swapped == CurrentPred;
5583             }
5584             return I->getOpcode() == E->getAltOpcode();
5585           },
5586           Mask);
5587       CommonCost =
5588           TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy, Mask);
5589       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5590       return CommonCost + VecCost - ScalarCost;
5591     }
5592     default:
5593       llvm_unreachable("Unknown instruction");
5594   }
5595 }
5596 
5597 bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const {
5598   LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
5599                     << VectorizableTree.size() << " is fully vectorizable .\n");
5600 
5601   auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) {
5602     SmallVector<int> Mask;
5603     return TE->State == TreeEntry::NeedToGather &&
5604            !any_of(TE->Scalars,
5605                    [this](Value *V) { return EphValues.contains(V); }) &&
5606            (allConstant(TE->Scalars) || isSplat(TE->Scalars) ||
5607             TE->Scalars.size() < Limit ||
5608             ((TE->getOpcode() == Instruction::ExtractElement ||
5609               all_of(TE->Scalars,
5610                      [](Value *V) {
5611                        return isa<ExtractElementInst, UndefValue>(V);
5612                      })) &&
5613              isFixedVectorShuffle(TE->Scalars, Mask)) ||
5614             (TE->State == TreeEntry::NeedToGather &&
5615              TE->getOpcode() == Instruction::Load && !TE->isAltShuffle()));
5616   };
5617 
5618   // We only handle trees of heights 1 and 2.
5619   if (VectorizableTree.size() == 1 &&
5620       (VectorizableTree[0]->State == TreeEntry::Vectorize ||
5621        (ForReduction &&
5622         AreVectorizableGathers(VectorizableTree[0].get(),
5623                                VectorizableTree[0]->Scalars.size()) &&
5624         VectorizableTree[0]->getVectorFactor() > 2)))
5625     return true;
5626 
5627   if (VectorizableTree.size() != 2)
5628     return false;
5629 
5630   // Handle splat and all-constants stores. Also try to vectorize tiny trees
5631   // with the second gather nodes if they have less scalar operands rather than
5632   // the initial tree element (may be profitable to shuffle the second gather)
5633   // or they are extractelements, which form shuffle.
5634   SmallVector<int> Mask;
5635   if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
5636       AreVectorizableGathers(VectorizableTree[1].get(),
5637                              VectorizableTree[0]->Scalars.size()))
5638     return true;
5639 
5640   // Gathering cost would be too much for tiny trees.
5641   if (VectorizableTree[0]->State == TreeEntry::NeedToGather ||
5642       (VectorizableTree[1]->State == TreeEntry::NeedToGather &&
5643        VectorizableTree[0]->State != TreeEntry::ScatterVectorize))
5644     return false;
5645 
5646   return true;
5647 }
5648 
5649 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts,
5650                                        TargetTransformInfo *TTI,
5651                                        bool MustMatchOrInst) {
5652   // Look past the root to find a source value. Arbitrarily follow the
5653   // path through operand 0 of any 'or'. Also, peek through optional
5654   // shift-left-by-multiple-of-8-bits.
5655   Value *ZextLoad = Root;
5656   const APInt *ShAmtC;
5657   bool FoundOr = false;
5658   while (!isa<ConstantExpr>(ZextLoad) &&
5659          (match(ZextLoad, m_Or(m_Value(), m_Value())) ||
5660           (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) &&
5661            ShAmtC->urem(8) == 0))) {
5662     auto *BinOp = cast<BinaryOperator>(ZextLoad);
5663     ZextLoad = BinOp->getOperand(0);
5664     if (BinOp->getOpcode() == Instruction::Or)
5665       FoundOr = true;
5666   }
5667   // Check if the input is an extended load of the required or/shift expression.
5668   Value *Load;
5669   if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root ||
5670       !match(ZextLoad, m_ZExt(m_Value(Load))) || !isa<LoadInst>(Load))
5671     return false;
5672 
5673   // Require that the total load bit width is a legal integer type.
5674   // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
5675   // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
5676   Type *SrcTy = Load->getType();
5677   unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts;
5678   if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth)))
5679     return false;
5680 
5681   // Everything matched - assume that we can fold the whole sequence using
5682   // load combining.
5683   LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "
5684              << *(cast<Instruction>(Root)) << "\n");
5685 
5686   return true;
5687 }
5688 
5689 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const {
5690   if (RdxKind != RecurKind::Or)
5691     return false;
5692 
5693   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5694   Value *FirstReduced = VectorizableTree[0]->Scalars[0];
5695   return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI,
5696                                     /* MatchOr */ false);
5697 }
5698 
5699 bool BoUpSLP::isLoadCombineCandidate() const {
5700   // Peek through a final sequence of stores and check if all operations are
5701   // likely to be load-combined.
5702   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5703   for (Value *Scalar : VectorizableTree[0]->Scalars) {
5704     Value *X;
5705     if (!match(Scalar, m_Store(m_Value(X), m_Value())) ||
5706         !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true))
5707       return false;
5708   }
5709   return true;
5710 }
5711 
5712 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const {
5713   // No need to vectorize inserts of gathered values.
5714   if (VectorizableTree.size() == 2 &&
5715       isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) &&
5716       VectorizableTree[1]->State == TreeEntry::NeedToGather)
5717     return true;
5718 
5719   // We can vectorize the tree if its size is greater than or equal to the
5720   // minimum size specified by the MinTreeSize command line option.
5721   if (VectorizableTree.size() >= MinTreeSize)
5722     return false;
5723 
5724   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
5725   // can vectorize it if we can prove it fully vectorizable.
5726   if (isFullyVectorizableTinyTree(ForReduction))
5727     return false;
5728 
5729   assert(VectorizableTree.empty()
5730              ? ExternalUses.empty()
5731              : true && "We shouldn't have any external users");
5732 
5733   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
5734   // vectorizable.
5735   return true;
5736 }
5737 
5738 InstructionCost BoUpSLP::getSpillCost() const {
5739   // Walk from the bottom of the tree to the top, tracking which values are
5740   // live. When we see a call instruction that is not part of our tree,
5741   // query TTI to see if there is a cost to keeping values live over it
5742   // (for example, if spills and fills are required).
5743   unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
5744   InstructionCost Cost = 0;
5745 
5746   SmallPtrSet<Instruction*, 4> LiveValues;
5747   Instruction *PrevInst = nullptr;
5748 
5749   // The entries in VectorizableTree are not necessarily ordered by their
5750   // position in basic blocks. Collect them and order them by dominance so later
5751   // instructions are guaranteed to be visited first. For instructions in
5752   // different basic blocks, we only scan to the beginning of the block, so
5753   // their order does not matter, as long as all instructions in a basic block
5754   // are grouped together. Using dominance ensures a deterministic order.
5755   SmallVector<Instruction *, 16> OrderedScalars;
5756   for (const auto &TEPtr : VectorizableTree) {
5757     Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
5758     if (!Inst)
5759       continue;
5760     OrderedScalars.push_back(Inst);
5761   }
5762   llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) {
5763     auto *NodeA = DT->getNode(A->getParent());
5764     auto *NodeB = DT->getNode(B->getParent());
5765     assert(NodeA && "Should only process reachable instructions");
5766     assert(NodeB && "Should only process reachable instructions");
5767     assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
5768            "Different nodes should have different DFS numbers");
5769     if (NodeA != NodeB)
5770       return NodeA->getDFSNumIn() < NodeB->getDFSNumIn();
5771     return B->comesBefore(A);
5772   });
5773 
5774   for (Instruction *Inst : OrderedScalars) {
5775     if (!PrevInst) {
5776       PrevInst = Inst;
5777       continue;
5778     }
5779 
5780     // Update LiveValues.
5781     LiveValues.erase(PrevInst);
5782     for (auto &J : PrevInst->operands()) {
5783       if (isa<Instruction>(&*J) && getTreeEntry(&*J))
5784         LiveValues.insert(cast<Instruction>(&*J));
5785     }
5786 
5787     LLVM_DEBUG({
5788       dbgs() << "SLP: #LV: " << LiveValues.size();
5789       for (auto *X : LiveValues)
5790         dbgs() << " " << X->getName();
5791       dbgs() << ", Looking at ";
5792       Inst->dump();
5793     });
5794 
5795     // Now find the sequence of instructions between PrevInst and Inst.
5796     unsigned NumCalls = 0;
5797     BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
5798                                  PrevInstIt =
5799                                      PrevInst->getIterator().getReverse();
5800     while (InstIt != PrevInstIt) {
5801       if (PrevInstIt == PrevInst->getParent()->rend()) {
5802         PrevInstIt = Inst->getParent()->rbegin();
5803         continue;
5804       }
5805 
5806       // Debug information does not impact spill cost.
5807       if ((isa<CallInst>(&*PrevInstIt) &&
5808            !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
5809           &*PrevInstIt != PrevInst)
5810         NumCalls++;
5811 
5812       ++PrevInstIt;
5813     }
5814 
5815     if (NumCalls) {
5816       SmallVector<Type*, 4> V;
5817       for (auto *II : LiveValues) {
5818         auto *ScalarTy = II->getType();
5819         if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy))
5820           ScalarTy = VectorTy->getElementType();
5821         V.push_back(FixedVectorType::get(ScalarTy, BundleWidth));
5822       }
5823       Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
5824     }
5825 
5826     PrevInst = Inst;
5827   }
5828 
5829   return Cost;
5830 }
5831 
5832 /// Check if two insertelement instructions are from the same buildvector.
5833 static bool areTwoInsertFromSameBuildVector(InsertElementInst *VU,
5834                                             InsertElementInst *V) {
5835   // Instructions must be from the same basic blocks.
5836   if (VU->getParent() != V->getParent())
5837     return false;
5838   // Checks if 2 insertelements are from the same buildvector.
5839   if (VU->getType() != V->getType())
5840     return false;
5841   // Multiple used inserts are separate nodes.
5842   if (!VU->hasOneUse() && !V->hasOneUse())
5843     return false;
5844   auto *IE1 = VU;
5845   auto *IE2 = V;
5846   // Go through the vector operand of insertelement instructions trying to find
5847   // either VU as the original vector for IE2 or V as the original vector for
5848   // IE1.
5849   do {
5850     if (IE2 == VU || IE1 == V)
5851       return true;
5852     if (IE1) {
5853       if (IE1 != VU && !IE1->hasOneUse())
5854         IE1 = nullptr;
5855       else
5856         IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0));
5857     }
5858     if (IE2) {
5859       if (IE2 != V && !IE2->hasOneUse())
5860         IE2 = nullptr;
5861       else
5862         IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0));
5863     }
5864   } while (IE1 || IE2);
5865   return false;
5866 }
5867 
5868 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) {
5869   InstructionCost Cost = 0;
5870   LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
5871                     << VectorizableTree.size() << ".\n");
5872 
5873   unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
5874 
5875   for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
5876     TreeEntry &TE = *VectorizableTree[I].get();
5877 
5878     InstructionCost C = getEntryCost(&TE, VectorizedVals);
5879     Cost += C;
5880     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
5881                       << " for bundle that starts with " << *TE.Scalars[0]
5882                       << ".\n"
5883                       << "SLP: Current total cost = " << Cost << "\n");
5884   }
5885 
5886   SmallPtrSet<Value *, 16> ExtractCostCalculated;
5887   InstructionCost ExtractCost = 0;
5888   SmallVector<unsigned> VF;
5889   SmallVector<SmallVector<int>> ShuffleMask;
5890   SmallVector<Value *> FirstUsers;
5891   SmallVector<APInt> DemandedElts;
5892   for (ExternalUser &EU : ExternalUses) {
5893     // We only add extract cost once for the same scalar.
5894     if (!isa_and_nonnull<InsertElementInst>(EU.User) &&
5895         !ExtractCostCalculated.insert(EU.Scalar).second)
5896       continue;
5897 
5898     // Uses by ephemeral values are free (because the ephemeral value will be
5899     // removed prior to code generation, and so the extraction will be
5900     // removed as well).
5901     if (EphValues.count(EU.User))
5902       continue;
5903 
5904     // No extract cost for vector "scalar"
5905     if (isa<FixedVectorType>(EU.Scalar->getType()))
5906       continue;
5907 
5908     // Already counted the cost for external uses when tried to adjust the cost
5909     // for extractelements, no need to add it again.
5910     if (isa<ExtractElementInst>(EU.Scalar))
5911       continue;
5912 
5913     // If found user is an insertelement, do not calculate extract cost but try
5914     // to detect it as a final shuffled/identity match.
5915     if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) {
5916       if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) {
5917         unsigned InsertIdx = *getInsertIndex(VU);
5918         auto *It = find_if(FirstUsers, [VU](Value *V) {
5919           return areTwoInsertFromSameBuildVector(VU,
5920                                                  cast<InsertElementInst>(V));
5921         });
5922         int VecId = -1;
5923         if (It == FirstUsers.end()) {
5924           VF.push_back(FTy->getNumElements());
5925           ShuffleMask.emplace_back(VF.back(), UndefMaskElem);
5926           // Find the insertvector, vectorized in tree, if any.
5927           Value *Base = VU;
5928           while (isa<InsertElementInst>(Base)) {
5929             // Build the mask for the vectorized insertelement instructions.
5930             if (const TreeEntry *E = getTreeEntry(Base)) {
5931               VU = cast<InsertElementInst>(Base);
5932               do {
5933                 int Idx = E->findLaneForValue(Base);
5934                 ShuffleMask.back()[Idx] = Idx;
5935                 Base = cast<InsertElementInst>(Base)->getOperand(0);
5936               } while (E == getTreeEntry(Base));
5937               break;
5938             }
5939             Base = cast<InsertElementInst>(Base)->getOperand(0);
5940           }
5941           FirstUsers.push_back(VU);
5942           DemandedElts.push_back(APInt::getZero(VF.back()));
5943           VecId = FirstUsers.size() - 1;
5944         } else {
5945           VecId = std::distance(FirstUsers.begin(), It);
5946         }
5947         ShuffleMask[VecId][InsertIdx] = EU.Lane;
5948         DemandedElts[VecId].setBit(InsertIdx);
5949         continue;
5950       }
5951     }
5952 
5953     // If we plan to rewrite the tree in a smaller type, we will need to sign
5954     // extend the extracted value back to the original type. Here, we account
5955     // for the extract and the added cost of the sign extend if needed.
5956     auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth);
5957     auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
5958     if (MinBWs.count(ScalarRoot)) {
5959       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
5960       auto Extend =
5961           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
5962       VecTy = FixedVectorType::get(MinTy, BundleWidth);
5963       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
5964                                                    VecTy, EU.Lane);
5965     } else {
5966       ExtractCost +=
5967           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
5968     }
5969   }
5970 
5971   InstructionCost SpillCost = getSpillCost();
5972   Cost += SpillCost + ExtractCost;
5973   if (FirstUsers.size() == 1) {
5974     int Limit = ShuffleMask.front().size() * 2;
5975     if (all_of(ShuffleMask.front(), [Limit](int Idx) { return Idx < Limit; }) &&
5976         !ShuffleVectorInst::isIdentityMask(ShuffleMask.front())) {
5977       InstructionCost C = TTI->getShuffleCost(
5978           TTI::SK_PermuteSingleSrc,
5979           cast<FixedVectorType>(FirstUsers.front()->getType()),
5980           ShuffleMask.front());
5981       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
5982                         << " for final shuffle of insertelement external users "
5983                         << *VectorizableTree.front()->Scalars.front() << ".\n"
5984                         << "SLP: Current total cost = " << Cost << "\n");
5985       Cost += C;
5986     }
5987     InstructionCost InsertCost = TTI->getScalarizationOverhead(
5988         cast<FixedVectorType>(FirstUsers.front()->getType()),
5989         DemandedElts.front(), /*Insert*/ true, /*Extract*/ false);
5990     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
5991                       << " for insertelements gather.\n"
5992                       << "SLP: Current total cost = " << Cost << "\n");
5993     Cost -= InsertCost;
5994   } else if (FirstUsers.size() >= 2) {
5995     unsigned MaxVF = *std::max_element(VF.begin(), VF.end());
5996     // Combined masks of the first 2 vectors.
5997     SmallVector<int> CombinedMask(MaxVF, UndefMaskElem);
5998     copy(ShuffleMask.front(), CombinedMask.begin());
5999     APInt CombinedDemandedElts = DemandedElts.front().zextOrSelf(MaxVF);
6000     auto *VecTy = FixedVectorType::get(
6001         cast<VectorType>(FirstUsers.front()->getType())->getElementType(),
6002         MaxVF);
6003     for (int I = 0, E = ShuffleMask[1].size(); I < E; ++I) {
6004       if (ShuffleMask[1][I] != UndefMaskElem) {
6005         CombinedMask[I] = ShuffleMask[1][I] + MaxVF;
6006         CombinedDemandedElts.setBit(I);
6007       }
6008     }
6009     InstructionCost C =
6010         TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6011     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6012                       << " for final shuffle of vector node and external "
6013                          "insertelement users "
6014                       << *VectorizableTree.front()->Scalars.front() << ".\n"
6015                       << "SLP: Current total cost = " << Cost << "\n");
6016     Cost += C;
6017     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6018         VecTy, CombinedDemandedElts, /*Insert*/ true, /*Extract*/ false);
6019     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6020                       << " for insertelements gather.\n"
6021                       << "SLP: Current total cost = " << Cost << "\n");
6022     Cost -= InsertCost;
6023     for (int I = 2, E = FirstUsers.size(); I < E; ++I) {
6024       // Other elements - permutation of 2 vectors (the initial one and the
6025       // next Ith incoming vector).
6026       unsigned VF = ShuffleMask[I].size();
6027       for (unsigned Idx = 0; Idx < VF; ++Idx) {
6028         int Mask = ShuffleMask[I][Idx];
6029         if (Mask != UndefMaskElem)
6030           CombinedMask[Idx] = MaxVF + Mask;
6031         else if (CombinedMask[Idx] != UndefMaskElem)
6032           CombinedMask[Idx] = Idx;
6033       }
6034       for (unsigned Idx = VF; Idx < MaxVF; ++Idx)
6035         if (CombinedMask[Idx] != UndefMaskElem)
6036           CombinedMask[Idx] = Idx;
6037       InstructionCost C =
6038           TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6039       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6040                         << " for final shuffle of vector node and external "
6041                            "insertelement users "
6042                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6043                         << "SLP: Current total cost = " << Cost << "\n");
6044       Cost += C;
6045       InstructionCost InsertCost = TTI->getScalarizationOverhead(
6046           cast<FixedVectorType>(FirstUsers[I]->getType()), DemandedElts[I],
6047           /*Insert*/ true, /*Extract*/ false);
6048       LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6049                         << " for insertelements gather.\n"
6050                         << "SLP: Current total cost = " << Cost << "\n");
6051       Cost -= InsertCost;
6052     }
6053   }
6054 
6055 #ifndef NDEBUG
6056   SmallString<256> Str;
6057   {
6058     raw_svector_ostream OS(Str);
6059     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
6060        << "SLP: Extract Cost = " << ExtractCost << ".\n"
6061        << "SLP: Total Cost = " << Cost << ".\n";
6062   }
6063   LLVM_DEBUG(dbgs() << Str);
6064   if (ViewSLPTree)
6065     ViewGraph(this, "SLP" + F->getName(), false, Str);
6066 #endif
6067 
6068   return Cost;
6069 }
6070 
6071 Optional<TargetTransformInfo::ShuffleKind>
6072 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
6073                                SmallVectorImpl<const TreeEntry *> &Entries) {
6074   // TODO: currently checking only for Scalars in the tree entry, need to count
6075   // reused elements too for better cost estimation.
6076   Mask.assign(TE->Scalars.size(), UndefMaskElem);
6077   Entries.clear();
6078   // Build a lists of values to tree entries.
6079   DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs;
6080   for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) {
6081     if (EntryPtr.get() == TE)
6082       break;
6083     if (EntryPtr->State != TreeEntry::NeedToGather)
6084       continue;
6085     for (Value *V : EntryPtr->Scalars)
6086       ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get());
6087   }
6088   // Find all tree entries used by the gathered values. If no common entries
6089   // found - not a shuffle.
6090   // Here we build a set of tree nodes for each gathered value and trying to
6091   // find the intersection between these sets. If we have at least one common
6092   // tree node for each gathered value - we have just a permutation of the
6093   // single vector. If we have 2 different sets, we're in situation where we
6094   // have a permutation of 2 input vectors.
6095   SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs;
6096   DenseMap<Value *, int> UsedValuesEntry;
6097   for (Value *V : TE->Scalars) {
6098     if (isa<UndefValue>(V))
6099       continue;
6100     // Build a list of tree entries where V is used.
6101     SmallPtrSet<const TreeEntry *, 4> VToTEs;
6102     auto It = ValueToTEs.find(V);
6103     if (It != ValueToTEs.end())
6104       VToTEs = It->second;
6105     if (const TreeEntry *VTE = getTreeEntry(V))
6106       VToTEs.insert(VTE);
6107     if (VToTEs.empty())
6108       return None;
6109     if (UsedTEs.empty()) {
6110       // The first iteration, just insert the list of nodes to vector.
6111       UsedTEs.push_back(VToTEs);
6112     } else {
6113       // Need to check if there are any previously used tree nodes which use V.
6114       // If there are no such nodes, consider that we have another one input
6115       // vector.
6116       SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs);
6117       unsigned Idx = 0;
6118       for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) {
6119         // Do we have a non-empty intersection of previously listed tree entries
6120         // and tree entries using current V?
6121         set_intersect(VToTEs, Set);
6122         if (!VToTEs.empty()) {
6123           // Yes, write the new subset and continue analysis for the next
6124           // scalar.
6125           Set.swap(VToTEs);
6126           break;
6127         }
6128         VToTEs = SavedVToTEs;
6129         ++Idx;
6130       }
6131       // No non-empty intersection found - need to add a second set of possible
6132       // source vectors.
6133       if (Idx == UsedTEs.size()) {
6134         // If the number of input vectors is greater than 2 - not a permutation,
6135         // fallback to the regular gather.
6136         if (UsedTEs.size() == 2)
6137           return None;
6138         UsedTEs.push_back(SavedVToTEs);
6139         Idx = UsedTEs.size() - 1;
6140       }
6141       UsedValuesEntry.try_emplace(V, Idx);
6142     }
6143   }
6144 
6145   unsigned VF = 0;
6146   if (UsedTEs.size() == 1) {
6147     // Try to find the perfect match in another gather node at first.
6148     auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) {
6149       return EntryPtr->isSame(TE->Scalars);
6150     });
6151     if (It != UsedTEs.front().end()) {
6152       Entries.push_back(*It);
6153       std::iota(Mask.begin(), Mask.end(), 0);
6154       return TargetTransformInfo::SK_PermuteSingleSrc;
6155     }
6156     // No perfect match, just shuffle, so choose the first tree node.
6157     Entries.push_back(*UsedTEs.front().begin());
6158   } else {
6159     // Try to find nodes with the same vector factor.
6160     assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries.");
6161     DenseMap<int, const TreeEntry *> VFToTE;
6162     for (const TreeEntry *TE : UsedTEs.front())
6163       VFToTE.try_emplace(TE->getVectorFactor(), TE);
6164     for (const TreeEntry *TE : UsedTEs.back()) {
6165       auto It = VFToTE.find(TE->getVectorFactor());
6166       if (It != VFToTE.end()) {
6167         VF = It->first;
6168         Entries.push_back(It->second);
6169         Entries.push_back(TE);
6170         break;
6171       }
6172     }
6173     // No 2 source vectors with the same vector factor - give up and do regular
6174     // gather.
6175     if (Entries.empty())
6176       return None;
6177   }
6178 
6179   // Build a shuffle mask for better cost estimation and vector emission.
6180   for (int I = 0, E = TE->Scalars.size(); I < E; ++I) {
6181     Value *V = TE->Scalars[I];
6182     if (isa<UndefValue>(V))
6183       continue;
6184     unsigned Idx = UsedValuesEntry.lookup(V);
6185     const TreeEntry *VTE = Entries[Idx];
6186     int FoundLane = VTE->findLaneForValue(V);
6187     Mask[I] = Idx * VF + FoundLane;
6188     // Extra check required by isSingleSourceMaskImpl function (called by
6189     // ShuffleVectorInst::isSingleSourceMask).
6190     if (Mask[I] >= 2 * E)
6191       return None;
6192   }
6193   switch (Entries.size()) {
6194   case 1:
6195     return TargetTransformInfo::SK_PermuteSingleSrc;
6196   case 2:
6197     return TargetTransformInfo::SK_PermuteTwoSrc;
6198   default:
6199     break;
6200   }
6201   return None;
6202 }
6203 
6204 InstructionCost BoUpSLP::getGatherCost(FixedVectorType *Ty,
6205                                        const APInt &ShuffledIndices,
6206                                        bool NeedToShuffle) const {
6207   InstructionCost Cost =
6208       TTI->getScalarizationOverhead(Ty, ~ShuffledIndices, /*Insert*/ true,
6209                                     /*Extract*/ false);
6210   if (NeedToShuffle)
6211     Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
6212   return Cost;
6213 }
6214 
6215 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
6216   // Find the type of the operands in VL.
6217   Type *ScalarTy = VL[0]->getType();
6218   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
6219     ScalarTy = SI->getValueOperand()->getType();
6220   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
6221   bool DuplicateNonConst = false;
6222   // Find the cost of inserting/extracting values from the vector.
6223   // Check if the same elements are inserted several times and count them as
6224   // shuffle candidates.
6225   APInt ShuffledElements = APInt::getZero(VL.size());
6226   DenseSet<Value *> UniqueElements;
6227   // Iterate in reverse order to consider insert elements with the high cost.
6228   for (unsigned I = VL.size(); I > 0; --I) {
6229     unsigned Idx = I - 1;
6230     // No need to shuffle duplicates for constants.
6231     if (isConstant(VL[Idx])) {
6232       ShuffledElements.setBit(Idx);
6233       continue;
6234     }
6235     if (!UniqueElements.insert(VL[Idx]).second) {
6236       DuplicateNonConst = true;
6237       ShuffledElements.setBit(Idx);
6238     }
6239   }
6240   return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst);
6241 }
6242 
6243 // Perform operand reordering on the instructions in VL and return the reordered
6244 // operands in Left and Right.
6245 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
6246                                              SmallVectorImpl<Value *> &Left,
6247                                              SmallVectorImpl<Value *> &Right,
6248                                              const DataLayout &DL,
6249                                              ScalarEvolution &SE,
6250                                              const BoUpSLP &R) {
6251   if (VL.empty())
6252     return;
6253   VLOperands Ops(VL, DL, SE, R);
6254   // Reorder the operands in place.
6255   Ops.reorder();
6256   Left = Ops.getVL(0);
6257   Right = Ops.getVL(1);
6258 }
6259 
6260 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) {
6261   // Get the basic block this bundle is in. All instructions in the bundle
6262   // should be in this block.
6263   auto *Front = E->getMainOp();
6264   auto *BB = Front->getParent();
6265   assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool {
6266     auto *I = cast<Instruction>(V);
6267     return !E->isOpcodeOrAlt(I) || I->getParent() == BB;
6268   }));
6269 
6270   // The last instruction in the bundle in program order.
6271   Instruction *LastInst = nullptr;
6272 
6273   // Find the last instruction. The common case should be that BB has been
6274   // scheduled, and the last instruction is VL.back(). So we start with
6275   // VL.back() and iterate over schedule data until we reach the end of the
6276   // bundle. The end of the bundle is marked by null ScheduleData.
6277   if (BlocksSchedules.count(BB)) {
6278     auto *Bundle =
6279         BlocksSchedules[BB]->getScheduleData(E->isOneOf(E->Scalars.back()));
6280     if (Bundle && Bundle->isPartOfBundle())
6281       for (; Bundle; Bundle = Bundle->NextInBundle)
6282         if (Bundle->OpValue == Bundle->Inst)
6283           LastInst = Bundle->Inst;
6284   }
6285 
6286   // LastInst can still be null at this point if there's either not an entry
6287   // for BB in BlocksSchedules or there's no ScheduleData available for
6288   // VL.back(). This can be the case if buildTree_rec aborts for various
6289   // reasons (e.g., the maximum recursion depth is reached, the maximum region
6290   // size is reached, etc.). ScheduleData is initialized in the scheduling
6291   // "dry-run".
6292   //
6293   // If this happens, we can still find the last instruction by brute force. We
6294   // iterate forwards from Front (inclusive) until we either see all
6295   // instructions in the bundle or reach the end of the block. If Front is the
6296   // last instruction in program order, LastInst will be set to Front, and we
6297   // will visit all the remaining instructions in the block.
6298   //
6299   // One of the reasons we exit early from buildTree_rec is to place an upper
6300   // bound on compile-time. Thus, taking an additional compile-time hit here is
6301   // not ideal. However, this should be exceedingly rare since it requires that
6302   // we both exit early from buildTree_rec and that the bundle be out-of-order
6303   // (causing us to iterate all the way to the end of the block).
6304   if (!LastInst) {
6305     SmallPtrSet<Value *, 16> Bundle(E->Scalars.begin(), E->Scalars.end());
6306     for (auto &I : make_range(BasicBlock::iterator(Front), BB->end())) {
6307       if (Bundle.erase(&I) && E->isOpcodeOrAlt(&I))
6308         LastInst = &I;
6309       if (Bundle.empty())
6310         break;
6311     }
6312   }
6313   assert(LastInst && "Failed to find last instruction in bundle");
6314 
6315   // Set the insertion point after the last instruction in the bundle. Set the
6316   // debug location to Front.
6317   Builder.SetInsertPoint(BB, ++LastInst->getIterator());
6318   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6319 }
6320 
6321 Value *BoUpSLP::gather(ArrayRef<Value *> VL) {
6322   // List of instructions/lanes from current block and/or the blocks which are
6323   // part of the current loop. These instructions will be inserted at the end to
6324   // make it possible to optimize loops and hoist invariant instructions out of
6325   // the loops body with better chances for success.
6326   SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts;
6327   SmallSet<int, 4> PostponedIndices;
6328   Loop *L = LI->getLoopFor(Builder.GetInsertBlock());
6329   auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) {
6330     SmallPtrSet<BasicBlock *, 4> Visited;
6331     while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second)
6332       InsertBB = InsertBB->getSinglePredecessor();
6333     return InsertBB && InsertBB == InstBB;
6334   };
6335   for (int I = 0, E = VL.size(); I < E; ++I) {
6336     if (auto *Inst = dyn_cast<Instruction>(VL[I]))
6337       if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) ||
6338            getTreeEntry(Inst) || (L && (L->contains(Inst)))) &&
6339           PostponedIndices.insert(I).second)
6340         PostponedInsts.emplace_back(Inst, I);
6341   }
6342 
6343   auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) {
6344     Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos));
6345     auto *InsElt = dyn_cast<InsertElementInst>(Vec);
6346     if (!InsElt)
6347       return Vec;
6348     GatherShuffleSeq.insert(InsElt);
6349     CSEBlocks.insert(InsElt->getParent());
6350     // Add to our 'need-to-extract' list.
6351     if (TreeEntry *Entry = getTreeEntry(V)) {
6352       // Find which lane we need to extract.
6353       unsigned FoundLane = Entry->findLaneForValue(V);
6354       ExternalUses.emplace_back(V, InsElt, FoundLane);
6355     }
6356     return Vec;
6357   };
6358   Value *Val0 =
6359       isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0];
6360   FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size());
6361   Value *Vec = PoisonValue::get(VecTy);
6362   SmallVector<int> NonConsts;
6363   // Insert constant values at first.
6364   for (int I = 0, E = VL.size(); I < E; ++I) {
6365     if (PostponedIndices.contains(I))
6366       continue;
6367     if (!isConstant(VL[I])) {
6368       NonConsts.push_back(I);
6369       continue;
6370     }
6371     Vec = CreateInsertElement(Vec, VL[I], I);
6372   }
6373   // Insert non-constant values.
6374   for (int I : NonConsts)
6375     Vec = CreateInsertElement(Vec, VL[I], I);
6376   // Append instructions, which are/may be part of the loop, in the end to make
6377   // it possible to hoist non-loop-based instructions.
6378   for (const std::pair<Value *, unsigned> &Pair : PostponedInsts)
6379     Vec = CreateInsertElement(Vec, Pair.first, Pair.second);
6380 
6381   return Vec;
6382 }
6383 
6384 namespace {
6385 /// Merges shuffle masks and emits final shuffle instruction, if required.
6386 class ShuffleInstructionBuilder {
6387   IRBuilderBase &Builder;
6388   const unsigned VF = 0;
6389   bool IsFinalized = false;
6390   SmallVector<int, 4> Mask;
6391   /// Holds all of the instructions that we gathered.
6392   SetVector<Instruction *> &GatherShuffleSeq;
6393   /// A list of blocks that we are going to CSE.
6394   SetVector<BasicBlock *> &CSEBlocks;
6395 
6396 public:
6397   ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF,
6398                             SetVector<Instruction *> &GatherShuffleSeq,
6399                             SetVector<BasicBlock *> &CSEBlocks)
6400       : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq),
6401         CSEBlocks(CSEBlocks) {}
6402 
6403   /// Adds a mask, inverting it before applying.
6404   void addInversedMask(ArrayRef<unsigned> SubMask) {
6405     if (SubMask.empty())
6406       return;
6407     SmallVector<int, 4> NewMask;
6408     inversePermutation(SubMask, NewMask);
6409     addMask(NewMask);
6410   }
6411 
6412   /// Functions adds masks, merging them into  single one.
6413   void addMask(ArrayRef<unsigned> SubMask) {
6414     SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end());
6415     addMask(NewMask);
6416   }
6417 
6418   void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); }
6419 
6420   Value *finalize(Value *V) {
6421     IsFinalized = true;
6422     unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements();
6423     if (VF == ValueVF && Mask.empty())
6424       return V;
6425     SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem);
6426     std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0);
6427     addMask(NormalizedMask);
6428 
6429     if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask))
6430       return V;
6431     Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle");
6432     if (auto *I = dyn_cast<Instruction>(Vec)) {
6433       GatherShuffleSeq.insert(I);
6434       CSEBlocks.insert(I->getParent());
6435     }
6436     return Vec;
6437   }
6438 
6439   ~ShuffleInstructionBuilder() {
6440     assert((IsFinalized || Mask.empty()) &&
6441            "Shuffle construction must be finalized.");
6442   }
6443 };
6444 } // namespace
6445 
6446 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
6447   unsigned VF = VL.size();
6448   InstructionsState S = getSameOpcode(VL);
6449   if (S.getOpcode()) {
6450     if (TreeEntry *E = getTreeEntry(S.OpValue))
6451       if (E->isSame(VL)) {
6452         Value *V = vectorizeTree(E);
6453         if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) {
6454           if (!E->ReuseShuffleIndices.empty()) {
6455             // Reshuffle to get only unique values.
6456             // If some of the scalars are duplicated in the vectorization tree
6457             // entry, we do not vectorize them but instead generate a mask for
6458             // the reuses. But if there are several users of the same entry,
6459             // they may have different vectorization factors. This is especially
6460             // important for PHI nodes. In this case, we need to adapt the
6461             // resulting instruction for the user vectorization factor and have
6462             // to reshuffle it again to take only unique elements of the vector.
6463             // Without this code the function incorrectly returns reduced vector
6464             // instruction with the same elements, not with the unique ones.
6465 
6466             // block:
6467             // %phi = phi <2 x > { .., %entry} {%shuffle, %block}
6468             // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0>
6469             // ... (use %2)
6470             // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0}
6471             // br %block
6472             SmallVector<int> UniqueIdxs(VF, UndefMaskElem);
6473             SmallSet<int, 4> UsedIdxs;
6474             int Pos = 0;
6475             int Sz = VL.size();
6476             for (int Idx : E->ReuseShuffleIndices) {
6477               if (Idx != Sz && Idx != UndefMaskElem &&
6478                   UsedIdxs.insert(Idx).second)
6479                 UniqueIdxs[Idx] = Pos;
6480               ++Pos;
6481             }
6482             assert(VF >= UsedIdxs.size() && "Expected vectorization factor "
6483                                             "less than original vector size.");
6484             UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem);
6485             V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle");
6486           } else {
6487             assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() &&
6488                    "Expected vectorization factor less "
6489                    "than original vector size.");
6490             SmallVector<int> UniformMask(VF, 0);
6491             std::iota(UniformMask.begin(), UniformMask.end(), 0);
6492             V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle");
6493           }
6494           if (auto *I = dyn_cast<Instruction>(V)) {
6495             GatherShuffleSeq.insert(I);
6496             CSEBlocks.insert(I->getParent());
6497           }
6498         }
6499         return V;
6500       }
6501   }
6502 
6503   // Check that every instruction appears once in this bundle.
6504   SmallVector<int> ReuseShuffleIndicies;
6505   SmallVector<Value *> UniqueValues;
6506   if (VL.size() > 2) {
6507     DenseMap<Value *, unsigned> UniquePositions;
6508     unsigned NumValues =
6509         std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) {
6510                                     return !isa<UndefValue>(V);
6511                                   }).base());
6512     VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues));
6513     int UniqueVals = 0;
6514     for (Value *V : VL.drop_back(VL.size() - VF)) {
6515       if (isa<UndefValue>(V)) {
6516         ReuseShuffleIndicies.emplace_back(UndefMaskElem);
6517         continue;
6518       }
6519       if (isConstant(V)) {
6520         ReuseShuffleIndicies.emplace_back(UniqueValues.size());
6521         UniqueValues.emplace_back(V);
6522         continue;
6523       }
6524       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
6525       ReuseShuffleIndicies.emplace_back(Res.first->second);
6526       if (Res.second) {
6527         UniqueValues.emplace_back(V);
6528         ++UniqueVals;
6529       }
6530     }
6531     if (UniqueVals == 1 && UniqueValues.size() == 1) {
6532       // Emit pure splat vector.
6533       ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(),
6534                                   UndefMaskElem);
6535     } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) {
6536       ReuseShuffleIndicies.clear();
6537       UniqueValues.clear();
6538       UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues));
6539     }
6540     UniqueValues.append(VF - UniqueValues.size(),
6541                         PoisonValue::get(VL[0]->getType()));
6542     VL = UniqueValues;
6543   }
6544 
6545   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6546                                            CSEBlocks);
6547   Value *Vec = gather(VL);
6548   if (!ReuseShuffleIndicies.empty()) {
6549     ShuffleBuilder.addMask(ReuseShuffleIndicies);
6550     Vec = ShuffleBuilder.finalize(Vec);
6551   }
6552   return Vec;
6553 }
6554 
6555 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
6556   IRBuilder<>::InsertPointGuard Guard(Builder);
6557 
6558   if (E->VectorizedValue) {
6559     LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
6560     return E->VectorizedValue;
6561   }
6562 
6563   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
6564   unsigned VF = E->getVectorFactor();
6565   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6566                                            CSEBlocks);
6567   if (E->State == TreeEntry::NeedToGather) {
6568     if (E->getMainOp())
6569       setInsertPointAfterBundle(E);
6570     Value *Vec;
6571     SmallVector<int> Mask;
6572     SmallVector<const TreeEntry *> Entries;
6573     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
6574         isGatherShuffledEntry(E, Mask, Entries);
6575     if (Shuffle.hasValue()) {
6576       assert((Entries.size() == 1 || Entries.size() == 2) &&
6577              "Expected shuffle of 1 or 2 entries.");
6578       Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue,
6579                                         Entries.back()->VectorizedValue, Mask);
6580       if (auto *I = dyn_cast<Instruction>(Vec)) {
6581         GatherShuffleSeq.insert(I);
6582         CSEBlocks.insert(I->getParent());
6583       }
6584     } else {
6585       Vec = gather(E->Scalars);
6586     }
6587     if (NeedToShuffleReuses) {
6588       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6589       Vec = ShuffleBuilder.finalize(Vec);
6590     }
6591     E->VectorizedValue = Vec;
6592     return Vec;
6593   }
6594 
6595   assert((E->State == TreeEntry::Vectorize ||
6596           E->State == TreeEntry::ScatterVectorize) &&
6597          "Unhandled state");
6598   unsigned ShuffleOrOp =
6599       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
6600   Instruction *VL0 = E->getMainOp();
6601   Type *ScalarTy = VL0->getType();
6602   if (auto *Store = dyn_cast<StoreInst>(VL0))
6603     ScalarTy = Store->getValueOperand()->getType();
6604   else if (auto *IE = dyn_cast<InsertElementInst>(VL0))
6605     ScalarTy = IE->getOperand(1)->getType();
6606   auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
6607   switch (ShuffleOrOp) {
6608     case Instruction::PHI: {
6609       assert(
6610           (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) &&
6611           "PHI reordering is free.");
6612       auto *PH = cast<PHINode>(VL0);
6613       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
6614       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6615       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
6616       Value *V = NewPhi;
6617       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6618       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6619       V = ShuffleBuilder.finalize(V);
6620 
6621       E->VectorizedValue = V;
6622 
6623       // PHINodes may have multiple entries from the same block. We want to
6624       // visit every block once.
6625       SmallPtrSet<BasicBlock*, 4> VisitedBBs;
6626 
6627       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
6628         ValueList Operands;
6629         BasicBlock *IBB = PH->getIncomingBlock(i);
6630 
6631         if (!VisitedBBs.insert(IBB).second) {
6632           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
6633           continue;
6634         }
6635 
6636         Builder.SetInsertPoint(IBB->getTerminator());
6637         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6638         Value *Vec = vectorizeTree(E->getOperand(i));
6639         NewPhi->addIncoming(Vec, IBB);
6640       }
6641 
6642       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
6643              "Invalid number of incoming values");
6644       return V;
6645     }
6646 
6647     case Instruction::ExtractElement: {
6648       Value *V = E->getSingleOperand(0);
6649       Builder.SetInsertPoint(VL0);
6650       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6651       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6652       V = ShuffleBuilder.finalize(V);
6653       E->VectorizedValue = V;
6654       return V;
6655     }
6656     case Instruction::ExtractValue: {
6657       auto *LI = cast<LoadInst>(E->getSingleOperand(0));
6658       Builder.SetInsertPoint(LI);
6659       auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
6660       Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
6661       LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
6662       Value *NewV = propagateMetadata(V, E->Scalars);
6663       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6664       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6665       NewV = ShuffleBuilder.finalize(NewV);
6666       E->VectorizedValue = NewV;
6667       return NewV;
6668     }
6669     case Instruction::InsertElement: {
6670       assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique");
6671       Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back()));
6672       Value *V = vectorizeTree(E->getOperand(1));
6673 
6674       // Create InsertVector shuffle if necessary
6675       auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
6676         return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0));
6677       }));
6678       const unsigned NumElts =
6679           cast<FixedVectorType>(FirstInsert->getType())->getNumElements();
6680       const unsigned NumScalars = E->Scalars.size();
6681 
6682       unsigned Offset = *getInsertIndex(VL0);
6683       assert(Offset < NumElts && "Failed to find vector index offset");
6684 
6685       // Create shuffle to resize vector
6686       SmallVector<int> Mask;
6687       if (!E->ReorderIndices.empty()) {
6688         inversePermutation(E->ReorderIndices, Mask);
6689         Mask.append(NumElts - NumScalars, UndefMaskElem);
6690       } else {
6691         Mask.assign(NumElts, UndefMaskElem);
6692         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
6693       }
6694       // Create InsertVector shuffle if necessary
6695       bool IsIdentity = true;
6696       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
6697       Mask.swap(PrevMask);
6698       for (unsigned I = 0; I < NumScalars; ++I) {
6699         Value *Scalar = E->Scalars[PrevMask[I]];
6700         unsigned InsertIdx = *getInsertIndex(Scalar);
6701         IsIdentity &= InsertIdx - Offset == I;
6702         Mask[InsertIdx - Offset] = I;
6703       }
6704       if (!IsIdentity || NumElts != NumScalars) {
6705         V = Builder.CreateShuffleVector(V, Mask);
6706         if (auto *I = dyn_cast<Instruction>(V)) {
6707           GatherShuffleSeq.insert(I);
6708           CSEBlocks.insert(I->getParent());
6709         }
6710       }
6711 
6712       if ((!IsIdentity || Offset != 0 ||
6713            !isUndefVector(FirstInsert->getOperand(0))) &&
6714           NumElts != NumScalars) {
6715         SmallVector<int> InsertMask(NumElts);
6716         std::iota(InsertMask.begin(), InsertMask.end(), 0);
6717         for (unsigned I = 0; I < NumElts; I++) {
6718           if (Mask[I] != UndefMaskElem)
6719             InsertMask[Offset + I] = NumElts + I;
6720         }
6721 
6722         V = Builder.CreateShuffleVector(
6723             FirstInsert->getOperand(0), V, InsertMask,
6724             cast<Instruction>(E->Scalars.back())->getName());
6725         if (auto *I = dyn_cast<Instruction>(V)) {
6726           GatherShuffleSeq.insert(I);
6727           CSEBlocks.insert(I->getParent());
6728         }
6729       }
6730 
6731       ++NumVectorInstructions;
6732       E->VectorizedValue = V;
6733       return V;
6734     }
6735     case Instruction::ZExt:
6736     case Instruction::SExt:
6737     case Instruction::FPToUI:
6738     case Instruction::FPToSI:
6739     case Instruction::FPExt:
6740     case Instruction::PtrToInt:
6741     case Instruction::IntToPtr:
6742     case Instruction::SIToFP:
6743     case Instruction::UIToFP:
6744     case Instruction::Trunc:
6745     case Instruction::FPTrunc:
6746     case Instruction::BitCast: {
6747       setInsertPointAfterBundle(E);
6748 
6749       Value *InVec = vectorizeTree(E->getOperand(0));
6750 
6751       if (E->VectorizedValue) {
6752         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6753         return E->VectorizedValue;
6754       }
6755 
6756       auto *CI = cast<CastInst>(VL0);
6757       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
6758       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6759       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6760       V = ShuffleBuilder.finalize(V);
6761 
6762       E->VectorizedValue = V;
6763       ++NumVectorInstructions;
6764       return V;
6765     }
6766     case Instruction::FCmp:
6767     case Instruction::ICmp: {
6768       setInsertPointAfterBundle(E);
6769 
6770       Value *L = vectorizeTree(E->getOperand(0));
6771       Value *R = vectorizeTree(E->getOperand(1));
6772 
6773       if (E->VectorizedValue) {
6774         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6775         return E->VectorizedValue;
6776       }
6777 
6778       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
6779       Value *V = Builder.CreateCmp(P0, L, R);
6780       propagateIRFlags(V, E->Scalars, VL0);
6781       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6782       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6783       V = ShuffleBuilder.finalize(V);
6784 
6785       E->VectorizedValue = V;
6786       ++NumVectorInstructions;
6787       return V;
6788     }
6789     case Instruction::Select: {
6790       setInsertPointAfterBundle(E);
6791 
6792       Value *Cond = vectorizeTree(E->getOperand(0));
6793       Value *True = vectorizeTree(E->getOperand(1));
6794       Value *False = vectorizeTree(E->getOperand(2));
6795 
6796       if (E->VectorizedValue) {
6797         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6798         return E->VectorizedValue;
6799       }
6800 
6801       Value *V = Builder.CreateSelect(Cond, True, False);
6802       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6803       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6804       V = ShuffleBuilder.finalize(V);
6805 
6806       E->VectorizedValue = V;
6807       ++NumVectorInstructions;
6808       return V;
6809     }
6810     case Instruction::FNeg: {
6811       setInsertPointAfterBundle(E);
6812 
6813       Value *Op = vectorizeTree(E->getOperand(0));
6814 
6815       if (E->VectorizedValue) {
6816         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6817         return E->VectorizedValue;
6818       }
6819 
6820       Value *V = Builder.CreateUnOp(
6821           static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
6822       propagateIRFlags(V, E->Scalars, VL0);
6823       if (auto *I = dyn_cast<Instruction>(V))
6824         V = propagateMetadata(I, E->Scalars);
6825 
6826       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6827       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6828       V = ShuffleBuilder.finalize(V);
6829 
6830       E->VectorizedValue = V;
6831       ++NumVectorInstructions;
6832 
6833       return V;
6834     }
6835     case Instruction::Add:
6836     case Instruction::FAdd:
6837     case Instruction::Sub:
6838     case Instruction::FSub:
6839     case Instruction::Mul:
6840     case Instruction::FMul:
6841     case Instruction::UDiv:
6842     case Instruction::SDiv:
6843     case Instruction::FDiv:
6844     case Instruction::URem:
6845     case Instruction::SRem:
6846     case Instruction::FRem:
6847     case Instruction::Shl:
6848     case Instruction::LShr:
6849     case Instruction::AShr:
6850     case Instruction::And:
6851     case Instruction::Or:
6852     case Instruction::Xor: {
6853       setInsertPointAfterBundle(E);
6854 
6855       Value *LHS = vectorizeTree(E->getOperand(0));
6856       Value *RHS = vectorizeTree(E->getOperand(1));
6857 
6858       if (E->VectorizedValue) {
6859         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6860         return E->VectorizedValue;
6861       }
6862 
6863       Value *V = Builder.CreateBinOp(
6864           static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
6865           RHS);
6866       propagateIRFlags(V, E->Scalars, VL0);
6867       if (auto *I = dyn_cast<Instruction>(V))
6868         V = propagateMetadata(I, E->Scalars);
6869 
6870       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6871       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6872       V = ShuffleBuilder.finalize(V);
6873 
6874       E->VectorizedValue = V;
6875       ++NumVectorInstructions;
6876 
6877       return V;
6878     }
6879     case Instruction::Load: {
6880       // Loads are inserted at the head of the tree because we don't want to
6881       // sink them all the way down past store instructions.
6882       setInsertPointAfterBundle(E);
6883 
6884       LoadInst *LI = cast<LoadInst>(VL0);
6885       Instruction *NewLI;
6886       unsigned AS = LI->getPointerAddressSpace();
6887       Value *PO = LI->getPointerOperand();
6888       if (E->State == TreeEntry::Vectorize) {
6889 
6890         Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS));
6891 
6892         // The pointer operand uses an in-tree scalar so we add the new BitCast
6893         // to ExternalUses list to make sure that an extract will be generated
6894         // in the future.
6895         if (TreeEntry *Entry = getTreeEntry(PO)) {
6896           // Find which lane we need to extract.
6897           unsigned FoundLane = Entry->findLaneForValue(PO);
6898           ExternalUses.emplace_back(PO, cast<User>(VecPtr), FoundLane);
6899         }
6900 
6901         NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
6902       } else {
6903         assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state");
6904         Value *VecPtr = vectorizeTree(E->getOperand(0));
6905         // Use the minimum alignment of the gathered loads.
6906         Align CommonAlignment = LI->getAlign();
6907         for (Value *V : E->Scalars)
6908           CommonAlignment =
6909               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
6910         NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment);
6911       }
6912       Value *V = propagateMetadata(NewLI, E->Scalars);
6913 
6914       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6915       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6916       V = ShuffleBuilder.finalize(V);
6917       E->VectorizedValue = V;
6918       ++NumVectorInstructions;
6919       return V;
6920     }
6921     case Instruction::Store: {
6922       auto *SI = cast<StoreInst>(VL0);
6923       unsigned AS = SI->getPointerAddressSpace();
6924 
6925       setInsertPointAfterBundle(E);
6926 
6927       Value *VecValue = vectorizeTree(E->getOperand(0));
6928       ShuffleBuilder.addMask(E->ReorderIndices);
6929       VecValue = ShuffleBuilder.finalize(VecValue);
6930 
6931       Value *ScalarPtr = SI->getPointerOperand();
6932       Value *VecPtr = Builder.CreateBitCast(
6933           ScalarPtr, VecValue->getType()->getPointerTo(AS));
6934       StoreInst *ST = Builder.CreateAlignedStore(VecValue, VecPtr,
6935                                                  SI->getAlign());
6936 
6937       // The pointer operand uses an in-tree scalar, so add the new BitCast to
6938       // ExternalUses to make sure that an extract will be generated in the
6939       // future.
6940       if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) {
6941         // Find which lane we need to extract.
6942         unsigned FoundLane = Entry->findLaneForValue(ScalarPtr);
6943         ExternalUses.push_back(
6944             ExternalUser(ScalarPtr, cast<User>(VecPtr), FoundLane));
6945       }
6946 
6947       Value *V = propagateMetadata(ST, E->Scalars);
6948 
6949       E->VectorizedValue = V;
6950       ++NumVectorInstructions;
6951       return V;
6952     }
6953     case Instruction::GetElementPtr: {
6954       auto *GEP0 = cast<GetElementPtrInst>(VL0);
6955       setInsertPointAfterBundle(E);
6956 
6957       Value *Op0 = vectorizeTree(E->getOperand(0));
6958 
6959       SmallVector<Value *> OpVecs;
6960       for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) {
6961         Value *OpVec = vectorizeTree(E->getOperand(J));
6962         OpVecs.push_back(OpVec);
6963       }
6964 
6965       Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs);
6966       if (Instruction *I = dyn_cast<Instruction>(V))
6967         V = propagateMetadata(I, E->Scalars);
6968 
6969       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6970       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6971       V = ShuffleBuilder.finalize(V);
6972 
6973       E->VectorizedValue = V;
6974       ++NumVectorInstructions;
6975 
6976       return V;
6977     }
6978     case Instruction::Call: {
6979       CallInst *CI = cast<CallInst>(VL0);
6980       setInsertPointAfterBundle(E);
6981 
6982       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
6983       if (Function *FI = CI->getCalledFunction())
6984         IID = FI->getIntrinsicID();
6985 
6986       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
6987 
6988       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
6989       bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
6990                           VecCallCosts.first <= VecCallCosts.second;
6991 
6992       Value *ScalarArg = nullptr;
6993       std::vector<Value *> OpVecs;
6994       SmallVector<Type *, 2> TysForDecl =
6995           {FixedVectorType::get(CI->getType(), E->Scalars.size())};
6996       for (int j = 0, e = CI->arg_size(); j < e; ++j) {
6997         ValueList OpVL;
6998         // Some intrinsics have scalar arguments. This argument should not be
6999         // vectorized.
7000         if (UseIntrinsic && hasVectorInstrinsicScalarOpd(IID, j)) {
7001           CallInst *CEI = cast<CallInst>(VL0);
7002           ScalarArg = CEI->getArgOperand(j);
7003           OpVecs.push_back(CEI->getArgOperand(j));
7004           if (hasVectorInstrinsicOverloadedScalarOpd(IID, j))
7005             TysForDecl.push_back(ScalarArg->getType());
7006           continue;
7007         }
7008 
7009         Value *OpVec = vectorizeTree(E->getOperand(j));
7010         LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
7011         OpVecs.push_back(OpVec);
7012       }
7013 
7014       Function *CF;
7015       if (!UseIntrinsic) {
7016         VFShape Shape =
7017             VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
7018                                   VecTy->getNumElements())),
7019                          false /*HasGlobalPred*/);
7020         CF = VFDatabase(*CI).getVectorizedFunction(Shape);
7021       } else {
7022         CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl);
7023       }
7024 
7025       SmallVector<OperandBundleDef, 1> OpBundles;
7026       CI->getOperandBundlesAsDefs(OpBundles);
7027       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
7028 
7029       // The scalar argument uses an in-tree scalar so we add the new vectorized
7030       // call to ExternalUses list to make sure that an extract will be
7031       // generated in the future.
7032       if (ScalarArg) {
7033         if (TreeEntry *Entry = getTreeEntry(ScalarArg)) {
7034           // Find which lane we need to extract.
7035           unsigned FoundLane = Entry->findLaneForValue(ScalarArg);
7036           ExternalUses.push_back(
7037               ExternalUser(ScalarArg, cast<User>(V), FoundLane));
7038         }
7039       }
7040 
7041       propagateIRFlags(V, E->Scalars, VL0);
7042       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7043       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7044       V = ShuffleBuilder.finalize(V);
7045 
7046       E->VectorizedValue = V;
7047       ++NumVectorInstructions;
7048       return V;
7049     }
7050     case Instruction::ShuffleVector: {
7051       assert(E->isAltShuffle() &&
7052              ((Instruction::isBinaryOp(E->getOpcode()) &&
7053                Instruction::isBinaryOp(E->getAltOpcode())) ||
7054               (Instruction::isCast(E->getOpcode()) &&
7055                Instruction::isCast(E->getAltOpcode())) ||
7056               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
7057              "Invalid Shuffle Vector Operand");
7058 
7059       Value *LHS = nullptr, *RHS = nullptr;
7060       if (Instruction::isBinaryOp(E->getOpcode()) || isa<CmpInst>(VL0)) {
7061         setInsertPointAfterBundle(E);
7062         LHS = vectorizeTree(E->getOperand(0));
7063         RHS = vectorizeTree(E->getOperand(1));
7064       } else {
7065         setInsertPointAfterBundle(E);
7066         LHS = vectorizeTree(E->getOperand(0));
7067       }
7068 
7069       if (E->VectorizedValue) {
7070         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7071         return E->VectorizedValue;
7072       }
7073 
7074       Value *V0, *V1;
7075       if (Instruction::isBinaryOp(E->getOpcode())) {
7076         V0 = Builder.CreateBinOp(
7077             static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
7078         V1 = Builder.CreateBinOp(
7079             static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
7080       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
7081         V0 = Builder.CreateCmp(CI0->getPredicate(), LHS, RHS);
7082         auto *AltCI = cast<CmpInst>(E->getAltOp());
7083         CmpInst::Predicate AltPred = AltCI->getPredicate();
7084         unsigned AltIdx =
7085             std::distance(E->Scalars.begin(), find(E->Scalars, AltCI));
7086         if (AltCI->getOperand(0) != E->getOperand(0)[AltIdx])
7087           AltPred = CmpInst::getSwappedPredicate(AltPred);
7088         V1 = Builder.CreateCmp(AltPred, LHS, RHS);
7089       } else {
7090         V0 = Builder.CreateCast(
7091             static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
7092         V1 = Builder.CreateCast(
7093             static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
7094       }
7095       // Add V0 and V1 to later analysis to try to find and remove matching
7096       // instruction, if any.
7097       for (Value *V : {V0, V1}) {
7098         if (auto *I = dyn_cast<Instruction>(V)) {
7099           GatherShuffleSeq.insert(I);
7100           CSEBlocks.insert(I->getParent());
7101         }
7102       }
7103 
7104       // Create shuffle to take alternate operations from the vector.
7105       // Also, gather up main and alt scalar ops to propagate IR flags to
7106       // each vector operation.
7107       ValueList OpScalars, AltScalars;
7108       SmallVector<int> Mask;
7109       buildSuffleEntryMask(
7110           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
7111           [E](Instruction *I) {
7112             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
7113             if (auto *CI0 = dyn_cast<CmpInst>(E->getMainOp())) {
7114               auto *AltCI0 = cast<CmpInst>(E->getAltOp());
7115               auto *CI = cast<CmpInst>(I);
7116               CmpInst::Predicate P0 = CI0->getPredicate();
7117               CmpInst::Predicate AltP0 = AltCI0->getPredicate();
7118               assert(P0 != AltP0 &&
7119                      "Expected different main/alternate predicates.");
7120               CmpInst::Predicate AltP0Swapped =
7121                   CmpInst::getSwappedPredicate(AltP0);
7122               CmpInst::Predicate CurrentPred = CI->getPredicate();
7123               if (P0 == AltP0Swapped)
7124                 return (P0 == CurrentPred &&
7125                         !areCompatibleCmpOps(
7126                             CI0->getOperand(0), CI0->getOperand(1),
7127                             CI->getOperand(0), CI->getOperand(1))) ||
7128                        (AltP0 == CurrentPred &&
7129                         !areCompatibleCmpOps(
7130                             CI0->getOperand(0), CI0->getOperand(1),
7131                             CI->getOperand(1), CI->getOperand(0)));
7132               return AltP0 == CurrentPred || AltP0Swapped == CurrentPred;
7133             }
7134             return I->getOpcode() == E->getAltOpcode();
7135           },
7136           Mask, &OpScalars, &AltScalars);
7137 
7138       propagateIRFlags(V0, OpScalars);
7139       propagateIRFlags(V1, AltScalars);
7140 
7141       Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
7142       if (auto *I = dyn_cast<Instruction>(V)) {
7143         V = propagateMetadata(I, E->Scalars);
7144         GatherShuffleSeq.insert(I);
7145         CSEBlocks.insert(I->getParent());
7146       }
7147       V = ShuffleBuilder.finalize(V);
7148 
7149       E->VectorizedValue = V;
7150       ++NumVectorInstructions;
7151 
7152       return V;
7153     }
7154     default:
7155     llvm_unreachable("unknown inst");
7156   }
7157   return nullptr;
7158 }
7159 
7160 Value *BoUpSLP::vectorizeTree() {
7161   ExtraValueToDebugLocsMap ExternallyUsedValues;
7162   return vectorizeTree(ExternallyUsedValues);
7163 }
7164 
7165 Value *
7166 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
7167   // All blocks must be scheduled before any instructions are inserted.
7168   for (auto &BSIter : BlocksSchedules) {
7169     scheduleBlock(BSIter.second.get());
7170   }
7171 
7172   Builder.SetInsertPoint(&F->getEntryBlock().front());
7173   auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
7174 
7175   // If the vectorized tree can be rewritten in a smaller type, we truncate the
7176   // vectorized root. InstCombine will then rewrite the entire expression. We
7177   // sign extend the extracted values below.
7178   auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
7179   if (MinBWs.count(ScalarRoot)) {
7180     if (auto *I = dyn_cast<Instruction>(VectorRoot)) {
7181       // If current instr is a phi and not the last phi, insert it after the
7182       // last phi node.
7183       if (isa<PHINode>(I))
7184         Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt());
7185       else
7186         Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
7187     }
7188     auto BundleWidth = VectorizableTree[0]->Scalars.size();
7189     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
7190     auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
7191     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
7192     VectorizableTree[0]->VectorizedValue = Trunc;
7193   }
7194 
7195   LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
7196                     << " values .\n");
7197 
7198   // Extract all of the elements with the external uses.
7199   for (const auto &ExternalUse : ExternalUses) {
7200     Value *Scalar = ExternalUse.Scalar;
7201     llvm::User *User = ExternalUse.User;
7202 
7203     // Skip users that we already RAUW. This happens when one instruction
7204     // has multiple uses of the same value.
7205     if (User && !is_contained(Scalar->users(), User))
7206       continue;
7207     TreeEntry *E = getTreeEntry(Scalar);
7208     assert(E && "Invalid scalar");
7209     assert(E->State != TreeEntry::NeedToGather &&
7210            "Extracting from a gather list");
7211 
7212     Value *Vec = E->VectorizedValue;
7213     assert(Vec && "Can't find vectorizable value");
7214 
7215     Value *Lane = Builder.getInt32(ExternalUse.Lane);
7216     auto ExtractAndExtendIfNeeded = [&](Value *Vec) {
7217       if (Scalar->getType() != Vec->getType()) {
7218         Value *Ex;
7219         // "Reuse" the existing extract to improve final codegen.
7220         if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) {
7221           Ex = Builder.CreateExtractElement(ES->getOperand(0),
7222                                             ES->getOperand(1));
7223         } else {
7224           Ex = Builder.CreateExtractElement(Vec, Lane);
7225         }
7226         // If necessary, sign-extend or zero-extend ScalarRoot
7227         // to the larger type.
7228         if (!MinBWs.count(ScalarRoot))
7229           return Ex;
7230         if (MinBWs[ScalarRoot].second)
7231           return Builder.CreateSExt(Ex, Scalar->getType());
7232         return Builder.CreateZExt(Ex, Scalar->getType());
7233       }
7234       assert(isa<FixedVectorType>(Scalar->getType()) &&
7235              isa<InsertElementInst>(Scalar) &&
7236              "In-tree scalar of vector type is not insertelement?");
7237       return Vec;
7238     };
7239     // If User == nullptr, the Scalar is used as extra arg. Generate
7240     // ExtractElement instruction and update the record for this scalar in
7241     // ExternallyUsedValues.
7242     if (!User) {
7243       assert(ExternallyUsedValues.count(Scalar) &&
7244              "Scalar with nullptr as an external user must be registered in "
7245              "ExternallyUsedValues map");
7246       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7247         Builder.SetInsertPoint(VecI->getParent(),
7248                                std::next(VecI->getIterator()));
7249       } else {
7250         Builder.SetInsertPoint(&F->getEntryBlock().front());
7251       }
7252       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7253       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
7254       auto &NewInstLocs = ExternallyUsedValues[NewInst];
7255       auto It = ExternallyUsedValues.find(Scalar);
7256       assert(It != ExternallyUsedValues.end() &&
7257              "Externally used scalar is not found in ExternallyUsedValues");
7258       NewInstLocs.append(It->second);
7259       ExternallyUsedValues.erase(Scalar);
7260       // Required to update internally referenced instructions.
7261       Scalar->replaceAllUsesWith(NewInst);
7262       continue;
7263     }
7264 
7265     // Generate extracts for out-of-tree users.
7266     // Find the insertion point for the extractelement lane.
7267     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7268       if (PHINode *PH = dyn_cast<PHINode>(User)) {
7269         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
7270           if (PH->getIncomingValue(i) == Scalar) {
7271             Instruction *IncomingTerminator =
7272                 PH->getIncomingBlock(i)->getTerminator();
7273             if (isa<CatchSwitchInst>(IncomingTerminator)) {
7274               Builder.SetInsertPoint(VecI->getParent(),
7275                                      std::next(VecI->getIterator()));
7276             } else {
7277               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
7278             }
7279             Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7280             CSEBlocks.insert(PH->getIncomingBlock(i));
7281             PH->setOperand(i, NewInst);
7282           }
7283         }
7284       } else {
7285         Builder.SetInsertPoint(cast<Instruction>(User));
7286         Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7287         CSEBlocks.insert(cast<Instruction>(User)->getParent());
7288         User->replaceUsesOfWith(Scalar, NewInst);
7289       }
7290     } else {
7291       Builder.SetInsertPoint(&F->getEntryBlock().front());
7292       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7293       CSEBlocks.insert(&F->getEntryBlock());
7294       User->replaceUsesOfWith(Scalar, NewInst);
7295     }
7296 
7297     LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
7298   }
7299 
7300   // For each vectorized value:
7301   for (auto &TEPtr : VectorizableTree) {
7302     TreeEntry *Entry = TEPtr.get();
7303 
7304     // No need to handle users of gathered values.
7305     if (Entry->State == TreeEntry::NeedToGather)
7306       continue;
7307 
7308     assert(Entry->VectorizedValue && "Can't find vectorizable value");
7309 
7310     // For each lane:
7311     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
7312       Value *Scalar = Entry->Scalars[Lane];
7313 
7314 #ifndef NDEBUG
7315       Type *Ty = Scalar->getType();
7316       if (!Ty->isVoidTy()) {
7317         for (User *U : Scalar->users()) {
7318           LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
7319 
7320           // It is legal to delete users in the ignorelist.
7321           assert((getTreeEntry(U) || is_contained(UserIgnoreList, U) ||
7322                   (isa_and_nonnull<Instruction>(U) &&
7323                    isDeleted(cast<Instruction>(U)))) &&
7324                  "Deleting out-of-tree value");
7325         }
7326       }
7327 #endif
7328       LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
7329       eraseInstruction(cast<Instruction>(Scalar));
7330     }
7331   }
7332 
7333   Builder.ClearInsertionPoint();
7334   InstrElementSize.clear();
7335 
7336   return VectorizableTree[0]->VectorizedValue;
7337 }
7338 
7339 void BoUpSLP::optimizeGatherSequence() {
7340   LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleSeq.size()
7341                     << " gather sequences instructions.\n");
7342   // LICM InsertElementInst sequences.
7343   for (Instruction *I : GatherShuffleSeq) {
7344     if (isDeleted(I))
7345       continue;
7346 
7347     // Check if this block is inside a loop.
7348     Loop *L = LI->getLoopFor(I->getParent());
7349     if (!L)
7350       continue;
7351 
7352     // Check if it has a preheader.
7353     BasicBlock *PreHeader = L->getLoopPreheader();
7354     if (!PreHeader)
7355       continue;
7356 
7357     // If the vector or the element that we insert into it are
7358     // instructions that are defined in this basic block then we can't
7359     // hoist this instruction.
7360     if (any_of(I->operands(), [L](Value *V) {
7361           auto *OpI = dyn_cast<Instruction>(V);
7362           return OpI && L->contains(OpI);
7363         }))
7364       continue;
7365 
7366     // We can hoist this instruction. Move it to the pre-header.
7367     I->moveBefore(PreHeader->getTerminator());
7368   }
7369 
7370   // Make a list of all reachable blocks in our CSE queue.
7371   SmallVector<const DomTreeNode *, 8> CSEWorkList;
7372   CSEWorkList.reserve(CSEBlocks.size());
7373   for (BasicBlock *BB : CSEBlocks)
7374     if (DomTreeNode *N = DT->getNode(BB)) {
7375       assert(DT->isReachableFromEntry(N));
7376       CSEWorkList.push_back(N);
7377     }
7378 
7379   // Sort blocks by domination. This ensures we visit a block after all blocks
7380   // dominating it are visited.
7381   llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) {
7382     assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) &&
7383            "Different nodes should have different DFS numbers");
7384     return A->getDFSNumIn() < B->getDFSNumIn();
7385   });
7386 
7387   // Less defined shuffles can be replaced by the more defined copies.
7388   // Between two shuffles one is less defined if it has the same vector operands
7389   // and its mask indeces are the same as in the first one or undefs. E.g.
7390   // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0,
7391   // poison, <0, 0, 0, 0>.
7392   auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2,
7393                                            SmallVectorImpl<int> &NewMask) {
7394     if (I1->getType() != I2->getType())
7395       return false;
7396     auto *SI1 = dyn_cast<ShuffleVectorInst>(I1);
7397     auto *SI2 = dyn_cast<ShuffleVectorInst>(I2);
7398     if (!SI1 || !SI2)
7399       return I1->isIdenticalTo(I2);
7400     if (SI1->isIdenticalTo(SI2))
7401       return true;
7402     for (int I = 0, E = SI1->getNumOperands(); I < E; ++I)
7403       if (SI1->getOperand(I) != SI2->getOperand(I))
7404         return false;
7405     // Check if the second instruction is more defined than the first one.
7406     NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end());
7407     ArrayRef<int> SM1 = SI1->getShuffleMask();
7408     // Count trailing undefs in the mask to check the final number of used
7409     // registers.
7410     unsigned LastUndefsCnt = 0;
7411     for (int I = 0, E = NewMask.size(); I < E; ++I) {
7412       if (SM1[I] == UndefMaskElem)
7413         ++LastUndefsCnt;
7414       else
7415         LastUndefsCnt = 0;
7416       if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem &&
7417           NewMask[I] != SM1[I])
7418         return false;
7419       if (NewMask[I] == UndefMaskElem)
7420         NewMask[I] = SM1[I];
7421     }
7422     // Check if the last undefs actually change the final number of used vector
7423     // registers.
7424     return SM1.size() - LastUndefsCnt > 1 &&
7425            TTI->getNumberOfParts(SI1->getType()) ==
7426                TTI->getNumberOfParts(
7427                    FixedVectorType::get(SI1->getType()->getElementType(),
7428                                         SM1.size() - LastUndefsCnt));
7429   };
7430   // Perform O(N^2) search over the gather/shuffle sequences and merge identical
7431   // instructions. TODO: We can further optimize this scan if we split the
7432   // instructions into different buckets based on the insert lane.
7433   SmallVector<Instruction *, 16> Visited;
7434   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
7435     assert(*I &&
7436            (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
7437            "Worklist not sorted properly!");
7438     BasicBlock *BB = (*I)->getBlock();
7439     // For all instructions in blocks containing gather sequences:
7440     for (Instruction &In : llvm::make_early_inc_range(*BB)) {
7441       if (isDeleted(&In))
7442         continue;
7443       if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) &&
7444           !isa<ShuffleVectorInst>(&In) && !GatherShuffleSeq.contains(&In))
7445         continue;
7446 
7447       // Check if we can replace this instruction with any of the
7448       // visited instructions.
7449       bool Replaced = false;
7450       for (Instruction *&V : Visited) {
7451         SmallVector<int> NewMask;
7452         if (IsIdenticalOrLessDefined(&In, V, NewMask) &&
7453             DT->dominates(V->getParent(), In.getParent())) {
7454           In.replaceAllUsesWith(V);
7455           eraseInstruction(&In);
7456           if (auto *SI = dyn_cast<ShuffleVectorInst>(V))
7457             if (!NewMask.empty())
7458               SI->setShuffleMask(NewMask);
7459           Replaced = true;
7460           break;
7461         }
7462         if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) &&
7463             GatherShuffleSeq.contains(V) &&
7464             IsIdenticalOrLessDefined(V, &In, NewMask) &&
7465             DT->dominates(In.getParent(), V->getParent())) {
7466           In.moveAfter(V);
7467           V->replaceAllUsesWith(&In);
7468           eraseInstruction(V);
7469           if (auto *SI = dyn_cast<ShuffleVectorInst>(&In))
7470             if (!NewMask.empty())
7471               SI->setShuffleMask(NewMask);
7472           V = &In;
7473           Replaced = true;
7474           break;
7475         }
7476       }
7477       if (!Replaced) {
7478         assert(!is_contained(Visited, &In));
7479         Visited.push_back(&In);
7480       }
7481     }
7482   }
7483   CSEBlocks.clear();
7484   GatherShuffleSeq.clear();
7485 }
7486 
7487 BoUpSLP::ScheduleData *
7488 BoUpSLP::BlockScheduling::buildBundle(ArrayRef<Value *> VL) {
7489   ScheduleData *Bundle = nullptr;
7490   ScheduleData *PrevInBundle = nullptr;
7491   for (Value *V : VL) {
7492     ScheduleData *BundleMember = getScheduleData(V);
7493     assert(BundleMember &&
7494            "no ScheduleData for bundle member "
7495            "(maybe not in same basic block)");
7496     assert(BundleMember->isSchedulingEntity() &&
7497            "bundle member already part of other bundle");
7498     if (PrevInBundle) {
7499       PrevInBundle->NextInBundle = BundleMember;
7500     } else {
7501       Bundle = BundleMember;
7502     }
7503 
7504     // Group the instructions to a bundle.
7505     BundleMember->FirstInBundle = Bundle;
7506     PrevInBundle = BundleMember;
7507   }
7508   assert(Bundle && "Failed to find schedule bundle");
7509   return Bundle;
7510 }
7511 
7512 // Groups the instructions to a bundle (which is then a single scheduling entity)
7513 // and schedules instructions until the bundle gets ready.
7514 Optional<BoUpSLP::ScheduleData *>
7515 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
7516                                             const InstructionsState &S) {
7517   // No need to schedule PHIs, insertelement, extractelement and extractvalue
7518   // instructions.
7519   if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue))
7520     return nullptr;
7521 
7522   // Initialize the instruction bundle.
7523   Instruction *OldScheduleEnd = ScheduleEnd;
7524   LLVM_DEBUG(dbgs() << "SLP:  bundle: " << *S.OpValue << "\n");
7525 
7526   auto TryScheduleBundleImpl = [this, OldScheduleEnd, SLP](bool ReSchedule,
7527                                                          ScheduleData *Bundle) {
7528     // The scheduling region got new instructions at the lower end (or it is a
7529     // new region for the first bundle). This makes it necessary to
7530     // recalculate all dependencies.
7531     // It is seldom that this needs to be done a second time after adding the
7532     // initial bundle to the region.
7533     if (ScheduleEnd != OldScheduleEnd) {
7534       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode())
7535         doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); });
7536       ReSchedule = true;
7537     }
7538     if (Bundle) {
7539       LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle
7540                         << " in block " << BB->getName() << "\n");
7541       calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP);
7542     }
7543 
7544     if (ReSchedule) {
7545       resetSchedule();
7546       initialFillReadyList(ReadyInsts);
7547     }
7548 
7549     // Now try to schedule the new bundle or (if no bundle) just calculate
7550     // dependencies. As soon as the bundle is "ready" it means that there are no
7551     // cyclic dependencies and we can schedule it. Note that's important that we
7552     // don't "schedule" the bundle yet (see cancelScheduling).
7553     while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) &&
7554            !ReadyInsts.empty()) {
7555       ScheduleData *Picked = ReadyInsts.pop_back_val();
7556       assert(Picked->isSchedulingEntity() && Picked->isReady() &&
7557              "must be ready to schedule");
7558       schedule(Picked, ReadyInsts);
7559     }
7560   };
7561 
7562   // Make sure that the scheduling region contains all
7563   // instructions of the bundle.
7564   for (Value *V : VL) {
7565     if (!extendSchedulingRegion(V, S)) {
7566       // If the scheduling region got new instructions at the lower end (or it
7567       // is a new region for the first bundle). This makes it necessary to
7568       // recalculate all dependencies.
7569       // Otherwise the compiler may crash trying to incorrectly calculate
7570       // dependencies and emit instruction in the wrong order at the actual
7571       // scheduling.
7572       TryScheduleBundleImpl(/*ReSchedule=*/false, nullptr);
7573       return None;
7574     }
7575   }
7576 
7577   bool ReSchedule = false;
7578   for (Value *V : VL) {
7579     ScheduleData *BundleMember = getScheduleData(V);
7580     assert(BundleMember &&
7581            "no ScheduleData for bundle member (maybe not in same basic block)");
7582 
7583     // Make sure we don't leave the pieces of the bundle in the ready list when
7584     // whole bundle might not be ready.
7585     ReadyInsts.remove(BundleMember);
7586 
7587     if (!BundleMember->IsScheduled)
7588       continue;
7589     // A bundle member was scheduled as single instruction before and now
7590     // needs to be scheduled as part of the bundle. We just get rid of the
7591     // existing schedule.
7592     LLVM_DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
7593                       << " was already scheduled\n");
7594     ReSchedule = true;
7595   }
7596 
7597   auto *Bundle = buildBundle(VL);
7598   TryScheduleBundleImpl(ReSchedule, Bundle);
7599   if (!Bundle->isReady()) {
7600     cancelScheduling(VL, S.OpValue);
7601     return None;
7602   }
7603   return Bundle;
7604 }
7605 
7606 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
7607                                                 Value *OpValue) {
7608   if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue))
7609     return;
7610 
7611   ScheduleData *Bundle = getScheduleData(OpValue);
7612   LLVM_DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
7613   assert(!Bundle->IsScheduled &&
7614          "Can't cancel bundle which is already scheduled");
7615   assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
7616          "tried to unbundle something which is not a bundle");
7617 
7618   // Remove the bundle from the ready list.
7619   if (Bundle->isReady())
7620     ReadyInsts.remove(Bundle);
7621 
7622   // Un-bundle: make single instructions out of the bundle.
7623   ScheduleData *BundleMember = Bundle;
7624   while (BundleMember) {
7625     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
7626     BundleMember->FirstInBundle = BundleMember;
7627     ScheduleData *Next = BundleMember->NextInBundle;
7628     BundleMember->NextInBundle = nullptr;
7629     if (BundleMember->unscheduledDepsInBundle() == 0) {
7630       ReadyInsts.insert(BundleMember);
7631     }
7632     BundleMember = Next;
7633   }
7634 }
7635 
7636 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
7637   // Allocate a new ScheduleData for the instruction.
7638   if (ChunkPos >= ChunkSize) {
7639     ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
7640     ChunkPos = 0;
7641   }
7642   return &(ScheduleDataChunks.back()[ChunkPos++]);
7643 }
7644 
7645 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
7646                                                       const InstructionsState &S) {
7647   if (getScheduleData(V, isOneOf(S, V)))
7648     return true;
7649   Instruction *I = dyn_cast<Instruction>(V);
7650   assert(I && "bundle member must be an instruction");
7651   assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) &&
7652          "phi nodes/insertelements/extractelements/extractvalues don't need to "
7653          "be scheduled");
7654   auto &&CheckSheduleForI = [this, &S](Instruction *I) -> bool {
7655     ScheduleData *ISD = getScheduleData(I);
7656     if (!ISD)
7657       return false;
7658     assert(isInSchedulingRegion(ISD) &&
7659            "ScheduleData not in scheduling region");
7660     ScheduleData *SD = allocateScheduleDataChunks();
7661     SD->Inst = I;
7662     SD->init(SchedulingRegionID, S.OpValue);
7663     ExtraScheduleDataMap[I][S.OpValue] = SD;
7664     return true;
7665   };
7666   if (CheckSheduleForI(I))
7667     return true;
7668   if (!ScheduleStart) {
7669     // It's the first instruction in the new region.
7670     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
7671     ScheduleStart = I;
7672     ScheduleEnd = I->getNextNode();
7673     if (isOneOf(S, I) != I)
7674       CheckSheduleForI(I);
7675     assert(ScheduleEnd && "tried to vectorize a terminator?");
7676     LLVM_DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
7677     return true;
7678   }
7679   // Search up and down at the same time, because we don't know if the new
7680   // instruction is above or below the existing scheduling region.
7681   BasicBlock::reverse_iterator UpIter =
7682       ++ScheduleStart->getIterator().getReverse();
7683   BasicBlock::reverse_iterator UpperEnd = BB->rend();
7684   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
7685   BasicBlock::iterator LowerEnd = BB->end();
7686   while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I &&
7687          &*DownIter != I) {
7688     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
7689       LLVM_DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
7690       return false;
7691     }
7692 
7693     ++UpIter;
7694     ++DownIter;
7695   }
7696   if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) {
7697     assert(I->getParent() == ScheduleStart->getParent() &&
7698            "Instruction is in wrong basic block.");
7699     initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
7700     ScheduleStart = I;
7701     if (isOneOf(S, I) != I)
7702       CheckSheduleForI(I);
7703     LLVM_DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I
7704                       << "\n");
7705     return true;
7706   }
7707   assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) &&
7708          "Expected to reach top of the basic block or instruction down the "
7709          "lower end.");
7710   assert(I->getParent() == ScheduleEnd->getParent() &&
7711          "Instruction is in wrong basic block.");
7712   initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
7713                    nullptr);
7714   ScheduleEnd = I->getNextNode();
7715   if (isOneOf(S, I) != I)
7716     CheckSheduleForI(I);
7717   assert(ScheduleEnd && "tried to vectorize a terminator?");
7718   LLVM_DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
7719   return true;
7720 }
7721 
7722 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
7723                                                 Instruction *ToI,
7724                                                 ScheduleData *PrevLoadStore,
7725                                                 ScheduleData *NextLoadStore) {
7726   ScheduleData *CurrentLoadStore = PrevLoadStore;
7727   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
7728     ScheduleData *SD = ScheduleDataMap[I];
7729     if (!SD) {
7730       SD = allocateScheduleDataChunks();
7731       ScheduleDataMap[I] = SD;
7732       SD->Inst = I;
7733     }
7734     assert(!isInSchedulingRegion(SD) &&
7735            "new ScheduleData already in scheduling region");
7736     SD->init(SchedulingRegionID, I);
7737 
7738     if (I->mayReadOrWriteMemory() &&
7739         (!isa<IntrinsicInst>(I) ||
7740          (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect &&
7741           cast<IntrinsicInst>(I)->getIntrinsicID() !=
7742               Intrinsic::pseudoprobe))) {
7743       // Update the linked list of memory accessing instructions.
7744       if (CurrentLoadStore) {
7745         CurrentLoadStore->NextLoadStore = SD;
7746       } else {
7747         FirstLoadStoreInRegion = SD;
7748       }
7749       CurrentLoadStore = SD;
7750     }
7751   }
7752   if (NextLoadStore) {
7753     if (CurrentLoadStore)
7754       CurrentLoadStore->NextLoadStore = NextLoadStore;
7755   } else {
7756     LastLoadStoreInRegion = CurrentLoadStore;
7757   }
7758 }
7759 
7760 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
7761                                                      bool InsertInReadyList,
7762                                                      BoUpSLP *SLP) {
7763   assert(SD->isSchedulingEntity());
7764 
7765   SmallVector<ScheduleData *, 10> WorkList;
7766   WorkList.push_back(SD);
7767 
7768   while (!WorkList.empty()) {
7769     ScheduleData *SD = WorkList.pop_back_val();
7770     for (ScheduleData *BundleMember = SD; BundleMember;
7771          BundleMember = BundleMember->NextInBundle) {
7772       assert(isInSchedulingRegion(BundleMember));
7773       if (BundleMember->hasValidDependencies())
7774         continue;
7775 
7776       LLVM_DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember
7777                  << "\n");
7778       BundleMember->Dependencies = 0;
7779       BundleMember->resetUnscheduledDeps();
7780 
7781       // Handle def-use chain dependencies.
7782       if (BundleMember->OpValue != BundleMember->Inst) {
7783         ScheduleData *UseSD = getScheduleData(BundleMember->Inst);
7784         if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
7785           BundleMember->Dependencies++;
7786           ScheduleData *DestBundle = UseSD->FirstInBundle;
7787           if (!DestBundle->IsScheduled)
7788             BundleMember->incrementUnscheduledDeps(1);
7789           if (!DestBundle->hasValidDependencies())
7790             WorkList.push_back(DestBundle);
7791         }
7792       } else {
7793         for (User *U : BundleMember->Inst->users()) {
7794           assert(isa<Instruction>(U) &&
7795                  "user of instruction must be instruction");
7796           ScheduleData *UseSD = getScheduleData(U);
7797           if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
7798             BundleMember->Dependencies++;
7799             ScheduleData *DestBundle = UseSD->FirstInBundle;
7800             if (!DestBundle->IsScheduled)
7801               BundleMember->incrementUnscheduledDeps(1);
7802             if (!DestBundle->hasValidDependencies())
7803               WorkList.push_back(DestBundle);
7804           }
7805         }
7806       }
7807 
7808       // Handle the memory dependencies (if any).
7809       ScheduleData *DepDest = BundleMember->NextLoadStore;
7810       if (!DepDest)
7811         continue;
7812       Instruction *SrcInst = BundleMember->Inst;
7813       assert(SrcInst->mayReadOrWriteMemory() &&
7814              "NextLoadStore list for non memory effecting bundle?");
7815       MemoryLocation SrcLoc = getLocation(SrcInst);
7816       bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
7817       unsigned numAliased = 0;
7818       unsigned DistToSrc = 1;
7819 
7820       for ( ; DepDest; DepDest = DepDest->NextLoadStore) {
7821         assert(isInSchedulingRegion(DepDest));
7822 
7823         // We have two limits to reduce the complexity:
7824         // 1) AliasedCheckLimit: It's a small limit to reduce calls to
7825         //    SLP->isAliased (which is the expensive part in this loop).
7826         // 2) MaxMemDepDistance: It's for very large blocks and it aborts
7827         //    the whole loop (even if the loop is fast, it's quadratic).
7828         //    It's important for the loop break condition (see below) to
7829         //    check this limit even between two read-only instructions.
7830         if (DistToSrc >= MaxMemDepDistance ||
7831             ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
7832              (numAliased >= AliasedCheckLimit ||
7833               SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
7834 
7835           // We increment the counter only if the locations are aliased
7836           // (instead of counting all alias checks). This gives a better
7837           // balance between reduced runtime and accurate dependencies.
7838           numAliased++;
7839 
7840           DepDest->MemoryDependencies.push_back(BundleMember);
7841           BundleMember->Dependencies++;
7842           ScheduleData *DestBundle = DepDest->FirstInBundle;
7843           if (!DestBundle->IsScheduled) {
7844             BundleMember->incrementUnscheduledDeps(1);
7845           }
7846           if (!DestBundle->hasValidDependencies()) {
7847             WorkList.push_back(DestBundle);
7848           }
7849         }
7850 
7851         // Example, explaining the loop break condition: Let's assume our
7852         // starting instruction is i0 and MaxMemDepDistance = 3.
7853         //
7854         //                      +--------v--v--v
7855         //             i0,i1,i2,i3,i4,i5,i6,i7,i8
7856         //             +--------^--^--^
7857         //
7858         // MaxMemDepDistance let us stop alias-checking at i3 and we add
7859         // dependencies from i0 to i3,i4,.. (even if they are not aliased).
7860         // Previously we already added dependencies from i3 to i6,i7,i8
7861         // (because of MaxMemDepDistance). As we added a dependency from
7862         // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
7863         // and we can abort this loop at i6.
7864         if (DistToSrc >= 2 * MaxMemDepDistance)
7865           break;
7866         DistToSrc++;
7867       }
7868     }
7869     if (InsertInReadyList && SD->isReady()) {
7870       ReadyInsts.insert(SD);
7871       LLVM_DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst
7872                         << "\n");
7873     }
7874   }
7875 }
7876 
7877 void BoUpSLP::BlockScheduling::resetSchedule() {
7878   assert(ScheduleStart &&
7879          "tried to reset schedule on block which has not been scheduled");
7880   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
7881     doForAllOpcodes(I, [&](ScheduleData *SD) {
7882       assert(isInSchedulingRegion(SD) &&
7883              "ScheduleData not in scheduling region");
7884       SD->IsScheduled = false;
7885       SD->resetUnscheduledDeps();
7886     });
7887   }
7888   ReadyInsts.clear();
7889 }
7890 
7891 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
7892   if (!BS->ScheduleStart)
7893     return;
7894 
7895   LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
7896 
7897   BS->resetSchedule();
7898 
7899   // For the real scheduling we use a more sophisticated ready-list: it is
7900   // sorted by the original instruction location. This lets the final schedule
7901   // be as  close as possible to the original instruction order.
7902   struct ScheduleDataCompare {
7903     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
7904       return SD2->SchedulingPriority < SD1->SchedulingPriority;
7905     }
7906   };
7907   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
7908 
7909   // Ensure that all dependency data is updated and fill the ready-list with
7910   // initial instructions.
7911   int Idx = 0;
7912   int NumToSchedule = 0;
7913   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
7914        I = I->getNextNode()) {
7915     BS->doForAllOpcodes(I, [this, &Idx, &NumToSchedule, BS](ScheduleData *SD) {
7916       assert((isVectorLikeInstWithConstOps(SD->Inst) ||
7917               SD->isPartOfBundle() == (getTreeEntry(SD->Inst) != nullptr)) &&
7918              "scheduler and vectorizer bundle mismatch");
7919       SD->FirstInBundle->SchedulingPriority = Idx++;
7920       if (SD->isSchedulingEntity()) {
7921         BS->calculateDependencies(SD, false, this);
7922         NumToSchedule++;
7923       }
7924     });
7925   }
7926   BS->initialFillReadyList(ReadyInsts);
7927 
7928   Instruction *LastScheduledInst = BS->ScheduleEnd;
7929 
7930   // Do the "real" scheduling.
7931   while (!ReadyInsts.empty()) {
7932     ScheduleData *picked = *ReadyInsts.begin();
7933     ReadyInsts.erase(ReadyInsts.begin());
7934 
7935     // Move the scheduled instruction(s) to their dedicated places, if not
7936     // there yet.
7937     for (ScheduleData *BundleMember = picked; BundleMember;
7938          BundleMember = BundleMember->NextInBundle) {
7939       Instruction *pickedInst = BundleMember->Inst;
7940       if (pickedInst->getNextNode() != LastScheduledInst)
7941         pickedInst->moveBefore(LastScheduledInst);
7942       LastScheduledInst = pickedInst;
7943     }
7944 
7945     BS->schedule(picked, ReadyInsts);
7946     NumToSchedule--;
7947   }
7948   assert(NumToSchedule == 0 && "could not schedule all instructions");
7949 
7950   // Check that we didn't break any of our invariants.
7951 #ifdef EXPENSIVE_CHECKS
7952   BS->verify();
7953 #endif
7954 
7955 #ifndef NDEBUG
7956   // Check that all schedulable entities got scheduled
7957   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; I = I->getNextNode()) {
7958     BS->doForAllOpcodes(I, [&](ScheduleData *SD) {
7959       if (SD->isSchedulingEntity() && SD->hasValidDependencies()) {
7960         assert(SD->IsScheduled && "must be scheduled at this point");
7961       }
7962     });
7963   }
7964 #endif
7965 
7966   // Avoid duplicate scheduling of the block.
7967   BS->ScheduleStart = nullptr;
7968 }
7969 
7970 unsigned BoUpSLP::getVectorElementSize(Value *V) {
7971   // If V is a store, just return the width of the stored value (or value
7972   // truncated just before storing) without traversing the expression tree.
7973   // This is the common case.
7974   if (auto *Store = dyn_cast<StoreInst>(V)) {
7975     if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand()))
7976       return DL->getTypeSizeInBits(Trunc->getSrcTy());
7977     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
7978   }
7979 
7980   if (auto *IEI = dyn_cast<InsertElementInst>(V))
7981     return getVectorElementSize(IEI->getOperand(1));
7982 
7983   auto E = InstrElementSize.find(V);
7984   if (E != InstrElementSize.end())
7985     return E->second;
7986 
7987   // If V is not a store, we can traverse the expression tree to find loads
7988   // that feed it. The type of the loaded value may indicate a more suitable
7989   // width than V's type. We want to base the vector element size on the width
7990   // of memory operations where possible.
7991   SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist;
7992   SmallPtrSet<Instruction *, 16> Visited;
7993   if (auto *I = dyn_cast<Instruction>(V)) {
7994     Worklist.emplace_back(I, I->getParent());
7995     Visited.insert(I);
7996   }
7997 
7998   // Traverse the expression tree in bottom-up order looking for loads. If we
7999   // encounter an instruction we don't yet handle, we give up.
8000   auto Width = 0u;
8001   while (!Worklist.empty()) {
8002     Instruction *I;
8003     BasicBlock *Parent;
8004     std::tie(I, Parent) = Worklist.pop_back_val();
8005 
8006     // We should only be looking at scalar instructions here. If the current
8007     // instruction has a vector type, skip.
8008     auto *Ty = I->getType();
8009     if (isa<VectorType>(Ty))
8010       continue;
8011 
8012     // If the current instruction is a load, update MaxWidth to reflect the
8013     // width of the loaded value.
8014     if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) ||
8015         isa<ExtractValueInst>(I))
8016       Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty));
8017 
8018     // Otherwise, we need to visit the operands of the instruction. We only
8019     // handle the interesting cases from buildTree here. If an operand is an
8020     // instruction we haven't yet visited and from the same basic block as the
8021     // user or the use is a PHI node, we add it to the worklist.
8022     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
8023              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) ||
8024              isa<UnaryOperator>(I)) {
8025       for (Use &U : I->operands())
8026         if (auto *J = dyn_cast<Instruction>(U.get()))
8027           if (Visited.insert(J).second &&
8028               (isa<PHINode>(I) || J->getParent() == Parent))
8029             Worklist.emplace_back(J, J->getParent());
8030     } else {
8031       break;
8032     }
8033   }
8034 
8035   // If we didn't encounter a memory access in the expression tree, or if we
8036   // gave up for some reason, just return the width of V. Otherwise, return the
8037   // maximum width we found.
8038   if (!Width) {
8039     if (auto *CI = dyn_cast<CmpInst>(V))
8040       V = CI->getOperand(0);
8041     Width = DL->getTypeSizeInBits(V->getType());
8042   }
8043 
8044   for (Instruction *I : Visited)
8045     InstrElementSize[I] = Width;
8046 
8047   return Width;
8048 }
8049 
8050 // Determine if a value V in a vectorizable expression Expr can be demoted to a
8051 // smaller type with a truncation. We collect the values that will be demoted
8052 // in ToDemote and additional roots that require investigating in Roots.
8053 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
8054                                   SmallVectorImpl<Value *> &ToDemote,
8055                                   SmallVectorImpl<Value *> &Roots) {
8056   // We can always demote constants.
8057   if (isa<Constant>(V)) {
8058     ToDemote.push_back(V);
8059     return true;
8060   }
8061 
8062   // If the value is not an instruction in the expression with only one use, it
8063   // cannot be demoted.
8064   auto *I = dyn_cast<Instruction>(V);
8065   if (!I || !I->hasOneUse() || !Expr.count(I))
8066     return false;
8067 
8068   switch (I->getOpcode()) {
8069 
8070   // We can always demote truncations and extensions. Since truncations can
8071   // seed additional demotion, we save the truncated value.
8072   case Instruction::Trunc:
8073     Roots.push_back(I->getOperand(0));
8074     break;
8075   case Instruction::ZExt:
8076   case Instruction::SExt:
8077     if (isa<ExtractElementInst>(I->getOperand(0)) ||
8078         isa<InsertElementInst>(I->getOperand(0)))
8079       return false;
8080     break;
8081 
8082   // We can demote certain binary operations if we can demote both of their
8083   // operands.
8084   case Instruction::Add:
8085   case Instruction::Sub:
8086   case Instruction::Mul:
8087   case Instruction::And:
8088   case Instruction::Or:
8089   case Instruction::Xor:
8090     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
8091         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
8092       return false;
8093     break;
8094 
8095   // We can demote selects if we can demote their true and false values.
8096   case Instruction::Select: {
8097     SelectInst *SI = cast<SelectInst>(I);
8098     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
8099         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
8100       return false;
8101     break;
8102   }
8103 
8104   // We can demote phis if we can demote all their incoming operands. Note that
8105   // we don't need to worry about cycles since we ensure single use above.
8106   case Instruction::PHI: {
8107     PHINode *PN = cast<PHINode>(I);
8108     for (Value *IncValue : PN->incoming_values())
8109       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
8110         return false;
8111     break;
8112   }
8113 
8114   // Otherwise, conservatively give up.
8115   default:
8116     return false;
8117   }
8118 
8119   // Record the value that we can demote.
8120   ToDemote.push_back(V);
8121   return true;
8122 }
8123 
8124 void BoUpSLP::computeMinimumValueSizes() {
8125   // If there are no external uses, the expression tree must be rooted by a
8126   // store. We can't demote in-memory values, so there is nothing to do here.
8127   if (ExternalUses.empty())
8128     return;
8129 
8130   // We only attempt to truncate integer expressions.
8131   auto &TreeRoot = VectorizableTree[0]->Scalars;
8132   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
8133   if (!TreeRootIT)
8134     return;
8135 
8136   // If the expression is not rooted by a store, these roots should have
8137   // external uses. We will rely on InstCombine to rewrite the expression in
8138   // the narrower type. However, InstCombine only rewrites single-use values.
8139   // This means that if a tree entry other than a root is used externally, it
8140   // must have multiple uses and InstCombine will not rewrite it. The code
8141   // below ensures that only the roots are used externally.
8142   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
8143   for (auto &EU : ExternalUses)
8144     if (!Expr.erase(EU.Scalar))
8145       return;
8146   if (!Expr.empty())
8147     return;
8148 
8149   // Collect the scalar values of the vectorizable expression. We will use this
8150   // context to determine which values can be demoted. If we see a truncation,
8151   // we mark it as seeding another demotion.
8152   for (auto &EntryPtr : VectorizableTree)
8153     Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
8154 
8155   // Ensure the roots of the vectorizable tree don't form a cycle. They must
8156   // have a single external user that is not in the vectorizable tree.
8157   for (auto *Root : TreeRoot)
8158     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
8159       return;
8160 
8161   // Conservatively determine if we can actually truncate the roots of the
8162   // expression. Collect the values that can be demoted in ToDemote and
8163   // additional roots that require investigating in Roots.
8164   SmallVector<Value *, 32> ToDemote;
8165   SmallVector<Value *, 4> Roots;
8166   for (auto *Root : TreeRoot)
8167     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
8168       return;
8169 
8170   // The maximum bit width required to represent all the values that can be
8171   // demoted without loss of precision. It would be safe to truncate the roots
8172   // of the expression to this width.
8173   auto MaxBitWidth = 8u;
8174 
8175   // We first check if all the bits of the roots are demanded. If they're not,
8176   // we can truncate the roots to this narrower type.
8177   for (auto *Root : TreeRoot) {
8178     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
8179     MaxBitWidth = std::max<unsigned>(
8180         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
8181   }
8182 
8183   // True if the roots can be zero-extended back to their original type, rather
8184   // than sign-extended. We know that if the leading bits are not demanded, we
8185   // can safely zero-extend. So we initialize IsKnownPositive to True.
8186   bool IsKnownPositive = true;
8187 
8188   // If all the bits of the roots are demanded, we can try a little harder to
8189   // compute a narrower type. This can happen, for example, if the roots are
8190   // getelementptr indices. InstCombine promotes these indices to the pointer
8191   // width. Thus, all their bits are technically demanded even though the
8192   // address computation might be vectorized in a smaller type.
8193   //
8194   // We start by looking at each entry that can be demoted. We compute the
8195   // maximum bit width required to store the scalar by using ValueTracking to
8196   // compute the number of high-order bits we can truncate.
8197   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
8198       llvm::all_of(TreeRoot, [](Value *R) {
8199         assert(R->hasOneUse() && "Root should have only one use!");
8200         return isa<GetElementPtrInst>(R->user_back());
8201       })) {
8202     MaxBitWidth = 8u;
8203 
8204     // Determine if the sign bit of all the roots is known to be zero. If not,
8205     // IsKnownPositive is set to False.
8206     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
8207       KnownBits Known = computeKnownBits(R, *DL);
8208       return Known.isNonNegative();
8209     });
8210 
8211     // Determine the maximum number of bits required to store the scalar
8212     // values.
8213     for (auto *Scalar : ToDemote) {
8214       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
8215       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
8216       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
8217     }
8218 
8219     // If we can't prove that the sign bit is zero, we must add one to the
8220     // maximum bit width to account for the unknown sign bit. This preserves
8221     // the existing sign bit so we can safely sign-extend the root back to the
8222     // original type. Otherwise, if we know the sign bit is zero, we will
8223     // zero-extend the root instead.
8224     //
8225     // FIXME: This is somewhat suboptimal, as there will be cases where adding
8226     //        one to the maximum bit width will yield a larger-than-necessary
8227     //        type. In general, we need to add an extra bit only if we can't
8228     //        prove that the upper bit of the original type is equal to the
8229     //        upper bit of the proposed smaller type. If these two bits are the
8230     //        same (either zero or one) we know that sign-extending from the
8231     //        smaller type will result in the same value. Here, since we can't
8232     //        yet prove this, we are just making the proposed smaller type
8233     //        larger to ensure correctness.
8234     if (!IsKnownPositive)
8235       ++MaxBitWidth;
8236   }
8237 
8238   // Round MaxBitWidth up to the next power-of-two.
8239   if (!isPowerOf2_64(MaxBitWidth))
8240     MaxBitWidth = NextPowerOf2(MaxBitWidth);
8241 
8242   // If the maximum bit width we compute is less than the with of the roots'
8243   // type, we can proceed with the narrowing. Otherwise, do nothing.
8244   if (MaxBitWidth >= TreeRootIT->getBitWidth())
8245     return;
8246 
8247   // If we can truncate the root, we must collect additional values that might
8248   // be demoted as a result. That is, those seeded by truncations we will
8249   // modify.
8250   while (!Roots.empty())
8251     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
8252 
8253   // Finally, map the values we can demote to the maximum bit with we computed.
8254   for (auto *Scalar : ToDemote)
8255     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
8256 }
8257 
8258 namespace {
8259 
8260 /// The SLPVectorizer Pass.
8261 struct SLPVectorizer : public FunctionPass {
8262   SLPVectorizerPass Impl;
8263 
8264   /// Pass identification, replacement for typeid
8265   static char ID;
8266 
8267   explicit SLPVectorizer() : FunctionPass(ID) {
8268     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
8269   }
8270 
8271   bool doInitialization(Module &M) override { return false; }
8272 
8273   bool runOnFunction(Function &F) override {
8274     if (skipFunction(F))
8275       return false;
8276 
8277     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
8278     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
8279     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
8280     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
8281     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
8282     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
8283     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
8284     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
8285     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
8286     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
8287 
8288     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8289   }
8290 
8291   void getAnalysisUsage(AnalysisUsage &AU) const override {
8292     FunctionPass::getAnalysisUsage(AU);
8293     AU.addRequired<AssumptionCacheTracker>();
8294     AU.addRequired<ScalarEvolutionWrapperPass>();
8295     AU.addRequired<AAResultsWrapperPass>();
8296     AU.addRequired<TargetTransformInfoWrapperPass>();
8297     AU.addRequired<LoopInfoWrapperPass>();
8298     AU.addRequired<DominatorTreeWrapperPass>();
8299     AU.addRequired<DemandedBitsWrapperPass>();
8300     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
8301     AU.addRequired<InjectTLIMappingsLegacy>();
8302     AU.addPreserved<LoopInfoWrapperPass>();
8303     AU.addPreserved<DominatorTreeWrapperPass>();
8304     AU.addPreserved<AAResultsWrapperPass>();
8305     AU.addPreserved<GlobalsAAWrapperPass>();
8306     AU.setPreservesCFG();
8307   }
8308 };
8309 
8310 } // end anonymous namespace
8311 
8312 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
8313   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
8314   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
8315   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
8316   auto *AA = &AM.getResult<AAManager>(F);
8317   auto *LI = &AM.getResult<LoopAnalysis>(F);
8318   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
8319   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
8320   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
8321   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
8322 
8323   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8324   if (!Changed)
8325     return PreservedAnalyses::all();
8326 
8327   PreservedAnalyses PA;
8328   PA.preserveSet<CFGAnalyses>();
8329   return PA;
8330 }
8331 
8332 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
8333                                 TargetTransformInfo *TTI_,
8334                                 TargetLibraryInfo *TLI_, AAResults *AA_,
8335                                 LoopInfo *LI_, DominatorTree *DT_,
8336                                 AssumptionCache *AC_, DemandedBits *DB_,
8337                                 OptimizationRemarkEmitter *ORE_) {
8338   if (!RunSLPVectorization)
8339     return false;
8340   SE = SE_;
8341   TTI = TTI_;
8342   TLI = TLI_;
8343   AA = AA_;
8344   LI = LI_;
8345   DT = DT_;
8346   AC = AC_;
8347   DB = DB_;
8348   DL = &F.getParent()->getDataLayout();
8349 
8350   Stores.clear();
8351   GEPs.clear();
8352   bool Changed = false;
8353 
8354   // If the target claims to have no vector registers don't attempt
8355   // vectorization.
8356   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true))) {
8357     LLVM_DEBUG(
8358         dbgs() << "SLP: Didn't find any vector registers for target, abort.\n");
8359     return false;
8360   }
8361 
8362   // Don't vectorize when the attribute NoImplicitFloat is used.
8363   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
8364     return false;
8365 
8366   LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
8367 
8368   // Use the bottom up slp vectorizer to construct chains that start with
8369   // store instructions.
8370   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
8371 
8372   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
8373   // delete instructions.
8374 
8375   // Update DFS numbers now so that we can use them for ordering.
8376   DT->updateDFSNumbers();
8377 
8378   // Scan the blocks in the function in post order.
8379   for (auto BB : post_order(&F.getEntryBlock())) {
8380     collectSeedInstructions(BB);
8381 
8382     // Vectorize trees that end at stores.
8383     if (!Stores.empty()) {
8384       LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
8385                         << " underlying objects.\n");
8386       Changed |= vectorizeStoreChains(R);
8387     }
8388 
8389     // Vectorize trees that end at reductions.
8390     Changed |= vectorizeChainsInBlock(BB, R);
8391 
8392     // Vectorize the index computations of getelementptr instructions. This
8393     // is primarily intended to catch gather-like idioms ending at
8394     // non-consecutive loads.
8395     if (!GEPs.empty()) {
8396       LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
8397                         << " underlying objects.\n");
8398       Changed |= vectorizeGEPIndices(BB, R);
8399     }
8400   }
8401 
8402   if (Changed) {
8403     R.optimizeGatherSequence();
8404     LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
8405   }
8406   return Changed;
8407 }
8408 
8409 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
8410                                             unsigned Idx) {
8411   LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()
8412                     << "\n");
8413   const unsigned Sz = R.getVectorElementSize(Chain[0]);
8414   const unsigned MinVF = R.getMinVecRegSize() / Sz;
8415   unsigned VF = Chain.size();
8416 
8417   if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
8418     return false;
8419 
8420   LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx
8421                     << "\n");
8422 
8423   R.buildTree(Chain);
8424   if (R.isTreeTinyAndNotFullyVectorizable())
8425     return false;
8426   if (R.isLoadCombineCandidate())
8427     return false;
8428   R.reorderTopToBottom();
8429   R.reorderBottomToTop();
8430   R.buildExternalUses();
8431 
8432   R.computeMinimumValueSizes();
8433 
8434   InstructionCost Cost = R.getTreeCost();
8435 
8436   LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n");
8437   if (Cost < -SLPCostThreshold) {
8438     LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n");
8439 
8440     using namespace ore;
8441 
8442     R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
8443                                         cast<StoreInst>(Chain[0]))
8444                      << "Stores SLP vectorized with cost " << NV("Cost", Cost)
8445                      << " and with tree size "
8446                      << NV("TreeSize", R.getTreeSize()));
8447 
8448     R.vectorizeTree();
8449     return true;
8450   }
8451 
8452   return false;
8453 }
8454 
8455 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
8456                                         BoUpSLP &R) {
8457   // We may run into multiple chains that merge into a single chain. We mark the
8458   // stores that we vectorized so that we don't visit the same store twice.
8459   BoUpSLP::ValueSet VectorizedStores;
8460   bool Changed = false;
8461 
8462   int E = Stores.size();
8463   SmallBitVector Tails(E, false);
8464   int MaxIter = MaxStoreLookup.getValue();
8465   SmallVector<std::pair<int, int>, 16> ConsecutiveChain(
8466       E, std::make_pair(E, INT_MAX));
8467   SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false));
8468   int IterCnt;
8469   auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
8470                                   &CheckedPairs,
8471                                   &ConsecutiveChain](int K, int Idx) {
8472     if (IterCnt >= MaxIter)
8473       return true;
8474     if (CheckedPairs[Idx].test(K))
8475       return ConsecutiveChain[K].second == 1 &&
8476              ConsecutiveChain[K].first == Idx;
8477     ++IterCnt;
8478     CheckedPairs[Idx].set(K);
8479     CheckedPairs[K].set(Idx);
8480     Optional<int> Diff = getPointersDiff(
8481         Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(),
8482         Stores[Idx]->getValueOperand()->getType(),
8483         Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true);
8484     if (!Diff || *Diff == 0)
8485       return false;
8486     int Val = *Diff;
8487     if (Val < 0) {
8488       if (ConsecutiveChain[Idx].second > -Val) {
8489         Tails.set(K);
8490         ConsecutiveChain[Idx] = std::make_pair(K, -Val);
8491       }
8492       return false;
8493     }
8494     if (ConsecutiveChain[K].second <= Val)
8495       return false;
8496 
8497     Tails.set(Idx);
8498     ConsecutiveChain[K] = std::make_pair(Idx, Val);
8499     return Val == 1;
8500   };
8501   // Do a quadratic search on all of the given stores in reverse order and find
8502   // all of the pairs of stores that follow each other.
8503   for (int Idx = E - 1; Idx >= 0; --Idx) {
8504     // If a store has multiple consecutive store candidates, search according
8505     // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
8506     // This is because usually pairing with immediate succeeding or preceding
8507     // candidate create the best chance to find slp vectorization opportunity.
8508     const int MaxLookDepth = std::max(E - Idx, Idx + 1);
8509     IterCnt = 0;
8510     for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
8511       if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
8512           (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
8513         break;
8514   }
8515 
8516   // Tracks if we tried to vectorize stores starting from the given tail
8517   // already.
8518   SmallBitVector TriedTails(E, false);
8519   // For stores that start but don't end a link in the chain:
8520   for (int Cnt = E; Cnt > 0; --Cnt) {
8521     int I = Cnt - 1;
8522     if (ConsecutiveChain[I].first == E || Tails.test(I))
8523       continue;
8524     // We found a store instr that starts a chain. Now follow the chain and try
8525     // to vectorize it.
8526     BoUpSLP::ValueList Operands;
8527     // Collect the chain into a list.
8528     while (I != E && !VectorizedStores.count(Stores[I])) {
8529       Operands.push_back(Stores[I]);
8530       Tails.set(I);
8531       if (ConsecutiveChain[I].second != 1) {
8532         // Mark the new end in the chain and go back, if required. It might be
8533         // required if the original stores come in reversed order, for example.
8534         if (ConsecutiveChain[I].first != E &&
8535             Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) &&
8536             !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) {
8537           TriedTails.set(I);
8538           Tails.reset(ConsecutiveChain[I].first);
8539           if (Cnt < ConsecutiveChain[I].first + 2)
8540             Cnt = ConsecutiveChain[I].first + 2;
8541         }
8542         break;
8543       }
8544       // Move to the next value in the chain.
8545       I = ConsecutiveChain[I].first;
8546     }
8547     assert(!Operands.empty() && "Expected non-empty list of stores.");
8548 
8549     unsigned MaxVecRegSize = R.getMaxVecRegSize();
8550     unsigned EltSize = R.getVectorElementSize(Operands[0]);
8551     unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize);
8552 
8553     unsigned MinVF = R.getMinVF(EltSize);
8554     unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store),
8555                               MaxElts);
8556 
8557     // FIXME: Is division-by-2 the correct step? Should we assert that the
8558     // register size is a power-of-2?
8559     unsigned StartIdx = 0;
8560     for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) {
8561       for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
8562         ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size);
8563         if (!VectorizedStores.count(Slice.front()) &&
8564             !VectorizedStores.count(Slice.back()) &&
8565             vectorizeStoreChain(Slice, R, Cnt)) {
8566           // Mark the vectorized stores so that we don't vectorize them again.
8567           VectorizedStores.insert(Slice.begin(), Slice.end());
8568           Changed = true;
8569           // If we vectorized initial block, no need to try to vectorize it
8570           // again.
8571           if (Cnt == StartIdx)
8572             StartIdx += Size;
8573           Cnt += Size;
8574           continue;
8575         }
8576         ++Cnt;
8577       }
8578       // Check if the whole array was vectorized already - exit.
8579       if (StartIdx >= Operands.size())
8580         break;
8581     }
8582   }
8583 
8584   return Changed;
8585 }
8586 
8587 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
8588   // Initialize the collections. We will make a single pass over the block.
8589   Stores.clear();
8590   GEPs.clear();
8591 
8592   // Visit the store and getelementptr instructions in BB and organize them in
8593   // Stores and GEPs according to the underlying objects of their pointer
8594   // operands.
8595   for (Instruction &I : *BB) {
8596     // Ignore store instructions that are volatile or have a pointer operand
8597     // that doesn't point to a scalar type.
8598     if (auto *SI = dyn_cast<StoreInst>(&I)) {
8599       if (!SI->isSimple())
8600         continue;
8601       if (!isValidElementType(SI->getValueOperand()->getType()))
8602         continue;
8603       Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI);
8604     }
8605 
8606     // Ignore getelementptr instructions that have more than one index, a
8607     // constant index, or a pointer operand that doesn't point to a scalar
8608     // type.
8609     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
8610       auto Idx = GEP->idx_begin()->get();
8611       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
8612         continue;
8613       if (!isValidElementType(Idx->getType()))
8614         continue;
8615       if (GEP->getType()->isVectorTy())
8616         continue;
8617       GEPs[GEP->getPointerOperand()].push_back(GEP);
8618     }
8619   }
8620 }
8621 
8622 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
8623   if (!A || !B)
8624     return false;
8625   if (isa<InsertElementInst>(A) || isa<InsertElementInst>(B))
8626     return false;
8627   Value *VL[] = {A, B};
8628   return tryToVectorizeList(VL, R);
8629 }
8630 
8631 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
8632                                            bool LimitForRegisterSize) {
8633   if (VL.size() < 2)
8634     return false;
8635 
8636   LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
8637                     << VL.size() << ".\n");
8638 
8639   // Check that all of the parts are instructions of the same type,
8640   // we permit an alternate opcode via InstructionsState.
8641   InstructionsState S = getSameOpcode(VL);
8642   if (!S.getOpcode())
8643     return false;
8644 
8645   Instruction *I0 = cast<Instruction>(S.OpValue);
8646   // Make sure invalid types (including vector type) are rejected before
8647   // determining vectorization factor for scalar instructions.
8648   for (Value *V : VL) {
8649     Type *Ty = V->getType();
8650     if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) {
8651       // NOTE: the following will give user internal llvm type name, which may
8652       // not be useful.
8653       R.getORE()->emit([&]() {
8654         std::string type_str;
8655         llvm::raw_string_ostream rso(type_str);
8656         Ty->print(rso);
8657         return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
8658                << "Cannot SLP vectorize list: type "
8659                << rso.str() + " is unsupported by vectorizer";
8660       });
8661       return false;
8662     }
8663   }
8664 
8665   unsigned Sz = R.getVectorElementSize(I0);
8666   unsigned MinVF = R.getMinVF(Sz);
8667   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
8668   MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF);
8669   if (MaxVF < 2) {
8670     R.getORE()->emit([&]() {
8671       return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
8672              << "Cannot SLP vectorize list: vectorization factor "
8673              << "less than 2 is not supported";
8674     });
8675     return false;
8676   }
8677 
8678   bool Changed = false;
8679   bool CandidateFound = false;
8680   InstructionCost MinCost = SLPCostThreshold.getValue();
8681   Type *ScalarTy = VL[0]->getType();
8682   if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
8683     ScalarTy = IE->getOperand(1)->getType();
8684 
8685   unsigned NextInst = 0, MaxInst = VL.size();
8686   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
8687     // No actual vectorization should happen, if number of parts is the same as
8688     // provided vectorization factor (i.e. the scalar type is used for vector
8689     // code during codegen).
8690     auto *VecTy = FixedVectorType::get(ScalarTy, VF);
8691     if (TTI->getNumberOfParts(VecTy) == VF)
8692       continue;
8693     for (unsigned I = NextInst; I < MaxInst; ++I) {
8694       unsigned OpsWidth = 0;
8695 
8696       if (I + VF > MaxInst)
8697         OpsWidth = MaxInst - I;
8698       else
8699         OpsWidth = VF;
8700 
8701       if (!isPowerOf2_32(OpsWidth))
8702         continue;
8703 
8704       if ((LimitForRegisterSize && OpsWidth < MaxVF) ||
8705           (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2))
8706         break;
8707 
8708       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
8709       // Check that a previous iteration of this loop did not delete the Value.
8710       if (llvm::any_of(Ops, [&R](Value *V) {
8711             auto *I = dyn_cast<Instruction>(V);
8712             return I && R.isDeleted(I);
8713           }))
8714         continue;
8715 
8716       LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
8717                         << "\n");
8718 
8719       R.buildTree(Ops);
8720       if (R.isTreeTinyAndNotFullyVectorizable())
8721         continue;
8722       R.reorderTopToBottom();
8723       R.reorderBottomToTop(!isa<InsertElementInst>(Ops.front()));
8724       R.buildExternalUses();
8725 
8726       R.computeMinimumValueSizes();
8727       InstructionCost Cost = R.getTreeCost();
8728       CandidateFound = true;
8729       MinCost = std::min(MinCost, Cost);
8730 
8731       if (Cost < -SLPCostThreshold) {
8732         LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
8733         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
8734                                                     cast<Instruction>(Ops[0]))
8735                                  << "SLP vectorized with cost " << ore::NV("Cost", Cost)
8736                                  << " and with tree size "
8737                                  << ore::NV("TreeSize", R.getTreeSize()));
8738 
8739         R.vectorizeTree();
8740         // Move to the next bundle.
8741         I += VF - 1;
8742         NextInst = I + 1;
8743         Changed = true;
8744       }
8745     }
8746   }
8747 
8748   if (!Changed && CandidateFound) {
8749     R.getORE()->emit([&]() {
8750       return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
8751              << "List vectorization was possible but not beneficial with cost "
8752              << ore::NV("Cost", MinCost) << " >= "
8753              << ore::NV("Treshold", -SLPCostThreshold);
8754     });
8755   } else if (!Changed) {
8756     R.getORE()->emit([&]() {
8757       return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
8758              << "Cannot SLP vectorize list: vectorization was impossible"
8759              << " with available vectorization factors";
8760     });
8761   }
8762   return Changed;
8763 }
8764 
8765 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
8766   if (!I)
8767     return false;
8768 
8769   if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I))
8770     return false;
8771 
8772   Value *P = I->getParent();
8773 
8774   // Vectorize in current basic block only.
8775   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
8776   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
8777   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
8778     return false;
8779 
8780   // Try to vectorize V.
8781   if (tryToVectorizePair(Op0, Op1, R))
8782     return true;
8783 
8784   auto *A = dyn_cast<BinaryOperator>(Op0);
8785   auto *B = dyn_cast<BinaryOperator>(Op1);
8786   // Try to skip B.
8787   if (B && B->hasOneUse()) {
8788     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
8789     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
8790     if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
8791       return true;
8792     if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
8793       return true;
8794   }
8795 
8796   // Try to skip A.
8797   if (A && A->hasOneUse()) {
8798     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
8799     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
8800     if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
8801       return true;
8802     if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
8803       return true;
8804   }
8805   return false;
8806 }
8807 
8808 namespace {
8809 
8810 /// Model horizontal reductions.
8811 ///
8812 /// A horizontal reduction is a tree of reduction instructions that has values
8813 /// that can be put into a vector as its leaves. For example:
8814 ///
8815 /// mul mul mul mul
8816 ///  \  /    \  /
8817 ///   +       +
8818 ///    \     /
8819 ///       +
8820 /// This tree has "mul" as its leaf values and "+" as its reduction
8821 /// instructions. A reduction can feed into a store or a binary operation
8822 /// feeding a phi.
8823 ///    ...
8824 ///    \  /
8825 ///     +
8826 ///     |
8827 ///  phi +=
8828 ///
8829 ///  Or:
8830 ///    ...
8831 ///    \  /
8832 ///     +
8833 ///     |
8834 ///   *p =
8835 ///
8836 class HorizontalReduction {
8837   using ReductionOpsType = SmallVector<Value *, 16>;
8838   using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
8839   ReductionOpsListType ReductionOps;
8840   SmallVector<Value *, 32> ReducedVals;
8841   // Use map vector to make stable output.
8842   MapVector<Instruction *, Value *> ExtraArgs;
8843   WeakTrackingVH ReductionRoot;
8844   /// The type of reduction operation.
8845   RecurKind RdxKind;
8846 
8847   const unsigned INVALID_OPERAND_INDEX = std::numeric_limits<unsigned>::max();
8848 
8849   static bool isCmpSelMinMax(Instruction *I) {
8850     return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) &&
8851            RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I));
8852   }
8853 
8854   // And/or are potentially poison-safe logical patterns like:
8855   // select x, y, false
8856   // select x, true, y
8857   static bool isBoolLogicOp(Instruction *I) {
8858     return match(I, m_LogicalAnd(m_Value(), m_Value())) ||
8859            match(I, m_LogicalOr(m_Value(), m_Value()));
8860   }
8861 
8862   /// Checks if instruction is associative and can be vectorized.
8863   static bool isVectorizable(RecurKind Kind, Instruction *I) {
8864     if (Kind == RecurKind::None)
8865       return false;
8866 
8867     // Integer ops that map to select instructions or intrinsics are fine.
8868     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) ||
8869         isBoolLogicOp(I))
8870       return true;
8871 
8872     if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) {
8873       // FP min/max are associative except for NaN and -0.0. We do not
8874       // have to rule out -0.0 here because the intrinsic semantics do not
8875       // specify a fixed result for it.
8876       return I->getFastMathFlags().noNaNs();
8877     }
8878 
8879     return I->isAssociative();
8880   }
8881 
8882   static Value *getRdxOperand(Instruction *I, unsigned Index) {
8883     // Poison-safe 'or' takes the form: select X, true, Y
8884     // To make that work with the normal operand processing, we skip the
8885     // true value operand.
8886     // TODO: Change the code and data structures to handle this without a hack.
8887     if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1)
8888       return I->getOperand(2);
8889     return I->getOperand(Index);
8890   }
8891 
8892   /// Checks if the ParentStackElem.first should be marked as a reduction
8893   /// operation with an extra argument or as extra argument itself.
8894   void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem,
8895                     Value *ExtraArg) {
8896     if (ExtraArgs.count(ParentStackElem.first)) {
8897       ExtraArgs[ParentStackElem.first] = nullptr;
8898       // We ran into something like:
8899       // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg.
8900       // The whole ParentStackElem.first should be considered as an extra value
8901       // in this case.
8902       // Do not perform analysis of remaining operands of ParentStackElem.first
8903       // instruction, this whole instruction is an extra argument.
8904       ParentStackElem.second = INVALID_OPERAND_INDEX;
8905     } else {
8906       // We ran into something like:
8907       // ParentStackElem.first += ... + ExtraArg + ...
8908       ExtraArgs[ParentStackElem.first] = ExtraArg;
8909     }
8910   }
8911 
8912   /// Creates reduction operation with the current opcode.
8913   static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS,
8914                          Value *RHS, const Twine &Name, bool UseSelect) {
8915     unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind);
8916     switch (Kind) {
8917     case RecurKind::Or:
8918       if (UseSelect &&
8919           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
8920         return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name);
8921       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
8922                                  Name);
8923     case RecurKind::And:
8924       if (UseSelect &&
8925           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
8926         return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name);
8927       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
8928                                  Name);
8929     case RecurKind::Add:
8930     case RecurKind::Mul:
8931     case RecurKind::Xor:
8932     case RecurKind::FAdd:
8933     case RecurKind::FMul:
8934       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
8935                                  Name);
8936     case RecurKind::FMax:
8937       return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS);
8938     case RecurKind::FMin:
8939       return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS);
8940     case RecurKind::SMax:
8941       if (UseSelect) {
8942         Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name);
8943         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
8944       }
8945       return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS);
8946     case RecurKind::SMin:
8947       if (UseSelect) {
8948         Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name);
8949         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
8950       }
8951       return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS);
8952     case RecurKind::UMax:
8953       if (UseSelect) {
8954         Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name);
8955         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
8956       }
8957       return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS);
8958     case RecurKind::UMin:
8959       if (UseSelect) {
8960         Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name);
8961         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
8962       }
8963       return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS);
8964     default:
8965       llvm_unreachable("Unknown reduction operation.");
8966     }
8967   }
8968 
8969   /// Creates reduction operation with the current opcode with the IR flags
8970   /// from \p ReductionOps.
8971   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
8972                          Value *RHS, const Twine &Name,
8973                          const ReductionOpsListType &ReductionOps) {
8974     bool UseSelect = ReductionOps.size() == 2 ||
8975                      // Logical or/and.
8976                      (ReductionOps.size() == 1 &&
8977                       isa<SelectInst>(ReductionOps.front().front()));
8978     assert((!UseSelect || ReductionOps.size() != 2 ||
8979             isa<SelectInst>(ReductionOps[1][0])) &&
8980            "Expected cmp + select pairs for reduction");
8981     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect);
8982     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
8983       if (auto *Sel = dyn_cast<SelectInst>(Op)) {
8984         propagateIRFlags(Sel->getCondition(), ReductionOps[0]);
8985         propagateIRFlags(Op, ReductionOps[1]);
8986         return Op;
8987       }
8988     }
8989     propagateIRFlags(Op, ReductionOps[0]);
8990     return Op;
8991   }
8992 
8993   /// Creates reduction operation with the current opcode with the IR flags
8994   /// from \p I.
8995   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
8996                          Value *RHS, const Twine &Name, Instruction *I) {
8997     auto *SelI = dyn_cast<SelectInst>(I);
8998     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, SelI != nullptr);
8999     if (SelI && RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9000       if (auto *Sel = dyn_cast<SelectInst>(Op))
9001         propagateIRFlags(Sel->getCondition(), SelI->getCondition());
9002     }
9003     propagateIRFlags(Op, I);
9004     return Op;
9005   }
9006 
9007   static RecurKind getRdxKind(Instruction *I) {
9008     assert(I && "Expected instruction for reduction matching");
9009     if (match(I, m_Add(m_Value(), m_Value())))
9010       return RecurKind::Add;
9011     if (match(I, m_Mul(m_Value(), m_Value())))
9012       return RecurKind::Mul;
9013     if (match(I, m_And(m_Value(), m_Value())) ||
9014         match(I, m_LogicalAnd(m_Value(), m_Value())))
9015       return RecurKind::And;
9016     if (match(I, m_Or(m_Value(), m_Value())) ||
9017         match(I, m_LogicalOr(m_Value(), m_Value())))
9018       return RecurKind::Or;
9019     if (match(I, m_Xor(m_Value(), m_Value())))
9020       return RecurKind::Xor;
9021     if (match(I, m_FAdd(m_Value(), m_Value())))
9022       return RecurKind::FAdd;
9023     if (match(I, m_FMul(m_Value(), m_Value())))
9024       return RecurKind::FMul;
9025 
9026     if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value())))
9027       return RecurKind::FMax;
9028     if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value())))
9029       return RecurKind::FMin;
9030 
9031     // This matches either cmp+select or intrinsics. SLP is expected to handle
9032     // either form.
9033     // TODO: If we are canonicalizing to intrinsics, we can remove several
9034     //       special-case paths that deal with selects.
9035     if (match(I, m_SMax(m_Value(), m_Value())))
9036       return RecurKind::SMax;
9037     if (match(I, m_SMin(m_Value(), m_Value())))
9038       return RecurKind::SMin;
9039     if (match(I, m_UMax(m_Value(), m_Value())))
9040       return RecurKind::UMax;
9041     if (match(I, m_UMin(m_Value(), m_Value())))
9042       return RecurKind::UMin;
9043 
9044     if (auto *Select = dyn_cast<SelectInst>(I)) {
9045       // Try harder: look for min/max pattern based on instructions producing
9046       // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
9047       // During the intermediate stages of SLP, it's very common to have
9048       // pattern like this (since optimizeGatherSequence is run only once
9049       // at the end):
9050       // %1 = extractelement <2 x i32> %a, i32 0
9051       // %2 = extractelement <2 x i32> %a, i32 1
9052       // %cond = icmp sgt i32 %1, %2
9053       // %3 = extractelement <2 x i32> %a, i32 0
9054       // %4 = extractelement <2 x i32> %a, i32 1
9055       // %select = select i1 %cond, i32 %3, i32 %4
9056       CmpInst::Predicate Pred;
9057       Instruction *L1;
9058       Instruction *L2;
9059 
9060       Value *LHS = Select->getTrueValue();
9061       Value *RHS = Select->getFalseValue();
9062       Value *Cond = Select->getCondition();
9063 
9064       // TODO: Support inverse predicates.
9065       if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
9066         if (!isa<ExtractElementInst>(RHS) ||
9067             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9068           return RecurKind::None;
9069       } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
9070         if (!isa<ExtractElementInst>(LHS) ||
9071             !L1->isIdenticalTo(cast<Instruction>(LHS)))
9072           return RecurKind::None;
9073       } else {
9074         if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
9075           return RecurKind::None;
9076         if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
9077             !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
9078             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9079           return RecurKind::None;
9080       }
9081 
9082       switch (Pred) {
9083       default:
9084         return RecurKind::None;
9085       case CmpInst::ICMP_SGT:
9086       case CmpInst::ICMP_SGE:
9087         return RecurKind::SMax;
9088       case CmpInst::ICMP_SLT:
9089       case CmpInst::ICMP_SLE:
9090         return RecurKind::SMin;
9091       case CmpInst::ICMP_UGT:
9092       case CmpInst::ICMP_UGE:
9093         return RecurKind::UMax;
9094       case CmpInst::ICMP_ULT:
9095       case CmpInst::ICMP_ULE:
9096         return RecurKind::UMin;
9097       }
9098     }
9099     return RecurKind::None;
9100   }
9101 
9102   /// Get the index of the first operand.
9103   static unsigned getFirstOperandIndex(Instruction *I) {
9104     return isCmpSelMinMax(I) ? 1 : 0;
9105   }
9106 
9107   /// Total number of operands in the reduction operation.
9108   static unsigned getNumberOfOperands(Instruction *I) {
9109     return isCmpSelMinMax(I) ? 3 : 2;
9110   }
9111 
9112   /// Checks if the instruction is in basic block \p BB.
9113   /// For a cmp+sel min/max reduction check that both ops are in \p BB.
9114   static bool hasSameParent(Instruction *I, BasicBlock *BB) {
9115     if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) {
9116       auto *Sel = cast<SelectInst>(I);
9117       auto *Cmp = dyn_cast<Instruction>(Sel->getCondition());
9118       return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB;
9119     }
9120     return I->getParent() == BB;
9121   }
9122 
9123   /// Expected number of uses for reduction operations/reduced values.
9124   static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) {
9125     if (IsCmpSelMinMax) {
9126       // SelectInst must be used twice while the condition op must have single
9127       // use only.
9128       if (auto *Sel = dyn_cast<SelectInst>(I))
9129         return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse();
9130       return I->hasNUses(2);
9131     }
9132 
9133     // Arithmetic reduction operation must be used once only.
9134     return I->hasOneUse();
9135   }
9136 
9137   /// Initializes the list of reduction operations.
9138   void initReductionOps(Instruction *I) {
9139     if (isCmpSelMinMax(I))
9140       ReductionOps.assign(2, ReductionOpsType());
9141     else
9142       ReductionOps.assign(1, ReductionOpsType());
9143   }
9144 
9145   /// Add all reduction operations for the reduction instruction \p I.
9146   void addReductionOps(Instruction *I) {
9147     if (isCmpSelMinMax(I)) {
9148       ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
9149       ReductionOps[1].emplace_back(I);
9150     } else {
9151       ReductionOps[0].emplace_back(I);
9152     }
9153   }
9154 
9155   static Value *getLHS(RecurKind Kind, Instruction *I) {
9156     if (Kind == RecurKind::None)
9157       return nullptr;
9158     return I->getOperand(getFirstOperandIndex(I));
9159   }
9160   static Value *getRHS(RecurKind Kind, Instruction *I) {
9161     if (Kind == RecurKind::None)
9162       return nullptr;
9163     return I->getOperand(getFirstOperandIndex(I) + 1);
9164   }
9165 
9166 public:
9167   HorizontalReduction() = default;
9168 
9169   /// Try to find a reduction tree.
9170   bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst) {
9171     assert((!Phi || is_contained(Phi->operands(), Inst)) &&
9172            "Phi needs to use the binary operator");
9173     assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) ||
9174             isa<IntrinsicInst>(Inst)) &&
9175            "Expected binop, select, or intrinsic for reduction matching");
9176     RdxKind = getRdxKind(Inst);
9177 
9178     // We could have a initial reductions that is not an add.
9179     //  r *= v1 + v2 + v3 + v4
9180     // In such a case start looking for a tree rooted in the first '+'.
9181     if (Phi) {
9182       if (getLHS(RdxKind, Inst) == Phi) {
9183         Phi = nullptr;
9184         Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst));
9185         if (!Inst)
9186           return false;
9187         RdxKind = getRdxKind(Inst);
9188       } else if (getRHS(RdxKind, Inst) == Phi) {
9189         Phi = nullptr;
9190         Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst));
9191         if (!Inst)
9192           return false;
9193         RdxKind = getRdxKind(Inst);
9194       }
9195     }
9196 
9197     if (!isVectorizable(RdxKind, Inst))
9198       return false;
9199 
9200     // Analyze "regular" integer/FP types for reductions - no target-specific
9201     // types or pointers.
9202     Type *Ty = Inst->getType();
9203     if (!isValidElementType(Ty) || Ty->isPointerTy())
9204       return false;
9205 
9206     // Though the ultimate reduction may have multiple uses, its condition must
9207     // have only single use.
9208     if (auto *Sel = dyn_cast<SelectInst>(Inst))
9209       if (!Sel->getCondition()->hasOneUse())
9210         return false;
9211 
9212     ReductionRoot = Inst;
9213 
9214     // The opcode for leaf values that we perform a reduction on.
9215     // For example: load(x) + load(y) + load(z) + fptoui(w)
9216     // The leaf opcode for 'w' does not match, so we don't include it as a
9217     // potential candidate for the reduction.
9218     unsigned LeafOpcode = 0;
9219 
9220     // Post-order traverse the reduction tree starting at Inst. We only handle
9221     // true trees containing binary operators or selects.
9222     SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
9223     Stack.push_back(std::make_pair(Inst, getFirstOperandIndex(Inst)));
9224     initReductionOps(Inst);
9225     while (!Stack.empty()) {
9226       Instruction *TreeN = Stack.back().first;
9227       unsigned EdgeToVisit = Stack.back().second++;
9228       const RecurKind TreeRdxKind = getRdxKind(TreeN);
9229       bool IsReducedValue = TreeRdxKind != RdxKind;
9230 
9231       // Postorder visit.
9232       if (IsReducedValue || EdgeToVisit >= getNumberOfOperands(TreeN)) {
9233         if (IsReducedValue)
9234           ReducedVals.push_back(TreeN);
9235         else {
9236           auto ExtraArgsIter = ExtraArgs.find(TreeN);
9237           if (ExtraArgsIter != ExtraArgs.end() && !ExtraArgsIter->second) {
9238             // Check if TreeN is an extra argument of its parent operation.
9239             if (Stack.size() <= 1) {
9240               // TreeN can't be an extra argument as it is a root reduction
9241               // operation.
9242               return false;
9243             }
9244             // Yes, TreeN is an extra argument, do not add it to a list of
9245             // reduction operations.
9246             // Stack[Stack.size() - 2] always points to the parent operation.
9247             markExtraArg(Stack[Stack.size() - 2], TreeN);
9248             ExtraArgs.erase(TreeN);
9249           } else
9250             addReductionOps(TreeN);
9251         }
9252         // Retract.
9253         Stack.pop_back();
9254         continue;
9255       }
9256 
9257       // Visit operands.
9258       Value *EdgeVal = getRdxOperand(TreeN, EdgeToVisit);
9259       auto *EdgeInst = dyn_cast<Instruction>(EdgeVal);
9260       if (!EdgeInst) {
9261         // Edge value is not a reduction instruction or a leaf instruction.
9262         // (It may be a constant, function argument, or something else.)
9263         markExtraArg(Stack.back(), EdgeVal);
9264         continue;
9265       }
9266       RecurKind EdgeRdxKind = getRdxKind(EdgeInst);
9267       // Continue analysis if the next operand is a reduction operation or
9268       // (possibly) a leaf value. If the leaf value opcode is not set,
9269       // the first met operation != reduction operation is considered as the
9270       // leaf opcode.
9271       // Only handle trees in the current basic block.
9272       // Each tree node needs to have minimal number of users except for the
9273       // ultimate reduction.
9274       const bool IsRdxInst = EdgeRdxKind == RdxKind;
9275       if (EdgeInst != Phi && EdgeInst != Inst &&
9276           hasSameParent(EdgeInst, Inst->getParent()) &&
9277           hasRequiredNumberOfUses(isCmpSelMinMax(Inst), EdgeInst) &&
9278           (!LeafOpcode || LeafOpcode == EdgeInst->getOpcode() || IsRdxInst)) {
9279         if (IsRdxInst) {
9280           // We need to be able to reassociate the reduction operations.
9281           if (!isVectorizable(EdgeRdxKind, EdgeInst)) {
9282             // I is an extra argument for TreeN (its parent operation).
9283             markExtraArg(Stack.back(), EdgeInst);
9284             continue;
9285           }
9286         } else if (!LeafOpcode) {
9287           LeafOpcode = EdgeInst->getOpcode();
9288         }
9289         Stack.push_back(
9290             std::make_pair(EdgeInst, getFirstOperandIndex(EdgeInst)));
9291         continue;
9292       }
9293       // I is an extra argument for TreeN (its parent operation).
9294       markExtraArg(Stack.back(), EdgeInst);
9295     }
9296     return true;
9297   }
9298 
9299   /// Attempt to vectorize the tree found by matchAssociativeReduction.
9300   Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
9301     // If there are a sufficient number of reduction values, reduce
9302     // to a nearby power-of-2. We can safely generate oversized
9303     // vectors and rely on the backend to split them to legal sizes.
9304     unsigned NumReducedVals = ReducedVals.size();
9305     if (NumReducedVals < 4)
9306       return nullptr;
9307 
9308     // Intersect the fast-math-flags from all reduction operations.
9309     FastMathFlags RdxFMF;
9310     RdxFMF.set();
9311     for (ReductionOpsType &RdxOp : ReductionOps) {
9312       for (Value *RdxVal : RdxOp) {
9313         if (auto *FPMO = dyn_cast<FPMathOperator>(RdxVal))
9314           RdxFMF &= FPMO->getFastMathFlags();
9315       }
9316     }
9317 
9318     IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
9319     Builder.setFastMathFlags(RdxFMF);
9320 
9321     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
9322     // The same extra argument may be used several times, so log each attempt
9323     // to use it.
9324     for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) {
9325       assert(Pair.first && "DebugLoc must be set.");
9326       ExternallyUsedValues[Pair.second].push_back(Pair.first);
9327     }
9328 
9329     // The compare instruction of a min/max is the insertion point for new
9330     // instructions and may be replaced with a new compare instruction.
9331     auto getCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
9332       assert(isa<SelectInst>(RdxRootInst) &&
9333              "Expected min/max reduction to have select root instruction");
9334       Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
9335       assert(isa<Instruction>(ScalarCond) &&
9336              "Expected min/max reduction to have compare condition");
9337       return cast<Instruction>(ScalarCond);
9338     };
9339 
9340     // The reduction root is used as the insertion point for new instructions,
9341     // so set it as externally used to prevent it from being deleted.
9342     ExternallyUsedValues[ReductionRoot];
9343     SmallVector<Value *, 16> IgnoreList;
9344     for (ReductionOpsType &RdxOp : ReductionOps)
9345       IgnoreList.append(RdxOp.begin(), RdxOp.end());
9346 
9347     unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
9348     if (NumReducedVals > ReduxWidth) {
9349       // In the loop below, we are building a tree based on a window of
9350       // 'ReduxWidth' values.
9351       // If the operands of those values have common traits (compare predicate,
9352       // constant operand, etc), then we want to group those together to
9353       // minimize the cost of the reduction.
9354 
9355       // TODO: This should be extended to count common operands for
9356       //       compares and binops.
9357 
9358       // Step 1: Count the number of times each compare predicate occurs.
9359       SmallDenseMap<unsigned, unsigned> PredCountMap;
9360       for (Value *RdxVal : ReducedVals) {
9361         CmpInst::Predicate Pred;
9362         if (match(RdxVal, m_Cmp(Pred, m_Value(), m_Value())))
9363           ++PredCountMap[Pred];
9364       }
9365       // Step 2: Sort the values so the most common predicates come first.
9366       stable_sort(ReducedVals, [&PredCountMap](Value *A, Value *B) {
9367         CmpInst::Predicate PredA, PredB;
9368         if (match(A, m_Cmp(PredA, m_Value(), m_Value())) &&
9369             match(B, m_Cmp(PredB, m_Value(), m_Value()))) {
9370           return PredCountMap[PredA] > PredCountMap[PredB];
9371         }
9372         return false;
9373       });
9374     }
9375 
9376     Value *VectorizedTree = nullptr;
9377     unsigned i = 0;
9378     while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) {
9379       ArrayRef<Value *> VL(&ReducedVals[i], ReduxWidth);
9380       V.buildTree(VL, IgnoreList);
9381       if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true))
9382         break;
9383       if (V.isLoadCombineReductionCandidate(RdxKind))
9384         break;
9385       V.reorderTopToBottom();
9386       V.reorderBottomToTop(/*IgnoreReorder=*/true);
9387       V.buildExternalUses(ExternallyUsedValues);
9388 
9389       // For a poison-safe boolean logic reduction, do not replace select
9390       // instructions with logic ops. All reduced values will be frozen (see
9391       // below) to prevent leaking poison.
9392       if (isa<SelectInst>(ReductionRoot) &&
9393           isBoolLogicOp(cast<Instruction>(ReductionRoot)) &&
9394           NumReducedVals != ReduxWidth)
9395         break;
9396 
9397       V.computeMinimumValueSizes();
9398 
9399       // Estimate cost.
9400       InstructionCost TreeCost =
9401           V.getTreeCost(makeArrayRef(&ReducedVals[i], ReduxWidth));
9402       InstructionCost ReductionCost =
9403           getReductionCost(TTI, ReducedVals[i], ReduxWidth, RdxFMF);
9404       InstructionCost Cost = TreeCost + ReductionCost;
9405       if (!Cost.isValid()) {
9406         LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n");
9407         return nullptr;
9408       }
9409       if (Cost >= -SLPCostThreshold) {
9410         V.getORE()->emit([&]() {
9411           return OptimizationRemarkMissed(SV_NAME, "HorSLPNotBeneficial",
9412                                           cast<Instruction>(VL[0]))
9413                  << "Vectorizing horizontal reduction is possible"
9414                  << "but not beneficial with cost " << ore::NV("Cost", Cost)
9415                  << " and threshold "
9416                  << ore::NV("Threshold", -SLPCostThreshold);
9417         });
9418         break;
9419       }
9420 
9421       LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
9422                         << Cost << ". (HorRdx)\n");
9423       V.getORE()->emit([&]() {
9424         return OptimizationRemark(SV_NAME, "VectorizedHorizontalReduction",
9425                                   cast<Instruction>(VL[0]))
9426                << "Vectorized horizontal reduction with cost "
9427                << ore::NV("Cost", Cost) << " and with tree size "
9428                << ore::NV("TreeSize", V.getTreeSize());
9429       });
9430 
9431       // Vectorize a tree.
9432       DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
9433       Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues);
9434 
9435       // Emit a reduction. If the root is a select (min/max idiom), the insert
9436       // point is the compare condition of that select.
9437       Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
9438       if (isCmpSelMinMax(RdxRootInst))
9439         Builder.SetInsertPoint(getCmpForMinMaxReduction(RdxRootInst));
9440       else
9441         Builder.SetInsertPoint(RdxRootInst);
9442 
9443       // To prevent poison from leaking across what used to be sequential, safe,
9444       // scalar boolean logic operations, the reduction operand must be frozen.
9445       if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst))
9446         VectorizedRoot = Builder.CreateFreeze(VectorizedRoot);
9447 
9448       Value *ReducedSubTree =
9449           emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
9450 
9451       if (!VectorizedTree) {
9452         // Initialize the final value in the reduction.
9453         VectorizedTree = ReducedSubTree;
9454       } else {
9455         // Update the final value in the reduction.
9456         Builder.SetCurrentDebugLocation(Loc);
9457         VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9458                                   ReducedSubTree, "op.rdx", ReductionOps);
9459       }
9460       i += ReduxWidth;
9461       ReduxWidth = PowerOf2Floor(NumReducedVals - i);
9462     }
9463 
9464     if (VectorizedTree) {
9465       // Finish the reduction.
9466       for (; i < NumReducedVals; ++i) {
9467         auto *I = cast<Instruction>(ReducedVals[i]);
9468         Builder.SetCurrentDebugLocation(I->getDebugLoc());
9469         VectorizedTree =
9470             createOp(Builder, RdxKind, VectorizedTree, I, "", ReductionOps);
9471       }
9472       for (auto &Pair : ExternallyUsedValues) {
9473         // Add each externally used value to the final reduction.
9474         for (auto *I : Pair.second) {
9475           Builder.SetCurrentDebugLocation(I->getDebugLoc());
9476           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9477                                     Pair.first, "op.extra", I);
9478         }
9479       }
9480 
9481       ReductionRoot->replaceAllUsesWith(VectorizedTree);
9482 
9483       // Mark all scalar reduction ops for deletion, they are replaced by the
9484       // vector reductions.
9485       V.eraseInstructions(IgnoreList);
9486     }
9487     return VectorizedTree;
9488   }
9489 
9490   unsigned numReductionValues() const { return ReducedVals.size(); }
9491 
9492 private:
9493   /// Calculate the cost of a reduction.
9494   InstructionCost getReductionCost(TargetTransformInfo *TTI,
9495                                    Value *FirstReducedVal, unsigned ReduxWidth,
9496                                    FastMathFlags FMF) {
9497     TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
9498     Type *ScalarTy = FirstReducedVal->getType();
9499     FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth);
9500     InstructionCost VectorCost, ScalarCost;
9501     switch (RdxKind) {
9502     case RecurKind::Add:
9503     case RecurKind::Mul:
9504     case RecurKind::Or:
9505     case RecurKind::And:
9506     case RecurKind::Xor:
9507     case RecurKind::FAdd:
9508     case RecurKind::FMul: {
9509       unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind);
9510       VectorCost =
9511           TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind);
9512       ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind);
9513       break;
9514     }
9515     case RecurKind::FMax:
9516     case RecurKind::FMin: {
9517       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9518       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9519       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
9520                                                /*IsUnsigned=*/false, CostKind);
9521       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9522       ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy,
9523                                            SclCondTy, RdxPred, CostKind) +
9524                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9525                                            SclCondTy, RdxPred, CostKind);
9526       break;
9527     }
9528     case RecurKind::SMax:
9529     case RecurKind::SMin:
9530     case RecurKind::UMax:
9531     case RecurKind::UMin: {
9532       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9533       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9534       bool IsUnsigned =
9535           RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin;
9536       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, IsUnsigned,
9537                                                CostKind);
9538       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9539       ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
9540                                            SclCondTy, RdxPred, CostKind) +
9541                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9542                                            SclCondTy, RdxPred, CostKind);
9543       break;
9544     }
9545     default:
9546       llvm_unreachable("Expected arithmetic or min/max reduction operation");
9547     }
9548 
9549     // Scalar cost is repeated for N-1 elements.
9550     ScalarCost *= (ReduxWidth - 1);
9551     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost
9552                       << " for reduction that starts with " << *FirstReducedVal
9553                       << " (It is a splitting reduction)\n");
9554     return VectorCost - ScalarCost;
9555   }
9556 
9557   /// Emit a horizontal reduction of the vectorized value.
9558   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
9559                        unsigned ReduxWidth, const TargetTransformInfo *TTI) {
9560     assert(VectorizedValue && "Need to have a vectorized tree node");
9561     assert(isPowerOf2_32(ReduxWidth) &&
9562            "We only handle power-of-two reductions for now");
9563     assert(RdxKind != RecurKind::FMulAdd &&
9564            "A call to the llvm.fmuladd intrinsic is not handled yet");
9565 
9566     ++NumVectorInstructions;
9567     return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind);
9568   }
9569 };
9570 
9571 } // end anonymous namespace
9572 
9573 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) {
9574   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
9575     return cast<FixedVectorType>(IE->getType())->getNumElements();
9576 
9577   unsigned AggregateSize = 1;
9578   auto *IV = cast<InsertValueInst>(InsertInst);
9579   Type *CurrentType = IV->getType();
9580   do {
9581     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
9582       for (auto *Elt : ST->elements())
9583         if (Elt != ST->getElementType(0)) // check homogeneity
9584           return None;
9585       AggregateSize *= ST->getNumElements();
9586       CurrentType = ST->getElementType(0);
9587     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
9588       AggregateSize *= AT->getNumElements();
9589       CurrentType = AT->getElementType();
9590     } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
9591       AggregateSize *= VT->getNumElements();
9592       return AggregateSize;
9593     } else if (CurrentType->isSingleValueType()) {
9594       return AggregateSize;
9595     } else {
9596       return None;
9597     }
9598   } while (true);
9599 }
9600 
9601 static void findBuildAggregate_rec(Instruction *LastInsertInst,
9602                                    TargetTransformInfo *TTI,
9603                                    SmallVectorImpl<Value *> &BuildVectorOpds,
9604                                    SmallVectorImpl<Value *> &InsertElts,
9605                                    unsigned OperandOffset) {
9606   do {
9607     Value *InsertedOperand = LastInsertInst->getOperand(1);
9608     Optional<unsigned> OperandIndex =
9609         getInsertIndex(LastInsertInst, OperandOffset);
9610     if (!OperandIndex)
9611       return;
9612     if (isa<InsertElementInst>(InsertedOperand) ||
9613         isa<InsertValueInst>(InsertedOperand)) {
9614       findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI,
9615                              BuildVectorOpds, InsertElts, *OperandIndex);
9616 
9617     } else {
9618       BuildVectorOpds[*OperandIndex] = InsertedOperand;
9619       InsertElts[*OperandIndex] = LastInsertInst;
9620     }
9621     LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0));
9622   } while (LastInsertInst != nullptr &&
9623            (isa<InsertValueInst>(LastInsertInst) ||
9624             isa<InsertElementInst>(LastInsertInst)) &&
9625            LastInsertInst->hasOneUse());
9626 }
9627 
9628 /// Recognize construction of vectors like
9629 ///  %ra = insertelement <4 x float> poison, float %s0, i32 0
9630 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
9631 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
9632 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
9633 ///  starting from the last insertelement or insertvalue instruction.
9634 ///
9635 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>},
9636 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
9637 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
9638 ///
9639 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
9640 ///
9641 /// \return true if it matches.
9642 static bool findBuildAggregate(Instruction *LastInsertInst,
9643                                TargetTransformInfo *TTI,
9644                                SmallVectorImpl<Value *> &BuildVectorOpds,
9645                                SmallVectorImpl<Value *> &InsertElts) {
9646 
9647   assert((isa<InsertElementInst>(LastInsertInst) ||
9648           isa<InsertValueInst>(LastInsertInst)) &&
9649          "Expected insertelement or insertvalue instruction!");
9650 
9651   assert((BuildVectorOpds.empty() && InsertElts.empty()) &&
9652          "Expected empty result vectors!");
9653 
9654   Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst);
9655   if (!AggregateSize)
9656     return false;
9657   BuildVectorOpds.resize(*AggregateSize);
9658   InsertElts.resize(*AggregateSize);
9659 
9660   findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts, 0);
9661   llvm::erase_value(BuildVectorOpds, nullptr);
9662   llvm::erase_value(InsertElts, nullptr);
9663   if (BuildVectorOpds.size() >= 2)
9664     return true;
9665 
9666   return false;
9667 }
9668 
9669 /// Try and get a reduction value from a phi node.
9670 ///
9671 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
9672 /// if they come from either \p ParentBB or a containing loop latch.
9673 ///
9674 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
9675 /// if not possible.
9676 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
9677                                 BasicBlock *ParentBB, LoopInfo *LI) {
9678   // There are situations where the reduction value is not dominated by the
9679   // reduction phi. Vectorizing such cases has been reported to cause
9680   // miscompiles. See PR25787.
9681   auto DominatedReduxValue = [&](Value *R) {
9682     return isa<Instruction>(R) &&
9683            DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
9684   };
9685 
9686   Value *Rdx = nullptr;
9687 
9688   // Return the incoming value if it comes from the same BB as the phi node.
9689   if (P->getIncomingBlock(0) == ParentBB) {
9690     Rdx = P->getIncomingValue(0);
9691   } else if (P->getIncomingBlock(1) == ParentBB) {
9692     Rdx = P->getIncomingValue(1);
9693   }
9694 
9695   if (Rdx && DominatedReduxValue(Rdx))
9696     return Rdx;
9697 
9698   // Otherwise, check whether we have a loop latch to look at.
9699   Loop *BBL = LI->getLoopFor(ParentBB);
9700   if (!BBL)
9701     return nullptr;
9702   BasicBlock *BBLatch = BBL->getLoopLatch();
9703   if (!BBLatch)
9704     return nullptr;
9705 
9706   // There is a loop latch, return the incoming value if it comes from
9707   // that. This reduction pattern occasionally turns up.
9708   if (P->getIncomingBlock(0) == BBLatch) {
9709     Rdx = P->getIncomingValue(0);
9710   } else if (P->getIncomingBlock(1) == BBLatch) {
9711     Rdx = P->getIncomingValue(1);
9712   }
9713 
9714   if (Rdx && DominatedReduxValue(Rdx))
9715     return Rdx;
9716 
9717   return nullptr;
9718 }
9719 
9720 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) {
9721   if (match(I, m_BinOp(m_Value(V0), m_Value(V1))))
9722     return true;
9723   if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1))))
9724     return true;
9725   if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1))))
9726     return true;
9727   if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1))))
9728     return true;
9729   if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1))))
9730     return true;
9731   if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1))))
9732     return true;
9733   if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1))))
9734     return true;
9735   return false;
9736 }
9737 
9738 /// Attempt to reduce a horizontal reduction.
9739 /// If it is legal to match a horizontal reduction feeding the phi node \a P
9740 /// with reduction operators \a Root (or one of its operands) in a basic block
9741 /// \a BB, then check if it can be done. If horizontal reduction is not found
9742 /// and root instruction is a binary operation, vectorization of the operands is
9743 /// attempted.
9744 /// \returns true if a horizontal reduction was matched and reduced or operands
9745 /// of one of the binary instruction were vectorized.
9746 /// \returns false if a horizontal reduction was not matched (or not possible)
9747 /// or no vectorization of any binary operation feeding \a Root instruction was
9748 /// performed.
9749 static bool tryToVectorizeHorReductionOrInstOperands(
9750     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
9751     TargetTransformInfo *TTI,
9752     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
9753   if (!ShouldVectorizeHor)
9754     return false;
9755 
9756   if (!Root)
9757     return false;
9758 
9759   if (Root->getParent() != BB || isa<PHINode>(Root))
9760     return false;
9761   // Start analysis starting from Root instruction. If horizontal reduction is
9762   // found, try to vectorize it. If it is not a horizontal reduction or
9763   // vectorization is not possible or not effective, and currently analyzed
9764   // instruction is a binary operation, try to vectorize the operands, using
9765   // pre-order DFS traversal order. If the operands were not vectorized, repeat
9766   // the same procedure considering each operand as a possible root of the
9767   // horizontal reduction.
9768   // Interrupt the process if the Root instruction itself was vectorized or all
9769   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
9770   // Skip the analysis of CmpInsts.Compiler implements postanalysis of the
9771   // CmpInsts so we can skip extra attempts in
9772   // tryToVectorizeHorReductionOrInstOperands and save compile time.
9773   std::queue<std::pair<Instruction *, unsigned>> Stack;
9774   Stack.emplace(Root, 0);
9775   SmallPtrSet<Value *, 8> VisitedInstrs;
9776   SmallVector<WeakTrackingVH> PostponedInsts;
9777   bool Res = false;
9778   auto &&TryToReduce = [TTI, &P, &R](Instruction *Inst, Value *&B0,
9779                                      Value *&B1) -> Value * {
9780     bool IsBinop = matchRdxBop(Inst, B0, B1);
9781     bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value()));
9782     if (IsBinop || IsSelect) {
9783       HorizontalReduction HorRdx;
9784       if (HorRdx.matchAssociativeReduction(P, Inst))
9785         return HorRdx.tryToReduce(R, TTI);
9786     }
9787     return nullptr;
9788   };
9789   while (!Stack.empty()) {
9790     Instruction *Inst;
9791     unsigned Level;
9792     std::tie(Inst, Level) = Stack.front();
9793     Stack.pop();
9794     // Do not try to analyze instruction that has already been vectorized.
9795     // This may happen when we vectorize instruction operands on a previous
9796     // iteration while stack was populated before that happened.
9797     if (R.isDeleted(Inst))
9798       continue;
9799     Value *B0 = nullptr, *B1 = nullptr;
9800     if (Value *V = TryToReduce(Inst, B0, B1)) {
9801       Res = true;
9802       // Set P to nullptr to avoid re-analysis of phi node in
9803       // matchAssociativeReduction function unless this is the root node.
9804       P = nullptr;
9805       if (auto *I = dyn_cast<Instruction>(V)) {
9806         // Try to find another reduction.
9807         Stack.emplace(I, Level);
9808         continue;
9809       }
9810     } else {
9811       bool IsBinop = B0 && B1;
9812       if (P && IsBinop) {
9813         Inst = dyn_cast<Instruction>(B0);
9814         if (Inst == P)
9815           Inst = dyn_cast<Instruction>(B1);
9816         if (!Inst) {
9817           // Set P to nullptr to avoid re-analysis of phi node in
9818           // matchAssociativeReduction function unless this is the root node.
9819           P = nullptr;
9820           continue;
9821         }
9822       }
9823       // Set P to nullptr to avoid re-analysis of phi node in
9824       // matchAssociativeReduction function unless this is the root node.
9825       P = nullptr;
9826       // Do not try to vectorize CmpInst operands, this is done separately.
9827       // Final attempt for binop args vectorization should happen after the loop
9828       // to try to find reductions.
9829       if (!isa<CmpInst>(Inst))
9830         PostponedInsts.push_back(Inst);
9831     }
9832 
9833     // Try to vectorize operands.
9834     // Continue analysis for the instruction from the same basic block only to
9835     // save compile time.
9836     if (++Level < RecursionMaxDepth)
9837       for (auto *Op : Inst->operand_values())
9838         if (VisitedInstrs.insert(Op).second)
9839           if (auto *I = dyn_cast<Instruction>(Op))
9840             // Do not try to vectorize CmpInst operands,  this is done
9841             // separately.
9842             if (!isa<PHINode>(I) && !isa<CmpInst>(I) && !R.isDeleted(I) &&
9843                 I->getParent() == BB)
9844               Stack.emplace(I, Level);
9845   }
9846   // Try to vectorized binops where reductions were not found.
9847   for (Value *V : PostponedInsts)
9848     if (auto *Inst = dyn_cast<Instruction>(V))
9849       if (!R.isDeleted(Inst))
9850         Res |= Vectorize(Inst, R);
9851   return Res;
9852 }
9853 
9854 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
9855                                                  BasicBlock *BB, BoUpSLP &R,
9856                                                  TargetTransformInfo *TTI) {
9857   auto *I = dyn_cast_or_null<Instruction>(V);
9858   if (!I)
9859     return false;
9860 
9861   if (!isa<BinaryOperator>(I))
9862     P = nullptr;
9863   // Try to match and vectorize a horizontal reduction.
9864   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
9865     return tryToVectorize(I, R);
9866   };
9867   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI,
9868                                                   ExtraVectorization);
9869 }
9870 
9871 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
9872                                                  BasicBlock *BB, BoUpSLP &R) {
9873   const DataLayout &DL = BB->getModule()->getDataLayout();
9874   if (!R.canMapToVector(IVI->getType(), DL))
9875     return false;
9876 
9877   SmallVector<Value *, 16> BuildVectorOpds;
9878   SmallVector<Value *, 16> BuildVectorInsts;
9879   if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts))
9880     return false;
9881 
9882   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
9883   // Aggregate value is unlikely to be processed in vector register.
9884   return tryToVectorizeList(BuildVectorOpds, R);
9885 }
9886 
9887 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
9888                                                    BasicBlock *BB, BoUpSLP &R) {
9889   SmallVector<Value *, 16> BuildVectorInsts;
9890   SmallVector<Value *, 16> BuildVectorOpds;
9891   SmallVector<int> Mask;
9892   if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
9893       (llvm::all_of(
9894            BuildVectorOpds,
9895            [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) &&
9896        isFixedVectorShuffle(BuildVectorOpds, Mask)))
9897     return false;
9898 
9899   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n");
9900   return tryToVectorizeList(BuildVectorInsts, R);
9901 }
9902 
9903 template <typename T>
9904 static bool
9905 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming,
9906                        function_ref<unsigned(T *)> Limit,
9907                        function_ref<bool(T *, T *)> Comparator,
9908                        function_ref<bool(T *, T *)> AreCompatible,
9909                        function_ref<bool(ArrayRef<T *>, bool)> TryToVectorizeHelper,
9910                        bool LimitForRegisterSize) {
9911   bool Changed = false;
9912   // Sort by type, parent, operands.
9913   stable_sort(Incoming, Comparator);
9914 
9915   // Try to vectorize elements base on their type.
9916   SmallVector<T *> Candidates;
9917   for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) {
9918     // Look for the next elements with the same type, parent and operand
9919     // kinds.
9920     auto *SameTypeIt = IncIt;
9921     while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt))
9922       ++SameTypeIt;
9923 
9924     // Try to vectorize them.
9925     unsigned NumElts = (SameTypeIt - IncIt);
9926     LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes ("
9927                       << NumElts << ")\n");
9928     // The vectorization is a 3-state attempt:
9929     // 1. Try to vectorize instructions with the same/alternate opcodes with the
9930     // size of maximal register at first.
9931     // 2. Try to vectorize remaining instructions with the same type, if
9932     // possible. This may result in the better vectorization results rather than
9933     // if we try just to vectorize instructions with the same/alternate opcodes.
9934     // 3. Final attempt to try to vectorize all instructions with the
9935     // same/alternate ops only, this may result in some extra final
9936     // vectorization.
9937     if (NumElts > 1 &&
9938         TryToVectorizeHelper(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) {
9939       // Success start over because instructions might have been changed.
9940       Changed = true;
9941     } else if (NumElts < Limit(*IncIt) &&
9942                (Candidates.empty() ||
9943                 Candidates.front()->getType() == (*IncIt)->getType())) {
9944       Candidates.append(IncIt, std::next(IncIt, NumElts));
9945     }
9946     // Final attempt to vectorize instructions with the same types.
9947     if (Candidates.size() > 1 &&
9948         (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) {
9949       if (TryToVectorizeHelper(Candidates, /*LimitForRegisterSize=*/false)) {
9950         // Success start over because instructions might have been changed.
9951         Changed = true;
9952       } else if (LimitForRegisterSize) {
9953         // Try to vectorize using small vectors.
9954         for (auto *It = Candidates.begin(), *End = Candidates.end();
9955              It != End;) {
9956           auto *SameTypeIt = It;
9957           while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It))
9958             ++SameTypeIt;
9959           unsigned NumElts = (SameTypeIt - It);
9960           if (NumElts > 1 && TryToVectorizeHelper(makeArrayRef(It, NumElts),
9961                                             /*LimitForRegisterSize=*/false))
9962             Changed = true;
9963           It = SameTypeIt;
9964         }
9965       }
9966       Candidates.clear();
9967     }
9968 
9969     // Start over at the next instruction of a different type (or the end).
9970     IncIt = SameTypeIt;
9971   }
9972   return Changed;
9973 }
9974 
9975 /// Compare two cmp instructions. If IsCompatibility is true, function returns
9976 /// true if 2 cmps have same/swapped predicates and mos compatible corresponding
9977 /// operands. If IsCompatibility is false, function implements strict weak
9978 /// ordering relation between two cmp instructions, returning true if the first
9979 /// instruction is "less" than the second, i.e. its predicate is less than the
9980 /// predicate of the second or the operands IDs are less than the operands IDs
9981 /// of the second cmp instruction.
9982 template <bool IsCompatibility>
9983 static bool compareCmp(Value *V, Value *V2,
9984                        function_ref<bool(Instruction *)> IsDeleted) {
9985   auto *CI1 = cast<CmpInst>(V);
9986   auto *CI2 = cast<CmpInst>(V2);
9987   if (IsDeleted(CI2) || !isValidElementType(CI2->getType()))
9988     return false;
9989   if (CI1->getOperand(0)->getType()->getTypeID() <
9990       CI2->getOperand(0)->getType()->getTypeID())
9991     return !IsCompatibility;
9992   if (CI1->getOperand(0)->getType()->getTypeID() >
9993       CI2->getOperand(0)->getType()->getTypeID())
9994     return false;
9995   CmpInst::Predicate Pred1 = CI1->getPredicate();
9996   CmpInst::Predicate Pred2 = CI2->getPredicate();
9997   CmpInst::Predicate SwapPred1 = CmpInst::getSwappedPredicate(Pred1);
9998   CmpInst::Predicate SwapPred2 = CmpInst::getSwappedPredicate(Pred2);
9999   CmpInst::Predicate BasePred1 = std::min(Pred1, SwapPred1);
10000   CmpInst::Predicate BasePred2 = std::min(Pred2, SwapPred2);
10001   if (BasePred1 < BasePred2)
10002     return !IsCompatibility;
10003   if (BasePred1 > BasePred2)
10004     return false;
10005   // Compare operands.
10006   bool LEPreds = Pred1 <= Pred2;
10007   bool GEPreds = Pred1 >= Pred2;
10008   for (int I = 0, E = CI1->getNumOperands(); I < E; ++I) {
10009     auto *Op1 = CI1->getOperand(LEPreds ? I : E - I - 1);
10010     auto *Op2 = CI2->getOperand(GEPreds ? I : E - I - 1);
10011     if (Op1->getValueID() < Op2->getValueID())
10012       return !IsCompatibility;
10013     if (Op1->getValueID() > Op2->getValueID())
10014       return false;
10015     if (auto *I1 = dyn_cast<Instruction>(Op1))
10016       if (auto *I2 = dyn_cast<Instruction>(Op2)) {
10017         if (I1->getParent() != I2->getParent())
10018           return false;
10019         InstructionsState S = getSameOpcode({I1, I2});
10020         if (S.getOpcode())
10021           continue;
10022         return false;
10023       }
10024   }
10025   return IsCompatibility;
10026 }
10027 
10028 bool SLPVectorizerPass::vectorizeSimpleInstructions(
10029     SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R,
10030     bool AtTerminator) {
10031   bool OpsChanged = false;
10032   SmallVector<Instruction *, 4> PostponedCmps;
10033   for (auto *I : reverse(Instructions)) {
10034     if (R.isDeleted(I))
10035       continue;
10036     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I))
10037       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
10038     else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I))
10039       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
10040     else if (isa<CmpInst>(I))
10041       PostponedCmps.push_back(I);
10042   }
10043   if (AtTerminator) {
10044     // Try to find reductions first.
10045     for (Instruction *I : PostponedCmps) {
10046       if (R.isDeleted(I))
10047         continue;
10048       for (Value *Op : I->operands())
10049         OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI);
10050     }
10051     // Try to vectorize operands as vector bundles.
10052     for (Instruction *I : PostponedCmps) {
10053       if (R.isDeleted(I))
10054         continue;
10055       OpsChanged |= tryToVectorize(I, R);
10056     }
10057     // Try to vectorize list of compares.
10058     // Sort by type, compare predicate, etc.
10059     auto &&CompareSorter = [&R](Value *V, Value *V2) {
10060       return compareCmp<false>(V, V2,
10061                                [&R](Instruction *I) { return R.isDeleted(I); });
10062     };
10063 
10064     auto &&AreCompatibleCompares = [&R](Value *V1, Value *V2) {
10065       if (V1 == V2)
10066         return true;
10067       return compareCmp<true>(V1, V2,
10068                               [&R](Instruction *I) { return R.isDeleted(I); });
10069     };
10070     auto Limit = [&R](Value *V) {
10071       unsigned EltSize = R.getVectorElementSize(V);
10072       return std::max(2U, R.getMaxVecRegSize() / EltSize);
10073     };
10074 
10075     SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end());
10076     OpsChanged |= tryToVectorizeSequence<Value>(
10077         Vals, Limit, CompareSorter, AreCompatibleCompares,
10078         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10079           // Exclude possible reductions from other blocks.
10080           bool ArePossiblyReducedInOtherBlock =
10081               any_of(Candidates, [](Value *V) {
10082                 return any_of(V->users(), [V](User *U) {
10083                   return isa<SelectInst>(U) &&
10084                          cast<SelectInst>(U)->getParent() !=
10085                              cast<Instruction>(V)->getParent();
10086                 });
10087               });
10088           if (ArePossiblyReducedInOtherBlock)
10089             return false;
10090           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10091         },
10092         /*LimitForRegisterSize=*/true);
10093     Instructions.clear();
10094   } else {
10095     // Insert in reverse order since the PostponedCmps vector was filled in
10096     // reverse order.
10097     Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend());
10098   }
10099   return OpsChanged;
10100 }
10101 
10102 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
10103   bool Changed = false;
10104   SmallVector<Value *, 4> Incoming;
10105   SmallPtrSet<Value *, 16> VisitedInstrs;
10106   // Maps phi nodes to the non-phi nodes found in the use tree for each phi
10107   // node. Allows better to identify the chains that can be vectorized in the
10108   // better way.
10109   DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes;
10110   auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) {
10111     assert(isValidElementType(V1->getType()) &&
10112            isValidElementType(V2->getType()) &&
10113            "Expected vectorizable types only.");
10114     // It is fine to compare type IDs here, since we expect only vectorizable
10115     // types, like ints, floats and pointers, we don't care about other type.
10116     if (V1->getType()->getTypeID() < V2->getType()->getTypeID())
10117       return true;
10118     if (V1->getType()->getTypeID() > V2->getType()->getTypeID())
10119       return false;
10120     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10121     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10122     if (Opcodes1.size() < Opcodes2.size())
10123       return true;
10124     if (Opcodes1.size() > Opcodes2.size())
10125       return false;
10126     Optional<bool> ConstOrder;
10127     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10128       // Undefs are compatible with any other value.
10129       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) {
10130         if (!ConstOrder)
10131           ConstOrder =
10132               !isa<UndefValue>(Opcodes1[I]) && isa<UndefValue>(Opcodes2[I]);
10133         continue;
10134       }
10135       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10136         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10137           DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent());
10138           DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent());
10139           if (!NodeI1)
10140             return NodeI2 != nullptr;
10141           if (!NodeI2)
10142             return false;
10143           assert((NodeI1 == NodeI2) ==
10144                      (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10145                  "Different nodes should have different DFS numbers");
10146           if (NodeI1 != NodeI2)
10147             return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10148           InstructionsState S = getSameOpcode({I1, I2});
10149           if (S.getOpcode())
10150             continue;
10151           return I1->getOpcode() < I2->getOpcode();
10152         }
10153       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) {
10154         if (!ConstOrder)
10155           ConstOrder = Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID();
10156         continue;
10157       }
10158       if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID())
10159         return true;
10160       if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID())
10161         return false;
10162     }
10163     return ConstOrder && *ConstOrder;
10164   };
10165   auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) {
10166     if (V1 == V2)
10167       return true;
10168     if (V1->getType() != V2->getType())
10169       return false;
10170     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10171     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10172     if (Opcodes1.size() != Opcodes2.size())
10173       return false;
10174     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10175       // Undefs are compatible with any other value.
10176       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
10177         continue;
10178       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10179         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10180           if (I1->getParent() != I2->getParent())
10181             return false;
10182           InstructionsState S = getSameOpcode({I1, I2});
10183           if (S.getOpcode())
10184             continue;
10185           return false;
10186         }
10187       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
10188         continue;
10189       if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID())
10190         return false;
10191     }
10192     return true;
10193   };
10194   auto Limit = [&R](Value *V) {
10195     unsigned EltSize = R.getVectorElementSize(V);
10196     return std::max(2U, R.getMaxVecRegSize() / EltSize);
10197   };
10198 
10199   bool HaveVectorizedPhiNodes = false;
10200   do {
10201     // Collect the incoming values from the PHIs.
10202     Incoming.clear();
10203     for (Instruction &I : *BB) {
10204       PHINode *P = dyn_cast<PHINode>(&I);
10205       if (!P)
10206         break;
10207 
10208       // No need to analyze deleted, vectorized and non-vectorizable
10209       // instructions.
10210       if (!VisitedInstrs.count(P) && !R.isDeleted(P) &&
10211           isValidElementType(P->getType()))
10212         Incoming.push_back(P);
10213     }
10214 
10215     // Find the corresponding non-phi nodes for better matching when trying to
10216     // build the tree.
10217     for (Value *V : Incoming) {
10218       SmallVectorImpl<Value *> &Opcodes =
10219           PHIToOpcodes.try_emplace(V).first->getSecond();
10220       if (!Opcodes.empty())
10221         continue;
10222       SmallVector<Value *, 4> Nodes(1, V);
10223       SmallPtrSet<Value *, 4> Visited;
10224       while (!Nodes.empty()) {
10225         auto *PHI = cast<PHINode>(Nodes.pop_back_val());
10226         if (!Visited.insert(PHI).second)
10227           continue;
10228         for (Value *V : PHI->incoming_values()) {
10229           if (auto *PHI1 = dyn_cast<PHINode>((V))) {
10230             Nodes.push_back(PHI1);
10231             continue;
10232           }
10233           Opcodes.emplace_back(V);
10234         }
10235       }
10236     }
10237 
10238     HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>(
10239         Incoming, Limit, PHICompare, AreCompatiblePHIs,
10240         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10241           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10242         },
10243         /*LimitForRegisterSize=*/true);
10244     Changed |= HaveVectorizedPhiNodes;
10245     VisitedInstrs.insert(Incoming.begin(), Incoming.end());
10246   } while (HaveVectorizedPhiNodes);
10247 
10248   VisitedInstrs.clear();
10249 
10250   SmallVector<Instruction *, 8> PostProcessInstructions;
10251   SmallDenseSet<Instruction *, 4> KeyNodes;
10252   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
10253     // Skip instructions with scalable type. The num of elements is unknown at
10254     // compile-time for scalable type.
10255     if (isa<ScalableVectorType>(it->getType()))
10256       continue;
10257 
10258     // Skip instructions marked for the deletion.
10259     if (R.isDeleted(&*it))
10260       continue;
10261     // We may go through BB multiple times so skip the one we have checked.
10262     if (!VisitedInstrs.insert(&*it).second) {
10263       if (it->use_empty() && KeyNodes.contains(&*it) &&
10264           vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10265                                       it->isTerminator())) {
10266         // We would like to start over since some instructions are deleted
10267         // and the iterator may become invalid value.
10268         Changed = true;
10269         it = BB->begin();
10270         e = BB->end();
10271       }
10272       continue;
10273     }
10274 
10275     if (isa<DbgInfoIntrinsic>(it))
10276       continue;
10277 
10278     // Try to vectorize reductions that use PHINodes.
10279     if (PHINode *P = dyn_cast<PHINode>(it)) {
10280       // Check that the PHI is a reduction PHI.
10281       if (P->getNumIncomingValues() == 2) {
10282         // Try to match and vectorize a horizontal reduction.
10283         if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
10284                                      TTI)) {
10285           Changed = true;
10286           it = BB->begin();
10287           e = BB->end();
10288           continue;
10289         }
10290       }
10291       // Try to vectorize the incoming values of the PHI, to catch reductions
10292       // that feed into PHIs.
10293       for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) {
10294         // Skip if the incoming block is the current BB for now. Also, bypass
10295         // unreachable IR for efficiency and to avoid crashing.
10296         // TODO: Collect the skipped incoming values and try to vectorize them
10297         // after processing BB.
10298         if (BB == P->getIncomingBlock(I) ||
10299             !DT->isReachableFromEntry(P->getIncomingBlock(I)))
10300           continue;
10301 
10302         Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I),
10303                                             P->getIncomingBlock(I), R, TTI);
10304       }
10305       continue;
10306     }
10307 
10308     // Ran into an instruction without users, like terminator, or function call
10309     // with ignored return value, store. Ignore unused instructions (basing on
10310     // instruction type, except for CallInst and InvokeInst).
10311     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
10312                             isa<InvokeInst>(it))) {
10313       KeyNodes.insert(&*it);
10314       bool OpsChanged = false;
10315       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
10316         for (auto *V : it->operand_values()) {
10317           // Try to match and vectorize a horizontal reduction.
10318           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
10319         }
10320       }
10321       // Start vectorization of post-process list of instructions from the
10322       // top-tree instructions to try to vectorize as many instructions as
10323       // possible.
10324       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10325                                                 it->isTerminator());
10326       if (OpsChanged) {
10327         // We would like to start over since some instructions are deleted
10328         // and the iterator may become invalid value.
10329         Changed = true;
10330         it = BB->begin();
10331         e = BB->end();
10332         continue;
10333       }
10334     }
10335 
10336     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
10337         isa<InsertValueInst>(it))
10338       PostProcessInstructions.push_back(&*it);
10339   }
10340 
10341   return Changed;
10342 }
10343 
10344 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
10345   auto Changed = false;
10346   for (auto &Entry : GEPs) {
10347     // If the getelementptr list has fewer than two elements, there's nothing
10348     // to do.
10349     if (Entry.second.size() < 2)
10350       continue;
10351 
10352     LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
10353                       << Entry.second.size() << ".\n");
10354 
10355     // Process the GEP list in chunks suitable for the target's supported
10356     // vector size. If a vector register can't hold 1 element, we are done. We
10357     // are trying to vectorize the index computations, so the maximum number of
10358     // elements is based on the size of the index expression, rather than the
10359     // size of the GEP itself (the target's pointer size).
10360     unsigned MaxVecRegSize = R.getMaxVecRegSize();
10361     unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin());
10362     if (MaxVecRegSize < EltSize)
10363       continue;
10364 
10365     unsigned MaxElts = MaxVecRegSize / EltSize;
10366     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
10367       auto Len = std::min<unsigned>(BE - BI, MaxElts);
10368       ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len);
10369 
10370       // Initialize a set a candidate getelementptrs. Note that we use a
10371       // SetVector here to preserve program order. If the index computations
10372       // are vectorizable and begin with loads, we want to minimize the chance
10373       // of having to reorder them later.
10374       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
10375 
10376       // Some of the candidates may have already been vectorized after we
10377       // initially collected them. If so, they are marked as deleted, so remove
10378       // them from the set of candidates.
10379       Candidates.remove_if(
10380           [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
10381 
10382       // Remove from the set of candidates all pairs of getelementptrs with
10383       // constant differences. Such getelementptrs are likely not good
10384       // candidates for vectorization in a bottom-up phase since one can be
10385       // computed from the other. We also ensure all candidate getelementptr
10386       // indices are unique.
10387       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
10388         auto *GEPI = GEPList[I];
10389         if (!Candidates.count(GEPI))
10390           continue;
10391         auto *SCEVI = SE->getSCEV(GEPList[I]);
10392         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
10393           auto *GEPJ = GEPList[J];
10394           auto *SCEVJ = SE->getSCEV(GEPList[J]);
10395           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
10396             Candidates.remove(GEPI);
10397             Candidates.remove(GEPJ);
10398           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
10399             Candidates.remove(GEPJ);
10400           }
10401         }
10402       }
10403 
10404       // We break out of the above computation as soon as we know there are
10405       // fewer than two candidates remaining.
10406       if (Candidates.size() < 2)
10407         continue;
10408 
10409       // Add the single, non-constant index of each candidate to the bundle. We
10410       // ensured the indices met these constraints when we originally collected
10411       // the getelementptrs.
10412       SmallVector<Value *, 16> Bundle(Candidates.size());
10413       auto BundleIndex = 0u;
10414       for (auto *V : Candidates) {
10415         auto *GEP = cast<GetElementPtrInst>(V);
10416         auto *GEPIdx = GEP->idx_begin()->get();
10417         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
10418         Bundle[BundleIndex++] = GEPIdx;
10419       }
10420 
10421       // Try and vectorize the indices. We are currently only interested in
10422       // gather-like cases of the form:
10423       //
10424       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
10425       //
10426       // where the loads of "a", the loads of "b", and the subtractions can be
10427       // performed in parallel. It's likely that detecting this pattern in a
10428       // bottom-up phase will be simpler and less costly than building a
10429       // full-blown top-down phase beginning at the consecutive loads.
10430       Changed |= tryToVectorizeList(Bundle, R);
10431     }
10432   }
10433   return Changed;
10434 }
10435 
10436 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
10437   bool Changed = false;
10438   // Sort by type, base pointers and values operand. Value operands must be
10439   // compatible (have the same opcode, same parent), otherwise it is
10440   // definitely not profitable to try to vectorize them.
10441   auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) {
10442     if (V->getPointerOperandType()->getTypeID() <
10443         V2->getPointerOperandType()->getTypeID())
10444       return true;
10445     if (V->getPointerOperandType()->getTypeID() >
10446         V2->getPointerOperandType()->getTypeID())
10447       return false;
10448     // UndefValues are compatible with all other values.
10449     if (isa<UndefValue>(V->getValueOperand()) ||
10450         isa<UndefValue>(V2->getValueOperand()))
10451       return false;
10452     if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand()))
10453       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
10454         DomTreeNodeBase<llvm::BasicBlock> *NodeI1 =
10455             DT->getNode(I1->getParent());
10456         DomTreeNodeBase<llvm::BasicBlock> *NodeI2 =
10457             DT->getNode(I2->getParent());
10458         assert(NodeI1 && "Should only process reachable instructions");
10459         assert(NodeI1 && "Should only process reachable instructions");
10460         assert((NodeI1 == NodeI2) ==
10461                    (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10462                "Different nodes should have different DFS numbers");
10463         if (NodeI1 != NodeI2)
10464           return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10465         InstructionsState S = getSameOpcode({I1, I2});
10466         if (S.getOpcode())
10467           return false;
10468         return I1->getOpcode() < I2->getOpcode();
10469       }
10470     if (isa<Constant>(V->getValueOperand()) &&
10471         isa<Constant>(V2->getValueOperand()))
10472       return false;
10473     return V->getValueOperand()->getValueID() <
10474            V2->getValueOperand()->getValueID();
10475   };
10476 
10477   auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) {
10478     if (V1 == V2)
10479       return true;
10480     if (V1->getPointerOperandType() != V2->getPointerOperandType())
10481       return false;
10482     // Undefs are compatible with any other value.
10483     if (isa<UndefValue>(V1->getValueOperand()) ||
10484         isa<UndefValue>(V2->getValueOperand()))
10485       return true;
10486     if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand()))
10487       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
10488         if (I1->getParent() != I2->getParent())
10489           return false;
10490         InstructionsState S = getSameOpcode({I1, I2});
10491         return S.getOpcode() > 0;
10492       }
10493     if (isa<Constant>(V1->getValueOperand()) &&
10494         isa<Constant>(V2->getValueOperand()))
10495       return true;
10496     return V1->getValueOperand()->getValueID() ==
10497            V2->getValueOperand()->getValueID();
10498   };
10499   auto Limit = [&R, this](StoreInst *SI) {
10500     unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
10501     return R.getMinVF(EltSize);
10502   };
10503 
10504   // Attempt to sort and vectorize each of the store-groups.
10505   for (auto &Pair : Stores) {
10506     if (Pair.second.size() < 2)
10507       continue;
10508 
10509     LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
10510                       << Pair.second.size() << ".\n");
10511 
10512     if (!isValidElementType(Pair.second.front()->getValueOperand()->getType()))
10513       continue;
10514 
10515     Changed |= tryToVectorizeSequence<StoreInst>(
10516         Pair.second, Limit, StoreSorter, AreCompatibleStores,
10517         [this, &R](ArrayRef<StoreInst *> Candidates, bool) {
10518           return vectorizeStores(Candidates, R);
10519         },
10520         /*LimitForRegisterSize=*/false);
10521   }
10522   return Changed;
10523 }
10524 
10525 char SLPVectorizer::ID = 0;
10526 
10527 static const char lv_name[] = "SLP Vectorizer";
10528 
10529 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
10530 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
10531 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
10532 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
10533 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
10534 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
10535 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
10536 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
10537 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
10538 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
10539 
10540 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
10541