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<int> getInsertIndex(Value *InsertInst, unsigned Offset) {
732   int Index = Offset;
733   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst)) {
734     if (auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2))) {
735       auto *VT = cast<FixedVectorType>(IE->getType());
736       if (CI->getValue().uge(VT->getNumElements()))
737         return UndefMaskElem;
738       Index *= VT->getNumElements();
739       Index += CI->getZExtValue();
740       return Index;
741     }
742     if (isa<UndefValue>(IE->getOperand(2)))
743       return UndefMaskElem;
744     return None;
745   }
746 
747   auto *IV = cast<InsertValueInst>(InsertInst);
748   Type *CurrentType = IV->getType();
749   for (unsigned I : IV->indices()) {
750     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
751       Index *= ST->getNumElements();
752       CurrentType = ST->getElementType(I);
753     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
754       Index *= AT->getNumElements();
755       CurrentType = AT->getElementType();
756     } else {
757       return None;
758     }
759     Index += I;
760   }
761   return Index;
762 }
763 
764 /// Reorders the list of scalars in accordance with the given \p Order and then
765 /// the \p Mask. \p Order - is the original order of the scalars, need to
766 /// reorder scalars into an unordered state at first according to the given
767 /// order. Then the ordered scalars are shuffled once again in accordance with
768 /// the provided mask.
769 static void reorderScalars(SmallVectorImpl<Value *> &Scalars,
770                            ArrayRef<int> Mask) {
771   assert(!Mask.empty() && "Expected non-empty mask.");
772   SmallVector<Value *> Prev(Scalars.size(),
773                             UndefValue::get(Scalars.front()->getType()));
774   Prev.swap(Scalars);
775   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
776     if (Mask[I] != UndefMaskElem)
777       Scalars[Mask[I]] = Prev[I];
778 }
779 
780 namespace slpvectorizer {
781 
782 /// Bottom Up SLP Vectorizer.
783 class BoUpSLP {
784   struct TreeEntry;
785   struct ScheduleData;
786 
787 public:
788   using ValueList = SmallVector<Value *, 8>;
789   using InstrList = SmallVector<Instruction *, 16>;
790   using ValueSet = SmallPtrSet<Value *, 16>;
791   using StoreList = SmallVector<StoreInst *, 8>;
792   using ExtraValueToDebugLocsMap =
793       MapVector<Value *, SmallVector<Instruction *, 2>>;
794   using OrdersType = SmallVector<unsigned, 4>;
795 
796   BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
797           TargetLibraryInfo *TLi, AAResults *Aa, LoopInfo *Li,
798           DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB,
799           const DataLayout *DL, OptimizationRemarkEmitter *ORE)
800       : F(Func), SE(Se), TTI(Tti), TLI(TLi), AA(Aa), LI(Li), DT(Dt), AC(AC),
801         DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) {
802     CodeMetrics::collectEphemeralValues(F, AC, EphValues);
803     // Use the vector register size specified by the target unless overridden
804     // by a command-line option.
805     // TODO: It would be better to limit the vectorization factor based on
806     //       data type rather than just register size. For example, x86 AVX has
807     //       256-bit registers, but it does not support integer operations
808     //       at that width (that requires AVX2).
809     if (MaxVectorRegSizeOption.getNumOccurrences())
810       MaxVecRegSize = MaxVectorRegSizeOption;
811     else
812       MaxVecRegSize =
813           TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
814               .getFixedSize();
815 
816     if (MinVectorRegSizeOption.getNumOccurrences())
817       MinVecRegSize = MinVectorRegSizeOption;
818     else
819       MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
820   }
821 
822   /// Vectorize the tree that starts with the elements in \p VL.
823   /// Returns the vectorized root.
824   Value *vectorizeTree();
825 
826   /// Vectorize the tree but with the list of externally used values \p
827   /// ExternallyUsedValues. Values in this MapVector can be replaced but the
828   /// generated extractvalue instructions.
829   Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues);
830 
831   /// \returns the cost incurred by unwanted spills and fills, caused by
832   /// holding live values over call sites.
833   InstructionCost getSpillCost() const;
834 
835   /// \returns the vectorization cost of the subtree that starts at \p VL.
836   /// A negative number means that this is profitable.
837   InstructionCost getTreeCost(ArrayRef<Value *> VectorizedVals = None);
838 
839   /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
840   /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
841   void buildTree(ArrayRef<Value *> Roots,
842                  ArrayRef<Value *> UserIgnoreLst = None);
843 
844   /// Builds external uses of the vectorized scalars, i.e. the list of
845   /// vectorized scalars to be extracted, their lanes and their scalar users. \p
846   /// ExternallyUsedValues contains additional list of external uses to handle
847   /// vectorization of reductions.
848   void
849   buildExternalUses(const ExtraValueToDebugLocsMap &ExternallyUsedValues = {});
850 
851   /// Clear the internal data structures that are created by 'buildTree'.
852   void deleteTree() {
853     VectorizableTree.clear();
854     ScalarToTreeEntry.clear();
855     MustGather.clear();
856     ExternalUses.clear();
857     for (auto &Iter : BlocksSchedules) {
858       BlockScheduling *BS = Iter.second.get();
859       BS->clear();
860     }
861     MinBWs.clear();
862     InstrElementSize.clear();
863   }
864 
865   unsigned getTreeSize() const { return VectorizableTree.size(); }
866 
867   /// Perform LICM and CSE on the newly generated gather sequences.
868   void optimizeGatherSequence();
869 
870   /// Checks if the specified gather tree entry \p TE can be represented as a
871   /// shuffled vector entry + (possibly) permutation with other gathers. It
872   /// implements the checks only for possibly ordered scalars (Loads,
873   /// ExtractElement, ExtractValue), which can be part of the graph.
874   Optional<OrdersType> findReusedOrderedScalars(const TreeEntry &TE);
875 
876   /// Gets reordering data for the given tree entry. If the entry is vectorized
877   /// - just return ReorderIndices, otherwise check if the scalars can be
878   /// reordered and return the most optimal order.
879   /// \param TopToBottom If true, include the order of vectorized stores and
880   /// insertelement nodes, otherwise skip them.
881   Optional<OrdersType> getReorderingData(const TreeEntry &TE, bool TopToBottom);
882 
883   /// Reorders the current graph to the most profitable order starting from the
884   /// root node to the leaf nodes. The best order is chosen only from the nodes
885   /// of the same size (vectorization factor). Smaller nodes are considered
886   /// parts of subgraph with smaller VF and they are reordered independently. We
887   /// can make it because we still need to extend smaller nodes to the wider VF
888   /// and we can merge reordering shuffles with the widening shuffles.
889   void reorderTopToBottom();
890 
891   /// Reorders the current graph to the most profitable order starting from
892   /// leaves to the root. It allows to rotate small subgraphs and reduce the
893   /// number of reshuffles if the leaf nodes use the same order. In this case we
894   /// can merge the orders and just shuffle user node instead of shuffling its
895   /// operands. Plus, even the leaf nodes have different orders, it allows to
896   /// sink reordering in the graph closer to the root node and merge it later
897   /// during analysis.
898   void reorderBottomToTop(bool IgnoreReorder = false);
899 
900   /// \return The vector element size in bits to use when vectorizing the
901   /// expression tree ending at \p V. If V is a store, the size is the width of
902   /// the stored value. Otherwise, the size is the width of the largest loaded
903   /// value reaching V. This method is used by the vectorizer to calculate
904   /// vectorization factors.
905   unsigned getVectorElementSize(Value *V);
906 
907   /// Compute the minimum type sizes required to represent the entries in a
908   /// vectorizable tree.
909   void computeMinimumValueSizes();
910 
911   // \returns maximum vector register size as set by TTI or overridden by cl::opt.
912   unsigned getMaxVecRegSize() const {
913     return MaxVecRegSize;
914   }
915 
916   // \returns minimum vector register size as set by cl::opt.
917   unsigned getMinVecRegSize() const {
918     return MinVecRegSize;
919   }
920 
921   unsigned getMinVF(unsigned Sz) const {
922     return std::max(2U, getMinVecRegSize() / Sz);
923   }
924 
925   unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const {
926     unsigned MaxVF = MaxVFOption.getNumOccurrences() ?
927       MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode);
928     return MaxVF ? MaxVF : UINT_MAX;
929   }
930 
931   /// Check if homogeneous aggregate is isomorphic to some VectorType.
932   /// Accepts homogeneous multidimensional aggregate of scalars/vectors like
933   /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> },
934   /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on.
935   ///
936   /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
937   unsigned canMapToVector(Type *T, const DataLayout &DL) const;
938 
939   /// \returns True if the VectorizableTree is both tiny and not fully
940   /// vectorizable. We do not vectorize such trees.
941   bool isTreeTinyAndNotFullyVectorizable(bool ForReduction = false) const;
942 
943   /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values
944   /// can be load combined in the backend. Load combining may not be allowed in
945   /// the IR optimizer, so we do not want to alter the pattern. For example,
946   /// partially transforming a scalar bswap() pattern into vector code is
947   /// effectively impossible for the backend to undo.
948   /// TODO: If load combining is allowed in the IR optimizer, this analysis
949   ///       may not be necessary.
950   bool isLoadCombineReductionCandidate(RecurKind RdxKind) const;
951 
952   /// Assume that a vector of stores of bitwise-or/shifted/zexted loaded values
953   /// can be load combined in the backend. Load combining may not be allowed in
954   /// the IR optimizer, so we do not want to alter the pattern. For example,
955   /// partially transforming a scalar bswap() pattern into vector code is
956   /// effectively impossible for the backend to undo.
957   /// TODO: If load combining is allowed in the IR optimizer, this analysis
958   ///       may not be necessary.
959   bool isLoadCombineCandidate() const;
960 
961   OptimizationRemarkEmitter *getORE() { return ORE; }
962 
963   /// This structure holds any data we need about the edges being traversed
964   /// during buildTree_rec(). We keep track of:
965   /// (i) the user TreeEntry index, and
966   /// (ii) the index of the edge.
967   struct EdgeInfo {
968     EdgeInfo() = default;
969     EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx)
970         : UserTE(UserTE), EdgeIdx(EdgeIdx) {}
971     /// The user TreeEntry.
972     TreeEntry *UserTE = nullptr;
973     /// The operand index of the use.
974     unsigned EdgeIdx = UINT_MAX;
975 #ifndef NDEBUG
976     friend inline raw_ostream &operator<<(raw_ostream &OS,
977                                           const BoUpSLP::EdgeInfo &EI) {
978       EI.dump(OS);
979       return OS;
980     }
981     /// Debug print.
982     void dump(raw_ostream &OS) const {
983       OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null")
984          << " EdgeIdx:" << EdgeIdx << "}";
985     }
986     LLVM_DUMP_METHOD void dump() const { dump(dbgs()); }
987 #endif
988   };
989 
990   /// A helper data structure to hold the operands of a vector of instructions.
991   /// This supports a fixed vector length for all operand vectors.
992   class VLOperands {
993     /// For each operand we need (i) the value, and (ii) the opcode that it
994     /// would be attached to if the expression was in a left-linearized form.
995     /// This is required to avoid illegal operand reordering.
996     /// For example:
997     /// \verbatim
998     ///                         0 Op1
999     ///                         |/
1000     /// Op1 Op2   Linearized    + Op2
1001     ///   \ /     ---------->   |/
1002     ///    -                    -
1003     ///
1004     /// Op1 - Op2            (0 + Op1) - Op2
1005     /// \endverbatim
1006     ///
1007     /// Value Op1 is attached to a '+' operation, and Op2 to a '-'.
1008     ///
1009     /// Another way to think of this is to track all the operations across the
1010     /// path from the operand all the way to the root of the tree and to
1011     /// calculate the operation that corresponds to this path. For example, the
1012     /// path from Op2 to the root crosses the RHS of the '-', therefore the
1013     /// corresponding operation is a '-' (which matches the one in the
1014     /// linearized tree, as shown above).
1015     ///
1016     /// For lack of a better term, we refer to this operation as Accumulated
1017     /// Path Operation (APO).
1018     struct OperandData {
1019       OperandData() = default;
1020       OperandData(Value *V, bool APO, bool IsUsed)
1021           : V(V), APO(APO), IsUsed(IsUsed) {}
1022       /// The operand value.
1023       Value *V = nullptr;
1024       /// TreeEntries only allow a single opcode, or an alternate sequence of
1025       /// them (e.g, +, -). Therefore, we can safely use a boolean value for the
1026       /// APO. It is set to 'true' if 'V' is attached to an inverse operation
1027       /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise
1028       /// (e.g., Add/Mul)
1029       bool APO = false;
1030       /// Helper data for the reordering function.
1031       bool IsUsed = false;
1032     };
1033 
1034     /// During operand reordering, we are trying to select the operand at lane
1035     /// that matches best with the operand at the neighboring lane. Our
1036     /// selection is based on the type of value we are looking for. For example,
1037     /// if the neighboring lane has a load, we need to look for a load that is
1038     /// accessing a consecutive address. These strategies are summarized in the
1039     /// 'ReorderingMode' enumerator.
1040     enum class ReorderingMode {
1041       Load,     ///< Matching loads to consecutive memory addresses
1042       Opcode,   ///< Matching instructions based on opcode (same or alternate)
1043       Constant, ///< Matching constants
1044       Splat,    ///< Matching the same instruction multiple times (broadcast)
1045       Failed,   ///< We failed to create a vectorizable group
1046     };
1047 
1048     using OperandDataVec = SmallVector<OperandData, 2>;
1049 
1050     /// A vector of operand vectors.
1051     SmallVector<OperandDataVec, 4> OpsVec;
1052 
1053     const DataLayout &DL;
1054     ScalarEvolution &SE;
1055     const BoUpSLP &R;
1056 
1057     /// \returns the operand data at \p OpIdx and \p Lane.
1058     OperandData &getData(unsigned OpIdx, unsigned Lane) {
1059       return OpsVec[OpIdx][Lane];
1060     }
1061 
1062     /// \returns the operand data at \p OpIdx and \p Lane. Const version.
1063     const OperandData &getData(unsigned OpIdx, unsigned Lane) const {
1064       return OpsVec[OpIdx][Lane];
1065     }
1066 
1067     /// Clears the used flag for all entries.
1068     void clearUsed() {
1069       for (unsigned OpIdx = 0, NumOperands = getNumOperands();
1070            OpIdx != NumOperands; ++OpIdx)
1071         for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
1072              ++Lane)
1073           OpsVec[OpIdx][Lane].IsUsed = false;
1074     }
1075 
1076     /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2.
1077     void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) {
1078       std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]);
1079     }
1080 
1081     // The hard-coded scores listed here are not very important, though it shall
1082     // be higher for better matches to improve the resulting cost. When
1083     // computing the scores of matching one sub-tree with another, we are
1084     // basically counting the number of values that are matching. So even if all
1085     // scores are set to 1, we would still get a decent matching result.
1086     // However, sometimes we have to break ties. For example we may have to
1087     // choose between matching loads vs matching opcodes. This is what these
1088     // scores are helping us with: they provide the order of preference. Also,
1089     // this is important if the scalar is externally used or used in another
1090     // tree entry node in the different lane.
1091 
1092     /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]).
1093     static const int ScoreConsecutiveLoads = 4;
1094     /// Loads from reversed memory addresses, e.g. load(A[i+1]), load(A[i]).
1095     static const int ScoreReversedLoads = 3;
1096     /// ExtractElementInst from same vector and consecutive indexes.
1097     static const int ScoreConsecutiveExtracts = 4;
1098     /// ExtractElementInst from same vector and reversed indices.
1099     static const int ScoreReversedExtracts = 3;
1100     /// Constants.
1101     static const int ScoreConstants = 2;
1102     /// Instructions with the same opcode.
1103     static const int ScoreSameOpcode = 2;
1104     /// Instructions with alt opcodes (e.g, add + sub).
1105     static const int ScoreAltOpcodes = 1;
1106     /// Identical instructions (a.k.a. splat or broadcast).
1107     static const int ScoreSplat = 1;
1108     /// Matching with an undef is preferable to failing.
1109     static const int ScoreUndef = 1;
1110     /// Score for failing to find a decent match.
1111     static const int ScoreFail = 0;
1112     /// Score if all users are vectorized.
1113     static const int ScoreAllUserVectorized = 1;
1114 
1115     /// \returns the score of placing \p V1 and \p V2 in consecutive lanes.
1116     /// Also, checks if \p V1 and \p V2 are compatible with instructions in \p
1117     /// MainAltOps.
1118     static int getShallowScore(Value *V1, Value *V2, const DataLayout &DL,
1119                                ScalarEvolution &SE, int NumLanes,
1120                                ArrayRef<Value *> MainAltOps) {
1121       if (V1 == V2)
1122         return VLOperands::ScoreSplat;
1123 
1124       auto *LI1 = dyn_cast<LoadInst>(V1);
1125       auto *LI2 = dyn_cast<LoadInst>(V2);
1126       if (LI1 && LI2) {
1127         if (LI1->getParent() != LI2->getParent())
1128           return VLOperands::ScoreFail;
1129 
1130         Optional<int> Dist = getPointersDiff(
1131             LI1->getType(), LI1->getPointerOperand(), LI2->getType(),
1132             LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true);
1133         if (!Dist || *Dist == 0)
1134           return VLOperands::ScoreFail;
1135         // The distance is too large - still may be profitable to use masked
1136         // loads/gathers.
1137         if (std::abs(*Dist) > NumLanes / 2)
1138           return VLOperands::ScoreAltOpcodes;
1139         // This still will detect consecutive loads, but we might have "holes"
1140         // in some cases. It is ok for non-power-2 vectorization and may produce
1141         // better results. It should not affect current vectorization.
1142         return (*Dist > 0) ? VLOperands::ScoreConsecutiveLoads
1143                            : VLOperands::ScoreReversedLoads;
1144       }
1145 
1146       auto *C1 = dyn_cast<Constant>(V1);
1147       auto *C2 = dyn_cast<Constant>(V2);
1148       if (C1 && C2)
1149         return VLOperands::ScoreConstants;
1150 
1151       // Extracts from consecutive indexes of the same vector better score as
1152       // the extracts could be optimized away.
1153       Value *EV1;
1154       ConstantInt *Ex1Idx;
1155       if (match(V1, m_ExtractElt(m_Value(EV1), m_ConstantInt(Ex1Idx)))) {
1156         // Undefs are always profitable for extractelements.
1157         if (isa<UndefValue>(V2))
1158           return VLOperands::ScoreConsecutiveExtracts;
1159         Value *EV2 = nullptr;
1160         ConstantInt *Ex2Idx = nullptr;
1161         if (match(V2,
1162                   m_ExtractElt(m_Value(EV2), m_CombineOr(m_ConstantInt(Ex2Idx),
1163                                                          m_Undef())))) {
1164           // Undefs are always profitable for extractelements.
1165           if (!Ex2Idx)
1166             return VLOperands::ScoreConsecutiveExtracts;
1167           if (isUndefVector(EV2) && EV2->getType() == EV1->getType())
1168             return VLOperands::ScoreConsecutiveExtracts;
1169           if (EV2 == EV1) {
1170             int Idx1 = Ex1Idx->getZExtValue();
1171             int Idx2 = Ex2Idx->getZExtValue();
1172             int Dist = Idx2 - Idx1;
1173             // The distance is too large - still may be profitable to use
1174             // shuffles.
1175             if (std::abs(Dist) == 0)
1176               return VLOperands::ScoreSplat;
1177             if (std::abs(Dist) > NumLanes / 2)
1178               return VLOperands::ScoreSameOpcode;
1179             return (Dist > 0) ? VLOperands::ScoreConsecutiveExtracts
1180                               : VLOperands::ScoreReversedExtracts;
1181           }
1182           return VLOperands::ScoreAltOpcodes;
1183         }
1184         return VLOperands::ScoreFail;
1185       }
1186 
1187       auto *I1 = dyn_cast<Instruction>(V1);
1188       auto *I2 = dyn_cast<Instruction>(V2);
1189       if (I1 && I2) {
1190         if (I1->getParent() != I2->getParent())
1191           return VLOperands::ScoreFail;
1192         SmallVector<Value *, 4> Ops(MainAltOps.begin(), MainAltOps.end());
1193         Ops.push_back(I1);
1194         Ops.push_back(I2);
1195         InstructionsState S = getSameOpcode(Ops);
1196         // Note: Only consider instructions with <= 2 operands to avoid
1197         // complexity explosion.
1198         if (S.getOpcode() &&
1199             (S.MainOp->getNumOperands() <= 2 || !MainAltOps.empty() ||
1200              !S.isAltShuffle()) &&
1201             all_of(Ops, [&S](Value *V) {
1202               return cast<Instruction>(V)->getNumOperands() ==
1203                      S.MainOp->getNumOperands();
1204             }))
1205           return S.isAltShuffle() ? VLOperands::ScoreAltOpcodes
1206                                   : VLOperands::ScoreSameOpcode;
1207       }
1208 
1209       if (isa<UndefValue>(V2))
1210         return VLOperands::ScoreUndef;
1211 
1212       return VLOperands::ScoreFail;
1213     }
1214 
1215     /// \param Lane lane of the operands under analysis.
1216     /// \param OpIdx operand index in \p Lane lane we're looking the best
1217     /// candidate for.
1218     /// \param Idx operand index of the current candidate value.
1219     /// \returns The additional score due to possible broadcasting of the
1220     /// elements in the lane. It is more profitable to have power-of-2 unique
1221     /// elements in the lane, it will be vectorized with higher probability
1222     /// after removing duplicates. Currently the SLP vectorizer supports only
1223     /// vectorization of the power-of-2 number of unique scalars.
1224     int getSplatScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1225       Value *IdxLaneV = getData(Idx, Lane).V;
1226       if (!isa<Instruction>(IdxLaneV) || IdxLaneV == getData(OpIdx, Lane).V)
1227         return 0;
1228       SmallPtrSet<Value *, 4> Uniques;
1229       for (unsigned Ln = 0, E = getNumLanes(); Ln < E; ++Ln) {
1230         if (Ln == Lane)
1231           continue;
1232         Value *OpIdxLnV = getData(OpIdx, Ln).V;
1233         if (!isa<Instruction>(OpIdxLnV))
1234           return 0;
1235         Uniques.insert(OpIdxLnV);
1236       }
1237       int UniquesCount = Uniques.size();
1238       int UniquesCntWithIdxLaneV =
1239           Uniques.contains(IdxLaneV) ? UniquesCount : UniquesCount + 1;
1240       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1241       int UniquesCntWithOpIdxLaneV =
1242           Uniques.contains(OpIdxLaneV) ? UniquesCount : UniquesCount + 1;
1243       if (UniquesCntWithIdxLaneV == UniquesCntWithOpIdxLaneV)
1244         return 0;
1245       return (PowerOf2Ceil(UniquesCntWithOpIdxLaneV) -
1246               UniquesCntWithOpIdxLaneV) -
1247              (PowerOf2Ceil(UniquesCntWithIdxLaneV) - UniquesCntWithIdxLaneV);
1248     }
1249 
1250     /// \param Lane lane of the operands under analysis.
1251     /// \param OpIdx operand index in \p Lane lane we're looking the best
1252     /// candidate for.
1253     /// \param Idx operand index of the current candidate value.
1254     /// \returns The additional score for the scalar which users are all
1255     /// vectorized.
1256     int getExternalUseScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1257       Value *IdxLaneV = getData(Idx, Lane).V;
1258       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1259       // Do not care about number of uses for vector-like instructions
1260       // (extractelement/extractvalue with constant indices), they are extracts
1261       // themselves and already externally used. Vectorization of such
1262       // instructions does not add extra extractelement instruction, just may
1263       // remove it.
1264       if (isVectorLikeInstWithConstOps(IdxLaneV) &&
1265           isVectorLikeInstWithConstOps(OpIdxLaneV))
1266         return VLOperands::ScoreAllUserVectorized;
1267       auto *IdxLaneI = dyn_cast<Instruction>(IdxLaneV);
1268       if (!IdxLaneI || !isa<Instruction>(OpIdxLaneV))
1269         return 0;
1270       return R.areAllUsersVectorized(IdxLaneI, None)
1271                  ? VLOperands::ScoreAllUserVectorized
1272                  : 0;
1273     }
1274 
1275     /// Go through the operands of \p LHS and \p RHS recursively until \p
1276     /// MaxLevel, and return the cummulative score. For example:
1277     /// \verbatim
1278     ///  A[0]  B[0]  A[1]  B[1]  C[0] D[0]  B[1] A[1]
1279     ///     \ /         \ /         \ /        \ /
1280     ///      +           +           +          +
1281     ///     G1          G2          G3         G4
1282     /// \endverbatim
1283     /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at
1284     /// each level recursively, accumulating the score. It starts from matching
1285     /// the additions at level 0, then moves on to the loads (level 1). The
1286     /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and
1287     /// {B[0],B[1]} match with VLOperands::ScoreConsecutiveLoads, while
1288     /// {A[0],C[0]} has a score of VLOperands::ScoreFail.
1289     /// Please note that the order of the operands does not matter, as we
1290     /// evaluate the score of all profitable combinations of operands. In
1291     /// other words the score of G1 and G4 is the same as G1 and G2. This
1292     /// heuristic is based on ideas described in:
1293     ///   Look-ahead SLP: Auto-vectorization in the presence of commutative
1294     ///   operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha,
1295     ///   Luís F. W. Góes
1296     int getScoreAtLevelRec(Value *LHS, Value *RHS, int CurrLevel, int MaxLevel,
1297                            ArrayRef<Value *> MainAltOps) {
1298 
1299       // Get the shallow score of V1 and V2.
1300       int ShallowScoreAtThisLevel =
1301           getShallowScore(LHS, RHS, DL, SE, getNumLanes(), MainAltOps);
1302 
1303       // If reached MaxLevel,
1304       //  or if V1 and V2 are not instructions,
1305       //  or if they are SPLAT,
1306       //  or if they are not consecutive,
1307       //  or if profitable to vectorize loads or extractelements, early return
1308       //  the current cost.
1309       auto *I1 = dyn_cast<Instruction>(LHS);
1310       auto *I2 = dyn_cast<Instruction>(RHS);
1311       if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 ||
1312           ShallowScoreAtThisLevel == VLOperands::ScoreFail ||
1313           (((isa<LoadInst>(I1) && isa<LoadInst>(I2)) ||
1314             (I1->getNumOperands() > 2 && I2->getNumOperands() > 2) ||
1315             (isa<ExtractElementInst>(I1) && isa<ExtractElementInst>(I2))) &&
1316            ShallowScoreAtThisLevel))
1317         return ShallowScoreAtThisLevel;
1318       assert(I1 && I2 && "Should have early exited.");
1319 
1320       // Contains the I2 operand indexes that got matched with I1 operands.
1321       SmallSet<unsigned, 4> Op2Used;
1322 
1323       // Recursion towards the operands of I1 and I2. We are trying all possible
1324       // operand pairs, and keeping track of the best score.
1325       for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands();
1326            OpIdx1 != NumOperands1; ++OpIdx1) {
1327         // Try to pair op1I with the best operand of I2.
1328         int MaxTmpScore = 0;
1329         unsigned MaxOpIdx2 = 0;
1330         bool FoundBest = false;
1331         // If I2 is commutative try all combinations.
1332         unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1;
1333         unsigned ToIdx = isCommutative(I2)
1334                              ? I2->getNumOperands()
1335                              : std::min(I2->getNumOperands(), OpIdx1 + 1);
1336         assert(FromIdx <= ToIdx && "Bad index");
1337         for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) {
1338           // Skip operands already paired with OpIdx1.
1339           if (Op2Used.count(OpIdx2))
1340             continue;
1341           // Recursively calculate the cost at each level
1342           int TmpScore =
1343               getScoreAtLevelRec(I1->getOperand(OpIdx1), I2->getOperand(OpIdx2),
1344                                  CurrLevel + 1, MaxLevel, None);
1345           // Look for the best score.
1346           if (TmpScore > VLOperands::ScoreFail && TmpScore > MaxTmpScore) {
1347             MaxTmpScore = TmpScore;
1348             MaxOpIdx2 = OpIdx2;
1349             FoundBest = true;
1350           }
1351         }
1352         if (FoundBest) {
1353           // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it.
1354           Op2Used.insert(MaxOpIdx2);
1355           ShallowScoreAtThisLevel += MaxTmpScore;
1356         }
1357       }
1358       return ShallowScoreAtThisLevel;
1359     }
1360 
1361     /// Score scaling factor for fully compatible instructions but with
1362     /// different number of external uses. Allows better selection of the
1363     /// instructions with less external uses.
1364     static const int ScoreScaleFactor = 10;
1365 
1366     /// \Returns the look-ahead score, which tells us how much the sub-trees
1367     /// rooted at \p LHS and \p RHS match, the more they match the higher the
1368     /// score. This helps break ties in an informed way when we cannot decide on
1369     /// the order of the operands by just considering the immediate
1370     /// predecessors.
1371     int getLookAheadScore(Value *LHS, Value *RHS, ArrayRef<Value *> MainAltOps,
1372                           int Lane, unsigned OpIdx, unsigned Idx,
1373                           bool &IsUsed) {
1374       int Score =
1375           getScoreAtLevelRec(LHS, RHS, 1, LookAheadMaxDepth, MainAltOps);
1376       if (Score) {
1377         int SplatScore = getSplatScore(Lane, OpIdx, Idx);
1378         if (Score <= -SplatScore) {
1379           // Set the minimum score for splat-like sequence to avoid setting
1380           // failed state.
1381           Score = 1;
1382         } else {
1383           Score += SplatScore;
1384           // Scale score to see the difference between different operands
1385           // and similar operands but all vectorized/not all vectorized
1386           // uses. It does not affect actual selection of the best
1387           // compatible operand in general, just allows to select the
1388           // operand with all vectorized uses.
1389           Score *= ScoreScaleFactor;
1390           Score += getExternalUseScore(Lane, OpIdx, Idx);
1391           IsUsed = true;
1392         }
1393       }
1394       return Score;
1395     }
1396 
1397     /// Best defined scores per lanes between the passes. Used to choose the
1398     /// best operand (with the highest score) between the passes.
1399     /// The key - {Operand Index, Lane}.
1400     /// The value - the best score between the passes for the lane and the
1401     /// operand.
1402     SmallDenseMap<std::pair<unsigned, unsigned>, unsigned, 8>
1403         BestScoresPerLanes;
1404 
1405     // Search all operands in Ops[*][Lane] for the one that matches best
1406     // Ops[OpIdx][LastLane] and return its opreand index.
1407     // If no good match can be found, return None.
1408     Optional<unsigned> getBestOperand(unsigned OpIdx, int Lane, int LastLane,
1409                                       ArrayRef<ReorderingMode> ReorderingModes,
1410                                       ArrayRef<Value *> MainAltOps) {
1411       unsigned NumOperands = getNumOperands();
1412 
1413       // The operand of the previous lane at OpIdx.
1414       Value *OpLastLane = getData(OpIdx, LastLane).V;
1415 
1416       // Our strategy mode for OpIdx.
1417       ReorderingMode RMode = ReorderingModes[OpIdx];
1418       if (RMode == ReorderingMode::Failed)
1419         return None;
1420 
1421       // The linearized opcode of the operand at OpIdx, Lane.
1422       bool OpIdxAPO = getData(OpIdx, Lane).APO;
1423 
1424       // The best operand index and its score.
1425       // Sometimes we have more than one option (e.g., Opcode and Undefs), so we
1426       // are using the score to differentiate between the two.
1427       struct BestOpData {
1428         Optional<unsigned> Idx = None;
1429         unsigned Score = 0;
1430       } BestOp;
1431       BestOp.Score =
1432           BestScoresPerLanes.try_emplace(std::make_pair(OpIdx, Lane), 0)
1433               .first->second;
1434 
1435       // Track if the operand must be marked as used. If the operand is set to
1436       // Score 1 explicitly (because of non power-of-2 unique scalars, we may
1437       // want to reestimate the operands again on the following iterations).
1438       bool IsUsed =
1439           RMode == ReorderingMode::Splat || RMode == ReorderingMode::Constant;
1440       // Iterate through all unused operands and look for the best.
1441       for (unsigned Idx = 0; Idx != NumOperands; ++Idx) {
1442         // Get the operand at Idx and Lane.
1443         OperandData &OpData = getData(Idx, Lane);
1444         Value *Op = OpData.V;
1445         bool OpAPO = OpData.APO;
1446 
1447         // Skip already selected operands.
1448         if (OpData.IsUsed)
1449           continue;
1450 
1451         // Skip if we are trying to move the operand to a position with a
1452         // different opcode in the linearized tree form. This would break the
1453         // semantics.
1454         if (OpAPO != OpIdxAPO)
1455           continue;
1456 
1457         // Look for an operand that matches the current mode.
1458         switch (RMode) {
1459         case ReorderingMode::Load:
1460         case ReorderingMode::Constant:
1461         case ReorderingMode::Opcode: {
1462           bool LeftToRight = Lane > LastLane;
1463           Value *OpLeft = (LeftToRight) ? OpLastLane : Op;
1464           Value *OpRight = (LeftToRight) ? Op : OpLastLane;
1465           int Score = getLookAheadScore(OpLeft, OpRight, MainAltOps, Lane,
1466                                         OpIdx, Idx, IsUsed);
1467           if (Score > static_cast<int>(BestOp.Score)) {
1468             BestOp.Idx = Idx;
1469             BestOp.Score = Score;
1470             BestScoresPerLanes[std::make_pair(OpIdx, Lane)] = Score;
1471           }
1472           break;
1473         }
1474         case ReorderingMode::Splat:
1475           if (Op == OpLastLane)
1476             BestOp.Idx = Idx;
1477           break;
1478         case ReorderingMode::Failed:
1479           llvm_unreachable("Not expected Failed reordering mode.");
1480         }
1481       }
1482 
1483       if (BestOp.Idx) {
1484         getData(BestOp.Idx.getValue(), Lane).IsUsed = IsUsed;
1485         return BestOp.Idx;
1486       }
1487       // If we could not find a good match return None.
1488       return None;
1489     }
1490 
1491     /// Helper for reorderOperandVecs.
1492     /// \returns the lane that we should start reordering from. This is the one
1493     /// which has the least number of operands that can freely move about or
1494     /// less profitable because it already has the most optimal set of operands.
1495     unsigned getBestLaneToStartReordering() const {
1496       unsigned Min = UINT_MAX;
1497       unsigned SameOpNumber = 0;
1498       // std::pair<unsigned, unsigned> is used to implement a simple voting
1499       // algorithm and choose the lane with the least number of operands that
1500       // can freely move about or less profitable because it already has the
1501       // most optimal set of operands. The first unsigned is a counter for
1502       // voting, the second unsigned is the counter of lanes with instructions
1503       // with same/alternate opcodes and same parent basic block.
1504       MapVector<unsigned, std::pair<unsigned, unsigned>> HashMap;
1505       // Try to be closer to the original results, if we have multiple lanes
1506       // with same cost. If 2 lanes have the same cost, use the one with the
1507       // lowest index.
1508       for (int I = getNumLanes(); I > 0; --I) {
1509         unsigned Lane = I - 1;
1510         OperandsOrderData NumFreeOpsHash =
1511             getMaxNumOperandsThatCanBeReordered(Lane);
1512         // Compare the number of operands that can move and choose the one with
1513         // the least number.
1514         if (NumFreeOpsHash.NumOfAPOs < Min) {
1515           Min = NumFreeOpsHash.NumOfAPOs;
1516           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1517           HashMap.clear();
1518           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1519         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1520                    NumFreeOpsHash.NumOpsWithSameOpcodeParent < SameOpNumber) {
1521           // Select the most optimal lane in terms of number of operands that
1522           // should be moved around.
1523           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1524           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1525         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1526                    NumFreeOpsHash.NumOpsWithSameOpcodeParent == SameOpNumber) {
1527           auto It = HashMap.find(NumFreeOpsHash.Hash);
1528           if (It == HashMap.end())
1529             HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1530           else
1531             ++It->second.first;
1532         }
1533       }
1534       // Select the lane with the minimum counter.
1535       unsigned BestLane = 0;
1536       unsigned CntMin = UINT_MAX;
1537       for (const auto &Data : reverse(HashMap)) {
1538         if (Data.second.first < CntMin) {
1539           CntMin = Data.second.first;
1540           BestLane = Data.second.second;
1541         }
1542       }
1543       return BestLane;
1544     }
1545 
1546     /// Data structure that helps to reorder operands.
1547     struct OperandsOrderData {
1548       /// The best number of operands with the same APOs, which can be
1549       /// reordered.
1550       unsigned NumOfAPOs = UINT_MAX;
1551       /// Number of operands with the same/alternate instruction opcode and
1552       /// parent.
1553       unsigned NumOpsWithSameOpcodeParent = 0;
1554       /// Hash for the actual operands ordering.
1555       /// Used to count operands, actually their position id and opcode
1556       /// value. It is used in the voting mechanism to find the lane with the
1557       /// least number of operands that can freely move about or less profitable
1558       /// because it already has the most optimal set of operands. Can be
1559       /// replaced with SmallVector<unsigned> instead but hash code is faster
1560       /// and requires less memory.
1561       unsigned Hash = 0;
1562     };
1563     /// \returns the maximum number of operands that are allowed to be reordered
1564     /// for \p Lane and the number of compatible instructions(with the same
1565     /// parent/opcode). This is used as a heuristic for selecting the first lane
1566     /// to start operand reordering.
1567     OperandsOrderData getMaxNumOperandsThatCanBeReordered(unsigned Lane) const {
1568       unsigned CntTrue = 0;
1569       unsigned NumOperands = getNumOperands();
1570       // Operands with the same APO can be reordered. We therefore need to count
1571       // how many of them we have for each APO, like this: Cnt[APO] = x.
1572       // Since we only have two APOs, namely true and false, we can avoid using
1573       // a map. Instead we can simply count the number of operands that
1574       // correspond to one of them (in this case the 'true' APO), and calculate
1575       // the other by subtracting it from the total number of operands.
1576       // Operands with the same instruction opcode and parent are more
1577       // profitable since we don't need to move them in many cases, with a high
1578       // probability such lane already can be vectorized effectively.
1579       bool AllUndefs = true;
1580       unsigned NumOpsWithSameOpcodeParent = 0;
1581       Instruction *OpcodeI = nullptr;
1582       BasicBlock *Parent = nullptr;
1583       unsigned Hash = 0;
1584       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1585         const OperandData &OpData = getData(OpIdx, Lane);
1586         if (OpData.APO)
1587           ++CntTrue;
1588         // Use Boyer-Moore majority voting for finding the majority opcode and
1589         // the number of times it occurs.
1590         if (auto *I = dyn_cast<Instruction>(OpData.V)) {
1591           if (!OpcodeI || !getSameOpcode({OpcodeI, I}).getOpcode() ||
1592               I->getParent() != Parent) {
1593             if (NumOpsWithSameOpcodeParent == 0) {
1594               NumOpsWithSameOpcodeParent = 1;
1595               OpcodeI = I;
1596               Parent = I->getParent();
1597             } else {
1598               --NumOpsWithSameOpcodeParent;
1599             }
1600           } else {
1601             ++NumOpsWithSameOpcodeParent;
1602           }
1603         }
1604         Hash = hash_combine(
1605             Hash, hash_value((OpIdx + 1) * (OpData.V->getValueID() + 1)));
1606         AllUndefs = AllUndefs && isa<UndefValue>(OpData.V);
1607       }
1608       if (AllUndefs)
1609         return {};
1610       OperandsOrderData Data;
1611       Data.NumOfAPOs = std::max(CntTrue, NumOperands - CntTrue);
1612       Data.NumOpsWithSameOpcodeParent = NumOpsWithSameOpcodeParent;
1613       Data.Hash = Hash;
1614       return Data;
1615     }
1616 
1617     /// Go through the instructions in VL and append their operands.
1618     void appendOperandsOfVL(ArrayRef<Value *> VL) {
1619       assert(!VL.empty() && "Bad VL");
1620       assert((empty() || VL.size() == getNumLanes()) &&
1621              "Expected same number of lanes");
1622       assert(isa<Instruction>(VL[0]) && "Expected instruction");
1623       unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands();
1624       OpsVec.resize(NumOperands);
1625       unsigned NumLanes = VL.size();
1626       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1627         OpsVec[OpIdx].resize(NumLanes);
1628         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1629           assert(isa<Instruction>(VL[Lane]) && "Expected instruction");
1630           // Our tree has just 3 nodes: the root and two operands.
1631           // It is therefore trivial to get the APO. We only need to check the
1632           // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or
1633           // RHS operand. The LHS operand of both add and sub is never attached
1634           // to an inversese operation in the linearized form, therefore its APO
1635           // is false. The RHS is true only if VL[Lane] is an inverse operation.
1636 
1637           // Since operand reordering is performed on groups of commutative
1638           // operations or alternating sequences (e.g., +, -), we can safely
1639           // tell the inverse operations by checking commutativity.
1640           bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane]));
1641           bool APO = (OpIdx == 0) ? false : IsInverseOperation;
1642           OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx),
1643                                  APO, false};
1644         }
1645       }
1646     }
1647 
1648     /// \returns the number of operands.
1649     unsigned getNumOperands() const { return OpsVec.size(); }
1650 
1651     /// \returns the number of lanes.
1652     unsigned getNumLanes() const { return OpsVec[0].size(); }
1653 
1654     /// \returns the operand value at \p OpIdx and \p Lane.
1655     Value *getValue(unsigned OpIdx, unsigned Lane) const {
1656       return getData(OpIdx, Lane).V;
1657     }
1658 
1659     /// \returns true if the data structure is empty.
1660     bool empty() const { return OpsVec.empty(); }
1661 
1662     /// Clears the data.
1663     void clear() { OpsVec.clear(); }
1664 
1665     /// \Returns true if there are enough operands identical to \p Op to fill
1666     /// the whole vector.
1667     /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow.
1668     bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) {
1669       bool OpAPO = getData(OpIdx, Lane).APO;
1670       for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) {
1671         if (Ln == Lane)
1672           continue;
1673         // This is set to true if we found a candidate for broadcast at Lane.
1674         bool FoundCandidate = false;
1675         for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) {
1676           OperandData &Data = getData(OpI, Ln);
1677           if (Data.APO != OpAPO || Data.IsUsed)
1678             continue;
1679           if (Data.V == Op) {
1680             FoundCandidate = true;
1681             Data.IsUsed = true;
1682             break;
1683           }
1684         }
1685         if (!FoundCandidate)
1686           return false;
1687       }
1688       return true;
1689     }
1690 
1691   public:
1692     /// Initialize with all the operands of the instruction vector \p RootVL.
1693     VLOperands(ArrayRef<Value *> RootVL, const DataLayout &DL,
1694                ScalarEvolution &SE, const BoUpSLP &R)
1695         : DL(DL), SE(SE), R(R) {
1696       // Append all the operands of RootVL.
1697       appendOperandsOfVL(RootVL);
1698     }
1699 
1700     /// \Returns a value vector with the operands across all lanes for the
1701     /// opearnd at \p OpIdx.
1702     ValueList getVL(unsigned OpIdx) const {
1703       ValueList OpVL(OpsVec[OpIdx].size());
1704       assert(OpsVec[OpIdx].size() == getNumLanes() &&
1705              "Expected same num of lanes across all operands");
1706       for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane)
1707         OpVL[Lane] = OpsVec[OpIdx][Lane].V;
1708       return OpVL;
1709     }
1710 
1711     // Performs operand reordering for 2 or more operands.
1712     // The original operands are in OrigOps[OpIdx][Lane].
1713     // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'.
1714     void reorder() {
1715       unsigned NumOperands = getNumOperands();
1716       unsigned NumLanes = getNumLanes();
1717       // Each operand has its own mode. We are using this mode to help us select
1718       // the instructions for each lane, so that they match best with the ones
1719       // we have selected so far.
1720       SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands);
1721 
1722       // This is a greedy single-pass algorithm. We are going over each lane
1723       // once and deciding on the best order right away with no back-tracking.
1724       // However, in order to increase its effectiveness, we start with the lane
1725       // that has operands that can move the least. For example, given the
1726       // following lanes:
1727       //  Lane 0 : A[0] = B[0] + C[0]   // Visited 3rd
1728       //  Lane 1 : A[1] = C[1] - B[1]   // Visited 1st
1729       //  Lane 2 : A[2] = B[2] + C[2]   // Visited 2nd
1730       //  Lane 3 : A[3] = C[3] - B[3]   // Visited 4th
1731       // we will start at Lane 1, since the operands of the subtraction cannot
1732       // be reordered. Then we will visit the rest of the lanes in a circular
1733       // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3.
1734 
1735       // Find the first lane that we will start our search from.
1736       unsigned FirstLane = getBestLaneToStartReordering();
1737 
1738       // Initialize the modes.
1739       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1740         Value *OpLane0 = getValue(OpIdx, FirstLane);
1741         // Keep track if we have instructions with all the same opcode on one
1742         // side.
1743         if (isa<LoadInst>(OpLane0))
1744           ReorderingModes[OpIdx] = ReorderingMode::Load;
1745         else if (isa<Instruction>(OpLane0)) {
1746           // Check if OpLane0 should be broadcast.
1747           if (shouldBroadcast(OpLane0, OpIdx, FirstLane))
1748             ReorderingModes[OpIdx] = ReorderingMode::Splat;
1749           else
1750             ReorderingModes[OpIdx] = ReorderingMode::Opcode;
1751         }
1752         else if (isa<Constant>(OpLane0))
1753           ReorderingModes[OpIdx] = ReorderingMode::Constant;
1754         else if (isa<Argument>(OpLane0))
1755           // Our best hope is a Splat. It may save some cost in some cases.
1756           ReorderingModes[OpIdx] = ReorderingMode::Splat;
1757         else
1758           // NOTE: This should be unreachable.
1759           ReorderingModes[OpIdx] = ReorderingMode::Failed;
1760       }
1761 
1762       // Check that we don't have same operands. No need to reorder if operands
1763       // are just perfect diamond or shuffled diamond match. Do not do it only
1764       // for possible broadcasts or non-power of 2 number of scalars (just for
1765       // now).
1766       auto &&SkipReordering = [this]() {
1767         SmallPtrSet<Value *, 4> UniqueValues;
1768         ArrayRef<OperandData> Op0 = OpsVec.front();
1769         for (const OperandData &Data : Op0)
1770           UniqueValues.insert(Data.V);
1771         for (ArrayRef<OperandData> Op : drop_begin(OpsVec, 1)) {
1772           if (any_of(Op, [&UniqueValues](const OperandData &Data) {
1773                 return !UniqueValues.contains(Data.V);
1774               }))
1775             return false;
1776         }
1777         // TODO: Check if we can remove a check for non-power-2 number of
1778         // scalars after full support of non-power-2 vectorization.
1779         return UniqueValues.size() != 2 && isPowerOf2_32(UniqueValues.size());
1780       };
1781 
1782       // If the initial strategy fails for any of the operand indexes, then we
1783       // perform reordering again in a second pass. This helps avoid assigning
1784       // high priority to the failed strategy, and should improve reordering for
1785       // the non-failed operand indexes.
1786       for (int Pass = 0; Pass != 2; ++Pass) {
1787         // Check if no need to reorder operands since they're are perfect or
1788         // shuffled diamond match.
1789         // Need to to do it to avoid extra external use cost counting for
1790         // shuffled matches, which may cause regressions.
1791         if (SkipReordering())
1792           break;
1793         // Skip the second pass if the first pass did not fail.
1794         bool StrategyFailed = false;
1795         // Mark all operand data as free to use.
1796         clearUsed();
1797         // We keep the original operand order for the FirstLane, so reorder the
1798         // rest of the lanes. We are visiting the nodes in a circular fashion,
1799         // using FirstLane as the center point and increasing the radius
1800         // distance.
1801         SmallVector<SmallVector<Value *, 2>> MainAltOps(NumOperands);
1802         for (unsigned I = 0; I < NumOperands; ++I)
1803           MainAltOps[I].push_back(getData(I, FirstLane).V);
1804 
1805         for (unsigned Distance = 1; Distance != NumLanes; ++Distance) {
1806           // Visit the lane on the right and then the lane on the left.
1807           for (int Direction : {+1, -1}) {
1808             int Lane = FirstLane + Direction * Distance;
1809             if (Lane < 0 || Lane >= (int)NumLanes)
1810               continue;
1811             int LastLane = Lane - Direction;
1812             assert(LastLane >= 0 && LastLane < (int)NumLanes &&
1813                    "Out of bounds");
1814             // Look for a good match for each operand.
1815             for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1816               // Search for the operand that matches SortedOps[OpIdx][Lane-1].
1817               Optional<unsigned> BestIdx = getBestOperand(
1818                   OpIdx, Lane, LastLane, ReorderingModes, MainAltOps[OpIdx]);
1819               // By not selecting a value, we allow the operands that follow to
1820               // select a better matching value. We will get a non-null value in
1821               // the next run of getBestOperand().
1822               if (BestIdx) {
1823                 // Swap the current operand with the one returned by
1824                 // getBestOperand().
1825                 swap(OpIdx, BestIdx.getValue(), Lane);
1826               } else {
1827                 // We failed to find a best operand, set mode to 'Failed'.
1828                 ReorderingModes[OpIdx] = ReorderingMode::Failed;
1829                 // Enable the second pass.
1830                 StrategyFailed = true;
1831               }
1832               // Try to get the alternate opcode and follow it during analysis.
1833               if (MainAltOps[OpIdx].size() != 2) {
1834                 OperandData &AltOp = getData(OpIdx, Lane);
1835                 InstructionsState OpS =
1836                     getSameOpcode({MainAltOps[OpIdx].front(), AltOp.V});
1837                 if (OpS.getOpcode() && OpS.isAltShuffle())
1838                   MainAltOps[OpIdx].push_back(AltOp.V);
1839               }
1840             }
1841           }
1842         }
1843         // Skip second pass if the strategy did not fail.
1844         if (!StrategyFailed)
1845           break;
1846       }
1847     }
1848 
1849 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1850     LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) {
1851       switch (RMode) {
1852       case ReorderingMode::Load:
1853         return "Load";
1854       case ReorderingMode::Opcode:
1855         return "Opcode";
1856       case ReorderingMode::Constant:
1857         return "Constant";
1858       case ReorderingMode::Splat:
1859         return "Splat";
1860       case ReorderingMode::Failed:
1861         return "Failed";
1862       }
1863       llvm_unreachable("Unimplemented Reordering Type");
1864     }
1865 
1866     LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode,
1867                                                    raw_ostream &OS) {
1868       return OS << getModeStr(RMode);
1869     }
1870 
1871     /// Debug print.
1872     LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) {
1873       printMode(RMode, dbgs());
1874     }
1875 
1876     friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) {
1877       return printMode(RMode, OS);
1878     }
1879 
1880     LLVM_DUMP_METHOD raw_ostream &print(raw_ostream &OS) const {
1881       const unsigned Indent = 2;
1882       unsigned Cnt = 0;
1883       for (const OperandDataVec &OpDataVec : OpsVec) {
1884         OS << "Operand " << Cnt++ << "\n";
1885         for (const OperandData &OpData : OpDataVec) {
1886           OS.indent(Indent) << "{";
1887           if (Value *V = OpData.V)
1888             OS << *V;
1889           else
1890             OS << "null";
1891           OS << ", APO:" << OpData.APO << "}\n";
1892         }
1893         OS << "\n";
1894       }
1895       return OS;
1896     }
1897 
1898     /// Debug print.
1899     LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
1900 #endif
1901   };
1902 
1903   /// Checks if the instruction is marked for deletion.
1904   bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); }
1905 
1906   /// Marks values operands for later deletion by replacing them with Undefs.
1907   void eraseInstructions(ArrayRef<Value *> AV);
1908 
1909   ~BoUpSLP();
1910 
1911 private:
1912   /// Checks if all users of \p I are the part of the vectorization tree.
1913   bool areAllUsersVectorized(Instruction *I,
1914                              ArrayRef<Value *> VectorizedVals) const;
1915 
1916   /// \returns the cost of the vectorizable entry.
1917   InstructionCost getEntryCost(const TreeEntry *E,
1918                                ArrayRef<Value *> VectorizedVals);
1919 
1920   /// This is the recursive part of buildTree.
1921   void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth,
1922                      const EdgeInfo &EI);
1923 
1924   /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
1925   /// be vectorized to use the original vector (or aggregate "bitcast" to a
1926   /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
1927   /// returns false, setting \p CurrentOrder to either an empty vector or a
1928   /// non-identity permutation that allows to reuse extract instructions.
1929   bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
1930                        SmallVectorImpl<unsigned> &CurrentOrder) const;
1931 
1932   /// Vectorize a single entry in the tree.
1933   Value *vectorizeTree(TreeEntry *E);
1934 
1935   /// Vectorize a single entry in the tree, starting in \p VL.
1936   Value *vectorizeTree(ArrayRef<Value *> VL);
1937 
1938   /// \returns the scalarization cost for this type. Scalarization in this
1939   /// context means the creation of vectors from a group of scalars. If \p
1940   /// NeedToShuffle is true, need to add a cost of reshuffling some of the
1941   /// vector elements.
1942   InstructionCost getGatherCost(FixedVectorType *Ty,
1943                                 const DenseSet<unsigned> &ShuffledIndices,
1944                                 bool NeedToShuffle) const;
1945 
1946   /// Checks if the gathered \p VL can be represented as shuffle(s) of previous
1947   /// tree entries.
1948   /// \returns ShuffleKind, if gathered values can be represented as shuffles of
1949   /// previous tree entries. \p Mask is filled with the shuffle mask.
1950   Optional<TargetTransformInfo::ShuffleKind>
1951   isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
1952                         SmallVectorImpl<const TreeEntry *> &Entries);
1953 
1954   /// \returns the scalarization cost for this list of values. Assuming that
1955   /// this subtree gets vectorized, we may need to extract the values from the
1956   /// roots. This method calculates the cost of extracting the values.
1957   InstructionCost getGatherCost(ArrayRef<Value *> VL) const;
1958 
1959   /// Set the Builder insert point to one after the last instruction in
1960   /// the bundle
1961   void setInsertPointAfterBundle(const TreeEntry *E);
1962 
1963   /// \returns a vector from a collection of scalars in \p VL.
1964   Value *gather(ArrayRef<Value *> VL);
1965 
1966   /// \returns whether the VectorizableTree is fully vectorizable and will
1967   /// be beneficial even the tree height is tiny.
1968   bool isFullyVectorizableTinyTree(bool ForReduction) const;
1969 
1970   /// Reorder commutative or alt operands to get better probability of
1971   /// generating vectorized code.
1972   static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
1973                                              SmallVectorImpl<Value *> &Left,
1974                                              SmallVectorImpl<Value *> &Right,
1975                                              const DataLayout &DL,
1976                                              ScalarEvolution &SE,
1977                                              const BoUpSLP &R);
1978   struct TreeEntry {
1979     using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>;
1980     TreeEntry(VecTreeTy &Container) : Container(Container) {}
1981 
1982     /// \returns true if the scalars in VL are equal to this entry.
1983     bool isSame(ArrayRef<Value *> VL) const {
1984       auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) {
1985         if (Mask.size() != VL.size() && VL.size() == Scalars.size())
1986           return std::equal(VL.begin(), VL.end(), Scalars.begin());
1987         return VL.size() == Mask.size() &&
1988                std::equal(VL.begin(), VL.end(), Mask.begin(),
1989                           [Scalars](Value *V, int Idx) {
1990                             return (isa<UndefValue>(V) &&
1991                                     Idx == UndefMaskElem) ||
1992                                    (Idx != UndefMaskElem && V == Scalars[Idx]);
1993                           });
1994       };
1995       if (!ReorderIndices.empty()) {
1996         // TODO: implement matching if the nodes are just reordered, still can
1997         // treat the vector as the same if the list of scalars matches VL
1998         // directly, without reordering.
1999         SmallVector<int> Mask;
2000         inversePermutation(ReorderIndices, Mask);
2001         if (VL.size() == Scalars.size())
2002           return IsSame(Scalars, Mask);
2003         if (VL.size() == ReuseShuffleIndices.size()) {
2004           ::addMask(Mask, ReuseShuffleIndices);
2005           return IsSame(Scalars, Mask);
2006         }
2007         return false;
2008       }
2009       return IsSame(Scalars, ReuseShuffleIndices);
2010     }
2011 
2012     /// \returns true if current entry has same operands as \p TE.
2013     bool hasEqualOperands(const TreeEntry &TE) const {
2014       if (TE.getNumOperands() != getNumOperands())
2015         return false;
2016       SmallBitVector Used(getNumOperands());
2017       for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
2018         unsigned PrevCount = Used.count();
2019         for (unsigned K = 0; K < E; ++K) {
2020           if (Used.test(K))
2021             continue;
2022           if (getOperand(K) == TE.getOperand(I)) {
2023             Used.set(K);
2024             break;
2025           }
2026         }
2027         // Check if we actually found the matching operand.
2028         if (PrevCount == Used.count())
2029           return false;
2030       }
2031       return true;
2032     }
2033 
2034     /// \return Final vectorization factor for the node. Defined by the total
2035     /// number of vectorized scalars, including those, used several times in the
2036     /// entry and counted in the \a ReuseShuffleIndices, if any.
2037     unsigned getVectorFactor() const {
2038       if (!ReuseShuffleIndices.empty())
2039         return ReuseShuffleIndices.size();
2040       return Scalars.size();
2041     };
2042 
2043     /// A vector of scalars.
2044     ValueList Scalars;
2045 
2046     /// The Scalars are vectorized into this value. It is initialized to Null.
2047     Value *VectorizedValue = nullptr;
2048 
2049     /// Do we need to gather this sequence or vectorize it
2050     /// (either with vector instruction or with scatter/gather
2051     /// intrinsics for store/load)?
2052     enum EntryState { Vectorize, ScatterVectorize, NeedToGather };
2053     EntryState State;
2054 
2055     /// Does this sequence require some shuffling?
2056     SmallVector<int, 4> ReuseShuffleIndices;
2057 
2058     /// Does this entry require reordering?
2059     SmallVector<unsigned, 4> ReorderIndices;
2060 
2061     /// Points back to the VectorizableTree.
2062     ///
2063     /// Only used for Graphviz right now.  Unfortunately GraphTrait::NodeRef has
2064     /// to be a pointer and needs to be able to initialize the child iterator.
2065     /// Thus we need a reference back to the container to translate the indices
2066     /// to entries.
2067     VecTreeTy &Container;
2068 
2069     /// The TreeEntry index containing the user of this entry.  We can actually
2070     /// have multiple users so the data structure is not truly a tree.
2071     SmallVector<EdgeInfo, 1> UserTreeIndices;
2072 
2073     /// The index of this treeEntry in VectorizableTree.
2074     int Idx = -1;
2075 
2076   private:
2077     /// The operands of each instruction in each lane Operands[op_index][lane].
2078     /// Note: This helps avoid the replication of the code that performs the
2079     /// reordering of operands during buildTree_rec() and vectorizeTree().
2080     SmallVector<ValueList, 2> Operands;
2081 
2082     /// The main/alternate instruction.
2083     Instruction *MainOp = nullptr;
2084     Instruction *AltOp = nullptr;
2085 
2086   public:
2087     /// Set this bundle's \p OpIdx'th operand to \p OpVL.
2088     void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) {
2089       if (Operands.size() < OpIdx + 1)
2090         Operands.resize(OpIdx + 1);
2091       assert(Operands[OpIdx].empty() && "Already resized?");
2092       assert(OpVL.size() <= Scalars.size() &&
2093              "Number of operands is greater than the number of scalars.");
2094       Operands[OpIdx].resize(OpVL.size());
2095       copy(OpVL, Operands[OpIdx].begin());
2096     }
2097 
2098     /// Set the operands of this bundle in their original order.
2099     void setOperandsInOrder() {
2100       assert(Operands.empty() && "Already initialized?");
2101       auto *I0 = cast<Instruction>(Scalars[0]);
2102       Operands.resize(I0->getNumOperands());
2103       unsigned NumLanes = Scalars.size();
2104       for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands();
2105            OpIdx != NumOperands; ++OpIdx) {
2106         Operands[OpIdx].resize(NumLanes);
2107         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
2108           auto *I = cast<Instruction>(Scalars[Lane]);
2109           assert(I->getNumOperands() == NumOperands &&
2110                  "Expected same number of operands");
2111           Operands[OpIdx][Lane] = I->getOperand(OpIdx);
2112         }
2113       }
2114     }
2115 
2116     /// Reorders operands of the node to the given mask \p Mask.
2117     void reorderOperands(ArrayRef<int> Mask) {
2118       for (ValueList &Operand : Operands)
2119         reorderScalars(Operand, Mask);
2120     }
2121 
2122     /// \returns the \p OpIdx operand of this TreeEntry.
2123     ValueList &getOperand(unsigned OpIdx) {
2124       assert(OpIdx < Operands.size() && "Off bounds");
2125       return Operands[OpIdx];
2126     }
2127 
2128     /// \returns the \p OpIdx operand of this TreeEntry.
2129     ArrayRef<Value *> getOperand(unsigned OpIdx) const {
2130       assert(OpIdx < Operands.size() && "Off bounds");
2131       return Operands[OpIdx];
2132     }
2133 
2134     /// \returns the number of operands.
2135     unsigned getNumOperands() const { return Operands.size(); }
2136 
2137     /// \return the single \p OpIdx operand.
2138     Value *getSingleOperand(unsigned OpIdx) const {
2139       assert(OpIdx < Operands.size() && "Off bounds");
2140       assert(!Operands[OpIdx].empty() && "No operand available");
2141       return Operands[OpIdx][0];
2142     }
2143 
2144     /// Some of the instructions in the list have alternate opcodes.
2145     bool isAltShuffle() const { return MainOp != AltOp; }
2146 
2147     bool isOpcodeOrAlt(Instruction *I) const {
2148       unsigned CheckedOpcode = I->getOpcode();
2149       return (getOpcode() == CheckedOpcode ||
2150               getAltOpcode() == CheckedOpcode);
2151     }
2152 
2153     /// Chooses the correct key for scheduling data. If \p Op has the same (or
2154     /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is
2155     /// \p OpValue.
2156     Value *isOneOf(Value *Op) const {
2157       auto *I = dyn_cast<Instruction>(Op);
2158       if (I && isOpcodeOrAlt(I))
2159         return Op;
2160       return MainOp;
2161     }
2162 
2163     void setOperations(const InstructionsState &S) {
2164       MainOp = S.MainOp;
2165       AltOp = S.AltOp;
2166     }
2167 
2168     Instruction *getMainOp() const {
2169       return MainOp;
2170     }
2171 
2172     Instruction *getAltOp() const {
2173       return AltOp;
2174     }
2175 
2176     /// The main/alternate opcodes for the list of instructions.
2177     unsigned getOpcode() const {
2178       return MainOp ? MainOp->getOpcode() : 0;
2179     }
2180 
2181     unsigned getAltOpcode() const {
2182       return AltOp ? AltOp->getOpcode() : 0;
2183     }
2184 
2185     /// When ReuseReorderShuffleIndices is empty it just returns position of \p
2186     /// V within vector of Scalars. Otherwise, try to remap on its reuse index.
2187     int findLaneForValue(Value *V) const {
2188       unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V));
2189       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2190       if (!ReorderIndices.empty())
2191         FoundLane = ReorderIndices[FoundLane];
2192       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2193       if (!ReuseShuffleIndices.empty()) {
2194         FoundLane = std::distance(ReuseShuffleIndices.begin(),
2195                                   find(ReuseShuffleIndices, FoundLane));
2196       }
2197       return FoundLane;
2198     }
2199 
2200 #ifndef NDEBUG
2201     /// Debug printer.
2202     LLVM_DUMP_METHOD void dump() const {
2203       dbgs() << Idx << ".\n";
2204       for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) {
2205         dbgs() << "Operand " << OpI << ":\n";
2206         for (const Value *V : Operands[OpI])
2207           dbgs().indent(2) << *V << "\n";
2208       }
2209       dbgs() << "Scalars: \n";
2210       for (Value *V : Scalars)
2211         dbgs().indent(2) << *V << "\n";
2212       dbgs() << "State: ";
2213       switch (State) {
2214       case Vectorize:
2215         dbgs() << "Vectorize\n";
2216         break;
2217       case ScatterVectorize:
2218         dbgs() << "ScatterVectorize\n";
2219         break;
2220       case NeedToGather:
2221         dbgs() << "NeedToGather\n";
2222         break;
2223       }
2224       dbgs() << "MainOp: ";
2225       if (MainOp)
2226         dbgs() << *MainOp << "\n";
2227       else
2228         dbgs() << "NULL\n";
2229       dbgs() << "AltOp: ";
2230       if (AltOp)
2231         dbgs() << *AltOp << "\n";
2232       else
2233         dbgs() << "NULL\n";
2234       dbgs() << "VectorizedValue: ";
2235       if (VectorizedValue)
2236         dbgs() << *VectorizedValue << "\n";
2237       else
2238         dbgs() << "NULL\n";
2239       dbgs() << "ReuseShuffleIndices: ";
2240       if (ReuseShuffleIndices.empty())
2241         dbgs() << "Empty";
2242       else
2243         for (int ReuseIdx : ReuseShuffleIndices)
2244           dbgs() << ReuseIdx << ", ";
2245       dbgs() << "\n";
2246       dbgs() << "ReorderIndices: ";
2247       for (unsigned ReorderIdx : ReorderIndices)
2248         dbgs() << ReorderIdx << ", ";
2249       dbgs() << "\n";
2250       dbgs() << "UserTreeIndices: ";
2251       for (const auto &EInfo : UserTreeIndices)
2252         dbgs() << EInfo << ", ";
2253       dbgs() << "\n";
2254     }
2255 #endif
2256   };
2257 
2258 #ifndef NDEBUG
2259   void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost,
2260                      InstructionCost VecCost,
2261                      InstructionCost ScalarCost) const {
2262     dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump();
2263     dbgs() << "SLP: Costs:\n";
2264     dbgs() << "SLP:     ReuseShuffleCost = " << ReuseShuffleCost << "\n";
2265     dbgs() << "SLP:     VectorCost = " << VecCost << "\n";
2266     dbgs() << "SLP:     ScalarCost = " << ScalarCost << "\n";
2267     dbgs() << "SLP:     ReuseShuffleCost + VecCost - ScalarCost = " <<
2268                ReuseShuffleCost + VecCost - ScalarCost << "\n";
2269   }
2270 #endif
2271 
2272   /// Create a new VectorizableTree entry.
2273   TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle,
2274                           const InstructionsState &S,
2275                           const EdgeInfo &UserTreeIdx,
2276                           ArrayRef<int> ReuseShuffleIndices = None,
2277                           ArrayRef<unsigned> ReorderIndices = None) {
2278     TreeEntry::EntryState EntryState =
2279         Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather;
2280     return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx,
2281                         ReuseShuffleIndices, ReorderIndices);
2282   }
2283 
2284   TreeEntry *newTreeEntry(ArrayRef<Value *> VL,
2285                           TreeEntry::EntryState EntryState,
2286                           Optional<ScheduleData *> Bundle,
2287                           const InstructionsState &S,
2288                           const EdgeInfo &UserTreeIdx,
2289                           ArrayRef<int> ReuseShuffleIndices = None,
2290                           ArrayRef<unsigned> ReorderIndices = None) {
2291     assert(((!Bundle && EntryState == TreeEntry::NeedToGather) ||
2292             (Bundle && EntryState != TreeEntry::NeedToGather)) &&
2293            "Need to vectorize gather entry?");
2294     VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree));
2295     TreeEntry *Last = VectorizableTree.back().get();
2296     Last->Idx = VectorizableTree.size() - 1;
2297     Last->State = EntryState;
2298     Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
2299                                      ReuseShuffleIndices.end());
2300     if (ReorderIndices.empty()) {
2301       Last->Scalars.assign(VL.begin(), VL.end());
2302       Last->setOperations(S);
2303     } else {
2304       // Reorder scalars and build final mask.
2305       Last->Scalars.assign(VL.size(), nullptr);
2306       transform(ReorderIndices, Last->Scalars.begin(),
2307                 [VL](unsigned Idx) -> Value * {
2308                   if (Idx >= VL.size())
2309                     return UndefValue::get(VL.front()->getType());
2310                   return VL[Idx];
2311                 });
2312       InstructionsState S = getSameOpcode(Last->Scalars);
2313       Last->setOperations(S);
2314       Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end());
2315     }
2316     if (Last->State != TreeEntry::NeedToGather) {
2317       for (Value *V : VL) {
2318         assert(!getTreeEntry(V) && "Scalar already in tree!");
2319         ScalarToTreeEntry[V] = Last;
2320       }
2321       // Update the scheduler bundle to point to this TreeEntry.
2322       unsigned Lane = 0;
2323       for (ScheduleData *BundleMember = Bundle.getValue(); BundleMember;
2324            BundleMember = BundleMember->NextInBundle) {
2325         BundleMember->TE = Last;
2326         BundleMember->Lane = Lane;
2327         ++Lane;
2328       }
2329       assert((!Bundle.getValue() || Lane == VL.size()) &&
2330              "Bundle and VL out of sync");
2331     } else {
2332       MustGather.insert(VL.begin(), VL.end());
2333     }
2334 
2335     if (UserTreeIdx.UserTE)
2336       Last->UserTreeIndices.push_back(UserTreeIdx);
2337 
2338     return Last;
2339   }
2340 
2341   /// -- Vectorization State --
2342   /// Holds all of the tree entries.
2343   TreeEntry::VecTreeTy VectorizableTree;
2344 
2345 #ifndef NDEBUG
2346   /// Debug printer.
2347   LLVM_DUMP_METHOD void dumpVectorizableTree() const {
2348     for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) {
2349       VectorizableTree[Id]->dump();
2350       dbgs() << "\n";
2351     }
2352   }
2353 #endif
2354 
2355   TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); }
2356 
2357   const TreeEntry *getTreeEntry(Value *V) const {
2358     return ScalarToTreeEntry.lookup(V);
2359   }
2360 
2361   /// Maps a specific scalar to its tree entry.
2362   SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry;
2363 
2364   /// Maps a value to the proposed vectorizable size.
2365   SmallDenseMap<Value *, unsigned> InstrElementSize;
2366 
2367   /// A list of scalars that we found that we need to keep as scalars.
2368   ValueSet MustGather;
2369 
2370   /// This POD struct describes one external user in the vectorized tree.
2371   struct ExternalUser {
2372     ExternalUser(Value *S, llvm::User *U, int L)
2373         : Scalar(S), User(U), Lane(L) {}
2374 
2375     // Which scalar in our function.
2376     Value *Scalar;
2377 
2378     // Which user that uses the scalar.
2379     llvm::User *User;
2380 
2381     // Which lane does the scalar belong to.
2382     int Lane;
2383   };
2384   using UserList = SmallVector<ExternalUser, 16>;
2385 
2386   /// Checks if two instructions may access the same memory.
2387   ///
2388   /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
2389   /// is invariant in the calling loop.
2390   bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
2391                  Instruction *Inst2) {
2392     // First check if the result is already in the cache.
2393     AliasCacheKey key = std::make_pair(Inst1, Inst2);
2394     Optional<bool> &result = AliasCache[key];
2395     if (result.hasValue()) {
2396       return result.getValue();
2397     }
2398     bool aliased = true;
2399     if (Loc1.Ptr && isSimple(Inst1))
2400       aliased = isModOrRefSet(AA->getModRefInfo(Inst2, Loc1));
2401     // Store the result in the cache.
2402     result = aliased;
2403     return aliased;
2404   }
2405 
2406   using AliasCacheKey = std::pair<Instruction *, Instruction *>;
2407 
2408   /// Cache for alias results.
2409   /// TODO: consider moving this to the AliasAnalysis itself.
2410   DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
2411 
2412   /// Removes an instruction from its block and eventually deletes it.
2413   /// It's like Instruction::eraseFromParent() except that the actual deletion
2414   /// is delayed until BoUpSLP is destructed.
2415   /// This is required to ensure that there are no incorrect collisions in the
2416   /// AliasCache, which can happen if a new instruction is allocated at the
2417   /// same address as a previously deleted instruction.
2418   void eraseInstruction(Instruction *I, bool ReplaceOpsWithUndef = false) {
2419     auto It = DeletedInstructions.try_emplace(I, ReplaceOpsWithUndef).first;
2420     It->getSecond() = It->getSecond() && ReplaceOpsWithUndef;
2421   }
2422 
2423   /// Temporary store for deleted instructions. Instructions will be deleted
2424   /// eventually when the BoUpSLP is destructed.
2425   DenseMap<Instruction *, bool> DeletedInstructions;
2426 
2427   /// A list of values that need to extracted out of the tree.
2428   /// This list holds pairs of (Internal Scalar : External User). External User
2429   /// can be nullptr, it means that this Internal Scalar will be used later,
2430   /// after vectorization.
2431   UserList ExternalUses;
2432 
2433   /// Values used only by @llvm.assume calls.
2434   SmallPtrSet<const Value *, 32> EphValues;
2435 
2436   /// Holds all of the instructions that we gathered.
2437   SetVector<Instruction *> GatherShuffleSeq;
2438 
2439   /// A list of blocks that we are going to CSE.
2440   SetVector<BasicBlock *> CSEBlocks;
2441 
2442   /// Contains all scheduling relevant data for an instruction.
2443   /// A ScheduleData either represents a single instruction or a member of an
2444   /// instruction bundle (= a group of instructions which is combined into a
2445   /// vector instruction).
2446   struct ScheduleData {
2447     // The initial value for the dependency counters. It means that the
2448     // dependencies are not calculated yet.
2449     enum { InvalidDeps = -1 };
2450 
2451     ScheduleData() = default;
2452 
2453     void init(int BlockSchedulingRegionID, Value *OpVal) {
2454       FirstInBundle = this;
2455       NextInBundle = nullptr;
2456       NextLoadStore = nullptr;
2457       IsScheduled = false;
2458       SchedulingRegionID = BlockSchedulingRegionID;
2459       UnscheduledDepsInBundle = UnscheduledDeps;
2460       clearDependencies();
2461       OpValue = OpVal;
2462       TE = nullptr;
2463       Lane = -1;
2464     }
2465 
2466     /// Returns true if the dependency information has been calculated.
2467     bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
2468 
2469     /// Returns true for single instructions and for bundle representatives
2470     /// (= the head of a bundle).
2471     bool isSchedulingEntity() const { return FirstInBundle == this; }
2472 
2473     /// Returns true if it represents an instruction bundle and not only a
2474     /// single instruction.
2475     bool isPartOfBundle() const {
2476       return NextInBundle != nullptr || FirstInBundle != this;
2477     }
2478 
2479     /// Returns true if it is ready for scheduling, i.e. it has no more
2480     /// unscheduled depending instructions/bundles.
2481     bool isReady() const {
2482       assert(isSchedulingEntity() &&
2483              "can't consider non-scheduling entity for ready list");
2484       return UnscheduledDepsInBundle == 0 && !IsScheduled;
2485     }
2486 
2487     /// Modifies the number of unscheduled dependencies, also updating it for
2488     /// the whole bundle.
2489     int incrementUnscheduledDeps(int Incr) {
2490       UnscheduledDeps += Incr;
2491       return FirstInBundle->UnscheduledDepsInBundle += Incr;
2492     }
2493 
2494     /// Sets the number of unscheduled dependencies to the number of
2495     /// dependencies.
2496     void resetUnscheduledDeps() {
2497       incrementUnscheduledDeps(Dependencies - UnscheduledDeps);
2498     }
2499 
2500     /// Clears all dependency information.
2501     void clearDependencies() {
2502       Dependencies = InvalidDeps;
2503       resetUnscheduledDeps();
2504       MemoryDependencies.clear();
2505     }
2506 
2507     void dump(raw_ostream &os) const {
2508       if (!isSchedulingEntity()) {
2509         os << "/ " << *Inst;
2510       } else if (NextInBundle) {
2511         os << '[' << *Inst;
2512         ScheduleData *SD = NextInBundle;
2513         while (SD) {
2514           os << ';' << *SD->Inst;
2515           SD = SD->NextInBundle;
2516         }
2517         os << ']';
2518       } else {
2519         os << *Inst;
2520       }
2521     }
2522 
2523     Instruction *Inst = nullptr;
2524 
2525     /// Points to the head in an instruction bundle (and always to this for
2526     /// single instructions).
2527     ScheduleData *FirstInBundle = nullptr;
2528 
2529     /// Single linked list of all instructions in a bundle. Null if it is a
2530     /// single instruction.
2531     ScheduleData *NextInBundle = nullptr;
2532 
2533     /// Single linked list of all memory instructions (e.g. load, store, call)
2534     /// in the block - until the end of the scheduling region.
2535     ScheduleData *NextLoadStore = nullptr;
2536 
2537     /// The dependent memory instructions.
2538     /// This list is derived on demand in calculateDependencies().
2539     SmallVector<ScheduleData *, 4> MemoryDependencies;
2540 
2541     /// This ScheduleData is in the current scheduling region if this matches
2542     /// the current SchedulingRegionID of BlockScheduling.
2543     int SchedulingRegionID = 0;
2544 
2545     /// Used for getting a "good" final ordering of instructions.
2546     int SchedulingPriority = 0;
2547 
2548     /// The number of dependencies. Constitutes of the number of users of the
2549     /// instruction plus the number of dependent memory instructions (if any).
2550     /// This value is calculated on demand.
2551     /// If InvalidDeps, the number of dependencies is not calculated yet.
2552     int Dependencies = InvalidDeps;
2553 
2554     /// The number of dependencies minus the number of dependencies of scheduled
2555     /// instructions. As soon as this is zero, the instruction/bundle gets ready
2556     /// for scheduling.
2557     /// Note that this is negative as long as Dependencies is not calculated.
2558     int UnscheduledDeps = InvalidDeps;
2559 
2560     /// The sum of UnscheduledDeps in a bundle. Equals to UnscheduledDeps for
2561     /// single instructions.
2562     int UnscheduledDepsInBundle = InvalidDeps;
2563 
2564     /// True if this instruction is scheduled (or considered as scheduled in the
2565     /// dry-run).
2566     bool IsScheduled = false;
2567 
2568     /// Opcode of the current instruction in the schedule data.
2569     Value *OpValue = nullptr;
2570 
2571     /// The TreeEntry that this instruction corresponds to.
2572     TreeEntry *TE = nullptr;
2573 
2574     /// The lane of this node in the TreeEntry.
2575     int Lane = -1;
2576   };
2577 
2578 #ifndef NDEBUG
2579   friend inline raw_ostream &operator<<(raw_ostream &os,
2580                                         const BoUpSLP::ScheduleData &SD) {
2581     SD.dump(os);
2582     return os;
2583   }
2584 #endif
2585 
2586   friend struct GraphTraits<BoUpSLP *>;
2587   friend struct DOTGraphTraits<BoUpSLP *>;
2588 
2589   /// Contains all scheduling data for a basic block.
2590   struct BlockScheduling {
2591     BlockScheduling(BasicBlock *BB)
2592         : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
2593 
2594     void clear() {
2595       ReadyInsts.clear();
2596       ScheduleStart = nullptr;
2597       ScheduleEnd = nullptr;
2598       FirstLoadStoreInRegion = nullptr;
2599       LastLoadStoreInRegion = nullptr;
2600 
2601       // Reduce the maximum schedule region size by the size of the
2602       // previous scheduling run.
2603       ScheduleRegionSizeLimit -= ScheduleRegionSize;
2604       if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
2605         ScheduleRegionSizeLimit = MinScheduleRegionSize;
2606       ScheduleRegionSize = 0;
2607 
2608       // Make a new scheduling region, i.e. all existing ScheduleData is not
2609       // in the new region yet.
2610       ++SchedulingRegionID;
2611     }
2612 
2613     ScheduleData *getScheduleData(Value *V) {
2614       ScheduleData *SD = ScheduleDataMap[V];
2615       if (SD && SD->SchedulingRegionID == SchedulingRegionID)
2616         return SD;
2617       return nullptr;
2618     }
2619 
2620     ScheduleData *getScheduleData(Value *V, Value *Key) {
2621       if (V == Key)
2622         return getScheduleData(V);
2623       auto I = ExtraScheduleDataMap.find(V);
2624       if (I != ExtraScheduleDataMap.end()) {
2625         ScheduleData *SD = I->second[Key];
2626         if (SD && SD->SchedulingRegionID == SchedulingRegionID)
2627           return SD;
2628       }
2629       return nullptr;
2630     }
2631 
2632     bool isInSchedulingRegion(ScheduleData *SD) const {
2633       return SD->SchedulingRegionID == SchedulingRegionID;
2634     }
2635 
2636     /// Marks an instruction as scheduled and puts all dependent ready
2637     /// instructions into the ready-list.
2638     template <typename ReadyListType>
2639     void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
2640       SD->IsScheduled = true;
2641       LLVM_DEBUG(dbgs() << "SLP:   schedule " << *SD << "\n");
2642 
2643       for (ScheduleData *BundleMember = SD; BundleMember;
2644            BundleMember = BundleMember->NextInBundle) {
2645         if (BundleMember->Inst != BundleMember->OpValue)
2646           continue;
2647 
2648         // Handle the def-use chain dependencies.
2649 
2650         // Decrement the unscheduled counter and insert to ready list if ready.
2651         auto &&DecrUnsched = [this, &ReadyList](Instruction *I) {
2652           doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
2653             if (OpDef && OpDef->hasValidDependencies() &&
2654                 OpDef->incrementUnscheduledDeps(-1) == 0) {
2655               // There are no more unscheduled dependencies after
2656               // decrementing, so we can put the dependent instruction
2657               // into the ready list.
2658               ScheduleData *DepBundle = OpDef->FirstInBundle;
2659               assert(!DepBundle->IsScheduled &&
2660                      "already scheduled bundle gets ready");
2661               ReadyList.insert(DepBundle);
2662               LLVM_DEBUG(dbgs()
2663                          << "SLP:    gets ready (def): " << *DepBundle << "\n");
2664             }
2665           });
2666         };
2667 
2668         // If BundleMember is a vector bundle, its operands may have been
2669         // reordered duiring buildTree(). We therefore need to get its operands
2670         // through the TreeEntry.
2671         if (TreeEntry *TE = BundleMember->TE) {
2672           int Lane = BundleMember->Lane;
2673           assert(Lane >= 0 && "Lane not set");
2674 
2675           // Since vectorization tree is being built recursively this assertion
2676           // ensures that the tree entry has all operands set before reaching
2677           // this code. Couple of exceptions known at the moment are extracts
2678           // where their second (immediate) operand is not added. Since
2679           // immediates do not affect scheduler behavior this is considered
2680           // okay.
2681           auto *In = TE->getMainOp();
2682           assert(In &&
2683                  (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) ||
2684                   In->getNumOperands() == TE->getNumOperands()) &&
2685                  "Missed TreeEntry operands?");
2686           (void)In; // fake use to avoid build failure when assertions disabled
2687 
2688           for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands();
2689                OpIdx != NumOperands; ++OpIdx)
2690             if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane]))
2691               DecrUnsched(I);
2692         } else {
2693           // If BundleMember is a stand-alone instruction, no operand reordering
2694           // has taken place, so we directly access its operands.
2695           for (Use &U : BundleMember->Inst->operands())
2696             if (auto *I = dyn_cast<Instruction>(U.get()))
2697               DecrUnsched(I);
2698         }
2699         // Handle the memory dependencies.
2700         for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
2701           if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
2702             // There are no more unscheduled dependencies after decrementing,
2703             // so we can put the dependent instruction into the ready list.
2704             ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
2705             assert(!DepBundle->IsScheduled &&
2706                    "already scheduled bundle gets ready");
2707             ReadyList.insert(DepBundle);
2708             LLVM_DEBUG(dbgs()
2709                        << "SLP:    gets ready (mem): " << *DepBundle << "\n");
2710           }
2711         }
2712       }
2713     }
2714 
2715     void doForAllOpcodes(Value *V,
2716                          function_ref<void(ScheduleData *SD)> Action) {
2717       if (ScheduleData *SD = getScheduleData(V))
2718         Action(SD);
2719       auto I = ExtraScheduleDataMap.find(V);
2720       if (I != ExtraScheduleDataMap.end())
2721         for (auto &P : I->second)
2722           if (P.second->SchedulingRegionID == SchedulingRegionID)
2723             Action(P.second);
2724     }
2725 
2726     /// Put all instructions into the ReadyList which are ready for scheduling.
2727     template <typename ReadyListType>
2728     void initialFillReadyList(ReadyListType &ReadyList) {
2729       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2730         doForAllOpcodes(I, [&](ScheduleData *SD) {
2731           if (SD->isSchedulingEntity() && SD->isReady()) {
2732             ReadyList.insert(SD);
2733             LLVM_DEBUG(dbgs()
2734                        << "SLP:    initially in ready list: " << *I << "\n");
2735           }
2736         });
2737       }
2738     }
2739 
2740     /// Build a bundle from the ScheduleData nodes corresponding to the
2741     /// scalar instruction for each lane.
2742     ScheduleData *buildBundle(ArrayRef<Value *> VL);
2743 
2744     /// Checks if a bundle of instructions can be scheduled, i.e. has no
2745     /// cyclic dependencies. This is only a dry-run, no instructions are
2746     /// actually moved at this stage.
2747     /// \returns the scheduling bundle. The returned Optional value is non-None
2748     /// if \p VL is allowed to be scheduled.
2749     Optional<ScheduleData *>
2750     tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
2751                       const InstructionsState &S);
2752 
2753     /// Un-bundles a group of instructions.
2754     void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
2755 
2756     /// Allocates schedule data chunk.
2757     ScheduleData *allocateScheduleDataChunks();
2758 
2759     /// Extends the scheduling region so that V is inside the region.
2760     /// \returns true if the region size is within the limit.
2761     bool extendSchedulingRegion(Value *V, const InstructionsState &S);
2762 
2763     /// Initialize the ScheduleData structures for new instructions in the
2764     /// scheduling region.
2765     void initScheduleData(Instruction *FromI, Instruction *ToI,
2766                           ScheduleData *PrevLoadStore,
2767                           ScheduleData *NextLoadStore);
2768 
2769     /// Updates the dependency information of a bundle and of all instructions/
2770     /// bundles which depend on the original bundle.
2771     void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
2772                                BoUpSLP *SLP);
2773 
2774     /// Sets all instruction in the scheduling region to un-scheduled.
2775     void resetSchedule();
2776 
2777     BasicBlock *BB;
2778 
2779     /// Simple memory allocation for ScheduleData.
2780     std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
2781 
2782     /// The size of a ScheduleData array in ScheduleDataChunks.
2783     int ChunkSize;
2784 
2785     /// The allocator position in the current chunk, which is the last entry
2786     /// of ScheduleDataChunks.
2787     int ChunkPos;
2788 
2789     /// Attaches ScheduleData to Instruction.
2790     /// Note that the mapping survives during all vectorization iterations, i.e.
2791     /// ScheduleData structures are recycled.
2792     DenseMap<Value *, ScheduleData *> ScheduleDataMap;
2793 
2794     /// Attaches ScheduleData to Instruction with the leading key.
2795     DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
2796         ExtraScheduleDataMap;
2797 
2798     struct ReadyList : SmallVector<ScheduleData *, 8> {
2799       void insert(ScheduleData *SD) { push_back(SD); }
2800     };
2801 
2802     /// The ready-list for scheduling (only used for the dry-run).
2803     ReadyList ReadyInsts;
2804 
2805     /// The first instruction of the scheduling region.
2806     Instruction *ScheduleStart = nullptr;
2807 
2808     /// The first instruction _after_ the scheduling region.
2809     Instruction *ScheduleEnd = nullptr;
2810 
2811     /// The first memory accessing instruction in the scheduling region
2812     /// (can be null).
2813     ScheduleData *FirstLoadStoreInRegion = nullptr;
2814 
2815     /// The last memory accessing instruction in the scheduling region
2816     /// (can be null).
2817     ScheduleData *LastLoadStoreInRegion = nullptr;
2818 
2819     /// The current size of the scheduling region.
2820     int ScheduleRegionSize = 0;
2821 
2822     /// The maximum size allowed for the scheduling region.
2823     int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
2824 
2825     /// The ID of the scheduling region. For a new vectorization iteration this
2826     /// is incremented which "removes" all ScheduleData from the region.
2827     // Make sure that the initial SchedulingRegionID is greater than the
2828     // initial SchedulingRegionID in ScheduleData (which is 0).
2829     int SchedulingRegionID = 1;
2830   };
2831 
2832   /// Attaches the BlockScheduling structures to basic blocks.
2833   MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
2834 
2835   /// Performs the "real" scheduling. Done before vectorization is actually
2836   /// performed in a basic block.
2837   void scheduleBlock(BlockScheduling *BS);
2838 
2839   /// List of users to ignore during scheduling and that don't need extracting.
2840   ArrayRef<Value *> UserIgnoreList;
2841 
2842   /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
2843   /// sorted SmallVectors of unsigned.
2844   struct OrdersTypeDenseMapInfo {
2845     static OrdersType getEmptyKey() {
2846       OrdersType V;
2847       V.push_back(~1U);
2848       return V;
2849     }
2850 
2851     static OrdersType getTombstoneKey() {
2852       OrdersType V;
2853       V.push_back(~2U);
2854       return V;
2855     }
2856 
2857     static unsigned getHashValue(const OrdersType &V) {
2858       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
2859     }
2860 
2861     static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
2862       return LHS == RHS;
2863     }
2864   };
2865 
2866   // Analysis and block reference.
2867   Function *F;
2868   ScalarEvolution *SE;
2869   TargetTransformInfo *TTI;
2870   TargetLibraryInfo *TLI;
2871   AAResults *AA;
2872   LoopInfo *LI;
2873   DominatorTree *DT;
2874   AssumptionCache *AC;
2875   DemandedBits *DB;
2876   const DataLayout *DL;
2877   OptimizationRemarkEmitter *ORE;
2878 
2879   unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
2880   unsigned MinVecRegSize; // Set by cl::opt (default: 128).
2881 
2882   /// Instruction builder to construct the vectorized tree.
2883   IRBuilder<> Builder;
2884 
2885   /// A map of scalar integer values to the smallest bit width with which they
2886   /// can legally be represented. The values map to (width, signed) pairs,
2887   /// where "width" indicates the minimum bit width and "signed" is True if the
2888   /// value must be signed-extended, rather than zero-extended, back to its
2889   /// original width.
2890   MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
2891 };
2892 
2893 } // end namespace slpvectorizer
2894 
2895 template <> struct GraphTraits<BoUpSLP *> {
2896   using TreeEntry = BoUpSLP::TreeEntry;
2897 
2898   /// NodeRef has to be a pointer per the GraphWriter.
2899   using NodeRef = TreeEntry *;
2900 
2901   using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy;
2902 
2903   /// Add the VectorizableTree to the index iterator to be able to return
2904   /// TreeEntry pointers.
2905   struct ChildIteratorType
2906       : public iterator_adaptor_base<
2907             ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
2908     ContainerTy &VectorizableTree;
2909 
2910     ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W,
2911                       ContainerTy &VT)
2912         : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
2913 
2914     NodeRef operator*() { return I->UserTE; }
2915   };
2916 
2917   static NodeRef getEntryNode(BoUpSLP &R) {
2918     return R.VectorizableTree[0].get();
2919   }
2920 
2921   static ChildIteratorType child_begin(NodeRef N) {
2922     return {N->UserTreeIndices.begin(), N->Container};
2923   }
2924 
2925   static ChildIteratorType child_end(NodeRef N) {
2926     return {N->UserTreeIndices.end(), N->Container};
2927   }
2928 
2929   /// For the node iterator we just need to turn the TreeEntry iterator into a
2930   /// TreeEntry* iterator so that it dereferences to NodeRef.
2931   class nodes_iterator {
2932     using ItTy = ContainerTy::iterator;
2933     ItTy It;
2934 
2935   public:
2936     nodes_iterator(const ItTy &It2) : It(It2) {}
2937     NodeRef operator*() { return It->get(); }
2938     nodes_iterator operator++() {
2939       ++It;
2940       return *this;
2941     }
2942     bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
2943   };
2944 
2945   static nodes_iterator nodes_begin(BoUpSLP *R) {
2946     return nodes_iterator(R->VectorizableTree.begin());
2947   }
2948 
2949   static nodes_iterator nodes_end(BoUpSLP *R) {
2950     return nodes_iterator(R->VectorizableTree.end());
2951   }
2952 
2953   static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
2954 };
2955 
2956 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
2957   using TreeEntry = BoUpSLP::TreeEntry;
2958 
2959   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
2960 
2961   std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
2962     std::string Str;
2963     raw_string_ostream OS(Str);
2964     if (isSplat(Entry->Scalars))
2965       OS << "<splat> ";
2966     for (auto V : Entry->Scalars) {
2967       OS << *V;
2968       if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) {
2969             return EU.Scalar == V;
2970           }))
2971         OS << " <extract>";
2972       OS << "\n";
2973     }
2974     return Str;
2975   }
2976 
2977   static std::string getNodeAttributes(const TreeEntry *Entry,
2978                                        const BoUpSLP *) {
2979     if (Entry->State == TreeEntry::NeedToGather)
2980       return "color=red";
2981     return "";
2982   }
2983 };
2984 
2985 } // end namespace llvm
2986 
2987 BoUpSLP::~BoUpSLP() {
2988   for (const auto &Pair : DeletedInstructions) {
2989     // Replace operands of ignored instructions with Undefs in case if they were
2990     // marked for deletion.
2991     if (Pair.getSecond()) {
2992       Value *Undef = UndefValue::get(Pair.getFirst()->getType());
2993       Pair.getFirst()->replaceAllUsesWith(Undef);
2994     }
2995     Pair.getFirst()->dropAllReferences();
2996   }
2997   for (const auto &Pair : DeletedInstructions) {
2998     assert(Pair.getFirst()->use_empty() &&
2999            "trying to erase instruction with users.");
3000     Pair.getFirst()->eraseFromParent();
3001   }
3002 #ifdef EXPENSIVE_CHECKS
3003   // If we could guarantee that this call is not extremely slow, we could
3004   // remove the ifdef limitation (see PR47712).
3005   assert(!verifyFunction(*F, &dbgs()));
3006 #endif
3007 }
3008 
3009 void BoUpSLP::eraseInstructions(ArrayRef<Value *> AV) {
3010   for (auto *V : AV) {
3011     if (auto *I = dyn_cast<Instruction>(V))
3012       eraseInstruction(I, /*ReplaceOpsWithUndef=*/true);
3013   };
3014 }
3015 
3016 /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses
3017 /// contains original mask for the scalars reused in the node. Procedure
3018 /// transform this mask in accordance with the given \p Mask.
3019 static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) {
3020   assert(!Mask.empty() && Reuses.size() == Mask.size() &&
3021          "Expected non-empty mask.");
3022   SmallVector<int> Prev(Reuses.begin(), Reuses.end());
3023   Prev.swap(Reuses);
3024   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
3025     if (Mask[I] != UndefMaskElem)
3026       Reuses[Mask[I]] = Prev[I];
3027 }
3028 
3029 /// Reorders the given \p Order according to the given \p Mask. \p Order - is
3030 /// the original order of the scalars. Procedure transforms the provided order
3031 /// in accordance with the given \p Mask. If the resulting \p Order is just an
3032 /// identity order, \p Order is cleared.
3033 static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) {
3034   assert(!Mask.empty() && "Expected non-empty mask.");
3035   SmallVector<int> MaskOrder;
3036   if (Order.empty()) {
3037     MaskOrder.resize(Mask.size());
3038     std::iota(MaskOrder.begin(), MaskOrder.end(), 0);
3039   } else {
3040     inversePermutation(Order, MaskOrder);
3041   }
3042   reorderReuses(MaskOrder, Mask);
3043   if (ShuffleVectorInst::isIdentityMask(MaskOrder)) {
3044     Order.clear();
3045     return;
3046   }
3047   Order.assign(Mask.size(), Mask.size());
3048   for (unsigned I = 0, E = Mask.size(); I < E; ++I)
3049     if (MaskOrder[I] != UndefMaskElem)
3050       Order[MaskOrder[I]] = I;
3051   fixupOrderingIndices(Order);
3052 }
3053 
3054 Optional<BoUpSLP::OrdersType>
3055 BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) {
3056   assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
3057   unsigned NumScalars = TE.Scalars.size();
3058   OrdersType CurrentOrder(NumScalars, NumScalars);
3059   SmallVector<int> Positions;
3060   SmallBitVector UsedPositions(NumScalars);
3061   const TreeEntry *STE = nullptr;
3062   // Try to find all gathered scalars that are gets vectorized in other
3063   // vectorize node. Here we can have only one single tree vector node to
3064   // correctly identify order of the gathered scalars.
3065   for (unsigned I = 0; I < NumScalars; ++I) {
3066     Value *V = TE.Scalars[I];
3067     if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V))
3068       continue;
3069     if (const auto *LocalSTE = getTreeEntry(V)) {
3070       if (!STE)
3071         STE = LocalSTE;
3072       else if (STE != LocalSTE)
3073         // Take the order only from the single vector node.
3074         return None;
3075       unsigned Lane =
3076           std::distance(STE->Scalars.begin(), find(STE->Scalars, V));
3077       if (Lane >= NumScalars)
3078         return None;
3079       if (CurrentOrder[Lane] != NumScalars) {
3080         if (Lane != I)
3081           continue;
3082         UsedPositions.reset(CurrentOrder[Lane]);
3083       }
3084       // The partial identity (where only some elements of the gather node are
3085       // in the identity order) is good.
3086       CurrentOrder[Lane] = I;
3087       UsedPositions.set(I);
3088     }
3089   }
3090   // Need to keep the order if we have a vector entry and at least 2 scalars or
3091   // the vectorized entry has just 2 scalars.
3092   if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) {
3093     auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) {
3094       for (unsigned I = 0; I < NumScalars; ++I)
3095         if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars)
3096           return false;
3097       return true;
3098     };
3099     if (IsIdentityOrder(CurrentOrder)) {
3100       CurrentOrder.clear();
3101       return CurrentOrder;
3102     }
3103     auto *It = CurrentOrder.begin();
3104     for (unsigned I = 0; I < NumScalars;) {
3105       if (UsedPositions.test(I)) {
3106         ++I;
3107         continue;
3108       }
3109       if (*It == NumScalars) {
3110         *It = I;
3111         ++I;
3112       }
3113       ++It;
3114     }
3115     return CurrentOrder;
3116   }
3117   return None;
3118 }
3119 
3120 Optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE,
3121                                                          bool TopToBottom) {
3122   // No need to reorder if need to shuffle reuses, still need to shuffle the
3123   // node.
3124   if (!TE.ReuseShuffleIndices.empty())
3125     return None;
3126   if (TE.State == TreeEntry::Vectorize &&
3127       (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) ||
3128        (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) &&
3129       !TE.isAltShuffle())
3130     return TE.ReorderIndices;
3131   if (TE.State == TreeEntry::NeedToGather) {
3132     // TODO: add analysis of other gather nodes with extractelement
3133     // instructions and other values/instructions, not only undefs.
3134     if (((TE.getOpcode() == Instruction::ExtractElement &&
3135           !TE.isAltShuffle()) ||
3136          (all_of(TE.Scalars,
3137                  [](Value *V) {
3138                    return isa<UndefValue, ExtractElementInst>(V);
3139                  }) &&
3140           any_of(TE.Scalars,
3141                  [](Value *V) { return isa<ExtractElementInst>(V); }))) &&
3142         all_of(TE.Scalars,
3143                [](Value *V) {
3144                  auto *EE = dyn_cast<ExtractElementInst>(V);
3145                  return !EE || isa<FixedVectorType>(EE->getVectorOperandType());
3146                }) &&
3147         allSameType(TE.Scalars)) {
3148       // Check that gather of extractelements can be represented as
3149       // just a shuffle of a single vector.
3150       OrdersType CurrentOrder;
3151       bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder);
3152       if (Reuse || !CurrentOrder.empty()) {
3153         if (!CurrentOrder.empty())
3154           fixupOrderingIndices(CurrentOrder);
3155         return CurrentOrder;
3156       }
3157     }
3158     if (Optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE))
3159       return CurrentOrder;
3160   }
3161   return None;
3162 }
3163 
3164 void BoUpSLP::reorderTopToBottom() {
3165   // Maps VF to the graph nodes.
3166   DenseMap<unsigned, SetVector<TreeEntry *>> VFToOrderedEntries;
3167   // ExtractElement gather nodes which can be vectorized and need to handle
3168   // their ordering.
3169   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3170   // Find all reorderable nodes with the given VF.
3171   // Currently the are vectorized stores,loads,extracts + some gathering of
3172   // extracts.
3173   for_each(VectorizableTree, [this, &VFToOrderedEntries, &GathersToOrders](
3174                                  const std::unique_ptr<TreeEntry> &TE) {
3175     if (Optional<OrdersType> CurrentOrder =
3176             getReorderingData(*TE.get(), /*TopToBottom=*/true)) {
3177       // Do not include ordering for nodes used in the alt opcode vectorization,
3178       // better to reorder them during bottom-to-top stage. If follow the order
3179       // here, it causes reordering of the whole graph though actually it is
3180       // profitable just to reorder the subgraph that starts from the alternate
3181       // opcode vectorization node. Such nodes already end-up with the shuffle
3182       // instruction and it is just enough to change this shuffle rather than
3183       // rotate the scalars for the whole graph.
3184       unsigned Cnt = 0;
3185       const TreeEntry *UserTE = TE.get();
3186       while (UserTE && Cnt < RecursionMaxDepth) {
3187         if (UserTE->UserTreeIndices.size() != 1)
3188           break;
3189         if (all_of(UserTE->UserTreeIndices, [](const EdgeInfo &EI) {
3190               return EI.UserTE->State == TreeEntry::Vectorize &&
3191                      EI.UserTE->isAltShuffle() && EI.UserTE->Idx != 0;
3192             }))
3193           return;
3194         if (UserTE->UserTreeIndices.empty())
3195           UserTE = nullptr;
3196         else
3197           UserTE = UserTE->UserTreeIndices.back().UserTE;
3198         ++Cnt;
3199       }
3200       VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
3201       if (TE->State != TreeEntry::Vectorize)
3202         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3203     }
3204   });
3205 
3206   // Reorder the graph nodes according to their vectorization factor.
3207   for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1;
3208        VF /= 2) {
3209     auto It = VFToOrderedEntries.find(VF);
3210     if (It == VFToOrderedEntries.end())
3211       continue;
3212     // Try to find the most profitable order. We just are looking for the most
3213     // used order and reorder scalar elements in the nodes according to this
3214     // mostly used order.
3215     ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef();
3216     // All operands are reordered and used only in this node - propagate the
3217     // most used order to the user node.
3218     MapVector<OrdersType, unsigned,
3219               DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3220         OrdersUses;
3221     SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3222     for (const TreeEntry *OpTE : OrderedEntries) {
3223       // No need to reorder this nodes, still need to extend and to use shuffle,
3224       // just need to merge reordering shuffle and the reuse shuffle.
3225       if (!OpTE->ReuseShuffleIndices.empty())
3226         continue;
3227       // Count number of orders uses.
3228       const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3229         if (OpTE->State == TreeEntry::NeedToGather)
3230           return GathersToOrders.find(OpTE)->second;
3231         return OpTE->ReorderIndices;
3232       }();
3233       // Stores actually store the mask, not the order, need to invert.
3234       if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3235           OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3236         SmallVector<int> Mask;
3237         inversePermutation(Order, Mask);
3238         unsigned E = Order.size();
3239         OrdersType CurrentOrder(E, E);
3240         transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3241           return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3242         });
3243         fixupOrderingIndices(CurrentOrder);
3244         ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
3245       } else {
3246         ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
3247       }
3248     }
3249     // Set order of the user node.
3250     if (OrdersUses.empty())
3251       continue;
3252     // Choose the most used order.
3253     ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3254     unsigned Cnt = OrdersUses.front().second;
3255     for (const auto &Pair : drop_begin(OrdersUses)) {
3256       if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3257         BestOrder = Pair.first;
3258         Cnt = Pair.second;
3259       }
3260     }
3261     // Set order of the user node.
3262     if (BestOrder.empty())
3263       continue;
3264     SmallVector<int> Mask;
3265     inversePermutation(BestOrder, Mask);
3266     SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3267     unsigned E = BestOrder.size();
3268     transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3269       return I < E ? static_cast<int>(I) : UndefMaskElem;
3270     });
3271     // Do an actual reordering, if profitable.
3272     for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
3273       // Just do the reordering for the nodes with the given VF.
3274       if (TE->Scalars.size() != VF) {
3275         if (TE->ReuseShuffleIndices.size() == VF) {
3276           // Need to reorder the reuses masks of the operands with smaller VF to
3277           // be able to find the match between the graph nodes and scalar
3278           // operands of the given node during vectorization/cost estimation.
3279           assert(all_of(TE->UserTreeIndices,
3280                         [VF, &TE](const EdgeInfo &EI) {
3281                           return EI.UserTE->Scalars.size() == VF ||
3282                                  EI.UserTE->Scalars.size() ==
3283                                      TE->Scalars.size();
3284                         }) &&
3285                  "All users must be of VF size.");
3286           // Update ordering of the operands with the smaller VF than the given
3287           // one.
3288           reorderReuses(TE->ReuseShuffleIndices, Mask);
3289         }
3290         continue;
3291       }
3292       if (TE->State == TreeEntry::Vectorize &&
3293           isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst,
3294               InsertElementInst>(TE->getMainOp()) &&
3295           !TE->isAltShuffle()) {
3296         // Build correct orders for extract{element,value}, loads and
3297         // stores.
3298         reorderOrder(TE->ReorderIndices, Mask);
3299         if (isa<InsertElementInst, StoreInst>(TE->getMainOp()))
3300           TE->reorderOperands(Mask);
3301       } else {
3302         // Reorder the node and its operands.
3303         TE->reorderOperands(Mask);
3304         assert(TE->ReorderIndices.empty() &&
3305                "Expected empty reorder sequence.");
3306         reorderScalars(TE->Scalars, Mask);
3307       }
3308       if (!TE->ReuseShuffleIndices.empty()) {
3309         // Apply reversed order to keep the original ordering of the reused
3310         // elements to avoid extra reorder indices shuffling.
3311         OrdersType CurrentOrder;
3312         reorderOrder(CurrentOrder, MaskOrder);
3313         SmallVector<int> NewReuses;
3314         inversePermutation(CurrentOrder, NewReuses);
3315         addMask(NewReuses, TE->ReuseShuffleIndices);
3316         TE->ReuseShuffleIndices.swap(NewReuses);
3317       }
3318     }
3319   }
3320 }
3321 
3322 void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) {
3323   SetVector<TreeEntry *> OrderedEntries;
3324   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3325   // Find all reorderable leaf nodes with the given VF.
3326   // Currently the are vectorized loads,extracts without alternate operands +
3327   // some gathering of extracts.
3328   SmallVector<TreeEntry *> NonVectorized;
3329   for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders,
3330                               &NonVectorized](
3331                                  const std::unique_ptr<TreeEntry> &TE) {
3332     if (TE->State != TreeEntry::Vectorize)
3333       NonVectorized.push_back(TE.get());
3334     if (Optional<OrdersType> CurrentOrder =
3335             getReorderingData(*TE.get(), /*TopToBottom=*/false)) {
3336       OrderedEntries.insert(TE.get());
3337       if (TE->State != TreeEntry::Vectorize)
3338         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3339     }
3340   });
3341 
3342   // Checks if the operands of the users are reordarable and have only single
3343   // use.
3344   auto &&CheckOperands =
3345       [this, &NonVectorized](const auto &Data,
3346                              SmallVectorImpl<TreeEntry *> &GatherOps) {
3347         for (unsigned I = 0, E = Data.first->getNumOperands(); I < E; ++I) {
3348           if (any_of(Data.second,
3349                      [I](const std::pair<unsigned, TreeEntry *> &OpData) {
3350                        return OpData.first == I &&
3351                               OpData.second->State == TreeEntry::Vectorize;
3352                      }))
3353             continue;
3354           ArrayRef<Value *> VL = Data.first->getOperand(I);
3355           const TreeEntry *TE = nullptr;
3356           const auto *It = find_if(VL, [this, &TE](Value *V) {
3357             TE = getTreeEntry(V);
3358             return TE;
3359           });
3360           if (It != VL.end() && TE->isSame(VL))
3361             return false;
3362           TreeEntry *Gather = nullptr;
3363           if (count_if(NonVectorized, [VL, &Gather](TreeEntry *TE) {
3364                 assert(TE->State != TreeEntry::Vectorize &&
3365                        "Only non-vectorized nodes are expected.");
3366                 if (TE->isSame(VL)) {
3367                   Gather = TE;
3368                   return true;
3369                 }
3370                 return false;
3371               }) > 1)
3372             return false;
3373           if (Gather)
3374             GatherOps.push_back(Gather);
3375         }
3376         return true;
3377       };
3378   // 1. Propagate order to the graph nodes, which use only reordered nodes.
3379   // I.e., if the node has operands, that are reordered, try to make at least
3380   // one operand order in the natural order and reorder others + reorder the
3381   // user node itself.
3382   SmallPtrSet<const TreeEntry *, 4> Visited;
3383   while (!OrderedEntries.empty()) {
3384     // 1. Filter out only reordered nodes.
3385     // 2. If the entry has multiple uses - skip it and jump to the next node.
3386     MapVector<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users;
3387     SmallVector<TreeEntry *> Filtered;
3388     for (TreeEntry *TE : OrderedEntries) {
3389       if (!(TE->State == TreeEntry::Vectorize ||
3390             (TE->State == TreeEntry::NeedToGather &&
3391              GathersToOrders.count(TE))) ||
3392           TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3393           !all_of(drop_begin(TE->UserTreeIndices),
3394                   [TE](const EdgeInfo &EI) {
3395                     return EI.UserTE == TE->UserTreeIndices.front().UserTE;
3396                   }) ||
3397           !Visited.insert(TE).second) {
3398         Filtered.push_back(TE);
3399         continue;
3400       }
3401       // Build a map between user nodes and their operands order to speedup
3402       // search. The graph currently does not provide this dependency directly.
3403       for (EdgeInfo &EI : TE->UserTreeIndices) {
3404         TreeEntry *UserTE = EI.UserTE;
3405         auto It = Users.find(UserTE);
3406         if (It == Users.end())
3407           It = Users.insert({UserTE, {}}).first;
3408         It->second.emplace_back(EI.EdgeIdx, TE);
3409       }
3410     }
3411     // Erase filtered entries.
3412     for_each(Filtered,
3413              [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); });
3414     for (const auto &Data : Users) {
3415       // Check that operands are used only in the User node.
3416       SmallVector<TreeEntry *> GatherOps;
3417       if (!CheckOperands(Data, GatherOps)) {
3418         for_each(Data.second,
3419                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3420                    OrderedEntries.remove(Op.second);
3421                  });
3422         continue;
3423       }
3424       // All operands are reordered and used only in this node - propagate the
3425       // most used order to the user node.
3426       MapVector<OrdersType, unsigned,
3427                 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3428           OrdersUses;
3429       // Do the analysis for each tree entry only once, otherwise the order of
3430       // the same node my be considered several times, though might be not
3431       // profitable.
3432       SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3433       for (const auto &Op : Data.second) {
3434         TreeEntry *OpTE = Op.second;
3435         if (!VisitedOps.insert(OpTE).second)
3436           continue;
3437         if (!OpTE->ReuseShuffleIndices.empty() ||
3438             (IgnoreReorder && OpTE == VectorizableTree.front().get()))
3439           continue;
3440         const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3441           if (OpTE->State == TreeEntry::NeedToGather)
3442             return GathersToOrders.find(OpTE)->second;
3443           return OpTE->ReorderIndices;
3444         }();
3445         // Stores actually store the mask, not the order, need to invert.
3446         if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3447             OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3448           SmallVector<int> Mask;
3449           inversePermutation(Order, Mask);
3450           unsigned E = Order.size();
3451           OrdersType CurrentOrder(E, E);
3452           transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3453             return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3454           });
3455           fixupOrderingIndices(CurrentOrder);
3456           ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
3457         } else {
3458           ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
3459         }
3460         OrdersUses.insert(std::make_pair(OrdersType(), 0)).first->second +=
3461             OpTE->UserTreeIndices.size();
3462         assert(OrdersUses[{}] > 0 && "Counter cannot be less than 0.");
3463         --OrdersUses[{}];
3464       }
3465       // If no orders - skip current nodes and jump to the next one, if any.
3466       if (OrdersUses.empty()) {
3467         for_each(Data.second,
3468                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3469                    OrderedEntries.remove(Op.second);
3470                  });
3471         continue;
3472       }
3473       // Choose the best order.
3474       ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3475       unsigned Cnt = OrdersUses.front().second;
3476       for (const auto &Pair : drop_begin(OrdersUses)) {
3477         if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3478           BestOrder = Pair.first;
3479           Cnt = Pair.second;
3480         }
3481       }
3482       // Set order of the user node (reordering of operands and user nodes).
3483       if (BestOrder.empty()) {
3484         for_each(Data.second,
3485                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3486                    OrderedEntries.remove(Op.second);
3487                  });
3488         continue;
3489       }
3490       // Erase operands from OrderedEntries list and adjust their orders.
3491       VisitedOps.clear();
3492       SmallVector<int> Mask;
3493       inversePermutation(BestOrder, Mask);
3494       SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3495       unsigned E = BestOrder.size();
3496       transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3497         return I < E ? static_cast<int>(I) : UndefMaskElem;
3498       });
3499       for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) {
3500         TreeEntry *TE = Op.second;
3501         OrderedEntries.remove(TE);
3502         if (!VisitedOps.insert(TE).second)
3503           continue;
3504         if (!TE->ReuseShuffleIndices.empty() && TE->ReorderIndices.empty()) {
3505           // Just reorder reuses indices.
3506           reorderReuses(TE->ReuseShuffleIndices, Mask);
3507           continue;
3508         }
3509         // Gathers are processed separately.
3510         if (TE->State != TreeEntry::Vectorize)
3511           continue;
3512         assert((BestOrder.size() == TE->ReorderIndices.size() ||
3513                 TE->ReorderIndices.empty()) &&
3514                "Non-matching sizes of user/operand entries.");
3515         reorderOrder(TE->ReorderIndices, Mask);
3516       }
3517       // For gathers just need to reorder its scalars.
3518       for (TreeEntry *Gather : GatherOps) {
3519         assert(Gather->ReorderIndices.empty() &&
3520                "Unexpected reordering of gathers.");
3521         if (!Gather->ReuseShuffleIndices.empty()) {
3522           // Just reorder reuses indices.
3523           reorderReuses(Gather->ReuseShuffleIndices, Mask);
3524           continue;
3525         }
3526         reorderScalars(Gather->Scalars, Mask);
3527         OrderedEntries.remove(Gather);
3528       }
3529       // Reorder operands of the user node and set the ordering for the user
3530       // node itself.
3531       if (Data.first->State != TreeEntry::Vectorize ||
3532           !isa<ExtractElementInst, ExtractValueInst, LoadInst>(
3533               Data.first->getMainOp()) ||
3534           Data.first->isAltShuffle())
3535         Data.first->reorderOperands(Mask);
3536       if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) ||
3537           Data.first->isAltShuffle()) {
3538         reorderScalars(Data.first->Scalars, Mask);
3539         reorderOrder(Data.first->ReorderIndices, MaskOrder);
3540         if (Data.first->ReuseShuffleIndices.empty() &&
3541             !Data.first->ReorderIndices.empty() &&
3542             !Data.first->isAltShuffle()) {
3543           // Insert user node to the list to try to sink reordering deeper in
3544           // the graph.
3545           OrderedEntries.insert(Data.first);
3546         }
3547       } else {
3548         reorderOrder(Data.first->ReorderIndices, Mask);
3549       }
3550     }
3551   }
3552   // If the reordering is unnecessary, just remove the reorder.
3553   if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() &&
3554       VectorizableTree.front()->ReuseShuffleIndices.empty())
3555     VectorizableTree.front()->ReorderIndices.clear();
3556 }
3557 
3558 void BoUpSLP::buildExternalUses(
3559     const ExtraValueToDebugLocsMap &ExternallyUsedValues) {
3560   // Collect the values that we need to extract from the tree.
3561   for (auto &TEPtr : VectorizableTree) {
3562     TreeEntry *Entry = TEPtr.get();
3563 
3564     // No need to handle users of gathered values.
3565     if (Entry->State == TreeEntry::NeedToGather)
3566       continue;
3567 
3568     // For each lane:
3569     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
3570       Value *Scalar = Entry->Scalars[Lane];
3571       int FoundLane = Entry->findLaneForValue(Scalar);
3572 
3573       // Check if the scalar is externally used as an extra arg.
3574       auto ExtI = ExternallyUsedValues.find(Scalar);
3575       if (ExtI != ExternallyUsedValues.end()) {
3576         LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
3577                           << Lane << " from " << *Scalar << ".\n");
3578         ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
3579       }
3580       for (User *U : Scalar->users()) {
3581         LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
3582 
3583         Instruction *UserInst = dyn_cast<Instruction>(U);
3584         if (!UserInst)
3585           continue;
3586 
3587         if (isDeleted(UserInst))
3588           continue;
3589 
3590         // Skip in-tree scalars that become vectors
3591         if (TreeEntry *UseEntry = getTreeEntry(U)) {
3592           Value *UseScalar = UseEntry->Scalars[0];
3593           // Some in-tree scalars will remain as scalar in vectorized
3594           // instructions. If that is the case, the one in Lane 0 will
3595           // be used.
3596           if (UseScalar != U ||
3597               UseEntry->State == TreeEntry::ScatterVectorize ||
3598               !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
3599             LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
3600                               << ".\n");
3601             assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state");
3602             continue;
3603           }
3604         }
3605 
3606         // Ignore users in the user ignore list.
3607         if (is_contained(UserIgnoreList, UserInst))
3608           continue;
3609 
3610         LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
3611                           << Lane << " from " << *Scalar << ".\n");
3612         ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
3613       }
3614     }
3615   }
3616 }
3617 
3618 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
3619                         ArrayRef<Value *> UserIgnoreLst) {
3620   deleteTree();
3621   UserIgnoreList = UserIgnoreLst;
3622   if (!allSameType(Roots))
3623     return;
3624   buildTree_rec(Roots, 0, EdgeInfo());
3625 }
3626 
3627 namespace {
3628 /// Tracks the state we can represent the loads in the given sequence.
3629 enum class LoadsState { Gather, Vectorize, ScatterVectorize };
3630 } // anonymous namespace
3631 
3632 /// Checks if the given array of loads can be represented as a vectorized,
3633 /// scatter or just simple gather.
3634 static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0,
3635                                     const TargetTransformInfo &TTI,
3636                                     const DataLayout &DL, ScalarEvolution &SE,
3637                                     SmallVectorImpl<unsigned> &Order,
3638                                     SmallVectorImpl<Value *> &PointerOps) {
3639   // Check that a vectorized load would load the same memory as a scalar
3640   // load. For example, we don't want to vectorize loads that are smaller
3641   // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
3642   // treats loading/storing it as an i8 struct. If we vectorize loads/stores
3643   // from such a struct, we read/write packed bits disagreeing with the
3644   // unvectorized version.
3645   Type *ScalarTy = VL0->getType();
3646 
3647   if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy))
3648     return LoadsState::Gather;
3649 
3650   // Make sure all loads in the bundle are simple - we can't vectorize
3651   // atomic or volatile loads.
3652   PointerOps.clear();
3653   PointerOps.resize(VL.size());
3654   auto *POIter = PointerOps.begin();
3655   for (Value *V : VL) {
3656     auto *L = cast<LoadInst>(V);
3657     if (!L->isSimple())
3658       return LoadsState::Gather;
3659     *POIter = L->getPointerOperand();
3660     ++POIter;
3661   }
3662 
3663   Order.clear();
3664   // Check the order of pointer operands.
3665   if (llvm::sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order)) {
3666     Value *Ptr0;
3667     Value *PtrN;
3668     if (Order.empty()) {
3669       Ptr0 = PointerOps.front();
3670       PtrN = PointerOps.back();
3671     } else {
3672       Ptr0 = PointerOps[Order.front()];
3673       PtrN = PointerOps[Order.back()];
3674     }
3675     Optional<int> Diff =
3676         getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE);
3677     // Check that the sorted loads are consecutive.
3678     if (static_cast<unsigned>(*Diff) == VL.size() - 1)
3679       return LoadsState::Vectorize;
3680     Align CommonAlignment = cast<LoadInst>(VL0)->getAlign();
3681     for (Value *V : VL)
3682       CommonAlignment =
3683           commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
3684     if (TTI.isLegalMaskedGather(FixedVectorType::get(ScalarTy, VL.size()),
3685                                 CommonAlignment))
3686       return LoadsState::ScatterVectorize;
3687   }
3688 
3689   return LoadsState::Gather;
3690 }
3691 
3692 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
3693                             const EdgeInfo &UserTreeIdx) {
3694   assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
3695 
3696   SmallVector<int> ReuseShuffleIndicies;
3697   SmallVector<Value *> UniqueValues;
3698   auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues,
3699                                 &UserTreeIdx,
3700                                 this](const InstructionsState &S) {
3701     // Check that every instruction appears once in this bundle.
3702     DenseMap<Value *, unsigned> UniquePositions;
3703     for (Value *V : VL) {
3704       if (isConstant(V)) {
3705         ReuseShuffleIndicies.emplace_back(
3706             isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size());
3707         UniqueValues.emplace_back(V);
3708         continue;
3709       }
3710       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
3711       ReuseShuffleIndicies.emplace_back(Res.first->second);
3712       if (Res.second)
3713         UniqueValues.emplace_back(V);
3714     }
3715     size_t NumUniqueScalarValues = UniqueValues.size();
3716     if (NumUniqueScalarValues == VL.size()) {
3717       ReuseShuffleIndicies.clear();
3718     } else {
3719       LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
3720       if (NumUniqueScalarValues <= 1 ||
3721           (UniquePositions.size() == 1 && all_of(UniqueValues,
3722                                                  [](Value *V) {
3723                                                    return isa<UndefValue>(V) ||
3724                                                           !isConstant(V);
3725                                                  })) ||
3726           !llvm::isPowerOf2_32(NumUniqueScalarValues)) {
3727         LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
3728         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3729         return false;
3730       }
3731       VL = UniqueValues;
3732     }
3733     return true;
3734   };
3735 
3736   InstructionsState S = getSameOpcode(VL);
3737   if (Depth == RecursionMaxDepth) {
3738     LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
3739     if (TryToFindDuplicates(S))
3740       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3741                    ReuseShuffleIndicies);
3742     return;
3743   }
3744 
3745   // Don't handle scalable vectors
3746   if (S.getOpcode() == Instruction::ExtractElement &&
3747       isa<ScalableVectorType>(
3748           cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) {
3749     LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n");
3750     if (TryToFindDuplicates(S))
3751       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3752                    ReuseShuffleIndicies);
3753     return;
3754   }
3755 
3756   // Don't handle vectors.
3757   if (S.OpValue->getType()->isVectorTy() &&
3758       !isa<InsertElementInst>(S.OpValue)) {
3759     LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
3760     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3761     return;
3762   }
3763 
3764   if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
3765     if (SI->getValueOperand()->getType()->isVectorTy()) {
3766       LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
3767       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3768       return;
3769     }
3770 
3771   // If all of the operands are identical or constant we have a simple solution.
3772   // If we deal with insert/extract instructions, they all must have constant
3773   // indices, otherwise we should gather them, not try to vectorize.
3774   if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode() ||
3775       (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(S.MainOp) &&
3776        !all_of(VL, isVectorLikeInstWithConstOps))) {
3777     LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
3778     if (TryToFindDuplicates(S))
3779       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3780                    ReuseShuffleIndicies);
3781     return;
3782   }
3783 
3784   // We now know that this is a vector of instructions of the same type from
3785   // the same block.
3786 
3787   // Don't vectorize ephemeral values.
3788   for (Value *V : VL) {
3789     if (EphValues.count(V)) {
3790       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
3791                         << ") is ephemeral.\n");
3792       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3793       return;
3794     }
3795   }
3796 
3797   // Check if this is a duplicate of another entry.
3798   if (TreeEntry *E = getTreeEntry(S.OpValue)) {
3799     LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n");
3800     if (!E->isSame(VL)) {
3801       LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
3802       if (TryToFindDuplicates(S))
3803         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3804                      ReuseShuffleIndicies);
3805       return;
3806     }
3807     // Record the reuse of the tree node.  FIXME, currently this is only used to
3808     // properly draw the graph rather than for the actual vectorization.
3809     E->UserTreeIndices.push_back(UserTreeIdx);
3810     LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue
3811                       << ".\n");
3812     return;
3813   }
3814 
3815   // Check that none of the instructions in the bundle are already in the tree.
3816   for (Value *V : VL) {
3817     auto *I = dyn_cast<Instruction>(V);
3818     if (!I)
3819       continue;
3820     if (getTreeEntry(I)) {
3821       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
3822                         << ") is already in tree.\n");
3823       if (TryToFindDuplicates(S))
3824         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3825                      ReuseShuffleIndicies);
3826       return;
3827     }
3828   }
3829 
3830   // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
3831   for (Value *V : VL) {
3832     if (is_contained(UserIgnoreList, V)) {
3833       LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
3834       if (TryToFindDuplicates(S))
3835         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3836                      ReuseShuffleIndicies);
3837       return;
3838     }
3839   }
3840 
3841   // Check that all of the users of the scalars that we want to vectorize are
3842   // schedulable.
3843   auto *VL0 = cast<Instruction>(S.OpValue);
3844   BasicBlock *BB = VL0->getParent();
3845 
3846   if (!DT->isReachableFromEntry(BB)) {
3847     // Don't go into unreachable blocks. They may contain instructions with
3848     // dependency cycles which confuse the final scheduling.
3849     LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
3850     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3851     return;
3852   }
3853 
3854   // Check that every instruction appears once in this bundle.
3855   if (!TryToFindDuplicates(S))
3856     return;
3857 
3858   auto &BSRef = BlocksSchedules[BB];
3859   if (!BSRef)
3860     BSRef = std::make_unique<BlockScheduling>(BB);
3861 
3862   BlockScheduling &BS = *BSRef.get();
3863 
3864   Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S);
3865   if (!Bundle) {
3866     LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
3867     assert((!BS.getScheduleData(VL0) ||
3868             !BS.getScheduleData(VL0)->isPartOfBundle()) &&
3869            "tryScheduleBundle should cancelScheduling on failure");
3870     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3871                  ReuseShuffleIndicies);
3872     return;
3873   }
3874   LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
3875 
3876   unsigned ShuffleOrOp = S.isAltShuffle() ?
3877                 (unsigned) Instruction::ShuffleVector : S.getOpcode();
3878   switch (ShuffleOrOp) {
3879     case Instruction::PHI: {
3880       auto *PH = cast<PHINode>(VL0);
3881 
3882       // Check for terminator values (e.g. invoke).
3883       for (Value *V : VL)
3884         for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
3885           Instruction *Term = dyn_cast<Instruction>(
3886               cast<PHINode>(V)->getIncomingValueForBlock(
3887                   PH->getIncomingBlock(I)));
3888           if (Term && Term->isTerminator()) {
3889             LLVM_DEBUG(dbgs()
3890                        << "SLP: Need to swizzle PHINodes (terminator use).\n");
3891             BS.cancelScheduling(VL, VL0);
3892             newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3893                          ReuseShuffleIndicies);
3894             return;
3895           }
3896         }
3897 
3898       TreeEntry *TE =
3899           newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies);
3900       LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
3901 
3902       // Keeps the reordered operands to avoid code duplication.
3903       SmallVector<ValueList, 2> OperandsVec;
3904       for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
3905         if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) {
3906           ValueList Operands(VL.size(), PoisonValue::get(PH->getType()));
3907           TE->setOperand(I, Operands);
3908           OperandsVec.push_back(Operands);
3909           continue;
3910         }
3911         ValueList Operands;
3912         // Prepare the operand vector.
3913         for (Value *V : VL)
3914           Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(
3915               PH->getIncomingBlock(I)));
3916         TE->setOperand(I, Operands);
3917         OperandsVec.push_back(Operands);
3918       }
3919       for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx)
3920         buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx});
3921       return;
3922     }
3923     case Instruction::ExtractValue:
3924     case Instruction::ExtractElement: {
3925       OrdersType CurrentOrder;
3926       bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
3927       if (Reuse) {
3928         LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
3929         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3930                      ReuseShuffleIndicies);
3931         // This is a special case, as it does not gather, but at the same time
3932         // we are not extending buildTree_rec() towards the operands.
3933         ValueList Op0;
3934         Op0.assign(VL.size(), VL0->getOperand(0));
3935         VectorizableTree.back()->setOperand(0, Op0);
3936         return;
3937       }
3938       if (!CurrentOrder.empty()) {
3939         LLVM_DEBUG({
3940           dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
3941                     "with order";
3942           for (unsigned Idx : CurrentOrder)
3943             dbgs() << " " << Idx;
3944           dbgs() << "\n";
3945         });
3946         fixupOrderingIndices(CurrentOrder);
3947         // Insert new order with initial value 0, if it does not exist,
3948         // otherwise return the iterator to the existing one.
3949         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3950                      ReuseShuffleIndicies, CurrentOrder);
3951         // This is a special case, as it does not gather, but at the same time
3952         // we are not extending buildTree_rec() towards the operands.
3953         ValueList Op0;
3954         Op0.assign(VL.size(), VL0->getOperand(0));
3955         VectorizableTree.back()->setOperand(0, Op0);
3956         return;
3957       }
3958       LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
3959       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3960                    ReuseShuffleIndicies);
3961       BS.cancelScheduling(VL, VL0);
3962       return;
3963     }
3964     case Instruction::InsertElement: {
3965       assert(ReuseShuffleIndicies.empty() && "All inserts should be unique");
3966 
3967       // Check that we have a buildvector and not a shuffle of 2 or more
3968       // different vectors.
3969       ValueSet SourceVectors;
3970       int MinIdx = std::numeric_limits<int>::max();
3971       for (Value *V : VL) {
3972         SourceVectors.insert(cast<Instruction>(V)->getOperand(0));
3973         Optional<int> Idx = *getInsertIndex(V, 0);
3974         if (!Idx || *Idx == UndefMaskElem)
3975           continue;
3976         MinIdx = std::min(MinIdx, *Idx);
3977       }
3978 
3979       if (count_if(VL, [&SourceVectors](Value *V) {
3980             return !SourceVectors.contains(V);
3981           }) >= 2) {
3982         // Found 2nd source vector - cancel.
3983         LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with "
3984                              "different source vectors.\n");
3985         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3986         BS.cancelScheduling(VL, VL0);
3987         return;
3988       }
3989 
3990       auto OrdCompare = [](const std::pair<int, int> &P1,
3991                            const std::pair<int, int> &P2) {
3992         return P1.first > P2.first;
3993       };
3994       PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>,
3995                     decltype(OrdCompare)>
3996           Indices(OrdCompare);
3997       for (int I = 0, E = VL.size(); I < E; ++I) {
3998         Optional<int> Idx = *getInsertIndex(VL[I], 0);
3999         if (!Idx || *Idx == UndefMaskElem)
4000           continue;
4001         Indices.emplace(*Idx, I);
4002       }
4003       OrdersType CurrentOrder(VL.size(), VL.size());
4004       bool IsIdentity = true;
4005       for (int I = 0, E = VL.size(); I < E; ++I) {
4006         CurrentOrder[Indices.top().second] = I;
4007         IsIdentity &= Indices.top().second == I;
4008         Indices.pop();
4009       }
4010       if (IsIdentity)
4011         CurrentOrder.clear();
4012       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4013                                    None, CurrentOrder);
4014       LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n");
4015 
4016       constexpr int NumOps = 2;
4017       ValueList VectorOperands[NumOps];
4018       for (int I = 0; I < NumOps; ++I) {
4019         for (Value *V : VL)
4020           VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I));
4021 
4022         TE->setOperand(I, VectorOperands[I]);
4023       }
4024       buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1});
4025       return;
4026     }
4027     case Instruction::Load: {
4028       // Check that a vectorized load would load the same memory as a scalar
4029       // load. For example, we don't want to vectorize loads that are smaller
4030       // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
4031       // treats loading/storing it as an i8 struct. If we vectorize loads/stores
4032       // from such a struct, we read/write packed bits disagreeing with the
4033       // unvectorized version.
4034       SmallVector<Value *> PointerOps;
4035       OrdersType CurrentOrder;
4036       TreeEntry *TE = nullptr;
4037       switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, CurrentOrder,
4038                                 PointerOps)) {
4039       case LoadsState::Vectorize:
4040         if (CurrentOrder.empty()) {
4041           // Original loads are consecutive and does not require reordering.
4042           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4043                             ReuseShuffleIndicies);
4044           LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
4045         } else {
4046           fixupOrderingIndices(CurrentOrder);
4047           // Need to reorder.
4048           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4049                             ReuseShuffleIndicies, CurrentOrder);
4050           LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
4051         }
4052         TE->setOperandsInOrder();
4053         break;
4054       case LoadsState::ScatterVectorize:
4055         // Vectorizing non-consecutive loads with `llvm.masked.gather`.
4056         TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S,
4057                           UserTreeIdx, ReuseShuffleIndicies);
4058         TE->setOperandsInOrder();
4059         buildTree_rec(PointerOps, Depth + 1, {TE, 0});
4060         LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n");
4061         break;
4062       case LoadsState::Gather:
4063         BS.cancelScheduling(VL, VL0);
4064         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4065                      ReuseShuffleIndicies);
4066 #ifndef NDEBUG
4067         Type *ScalarTy = VL0->getType();
4068         if (DL->getTypeSizeInBits(ScalarTy) !=
4069             DL->getTypeAllocSizeInBits(ScalarTy))
4070           LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
4071         else if (any_of(VL, [](Value *V) {
4072                    return !cast<LoadInst>(V)->isSimple();
4073                  }))
4074           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
4075         else
4076           LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
4077 #endif // NDEBUG
4078         break;
4079       }
4080       return;
4081     }
4082     case Instruction::ZExt:
4083     case Instruction::SExt:
4084     case Instruction::FPToUI:
4085     case Instruction::FPToSI:
4086     case Instruction::FPExt:
4087     case Instruction::PtrToInt:
4088     case Instruction::IntToPtr:
4089     case Instruction::SIToFP:
4090     case Instruction::UIToFP:
4091     case Instruction::Trunc:
4092     case Instruction::FPTrunc:
4093     case Instruction::BitCast: {
4094       Type *SrcTy = VL0->getOperand(0)->getType();
4095       for (Value *V : VL) {
4096         Type *Ty = cast<Instruction>(V)->getOperand(0)->getType();
4097         if (Ty != SrcTy || !isValidElementType(Ty)) {
4098           BS.cancelScheduling(VL, VL0);
4099           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4100                        ReuseShuffleIndicies);
4101           LLVM_DEBUG(dbgs()
4102                      << "SLP: Gathering casts with different src types.\n");
4103           return;
4104         }
4105       }
4106       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4107                                    ReuseShuffleIndicies);
4108       LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
4109 
4110       TE->setOperandsInOrder();
4111       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4112         ValueList Operands;
4113         // Prepare the operand vector.
4114         for (Value *V : VL)
4115           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4116 
4117         buildTree_rec(Operands, Depth + 1, {TE, i});
4118       }
4119       return;
4120     }
4121     case Instruction::ICmp:
4122     case Instruction::FCmp: {
4123       // Check that all of the compares have the same predicate.
4124       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
4125       CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0);
4126       Type *ComparedTy = VL0->getOperand(0)->getType();
4127       for (Value *V : VL) {
4128         CmpInst *Cmp = cast<CmpInst>(V);
4129         if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) ||
4130             Cmp->getOperand(0)->getType() != ComparedTy) {
4131           BS.cancelScheduling(VL, VL0);
4132           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4133                        ReuseShuffleIndicies);
4134           LLVM_DEBUG(dbgs()
4135                      << "SLP: Gathering cmp with different predicate.\n");
4136           return;
4137         }
4138       }
4139 
4140       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4141                                    ReuseShuffleIndicies);
4142       LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
4143 
4144       ValueList Left, Right;
4145       if (cast<CmpInst>(VL0)->isCommutative()) {
4146         // Commutative predicate - collect + sort operands of the instructions
4147         // so that each side is more likely to have the same opcode.
4148         assert(P0 == SwapP0 && "Commutative Predicate mismatch");
4149         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4150       } else {
4151         // Collect operands - commute if it uses the swapped predicate.
4152         for (Value *V : VL) {
4153           auto *Cmp = cast<CmpInst>(V);
4154           Value *LHS = Cmp->getOperand(0);
4155           Value *RHS = Cmp->getOperand(1);
4156           if (Cmp->getPredicate() != P0)
4157             std::swap(LHS, RHS);
4158           Left.push_back(LHS);
4159           Right.push_back(RHS);
4160         }
4161       }
4162       TE->setOperand(0, Left);
4163       TE->setOperand(1, Right);
4164       buildTree_rec(Left, Depth + 1, {TE, 0});
4165       buildTree_rec(Right, Depth + 1, {TE, 1});
4166       return;
4167     }
4168     case Instruction::Select:
4169     case Instruction::FNeg:
4170     case Instruction::Add:
4171     case Instruction::FAdd:
4172     case Instruction::Sub:
4173     case Instruction::FSub:
4174     case Instruction::Mul:
4175     case Instruction::FMul:
4176     case Instruction::UDiv:
4177     case Instruction::SDiv:
4178     case Instruction::FDiv:
4179     case Instruction::URem:
4180     case Instruction::SRem:
4181     case Instruction::FRem:
4182     case Instruction::Shl:
4183     case Instruction::LShr:
4184     case Instruction::AShr:
4185     case Instruction::And:
4186     case Instruction::Or:
4187     case Instruction::Xor: {
4188       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4189                                    ReuseShuffleIndicies);
4190       LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n");
4191 
4192       // Sort operands of the instructions so that each side is more likely to
4193       // have the same opcode.
4194       if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
4195         ValueList Left, Right;
4196         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4197         TE->setOperand(0, Left);
4198         TE->setOperand(1, Right);
4199         buildTree_rec(Left, Depth + 1, {TE, 0});
4200         buildTree_rec(Right, Depth + 1, {TE, 1});
4201         return;
4202       }
4203 
4204       TE->setOperandsInOrder();
4205       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4206         ValueList Operands;
4207         // Prepare the operand vector.
4208         for (Value *V : VL)
4209           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4210 
4211         buildTree_rec(Operands, Depth + 1, {TE, i});
4212       }
4213       return;
4214     }
4215     case Instruction::GetElementPtr: {
4216       // We don't combine GEPs with complicated (nested) indexing.
4217       for (Value *V : VL) {
4218         if (cast<Instruction>(V)->getNumOperands() != 2) {
4219           LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
4220           BS.cancelScheduling(VL, VL0);
4221           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4222                        ReuseShuffleIndicies);
4223           return;
4224         }
4225       }
4226 
4227       // We can't combine several GEPs into one vector if they operate on
4228       // different types.
4229       Type *Ty0 = VL0->getOperand(0)->getType();
4230       for (Value *V : VL) {
4231         Type *CurTy = cast<Instruction>(V)->getOperand(0)->getType();
4232         if (Ty0 != CurTy) {
4233           LLVM_DEBUG(dbgs()
4234                      << "SLP: not-vectorizable GEP (different types).\n");
4235           BS.cancelScheduling(VL, VL0);
4236           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4237                        ReuseShuffleIndicies);
4238           return;
4239         }
4240       }
4241 
4242       // We don't combine GEPs with non-constant indexes.
4243       Type *Ty1 = VL0->getOperand(1)->getType();
4244       for (Value *V : VL) {
4245         auto Op = cast<Instruction>(V)->getOperand(1);
4246         if (!isa<ConstantInt>(Op) ||
4247             (Op->getType() != Ty1 &&
4248              Op->getType()->getScalarSizeInBits() >
4249                  DL->getIndexSizeInBits(
4250                      V->getType()->getPointerAddressSpace()))) {
4251           LLVM_DEBUG(dbgs()
4252                      << "SLP: not-vectorizable GEP (non-constant indexes).\n");
4253           BS.cancelScheduling(VL, VL0);
4254           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4255                        ReuseShuffleIndicies);
4256           return;
4257         }
4258       }
4259 
4260       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4261                                    ReuseShuffleIndicies);
4262       LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
4263       SmallVector<ValueList, 2> Operands(2);
4264       // Prepare the operand vector for pointer operands.
4265       for (Value *V : VL)
4266         Operands.front().push_back(
4267             cast<GetElementPtrInst>(V)->getPointerOperand());
4268       TE->setOperand(0, Operands.front());
4269       // Need to cast all indices to the same type before vectorization to
4270       // avoid crash.
4271       // Required to be able to find correct matches between different gather
4272       // nodes and reuse the vectorized values rather than trying to gather them
4273       // again.
4274       int IndexIdx = 1;
4275       Type *VL0Ty = VL0->getOperand(IndexIdx)->getType();
4276       Type *Ty = all_of(VL,
4277                         [VL0Ty, IndexIdx](Value *V) {
4278                           return VL0Ty == cast<GetElementPtrInst>(V)
4279                                               ->getOperand(IndexIdx)
4280                                               ->getType();
4281                         })
4282                      ? VL0Ty
4283                      : DL->getIndexType(cast<GetElementPtrInst>(VL0)
4284                                             ->getPointerOperandType()
4285                                             ->getScalarType());
4286       // Prepare the operand vector.
4287       for (Value *V : VL) {
4288         auto *Op = cast<Instruction>(V)->getOperand(IndexIdx);
4289         auto *CI = cast<ConstantInt>(Op);
4290         Operands.back().push_back(ConstantExpr::getIntegerCast(
4291             CI, Ty, CI->getValue().isSignBitSet()));
4292       }
4293       TE->setOperand(IndexIdx, Operands.back());
4294 
4295       for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I)
4296         buildTree_rec(Operands[I], Depth + 1, {TE, I});
4297       return;
4298     }
4299     case Instruction::Store: {
4300       // Check if the stores are consecutive or if we need to swizzle them.
4301       llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType();
4302       // Avoid types that are padded when being allocated as scalars, while
4303       // being packed together in a vector (such as i1).
4304       if (DL->getTypeSizeInBits(ScalarTy) !=
4305           DL->getTypeAllocSizeInBits(ScalarTy)) {
4306         BS.cancelScheduling(VL, VL0);
4307         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4308                      ReuseShuffleIndicies);
4309         LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n");
4310         return;
4311       }
4312       // Make sure all stores in the bundle are simple - we can't vectorize
4313       // atomic or volatile stores.
4314       SmallVector<Value *, 4> PointerOps(VL.size());
4315       ValueList Operands(VL.size());
4316       auto POIter = PointerOps.begin();
4317       auto OIter = Operands.begin();
4318       for (Value *V : VL) {
4319         auto *SI = cast<StoreInst>(V);
4320         if (!SI->isSimple()) {
4321           BS.cancelScheduling(VL, VL0);
4322           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4323                        ReuseShuffleIndicies);
4324           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n");
4325           return;
4326         }
4327         *POIter = SI->getPointerOperand();
4328         *OIter = SI->getValueOperand();
4329         ++POIter;
4330         ++OIter;
4331       }
4332 
4333       OrdersType CurrentOrder;
4334       // Check the order of pointer operands.
4335       if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) {
4336         Value *Ptr0;
4337         Value *PtrN;
4338         if (CurrentOrder.empty()) {
4339           Ptr0 = PointerOps.front();
4340           PtrN = PointerOps.back();
4341         } else {
4342           Ptr0 = PointerOps[CurrentOrder.front()];
4343           PtrN = PointerOps[CurrentOrder.back()];
4344         }
4345         Optional<int> Dist =
4346             getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE);
4347         // Check that the sorted pointer operands are consecutive.
4348         if (static_cast<unsigned>(*Dist) == VL.size() - 1) {
4349           if (CurrentOrder.empty()) {
4350             // Original stores are consecutive and does not require reordering.
4351             TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
4352                                          UserTreeIdx, ReuseShuffleIndicies);
4353             TE->setOperandsInOrder();
4354             buildTree_rec(Operands, Depth + 1, {TE, 0});
4355             LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
4356           } else {
4357             fixupOrderingIndices(CurrentOrder);
4358             TreeEntry *TE =
4359                 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4360                              ReuseShuffleIndicies, CurrentOrder);
4361             TE->setOperandsInOrder();
4362             buildTree_rec(Operands, Depth + 1, {TE, 0});
4363             LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n");
4364           }
4365           return;
4366         }
4367       }
4368 
4369       BS.cancelScheduling(VL, VL0);
4370       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4371                    ReuseShuffleIndicies);
4372       LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
4373       return;
4374     }
4375     case Instruction::Call: {
4376       // Check if the calls are all to the same vectorizable intrinsic or
4377       // library function.
4378       CallInst *CI = cast<CallInst>(VL0);
4379       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4380 
4381       VFShape Shape = VFShape::get(
4382           *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())),
4383           false /*HasGlobalPred*/);
4384       Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4385 
4386       if (!VecFunc && !isTriviallyVectorizable(ID)) {
4387         BS.cancelScheduling(VL, VL0);
4388         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4389                      ReuseShuffleIndicies);
4390         LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
4391         return;
4392       }
4393       Function *F = CI->getCalledFunction();
4394       unsigned NumArgs = CI->arg_size();
4395       SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr);
4396       for (unsigned j = 0; j != NumArgs; ++j)
4397         if (hasVectorInstrinsicScalarOpd(ID, j))
4398           ScalarArgs[j] = CI->getArgOperand(j);
4399       for (Value *V : VL) {
4400         CallInst *CI2 = dyn_cast<CallInst>(V);
4401         if (!CI2 || CI2->getCalledFunction() != F ||
4402             getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
4403             (VecFunc &&
4404              VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) ||
4405             !CI->hasIdenticalOperandBundleSchema(*CI2)) {
4406           BS.cancelScheduling(VL, VL0);
4407           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4408                        ReuseShuffleIndicies);
4409           LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V
4410                             << "\n");
4411           return;
4412         }
4413         // Some intrinsics have scalar arguments and should be same in order for
4414         // them to be vectorized.
4415         for (unsigned j = 0; j != NumArgs; ++j) {
4416           if (hasVectorInstrinsicScalarOpd(ID, j)) {
4417             Value *A1J = CI2->getArgOperand(j);
4418             if (ScalarArgs[j] != A1J) {
4419               BS.cancelScheduling(VL, VL0);
4420               newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4421                            ReuseShuffleIndicies);
4422               LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
4423                                 << " argument " << ScalarArgs[j] << "!=" << A1J
4424                                 << "\n");
4425               return;
4426             }
4427           }
4428         }
4429         // Verify that the bundle operands are identical between the two calls.
4430         if (CI->hasOperandBundles() &&
4431             !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
4432                         CI->op_begin() + CI->getBundleOperandsEndIndex(),
4433                         CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
4434           BS.cancelScheduling(VL, VL0);
4435           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4436                        ReuseShuffleIndicies);
4437           LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
4438                             << *CI << "!=" << *V << '\n');
4439           return;
4440         }
4441       }
4442 
4443       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4444                                    ReuseShuffleIndicies);
4445       TE->setOperandsInOrder();
4446       for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
4447         // For scalar operands no need to to create an entry since no need to
4448         // vectorize it.
4449         if (hasVectorInstrinsicScalarOpd(ID, i))
4450           continue;
4451         ValueList Operands;
4452         // Prepare the operand vector.
4453         for (Value *V : VL) {
4454           auto *CI2 = cast<CallInst>(V);
4455           Operands.push_back(CI2->getArgOperand(i));
4456         }
4457         buildTree_rec(Operands, Depth + 1, {TE, i});
4458       }
4459       return;
4460     }
4461     case Instruction::ShuffleVector: {
4462       // If this is not an alternate sequence of opcode like add-sub
4463       // then do not vectorize this instruction.
4464       if (!S.isAltShuffle()) {
4465         BS.cancelScheduling(VL, VL0);
4466         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4467                      ReuseShuffleIndicies);
4468         LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
4469         return;
4470       }
4471       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4472                                    ReuseShuffleIndicies);
4473       LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
4474 
4475       // Reorder operands if reordering would enable vectorization.
4476       auto *CI = dyn_cast<CmpInst>(VL0);
4477       if (isa<BinaryOperator>(VL0) || CI) {
4478         ValueList Left, Right;
4479         if (!CI || all_of(VL, [](Value *V) {
4480               return cast<CmpInst>(V)->isCommutative();
4481             })) {
4482           reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4483         } else {
4484           CmpInst::Predicate P0 = CI->getPredicate();
4485           CmpInst::Predicate AltP0 = cast<CmpInst>(S.AltOp)->getPredicate();
4486           assert(P0 != AltP0 &&
4487                  "Expected different main/alternate predicates.");
4488           CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
4489           Value *BaseOp0 = VL0->getOperand(0);
4490           Value *BaseOp1 = VL0->getOperand(1);
4491           // Collect operands - commute if it uses the swapped predicate or
4492           // alternate operation.
4493           for (Value *V : VL) {
4494             auto *Cmp = cast<CmpInst>(V);
4495             Value *LHS = Cmp->getOperand(0);
4496             Value *RHS = Cmp->getOperand(1);
4497             CmpInst::Predicate CurrentPred = Cmp->getPredicate();
4498             if (P0 == AltP0Swapped) {
4499               if ((P0 == CurrentPred &&
4500                    !areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)) ||
4501                   (AltP0 == CurrentPred &&
4502                    areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)))
4503                 std::swap(LHS, RHS);
4504             } else if (P0 != CurrentPred && AltP0 != CurrentPred) {
4505               std::swap(LHS, RHS);
4506             }
4507             Left.push_back(LHS);
4508             Right.push_back(RHS);
4509           }
4510         }
4511         TE->setOperand(0, Left);
4512         TE->setOperand(1, Right);
4513         buildTree_rec(Left, Depth + 1, {TE, 0});
4514         buildTree_rec(Right, Depth + 1, {TE, 1});
4515         return;
4516       }
4517 
4518       TE->setOperandsInOrder();
4519       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4520         ValueList Operands;
4521         // Prepare the operand vector.
4522         for (Value *V : VL)
4523           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4524 
4525         buildTree_rec(Operands, Depth + 1, {TE, i});
4526       }
4527       return;
4528     }
4529     default:
4530       BS.cancelScheduling(VL, VL0);
4531       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4532                    ReuseShuffleIndicies);
4533       LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
4534       return;
4535   }
4536 }
4537 
4538 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
4539   unsigned N = 1;
4540   Type *EltTy = T;
4541 
4542   while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) ||
4543          isa<VectorType>(EltTy)) {
4544     if (auto *ST = dyn_cast<StructType>(EltTy)) {
4545       // Check that struct is homogeneous.
4546       for (const auto *Ty : ST->elements())
4547         if (Ty != *ST->element_begin())
4548           return 0;
4549       N *= ST->getNumElements();
4550       EltTy = *ST->element_begin();
4551     } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) {
4552       N *= AT->getNumElements();
4553       EltTy = AT->getElementType();
4554     } else {
4555       auto *VT = cast<FixedVectorType>(EltTy);
4556       N *= VT->getNumElements();
4557       EltTy = VT->getElementType();
4558     }
4559   }
4560 
4561   if (!isValidElementType(EltTy))
4562     return 0;
4563   uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N));
4564   if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
4565     return 0;
4566   return N;
4567 }
4568 
4569 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
4570                               SmallVectorImpl<unsigned> &CurrentOrder) const {
4571   const auto *It = find_if(VL, [](Value *V) {
4572     return isa<ExtractElementInst, ExtractValueInst>(V);
4573   });
4574   assert(It != VL.end() && "Expected at least one extract instruction.");
4575   auto *E0 = cast<Instruction>(*It);
4576   assert(all_of(VL,
4577                 [](Value *V) {
4578                   return isa<UndefValue, ExtractElementInst, ExtractValueInst>(
4579                       V);
4580                 }) &&
4581          "Invalid opcode");
4582   // Check if all of the extracts come from the same vector and from the
4583   // correct offset.
4584   Value *Vec = E0->getOperand(0);
4585 
4586   CurrentOrder.clear();
4587 
4588   // We have to extract from a vector/aggregate with the same number of elements.
4589   unsigned NElts;
4590   if (E0->getOpcode() == Instruction::ExtractValue) {
4591     const DataLayout &DL = E0->getModule()->getDataLayout();
4592     NElts = canMapToVector(Vec->getType(), DL);
4593     if (!NElts)
4594       return false;
4595     // Check if load can be rewritten as load of vector.
4596     LoadInst *LI = dyn_cast<LoadInst>(Vec);
4597     if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
4598       return false;
4599   } else {
4600     NElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
4601   }
4602 
4603   if (NElts != VL.size())
4604     return false;
4605 
4606   // Check that all of the indices extract from the correct offset.
4607   bool ShouldKeepOrder = true;
4608   unsigned E = VL.size();
4609   // Assign to all items the initial value E + 1 so we can check if the extract
4610   // instruction index was used already.
4611   // Also, later we can check that all the indices are used and we have a
4612   // consecutive access in the extract instructions, by checking that no
4613   // element of CurrentOrder still has value E + 1.
4614   CurrentOrder.assign(E, E);
4615   unsigned I = 0;
4616   for (; I < E; ++I) {
4617     auto *Inst = dyn_cast<Instruction>(VL[I]);
4618     if (!Inst)
4619       continue;
4620     if (Inst->getOperand(0) != Vec)
4621       break;
4622     if (auto *EE = dyn_cast<ExtractElementInst>(Inst))
4623       if (isa<UndefValue>(EE->getIndexOperand()))
4624         continue;
4625     Optional<unsigned> Idx = getExtractIndex(Inst);
4626     if (!Idx)
4627       break;
4628     const unsigned ExtIdx = *Idx;
4629     if (ExtIdx != I) {
4630       if (ExtIdx >= E || CurrentOrder[ExtIdx] != E)
4631         break;
4632       ShouldKeepOrder = false;
4633       CurrentOrder[ExtIdx] = I;
4634     } else {
4635       if (CurrentOrder[I] != E)
4636         break;
4637       CurrentOrder[I] = I;
4638     }
4639   }
4640   if (I < E) {
4641     CurrentOrder.clear();
4642     return false;
4643   }
4644   if (ShouldKeepOrder)
4645     CurrentOrder.clear();
4646 
4647   return ShouldKeepOrder;
4648 }
4649 
4650 bool BoUpSLP::areAllUsersVectorized(Instruction *I,
4651                                     ArrayRef<Value *> VectorizedVals) const {
4652   return (I->hasOneUse() && is_contained(VectorizedVals, I)) ||
4653          all_of(I->users(), [this](User *U) {
4654            return ScalarToTreeEntry.count(U) > 0 ||
4655                   isVectorLikeInstWithConstOps(U) ||
4656                   (isa<ExtractElementInst>(U) && MustGather.contains(U));
4657          });
4658 }
4659 
4660 static std::pair<InstructionCost, InstructionCost>
4661 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy,
4662                    TargetTransformInfo *TTI, TargetLibraryInfo *TLI) {
4663   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4664 
4665   // Calculate the cost of the scalar and vector calls.
4666   SmallVector<Type *, 4> VecTys;
4667   for (Use &Arg : CI->args())
4668     VecTys.push_back(
4669         FixedVectorType::get(Arg->getType(), VecTy->getNumElements()));
4670   FastMathFlags FMF;
4671   if (auto *FPCI = dyn_cast<FPMathOperator>(CI))
4672     FMF = FPCI->getFastMathFlags();
4673   SmallVector<const Value *> Arguments(CI->args());
4674   IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF,
4675                                     dyn_cast<IntrinsicInst>(CI));
4676   auto IntrinsicCost =
4677     TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput);
4678 
4679   auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
4680                                      VecTy->getNumElements())),
4681                             false /*HasGlobalPred*/);
4682   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4683   auto LibCost = IntrinsicCost;
4684   if (!CI->isNoBuiltin() && VecFunc) {
4685     // Calculate the cost of the vector library call.
4686     // If the corresponding vector call is cheaper, return its cost.
4687     LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys,
4688                                     TTI::TCK_RecipThroughput);
4689   }
4690   return {IntrinsicCost, LibCost};
4691 }
4692 
4693 /// Compute the cost of creating a vector of type \p VecTy containing the
4694 /// extracted values from \p VL.
4695 static InstructionCost
4696 computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy,
4697                    TargetTransformInfo::ShuffleKind ShuffleKind,
4698                    ArrayRef<int> Mask, TargetTransformInfo &TTI) {
4699   unsigned NumOfParts = TTI.getNumberOfParts(VecTy);
4700 
4701   if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts ||
4702       VecTy->getNumElements() < NumOfParts)
4703     return TTI.getShuffleCost(ShuffleKind, VecTy, Mask);
4704 
4705   bool AllConsecutive = true;
4706   unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts;
4707   unsigned Idx = -1;
4708   InstructionCost Cost = 0;
4709 
4710   // Process extracts in blocks of EltsPerVector to check if the source vector
4711   // operand can be re-used directly. If not, add the cost of creating a shuffle
4712   // to extract the values into a vector register.
4713   for (auto *V : VL) {
4714     ++Idx;
4715 
4716     // Need to exclude undefs from analysis.
4717     if (isa<UndefValue>(V) || Mask[Idx] == UndefMaskElem)
4718       continue;
4719 
4720     // Reached the start of a new vector registers.
4721     if (Idx % EltsPerVector == 0) {
4722       AllConsecutive = true;
4723       continue;
4724     }
4725 
4726     // Check all extracts for a vector register on the target directly
4727     // extract values in order.
4728     unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V));
4729     if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != UndefMaskElem) {
4730       unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1]));
4731       AllConsecutive &= PrevIdx + 1 == CurrentIdx &&
4732                         CurrentIdx % EltsPerVector == Idx % EltsPerVector;
4733     }
4734 
4735     if (AllConsecutive)
4736       continue;
4737 
4738     // Skip all indices, except for the last index per vector block.
4739     if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size())
4740       continue;
4741 
4742     // If we have a series of extracts which are not consecutive and hence
4743     // cannot re-use the source vector register directly, compute the shuffle
4744     // cost to extract the a vector with EltsPerVector elements.
4745     Cost += TTI.getShuffleCost(
4746         TargetTransformInfo::SK_PermuteSingleSrc,
4747         FixedVectorType::get(VecTy->getElementType(), EltsPerVector));
4748   }
4749   return Cost;
4750 }
4751 
4752 /// Build shuffle mask for shuffle graph entries and lists of main and alternate
4753 /// operations operands.
4754 static void
4755 buildSuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices,
4756                      ArrayRef<int> ReusesIndices,
4757                      const function_ref<bool(Instruction *)> IsAltOp,
4758                      SmallVectorImpl<int> &Mask,
4759                      SmallVectorImpl<Value *> *OpScalars = nullptr,
4760                      SmallVectorImpl<Value *> *AltScalars = nullptr) {
4761   unsigned Sz = VL.size();
4762   Mask.assign(Sz, UndefMaskElem);
4763   SmallVector<int> OrderMask;
4764   if (!ReorderIndices.empty())
4765     inversePermutation(ReorderIndices, OrderMask);
4766   for (unsigned I = 0; I < Sz; ++I) {
4767     unsigned Idx = I;
4768     if (!ReorderIndices.empty())
4769       Idx = OrderMask[I];
4770     auto *OpInst = cast<Instruction>(VL[Idx]);
4771     if (IsAltOp(OpInst)) {
4772       Mask[I] = Sz + Idx;
4773       if (AltScalars)
4774         AltScalars->push_back(OpInst);
4775     } else {
4776       Mask[I] = Idx;
4777       if (OpScalars)
4778         OpScalars->push_back(OpInst);
4779     }
4780   }
4781   if (!ReusesIndices.empty()) {
4782     SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem);
4783     transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) {
4784       return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem;
4785     });
4786     Mask.swap(NewMask);
4787   }
4788 }
4789 
4790 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E,
4791                                       ArrayRef<Value *> VectorizedVals) {
4792   ArrayRef<Value*> VL = E->Scalars;
4793 
4794   Type *ScalarTy = VL[0]->getType();
4795   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
4796     ScalarTy = SI->getValueOperand()->getType();
4797   else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
4798     ScalarTy = CI->getOperand(0)->getType();
4799   else if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
4800     ScalarTy = IE->getOperand(1)->getType();
4801   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
4802   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
4803 
4804   // If we have computed a smaller type for the expression, update VecTy so
4805   // that the costs will be accurate.
4806   if (MinBWs.count(VL[0]))
4807     VecTy = FixedVectorType::get(
4808         IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
4809   unsigned EntryVF = E->getVectorFactor();
4810   auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF);
4811 
4812   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
4813   // FIXME: it tries to fix a problem with MSVC buildbots.
4814   TargetTransformInfo &TTIRef = *TTI;
4815   auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy,
4816                                VectorizedVals, E](InstructionCost &Cost) {
4817     DenseMap<Value *, int> ExtractVectorsTys;
4818     SmallPtrSet<Value *, 4> CheckedExtracts;
4819     for (auto *V : VL) {
4820       if (isa<UndefValue>(V))
4821         continue;
4822       // If all users of instruction are going to be vectorized and this
4823       // instruction itself is not going to be vectorized, consider this
4824       // instruction as dead and remove its cost from the final cost of the
4825       // vectorized tree.
4826       // Also, avoid adjusting the cost for extractelements with multiple uses
4827       // in different graph entries.
4828       const TreeEntry *VE = getTreeEntry(V);
4829       if (!CheckedExtracts.insert(V).second ||
4830           !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) ||
4831           (VE && VE != E))
4832         continue;
4833       auto *EE = cast<ExtractElementInst>(V);
4834       Optional<unsigned> EEIdx = getExtractIndex(EE);
4835       if (!EEIdx)
4836         continue;
4837       unsigned Idx = *EEIdx;
4838       if (TTIRef.getNumberOfParts(VecTy) !=
4839           TTIRef.getNumberOfParts(EE->getVectorOperandType())) {
4840         auto It =
4841             ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first;
4842         It->getSecond() = std::min<int>(It->second, Idx);
4843       }
4844       // Take credit for instruction that will become dead.
4845       if (EE->hasOneUse()) {
4846         Instruction *Ext = EE->user_back();
4847         if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
4848             all_of(Ext->users(),
4849                    [](User *U) { return isa<GetElementPtrInst>(U); })) {
4850           // Use getExtractWithExtendCost() to calculate the cost of
4851           // extractelement/ext pair.
4852           Cost -=
4853               TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(),
4854                                               EE->getVectorOperandType(), Idx);
4855           // Add back the cost of s|zext which is subtracted separately.
4856           Cost += TTIRef.getCastInstrCost(
4857               Ext->getOpcode(), Ext->getType(), EE->getType(),
4858               TTI::getCastContextHint(Ext), CostKind, Ext);
4859           continue;
4860         }
4861       }
4862       Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement,
4863                                         EE->getVectorOperandType(), Idx);
4864     }
4865     // Add a cost for subvector extracts/inserts if required.
4866     for (const auto &Data : ExtractVectorsTys) {
4867       auto *EEVTy = cast<FixedVectorType>(Data.first->getType());
4868       unsigned NumElts = VecTy->getNumElements();
4869       if (Data.second % NumElts == 0)
4870         continue;
4871       if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) {
4872         unsigned Idx = (Data.second / NumElts) * NumElts;
4873         unsigned EENumElts = EEVTy->getNumElements();
4874         if (Idx + NumElts <= EENumElts) {
4875           Cost +=
4876               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
4877                                     EEVTy, None, Idx, VecTy);
4878         } else {
4879           // Need to round up the subvector type vectorization factor to avoid a
4880           // crash in cost model functions. Make SubVT so that Idx + VF of SubVT
4881           // <= EENumElts.
4882           auto *SubVT =
4883               FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx);
4884           Cost +=
4885               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
4886                                     EEVTy, None, Idx, SubVT);
4887         }
4888       } else {
4889         Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector,
4890                                       VecTy, None, 0, EEVTy);
4891       }
4892     }
4893   };
4894   if (E->State == TreeEntry::NeedToGather) {
4895     if (allConstant(VL))
4896       return 0;
4897     if (isa<InsertElementInst>(VL[0]))
4898       return InstructionCost::getInvalid();
4899     SmallVector<int> Mask;
4900     SmallVector<const TreeEntry *> Entries;
4901     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
4902         isGatherShuffledEntry(E, Mask, Entries);
4903     if (Shuffle.hasValue()) {
4904       InstructionCost GatherCost = 0;
4905       if (ShuffleVectorInst::isIdentityMask(Mask)) {
4906         // Perfect match in the graph, will reuse the previously vectorized
4907         // node. Cost is 0.
4908         LLVM_DEBUG(
4909             dbgs()
4910             << "SLP: perfect diamond match for gather bundle that starts with "
4911             << *VL.front() << ".\n");
4912         if (NeedToShuffleReuses)
4913           GatherCost =
4914               TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
4915                                   FinalVecTy, E->ReuseShuffleIndices);
4916       } else {
4917         LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size()
4918                           << " entries for bundle that starts with "
4919                           << *VL.front() << ".\n");
4920         // Detected that instead of gather we can emit a shuffle of single/two
4921         // previously vectorized nodes. Add the cost of the permutation rather
4922         // than gather.
4923         ::addMask(Mask, E->ReuseShuffleIndices);
4924         GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask);
4925       }
4926       return GatherCost;
4927     }
4928     if ((E->getOpcode() == Instruction::ExtractElement ||
4929          all_of(E->Scalars,
4930                 [](Value *V) {
4931                   return isa<ExtractElementInst, UndefValue>(V);
4932                 })) &&
4933         allSameType(VL)) {
4934       // Check that gather of extractelements can be represented as just a
4935       // shuffle of a single/two vectors the scalars are extracted from.
4936       SmallVector<int> Mask;
4937       Optional<TargetTransformInfo::ShuffleKind> ShuffleKind =
4938           isFixedVectorShuffle(VL, Mask);
4939       if (ShuffleKind.hasValue()) {
4940         // Found the bunch of extractelement instructions that must be gathered
4941         // into a vector and can be represented as a permutation elements in a
4942         // single input vector or of 2 input vectors.
4943         InstructionCost Cost =
4944             computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI);
4945         AdjustExtractsCost(Cost);
4946         if (NeedToShuffleReuses)
4947           Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
4948                                       FinalVecTy, E->ReuseShuffleIndices);
4949         return Cost;
4950       }
4951     }
4952     if (isSplat(VL)) {
4953       // Found the broadcasting of the single scalar, calculate the cost as the
4954       // broadcast.
4955       assert(VecTy == FinalVecTy &&
4956              "No reused scalars expected for broadcast.");
4957       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy);
4958     }
4959     InstructionCost ReuseShuffleCost = 0;
4960     if (NeedToShuffleReuses)
4961       ReuseShuffleCost = TTI->getShuffleCost(
4962           TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices);
4963     // Improve gather cost for gather of loads, if we can group some of the
4964     // loads into vector loads.
4965     if (VL.size() > 2 && E->getOpcode() == Instruction::Load &&
4966         !E->isAltShuffle()) {
4967       BoUpSLP::ValueSet VectorizedLoads;
4968       unsigned StartIdx = 0;
4969       unsigned VF = VL.size() / 2;
4970       unsigned VectorizedCnt = 0;
4971       unsigned ScatterVectorizeCnt = 0;
4972       const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType());
4973       for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) {
4974         for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End;
4975              Cnt += VF) {
4976           ArrayRef<Value *> Slice = VL.slice(Cnt, VF);
4977           if (!VectorizedLoads.count(Slice.front()) &&
4978               !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) {
4979             SmallVector<Value *> PointerOps;
4980             OrdersType CurrentOrder;
4981             LoadsState LS = canVectorizeLoads(Slice, Slice.front(), *TTI, *DL,
4982                                               *SE, CurrentOrder, PointerOps);
4983             switch (LS) {
4984             case LoadsState::Vectorize:
4985             case LoadsState::ScatterVectorize:
4986               // Mark the vectorized loads so that we don't vectorize them
4987               // again.
4988               if (LS == LoadsState::Vectorize)
4989                 ++VectorizedCnt;
4990               else
4991                 ++ScatterVectorizeCnt;
4992               VectorizedLoads.insert(Slice.begin(), Slice.end());
4993               // If we vectorized initial block, no need to try to vectorize it
4994               // again.
4995               if (Cnt == StartIdx)
4996                 StartIdx += VF;
4997               break;
4998             case LoadsState::Gather:
4999               break;
5000             }
5001           }
5002         }
5003         // Check if the whole array was vectorized already - exit.
5004         if (StartIdx >= VL.size())
5005           break;
5006         // Found vectorizable parts - exit.
5007         if (!VectorizedLoads.empty())
5008           break;
5009       }
5010       if (!VectorizedLoads.empty()) {
5011         InstructionCost GatherCost = 0;
5012         unsigned NumParts = TTI->getNumberOfParts(VecTy);
5013         bool NeedInsertSubvectorAnalysis =
5014             !NumParts || (VL.size() / VF) > NumParts;
5015         // Get the cost for gathered loads.
5016         for (unsigned I = 0, End = VL.size(); I < End; I += VF) {
5017           if (VectorizedLoads.contains(VL[I]))
5018             continue;
5019           GatherCost += getGatherCost(VL.slice(I, VF));
5020         }
5021         // The cost for vectorized loads.
5022         InstructionCost ScalarsCost = 0;
5023         for (Value *V : VectorizedLoads) {
5024           auto *LI = cast<LoadInst>(V);
5025           ScalarsCost += TTI->getMemoryOpCost(
5026               Instruction::Load, LI->getType(), LI->getAlign(),
5027               LI->getPointerAddressSpace(), CostKind, LI);
5028         }
5029         auto *LI = cast<LoadInst>(E->getMainOp());
5030         auto *LoadTy = FixedVectorType::get(LI->getType(), VF);
5031         Align Alignment = LI->getAlign();
5032         GatherCost +=
5033             VectorizedCnt *
5034             TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment,
5035                                  LI->getPointerAddressSpace(), CostKind, LI);
5036         GatherCost += ScatterVectorizeCnt *
5037                       TTI->getGatherScatterOpCost(
5038                           Instruction::Load, LoadTy, LI->getPointerOperand(),
5039                           /*VariableMask=*/false, Alignment, CostKind, LI);
5040         if (NeedInsertSubvectorAnalysis) {
5041           // Add the cost for the subvectors insert.
5042           for (int I = VF, E = VL.size(); I < E; I += VF)
5043             GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy,
5044                                               None, I, LoadTy);
5045         }
5046         return ReuseShuffleCost + GatherCost - ScalarsCost;
5047       }
5048     }
5049     return ReuseShuffleCost + getGatherCost(VL);
5050   }
5051   InstructionCost CommonCost = 0;
5052   SmallVector<int> Mask;
5053   if (!E->ReorderIndices.empty()) {
5054     SmallVector<int> NewMask;
5055     if (E->getOpcode() == Instruction::Store) {
5056       // For stores the order is actually a mask.
5057       NewMask.resize(E->ReorderIndices.size());
5058       copy(E->ReorderIndices, NewMask.begin());
5059     } else {
5060       inversePermutation(E->ReorderIndices, NewMask);
5061     }
5062     ::addMask(Mask, NewMask);
5063   }
5064   if (NeedToShuffleReuses)
5065     ::addMask(Mask, E->ReuseShuffleIndices);
5066   if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask))
5067     CommonCost =
5068         TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask);
5069   assert((E->State == TreeEntry::Vectorize ||
5070           E->State == TreeEntry::ScatterVectorize) &&
5071          "Unhandled state");
5072   assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
5073   Instruction *VL0 = E->getMainOp();
5074   unsigned ShuffleOrOp =
5075       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
5076   switch (ShuffleOrOp) {
5077     case Instruction::PHI:
5078       return 0;
5079 
5080     case Instruction::ExtractValue:
5081     case Instruction::ExtractElement: {
5082       // The common cost of removal ExtractElement/ExtractValue instructions +
5083       // the cost of shuffles, if required to resuffle the original vector.
5084       if (NeedToShuffleReuses) {
5085         unsigned Idx = 0;
5086         for (unsigned I : E->ReuseShuffleIndices) {
5087           if (ShuffleOrOp == Instruction::ExtractElement) {
5088             auto *EE = cast<ExtractElementInst>(VL[I]);
5089             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5090                                                   EE->getVectorOperandType(),
5091                                                   *getExtractIndex(EE));
5092           } else {
5093             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5094                                                   VecTy, Idx);
5095             ++Idx;
5096           }
5097         }
5098         Idx = EntryVF;
5099         for (Value *V : VL) {
5100           if (ShuffleOrOp == Instruction::ExtractElement) {
5101             auto *EE = cast<ExtractElementInst>(V);
5102             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5103                                                   EE->getVectorOperandType(),
5104                                                   *getExtractIndex(EE));
5105           } else {
5106             --Idx;
5107             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5108                                                   VecTy, Idx);
5109           }
5110         }
5111       }
5112       if (ShuffleOrOp == Instruction::ExtractValue) {
5113         for (unsigned I = 0, E = VL.size(); I < E; ++I) {
5114           auto *EI = cast<Instruction>(VL[I]);
5115           // Take credit for instruction that will become dead.
5116           if (EI->hasOneUse()) {
5117             Instruction *Ext = EI->user_back();
5118             if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5119                 all_of(Ext->users(),
5120                        [](User *U) { return isa<GetElementPtrInst>(U); })) {
5121               // Use getExtractWithExtendCost() to calculate the cost of
5122               // extractelement/ext pair.
5123               CommonCost -= TTI->getExtractWithExtendCost(
5124                   Ext->getOpcode(), Ext->getType(), VecTy, I);
5125               // Add back the cost of s|zext which is subtracted separately.
5126               CommonCost += TTI->getCastInstrCost(
5127                   Ext->getOpcode(), Ext->getType(), EI->getType(),
5128                   TTI::getCastContextHint(Ext), CostKind, Ext);
5129               continue;
5130             }
5131           }
5132           CommonCost -=
5133               TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I);
5134         }
5135       } else {
5136         AdjustExtractsCost(CommonCost);
5137       }
5138       return CommonCost;
5139     }
5140     case Instruction::InsertElement: {
5141       assert(E->ReuseShuffleIndices.empty() &&
5142              "Unique insertelements only are expected.");
5143       auto *SrcVecTy = cast<FixedVectorType>(VL0->getType());
5144 
5145       unsigned const NumElts = SrcVecTy->getNumElements();
5146       unsigned const NumScalars = VL.size();
5147       APInt DemandedElts = APInt::getZero(NumElts);
5148       // TODO: Add support for Instruction::InsertValue.
5149       SmallVector<int> Mask;
5150       if (!E->ReorderIndices.empty()) {
5151         inversePermutation(E->ReorderIndices, Mask);
5152         Mask.append(NumElts - NumScalars, UndefMaskElem);
5153       } else {
5154         Mask.assign(NumElts, UndefMaskElem);
5155         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
5156       }
5157       unsigned Offset = *getInsertIndex(VL0, 0);
5158       bool IsIdentity = true;
5159       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
5160       Mask.swap(PrevMask);
5161       for (unsigned I = 0; I < NumScalars; ++I) {
5162         Optional<int> InsertIdx = getInsertIndex(VL[PrevMask[I]], 0);
5163         if (!InsertIdx || *InsertIdx == UndefMaskElem)
5164           continue;
5165         DemandedElts.setBit(*InsertIdx);
5166         IsIdentity &= *InsertIdx - Offset == I;
5167         Mask[*InsertIdx - Offset] = I;
5168       }
5169       assert(Offset < NumElts && "Failed to find vector index offset");
5170 
5171       InstructionCost Cost = 0;
5172       Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts,
5173                                             /*Insert*/ true, /*Extract*/ false);
5174 
5175       if (IsIdentity && NumElts != NumScalars && Offset % NumScalars != 0) {
5176         // FIXME: Replace with SK_InsertSubvector once it is properly supported.
5177         unsigned Sz = PowerOf2Ceil(Offset + NumScalars);
5178         Cost += TTI->getShuffleCost(
5179             TargetTransformInfo::SK_PermuteSingleSrc,
5180             FixedVectorType::get(SrcVecTy->getElementType(), Sz));
5181       } else if (!IsIdentity) {
5182         auto *FirstInsert =
5183             cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
5184               return !is_contained(E->Scalars,
5185                                    cast<Instruction>(V)->getOperand(0));
5186             }));
5187         if (isUndefVector(FirstInsert->getOperand(0))) {
5188           Cost += TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, SrcVecTy, Mask);
5189         } else {
5190           SmallVector<int> InsertMask(NumElts);
5191           std::iota(InsertMask.begin(), InsertMask.end(), 0);
5192           for (unsigned I = 0; I < NumElts; I++) {
5193             if (Mask[I] != UndefMaskElem)
5194               InsertMask[Offset + I] = NumElts + I;
5195           }
5196           Cost +=
5197               TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVecTy, InsertMask);
5198         }
5199       }
5200 
5201       return Cost;
5202     }
5203     case Instruction::ZExt:
5204     case Instruction::SExt:
5205     case Instruction::FPToUI:
5206     case Instruction::FPToSI:
5207     case Instruction::FPExt:
5208     case Instruction::PtrToInt:
5209     case Instruction::IntToPtr:
5210     case Instruction::SIToFP:
5211     case Instruction::UIToFP:
5212     case Instruction::Trunc:
5213     case Instruction::FPTrunc:
5214     case Instruction::BitCast: {
5215       Type *SrcTy = VL0->getOperand(0)->getType();
5216       InstructionCost ScalarEltCost =
5217           TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy,
5218                                 TTI::getCastContextHint(VL0), CostKind, VL0);
5219       if (NeedToShuffleReuses) {
5220         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5221       }
5222 
5223       // Calculate the cost of this instruction.
5224       InstructionCost ScalarCost = VL.size() * ScalarEltCost;
5225 
5226       auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size());
5227       InstructionCost VecCost = 0;
5228       // Check if the values are candidates to demote.
5229       if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
5230         VecCost = CommonCost + TTI->getCastInstrCost(
5231                                    E->getOpcode(), VecTy, SrcVecTy,
5232                                    TTI::getCastContextHint(VL0), CostKind, VL0);
5233       }
5234       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5235       return VecCost - ScalarCost;
5236     }
5237     case Instruction::FCmp:
5238     case Instruction::ICmp:
5239     case Instruction::Select: {
5240       // Calculate the cost of this instruction.
5241       InstructionCost ScalarEltCost =
5242           TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5243                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0);
5244       if (NeedToShuffleReuses) {
5245         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5246       }
5247       auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size());
5248       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5249 
5250       // Check if all entries in VL are either compares or selects with compares
5251       // as condition that have the same predicates.
5252       CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE;
5253       bool First = true;
5254       for (auto *V : VL) {
5255         CmpInst::Predicate CurrentPred;
5256         auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value());
5257         if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) &&
5258              !match(V, MatchCmp)) ||
5259             (!First && VecPred != CurrentPred)) {
5260           VecPred = CmpInst::BAD_ICMP_PREDICATE;
5261           break;
5262         }
5263         First = false;
5264         VecPred = CurrentPred;
5265       }
5266 
5267       InstructionCost VecCost = TTI->getCmpSelInstrCost(
5268           E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0);
5269       // Check if it is possible and profitable to use min/max for selects in
5270       // VL.
5271       //
5272       auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL);
5273       if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) {
5274         IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy,
5275                                           {VecTy, VecTy});
5276         InstructionCost IntrinsicCost =
5277             TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5278         // If the selects are the only uses of the compares, they will be dead
5279         // and we can adjust the cost by removing their cost.
5280         if (IntrinsicAndUse.second)
5281           IntrinsicCost -=
5282               TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy, MaskTy,
5283                                       CmpInst::BAD_ICMP_PREDICATE, CostKind);
5284         VecCost = std::min(VecCost, IntrinsicCost);
5285       }
5286       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5287       return CommonCost + VecCost - ScalarCost;
5288     }
5289     case Instruction::FNeg:
5290     case Instruction::Add:
5291     case Instruction::FAdd:
5292     case Instruction::Sub:
5293     case Instruction::FSub:
5294     case Instruction::Mul:
5295     case Instruction::FMul:
5296     case Instruction::UDiv:
5297     case Instruction::SDiv:
5298     case Instruction::FDiv:
5299     case Instruction::URem:
5300     case Instruction::SRem:
5301     case Instruction::FRem:
5302     case Instruction::Shl:
5303     case Instruction::LShr:
5304     case Instruction::AShr:
5305     case Instruction::And:
5306     case Instruction::Or:
5307     case Instruction::Xor: {
5308       // Certain instructions can be cheaper to vectorize if they have a
5309       // constant second vector operand.
5310       TargetTransformInfo::OperandValueKind Op1VK =
5311           TargetTransformInfo::OK_AnyValue;
5312       TargetTransformInfo::OperandValueKind Op2VK =
5313           TargetTransformInfo::OK_UniformConstantValue;
5314       TargetTransformInfo::OperandValueProperties Op1VP =
5315           TargetTransformInfo::OP_None;
5316       TargetTransformInfo::OperandValueProperties Op2VP =
5317           TargetTransformInfo::OP_PowerOf2;
5318 
5319       // If all operands are exactly the same ConstantInt then set the
5320       // operand kind to OK_UniformConstantValue.
5321       // If instead not all operands are constants, then set the operand kind
5322       // to OK_AnyValue. If all operands are constants but not the same,
5323       // then set the operand kind to OK_NonUniformConstantValue.
5324       ConstantInt *CInt0 = nullptr;
5325       for (unsigned i = 0, e = VL.size(); i < e; ++i) {
5326         const Instruction *I = cast<Instruction>(VL[i]);
5327         unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0;
5328         ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx));
5329         if (!CInt) {
5330           Op2VK = TargetTransformInfo::OK_AnyValue;
5331           Op2VP = TargetTransformInfo::OP_None;
5332           break;
5333         }
5334         if (Op2VP == TargetTransformInfo::OP_PowerOf2 &&
5335             !CInt->getValue().isPowerOf2())
5336           Op2VP = TargetTransformInfo::OP_None;
5337         if (i == 0) {
5338           CInt0 = CInt;
5339           continue;
5340         }
5341         if (CInt0 != CInt)
5342           Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5343       }
5344 
5345       SmallVector<const Value *, 4> Operands(VL0->operand_values());
5346       InstructionCost ScalarEltCost =
5347           TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK,
5348                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5349       if (NeedToShuffleReuses) {
5350         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5351       }
5352       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5353       InstructionCost VecCost =
5354           TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK,
5355                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5356       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5357       return CommonCost + VecCost - ScalarCost;
5358     }
5359     case Instruction::GetElementPtr: {
5360       TargetTransformInfo::OperandValueKind Op1VK =
5361           TargetTransformInfo::OK_AnyValue;
5362       TargetTransformInfo::OperandValueKind Op2VK =
5363           TargetTransformInfo::OK_UniformConstantValue;
5364 
5365       InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost(
5366           Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK);
5367       if (NeedToShuffleReuses) {
5368         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5369       }
5370       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5371       InstructionCost VecCost = TTI->getArithmeticInstrCost(
5372           Instruction::Add, VecTy, CostKind, Op1VK, Op2VK);
5373       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5374       return CommonCost + VecCost - ScalarCost;
5375     }
5376     case Instruction::Load: {
5377       // Cost of wide load - cost of scalar loads.
5378       Align Alignment = cast<LoadInst>(VL0)->getAlign();
5379       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5380           Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0);
5381       if (NeedToShuffleReuses) {
5382         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5383       }
5384       InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost;
5385       InstructionCost VecLdCost;
5386       if (E->State == TreeEntry::Vectorize) {
5387         VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0,
5388                                          CostKind, VL0);
5389       } else {
5390         assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState");
5391         Align CommonAlignment = Alignment;
5392         for (Value *V : VL)
5393           CommonAlignment =
5394               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
5395         VecLdCost = TTI->getGatherScatterOpCost(
5396             Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(),
5397             /*VariableMask=*/false, CommonAlignment, CostKind, VL0);
5398       }
5399       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost));
5400       return CommonCost + VecLdCost - ScalarLdCost;
5401     }
5402     case Instruction::Store: {
5403       // We know that we can merge the stores. Calculate the cost.
5404       bool IsReorder = !E->ReorderIndices.empty();
5405       auto *SI =
5406           cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0);
5407       Align Alignment = SI->getAlign();
5408       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5409           Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0);
5410       InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost;
5411       InstructionCost VecStCost = TTI->getMemoryOpCost(
5412           Instruction::Store, VecTy, Alignment, 0, CostKind, VL0);
5413       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost));
5414       return CommonCost + VecStCost - ScalarStCost;
5415     }
5416     case Instruction::Call: {
5417       CallInst *CI = cast<CallInst>(VL0);
5418       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5419 
5420       // Calculate the cost of the scalar and vector calls.
5421       IntrinsicCostAttributes CostAttrs(ID, *CI, 1);
5422       InstructionCost ScalarEltCost =
5423           TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5424       if (NeedToShuffleReuses) {
5425         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5426       }
5427       InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
5428 
5429       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
5430       InstructionCost VecCallCost =
5431           std::min(VecCallCosts.first, VecCallCosts.second);
5432 
5433       LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
5434                         << " (" << VecCallCost << "-" << ScalarCallCost << ")"
5435                         << " for " << *CI << "\n");
5436 
5437       return CommonCost + VecCallCost - ScalarCallCost;
5438     }
5439     case Instruction::ShuffleVector: {
5440       assert(E->isAltShuffle() &&
5441              ((Instruction::isBinaryOp(E->getOpcode()) &&
5442                Instruction::isBinaryOp(E->getAltOpcode())) ||
5443               (Instruction::isCast(E->getOpcode()) &&
5444                Instruction::isCast(E->getAltOpcode())) ||
5445               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
5446              "Invalid Shuffle Vector Operand");
5447       InstructionCost ScalarCost = 0;
5448       if (NeedToShuffleReuses) {
5449         for (unsigned Idx : E->ReuseShuffleIndices) {
5450           Instruction *I = cast<Instruction>(VL[Idx]);
5451           CommonCost -= TTI->getInstructionCost(I, CostKind);
5452         }
5453         for (Value *V : VL) {
5454           Instruction *I = cast<Instruction>(V);
5455           CommonCost += TTI->getInstructionCost(I, CostKind);
5456         }
5457       }
5458       for (Value *V : VL) {
5459         Instruction *I = cast<Instruction>(V);
5460         assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5461         ScalarCost += TTI->getInstructionCost(I, CostKind);
5462       }
5463       // VecCost is equal to sum of the cost of creating 2 vectors
5464       // and the cost of creating shuffle.
5465       InstructionCost VecCost = 0;
5466       // Try to find the previous shuffle node with the same operands and same
5467       // main/alternate ops.
5468       auto &&TryFindNodeWithEqualOperands = [this, E]() {
5469         for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
5470           if (TE.get() == E)
5471             break;
5472           if (TE->isAltShuffle() &&
5473               ((TE->getOpcode() == E->getOpcode() &&
5474                 TE->getAltOpcode() == E->getAltOpcode()) ||
5475                (TE->getOpcode() == E->getAltOpcode() &&
5476                 TE->getAltOpcode() == E->getOpcode())) &&
5477               TE->hasEqualOperands(*E))
5478             return true;
5479         }
5480         return false;
5481       };
5482       if (TryFindNodeWithEqualOperands()) {
5483         LLVM_DEBUG({
5484           dbgs() << "SLP: diamond match for alternate node found.\n";
5485           E->dump();
5486         });
5487         // No need to add new vector costs here since we're going to reuse
5488         // same main/alternate vector ops, just do different shuffling.
5489       } else if (Instruction::isBinaryOp(E->getOpcode())) {
5490         VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind);
5491         VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy,
5492                                                CostKind);
5493       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
5494         VecCost = TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy,
5495                                           Builder.getInt1Ty(),
5496                                           CI0->getPredicate(), CostKind, VL0);
5497         VecCost += TTI->getCmpSelInstrCost(
5498             E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5499             cast<CmpInst>(E->getAltOp())->getPredicate(), CostKind,
5500             E->getAltOp());
5501       } else {
5502         Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
5503         Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
5504         auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size());
5505         auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size());
5506         VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty,
5507                                         TTI::CastContextHint::None, CostKind);
5508         VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty,
5509                                          TTI::CastContextHint::None, CostKind);
5510       }
5511 
5512       SmallVector<int> Mask;
5513       buildSuffleEntryMask(
5514           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
5515           [E](Instruction *I) {
5516             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5517             if (auto *CI0 = dyn_cast<CmpInst>(E->getMainOp())) {
5518               auto *AltCI0 = cast<CmpInst>(E->getAltOp());
5519               auto *CI = cast<CmpInst>(I);
5520               CmpInst::Predicate P0 = CI0->getPredicate();
5521               CmpInst::Predicate AltP0 = AltCI0->getPredicate();
5522               assert(P0 != AltP0 &&
5523                      "Expected different main/alternate predicates.");
5524               CmpInst::Predicate AltP0Swapped =
5525                   CmpInst::getSwappedPredicate(AltP0);
5526               CmpInst::Predicate CurrentPred = CI->getPredicate();
5527               if (P0 == AltP0Swapped)
5528                 return (P0 == CurrentPred &&
5529                         !areCompatibleCmpOps(
5530                             CI0->getOperand(0), CI0->getOperand(1),
5531                             CI->getOperand(0), CI->getOperand(1))) ||
5532                        (AltP0 == CurrentPred &&
5533                         !areCompatibleCmpOps(
5534                             CI0->getOperand(0), CI0->getOperand(1),
5535                             CI->getOperand(1), CI->getOperand(0)));
5536               return AltP0 == CurrentPred || AltP0Swapped == CurrentPred;
5537             }
5538             return I->getOpcode() == E->getAltOpcode();
5539           },
5540           Mask);
5541       CommonCost =
5542           TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy, Mask);
5543       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5544       return CommonCost + VecCost - ScalarCost;
5545     }
5546     default:
5547       llvm_unreachable("Unknown instruction");
5548   }
5549 }
5550 
5551 bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const {
5552   LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
5553                     << VectorizableTree.size() << " is fully vectorizable .\n");
5554 
5555   auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) {
5556     SmallVector<int> Mask;
5557     return TE->State == TreeEntry::NeedToGather &&
5558            !any_of(TE->Scalars,
5559                    [this](Value *V) { return EphValues.contains(V); }) &&
5560            (allConstant(TE->Scalars) || isSplat(TE->Scalars) ||
5561             TE->Scalars.size() < Limit ||
5562             ((TE->getOpcode() == Instruction::ExtractElement ||
5563               all_of(TE->Scalars,
5564                      [](Value *V) {
5565                        return isa<ExtractElementInst, UndefValue>(V);
5566                      })) &&
5567              isFixedVectorShuffle(TE->Scalars, Mask)) ||
5568             (TE->State == TreeEntry::NeedToGather &&
5569              TE->getOpcode() == Instruction::Load && !TE->isAltShuffle()));
5570   };
5571 
5572   // We only handle trees of heights 1 and 2.
5573   if (VectorizableTree.size() == 1 &&
5574       (VectorizableTree[0]->State == TreeEntry::Vectorize ||
5575        (ForReduction &&
5576         AreVectorizableGathers(VectorizableTree[0].get(),
5577                                VectorizableTree[0]->Scalars.size()) &&
5578         VectorizableTree[0]->getVectorFactor() > 2)))
5579     return true;
5580 
5581   if (VectorizableTree.size() != 2)
5582     return false;
5583 
5584   // Handle splat and all-constants stores. Also try to vectorize tiny trees
5585   // with the second gather nodes if they have less scalar operands rather than
5586   // the initial tree element (may be profitable to shuffle the second gather)
5587   // or they are extractelements, which form shuffle.
5588   SmallVector<int> Mask;
5589   if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
5590       AreVectorizableGathers(VectorizableTree[1].get(),
5591                              VectorizableTree[0]->Scalars.size()))
5592     return true;
5593 
5594   // Gathering cost would be too much for tiny trees.
5595   if (VectorizableTree[0]->State == TreeEntry::NeedToGather ||
5596       (VectorizableTree[1]->State == TreeEntry::NeedToGather &&
5597        VectorizableTree[0]->State != TreeEntry::ScatterVectorize))
5598     return false;
5599 
5600   return true;
5601 }
5602 
5603 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts,
5604                                        TargetTransformInfo *TTI,
5605                                        bool MustMatchOrInst) {
5606   // Look past the root to find a source value. Arbitrarily follow the
5607   // path through operand 0 of any 'or'. Also, peek through optional
5608   // shift-left-by-multiple-of-8-bits.
5609   Value *ZextLoad = Root;
5610   const APInt *ShAmtC;
5611   bool FoundOr = false;
5612   while (!isa<ConstantExpr>(ZextLoad) &&
5613          (match(ZextLoad, m_Or(m_Value(), m_Value())) ||
5614           (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) &&
5615            ShAmtC->urem(8) == 0))) {
5616     auto *BinOp = cast<BinaryOperator>(ZextLoad);
5617     ZextLoad = BinOp->getOperand(0);
5618     if (BinOp->getOpcode() == Instruction::Or)
5619       FoundOr = true;
5620   }
5621   // Check if the input is an extended load of the required or/shift expression.
5622   Value *Load;
5623   if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root ||
5624       !match(ZextLoad, m_ZExt(m_Value(Load))) || !isa<LoadInst>(Load))
5625     return false;
5626 
5627   // Require that the total load bit width is a legal integer type.
5628   // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
5629   // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
5630   Type *SrcTy = Load->getType();
5631   unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts;
5632   if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth)))
5633     return false;
5634 
5635   // Everything matched - assume that we can fold the whole sequence using
5636   // load combining.
5637   LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "
5638              << *(cast<Instruction>(Root)) << "\n");
5639 
5640   return true;
5641 }
5642 
5643 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const {
5644   if (RdxKind != RecurKind::Or)
5645     return false;
5646 
5647   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5648   Value *FirstReduced = VectorizableTree[0]->Scalars[0];
5649   return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI,
5650                                     /* MatchOr */ false);
5651 }
5652 
5653 bool BoUpSLP::isLoadCombineCandidate() const {
5654   // Peek through a final sequence of stores and check if all operations are
5655   // likely to be load-combined.
5656   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5657   for (Value *Scalar : VectorizableTree[0]->Scalars) {
5658     Value *X;
5659     if (!match(Scalar, m_Store(m_Value(X), m_Value())) ||
5660         !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true))
5661       return false;
5662   }
5663   return true;
5664 }
5665 
5666 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const {
5667   // No need to vectorize inserts of gathered values.
5668   if (VectorizableTree.size() == 2 &&
5669       isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) &&
5670       VectorizableTree[1]->State == TreeEntry::NeedToGather)
5671     return true;
5672 
5673   // We can vectorize the tree if its size is greater than or equal to the
5674   // minimum size specified by the MinTreeSize command line option.
5675   if (VectorizableTree.size() >= MinTreeSize)
5676     return false;
5677 
5678   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
5679   // can vectorize it if we can prove it fully vectorizable.
5680   if (isFullyVectorizableTinyTree(ForReduction))
5681     return false;
5682 
5683   assert(VectorizableTree.empty()
5684              ? ExternalUses.empty()
5685              : true && "We shouldn't have any external users");
5686 
5687   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
5688   // vectorizable.
5689   return true;
5690 }
5691 
5692 InstructionCost BoUpSLP::getSpillCost() const {
5693   // Walk from the bottom of the tree to the top, tracking which values are
5694   // live. When we see a call instruction that is not part of our tree,
5695   // query TTI to see if there is a cost to keeping values live over it
5696   // (for example, if spills and fills are required).
5697   unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
5698   InstructionCost Cost = 0;
5699 
5700   SmallPtrSet<Instruction*, 4> LiveValues;
5701   Instruction *PrevInst = nullptr;
5702 
5703   // The entries in VectorizableTree are not necessarily ordered by their
5704   // position in basic blocks. Collect them and order them by dominance so later
5705   // instructions are guaranteed to be visited first. For instructions in
5706   // different basic blocks, we only scan to the beginning of the block, so
5707   // their order does not matter, as long as all instructions in a basic block
5708   // are grouped together. Using dominance ensures a deterministic order.
5709   SmallVector<Instruction *, 16> OrderedScalars;
5710   for (const auto &TEPtr : VectorizableTree) {
5711     Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
5712     if (!Inst)
5713       continue;
5714     OrderedScalars.push_back(Inst);
5715   }
5716   llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) {
5717     auto *NodeA = DT->getNode(A->getParent());
5718     auto *NodeB = DT->getNode(B->getParent());
5719     assert(NodeA && "Should only process reachable instructions");
5720     assert(NodeB && "Should only process reachable instructions");
5721     assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
5722            "Different nodes should have different DFS numbers");
5723     if (NodeA != NodeB)
5724       return NodeA->getDFSNumIn() < NodeB->getDFSNumIn();
5725     return B->comesBefore(A);
5726   });
5727 
5728   for (Instruction *Inst : OrderedScalars) {
5729     if (!PrevInst) {
5730       PrevInst = Inst;
5731       continue;
5732     }
5733 
5734     // Update LiveValues.
5735     LiveValues.erase(PrevInst);
5736     for (auto &J : PrevInst->operands()) {
5737       if (isa<Instruction>(&*J) && getTreeEntry(&*J))
5738         LiveValues.insert(cast<Instruction>(&*J));
5739     }
5740 
5741     LLVM_DEBUG({
5742       dbgs() << "SLP: #LV: " << LiveValues.size();
5743       for (auto *X : LiveValues)
5744         dbgs() << " " << X->getName();
5745       dbgs() << ", Looking at ";
5746       Inst->dump();
5747     });
5748 
5749     // Now find the sequence of instructions between PrevInst and Inst.
5750     unsigned NumCalls = 0;
5751     BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
5752                                  PrevInstIt =
5753                                      PrevInst->getIterator().getReverse();
5754     while (InstIt != PrevInstIt) {
5755       if (PrevInstIt == PrevInst->getParent()->rend()) {
5756         PrevInstIt = Inst->getParent()->rbegin();
5757         continue;
5758       }
5759 
5760       // Debug information does not impact spill cost.
5761       if ((isa<CallInst>(&*PrevInstIt) &&
5762            !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
5763           &*PrevInstIt != PrevInst)
5764         NumCalls++;
5765 
5766       ++PrevInstIt;
5767     }
5768 
5769     if (NumCalls) {
5770       SmallVector<Type*, 4> V;
5771       for (auto *II : LiveValues) {
5772         auto *ScalarTy = II->getType();
5773         if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy))
5774           ScalarTy = VectorTy->getElementType();
5775         V.push_back(FixedVectorType::get(ScalarTy, BundleWidth));
5776       }
5777       Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
5778     }
5779 
5780     PrevInst = Inst;
5781   }
5782 
5783   return Cost;
5784 }
5785 
5786 /// Check if two insertelement instructions are from the same buildvector.
5787 static bool areTwoInsertFromSameBuildVector(InsertElementInst *VU,
5788                                             InsertElementInst *V) {
5789   // Instructions must be from the same basic blocks.
5790   if (VU->getParent() != V->getParent())
5791     return false;
5792   // Checks if 2 insertelements are from the same buildvector.
5793   if (VU->getType() != V->getType())
5794     return false;
5795   // Multiple used inserts are separate nodes.
5796   if (!VU->hasOneUse() && !V->hasOneUse())
5797     return false;
5798   auto *IE1 = VU;
5799   auto *IE2 = V;
5800   // Go through the vector operand of insertelement instructions trying to find
5801   // either VU as the original vector for IE2 or V as the original vector for
5802   // IE1.
5803   do {
5804     if (IE2 == VU || IE1 == V)
5805       return true;
5806     if (IE1) {
5807       if (IE1 != VU && !IE1->hasOneUse())
5808         IE1 = nullptr;
5809       else
5810         IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0));
5811     }
5812     if (IE2) {
5813       if (IE2 != V && !IE2->hasOneUse())
5814         IE2 = nullptr;
5815       else
5816         IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0));
5817     }
5818   } while (IE1 || IE2);
5819   return false;
5820 }
5821 
5822 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) {
5823   InstructionCost Cost = 0;
5824   LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
5825                     << VectorizableTree.size() << ".\n");
5826 
5827   unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
5828 
5829   for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
5830     TreeEntry &TE = *VectorizableTree[I].get();
5831 
5832     InstructionCost C = getEntryCost(&TE, VectorizedVals);
5833     Cost += C;
5834     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
5835                       << " for bundle that starts with " << *TE.Scalars[0]
5836                       << ".\n"
5837                       << "SLP: Current total cost = " << Cost << "\n");
5838   }
5839 
5840   SmallPtrSet<Value *, 16> ExtractCostCalculated;
5841   InstructionCost ExtractCost = 0;
5842   SmallVector<unsigned> VF;
5843   SmallVector<SmallVector<int>> ShuffleMask;
5844   SmallVector<Value *> FirstUsers;
5845   SmallVector<APInt> DemandedElts;
5846   for (ExternalUser &EU : ExternalUses) {
5847     // We only add extract cost once for the same scalar.
5848     if (!isa_and_nonnull<InsertElementInst>(EU.User) &&
5849         !ExtractCostCalculated.insert(EU.Scalar).second)
5850       continue;
5851 
5852     // Uses by ephemeral values are free (because the ephemeral value will be
5853     // removed prior to code generation, and so the extraction will be
5854     // removed as well).
5855     if (EphValues.count(EU.User))
5856       continue;
5857 
5858     // No extract cost for vector "scalar"
5859     if (isa<FixedVectorType>(EU.Scalar->getType()))
5860       continue;
5861 
5862     // Already counted the cost for external uses when tried to adjust the cost
5863     // for extractelements, no need to add it again.
5864     if (isa<ExtractElementInst>(EU.Scalar))
5865       continue;
5866 
5867     // If found user is an insertelement, do not calculate extract cost but try
5868     // to detect it as a final shuffled/identity match.
5869     if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) {
5870       if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) {
5871         Optional<int> InsertIdx = getInsertIndex(VU, 0);
5872         if (!InsertIdx || *InsertIdx == UndefMaskElem)
5873           continue;
5874         auto *It = find_if(FirstUsers, [VU](Value *V) {
5875           return areTwoInsertFromSameBuildVector(VU,
5876                                                  cast<InsertElementInst>(V));
5877         });
5878         int VecId = -1;
5879         if (It == FirstUsers.end()) {
5880           VF.push_back(FTy->getNumElements());
5881           ShuffleMask.emplace_back(VF.back(), UndefMaskElem);
5882           // Find the insertvector, vectorized in tree, if any.
5883           Value *Base = VU;
5884           while (isa<InsertElementInst>(Base)) {
5885             // Build the mask for the vectorized insertelement instructions.
5886             if (const TreeEntry *E = getTreeEntry(Base)) {
5887               VU = cast<InsertElementInst>(Base);
5888               do {
5889                 int Idx = E->findLaneForValue(Base);
5890                 ShuffleMask.back()[Idx] = Idx;
5891                 Base = cast<InsertElementInst>(Base)->getOperand(0);
5892               } while (E == getTreeEntry(Base));
5893               break;
5894             }
5895             Base = cast<InsertElementInst>(Base)->getOperand(0);
5896           }
5897           FirstUsers.push_back(VU);
5898           DemandedElts.push_back(APInt::getZero(VF.back()));
5899           VecId = FirstUsers.size() - 1;
5900         } else {
5901           VecId = std::distance(FirstUsers.begin(), It);
5902         }
5903         int Idx = *InsertIdx;
5904         ShuffleMask[VecId][Idx] = EU.Lane;
5905         DemandedElts[VecId].setBit(Idx);
5906         continue;
5907       }
5908     }
5909 
5910     // If we plan to rewrite the tree in a smaller type, we will need to sign
5911     // extend the extracted value back to the original type. Here, we account
5912     // for the extract and the added cost of the sign extend if needed.
5913     auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth);
5914     auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
5915     if (MinBWs.count(ScalarRoot)) {
5916       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
5917       auto Extend =
5918           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
5919       VecTy = FixedVectorType::get(MinTy, BundleWidth);
5920       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
5921                                                    VecTy, EU.Lane);
5922     } else {
5923       ExtractCost +=
5924           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
5925     }
5926   }
5927 
5928   InstructionCost SpillCost = getSpillCost();
5929   Cost += SpillCost + ExtractCost;
5930   if (FirstUsers.size() == 1) {
5931     int Limit = ShuffleMask.front().size() * 2;
5932     if (all_of(ShuffleMask.front(), [Limit](int Idx) { return Idx < Limit; }) &&
5933         !ShuffleVectorInst::isIdentityMask(ShuffleMask.front())) {
5934       InstructionCost C = TTI->getShuffleCost(
5935           TTI::SK_PermuteSingleSrc,
5936           cast<FixedVectorType>(FirstUsers.front()->getType()),
5937           ShuffleMask.front());
5938       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
5939                         << " for final shuffle of insertelement external users "
5940                         << *VectorizableTree.front()->Scalars.front() << ".\n"
5941                         << "SLP: Current total cost = " << Cost << "\n");
5942       Cost += C;
5943     }
5944     InstructionCost InsertCost = TTI->getScalarizationOverhead(
5945         cast<FixedVectorType>(FirstUsers.front()->getType()),
5946         DemandedElts.front(), /*Insert*/ true, /*Extract*/ false);
5947     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
5948                       << " for insertelements gather.\n"
5949                       << "SLP: Current total cost = " << Cost << "\n");
5950     Cost -= InsertCost;
5951   } else if (FirstUsers.size() >= 2) {
5952     unsigned MaxVF = *std::max_element(VF.begin(), VF.end());
5953     // Combined masks of the first 2 vectors.
5954     SmallVector<int> CombinedMask(MaxVF, UndefMaskElem);
5955     copy(ShuffleMask.front(), CombinedMask.begin());
5956     APInt CombinedDemandedElts = DemandedElts.front().zextOrSelf(MaxVF);
5957     auto *VecTy = FixedVectorType::get(
5958         cast<VectorType>(FirstUsers.front()->getType())->getElementType(),
5959         MaxVF);
5960     for (int I = 0, E = ShuffleMask[1].size(); I < E; ++I) {
5961       if (ShuffleMask[1][I] != UndefMaskElem) {
5962         CombinedMask[I] = ShuffleMask[1][I] + MaxVF;
5963         CombinedDemandedElts.setBit(I);
5964       }
5965     }
5966     InstructionCost C =
5967         TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
5968     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
5969                       << " for final shuffle of vector node and external "
5970                          "insertelement users "
5971                       << *VectorizableTree.front()->Scalars.front() << ".\n"
5972                       << "SLP: Current total cost = " << Cost << "\n");
5973     Cost += C;
5974     InstructionCost InsertCost = TTI->getScalarizationOverhead(
5975         VecTy, CombinedDemandedElts, /*Insert*/ true, /*Extract*/ false);
5976     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
5977                       << " for insertelements gather.\n"
5978                       << "SLP: Current total cost = " << Cost << "\n");
5979     Cost -= InsertCost;
5980     for (int I = 2, E = FirstUsers.size(); I < E; ++I) {
5981       // Other elements - permutation of 2 vectors (the initial one and the
5982       // next Ith incoming vector).
5983       unsigned VF = ShuffleMask[I].size();
5984       for (unsigned Idx = 0; Idx < VF; ++Idx) {
5985         int Mask = ShuffleMask[I][Idx];
5986         if (Mask != UndefMaskElem)
5987           CombinedMask[Idx] = MaxVF + Mask;
5988         else if (CombinedMask[Idx] != UndefMaskElem)
5989           CombinedMask[Idx] = Idx;
5990       }
5991       for (unsigned Idx = VF; Idx < MaxVF; ++Idx)
5992         if (CombinedMask[Idx] != UndefMaskElem)
5993           CombinedMask[Idx] = Idx;
5994       InstructionCost C =
5995           TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
5996       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
5997                         << " for final shuffle of vector node and external "
5998                            "insertelement users "
5999                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6000                         << "SLP: Current total cost = " << Cost << "\n");
6001       Cost += C;
6002       InstructionCost InsertCost = TTI->getScalarizationOverhead(
6003           cast<FixedVectorType>(FirstUsers[I]->getType()), DemandedElts[I],
6004           /*Insert*/ true, /*Extract*/ false);
6005       LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6006                         << " for insertelements gather.\n"
6007                         << "SLP: Current total cost = " << Cost << "\n");
6008       Cost -= InsertCost;
6009     }
6010   }
6011 
6012 #ifndef NDEBUG
6013   SmallString<256> Str;
6014   {
6015     raw_svector_ostream OS(Str);
6016     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
6017        << "SLP: Extract Cost = " << ExtractCost << ".\n"
6018        << "SLP: Total Cost = " << Cost << ".\n";
6019   }
6020   LLVM_DEBUG(dbgs() << Str);
6021   if (ViewSLPTree)
6022     ViewGraph(this, "SLP" + F->getName(), false, Str);
6023 #endif
6024 
6025   return Cost;
6026 }
6027 
6028 Optional<TargetTransformInfo::ShuffleKind>
6029 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
6030                                SmallVectorImpl<const TreeEntry *> &Entries) {
6031   // TODO: currently checking only for Scalars in the tree entry, need to count
6032   // reused elements too for better cost estimation.
6033   Mask.assign(TE->Scalars.size(), UndefMaskElem);
6034   Entries.clear();
6035   // Build a lists of values to tree entries.
6036   DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs;
6037   for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) {
6038     if (EntryPtr.get() == TE)
6039       break;
6040     if (EntryPtr->State != TreeEntry::NeedToGather)
6041       continue;
6042     for (Value *V : EntryPtr->Scalars)
6043       ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get());
6044   }
6045   // Find all tree entries used by the gathered values. If no common entries
6046   // found - not a shuffle.
6047   // Here we build a set of tree nodes for each gathered value and trying to
6048   // find the intersection between these sets. If we have at least one common
6049   // tree node for each gathered value - we have just a permutation of the
6050   // single vector. If we have 2 different sets, we're in situation where we
6051   // have a permutation of 2 input vectors.
6052   SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs;
6053   DenseMap<Value *, int> UsedValuesEntry;
6054   for (Value *V : TE->Scalars) {
6055     if (isa<UndefValue>(V))
6056       continue;
6057     // Build a list of tree entries where V is used.
6058     SmallPtrSet<const TreeEntry *, 4> VToTEs;
6059     auto It = ValueToTEs.find(V);
6060     if (It != ValueToTEs.end())
6061       VToTEs = It->second;
6062     if (const TreeEntry *VTE = getTreeEntry(V))
6063       VToTEs.insert(VTE);
6064     if (VToTEs.empty())
6065       return None;
6066     if (UsedTEs.empty()) {
6067       // The first iteration, just insert the list of nodes to vector.
6068       UsedTEs.push_back(VToTEs);
6069     } else {
6070       // Need to check if there are any previously used tree nodes which use V.
6071       // If there are no such nodes, consider that we have another one input
6072       // vector.
6073       SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs);
6074       unsigned Idx = 0;
6075       for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) {
6076         // Do we have a non-empty intersection of previously listed tree entries
6077         // and tree entries using current V?
6078         set_intersect(VToTEs, Set);
6079         if (!VToTEs.empty()) {
6080           // Yes, write the new subset and continue analysis for the next
6081           // scalar.
6082           Set.swap(VToTEs);
6083           break;
6084         }
6085         VToTEs = SavedVToTEs;
6086         ++Idx;
6087       }
6088       // No non-empty intersection found - need to add a second set of possible
6089       // source vectors.
6090       if (Idx == UsedTEs.size()) {
6091         // If the number of input vectors is greater than 2 - not a permutation,
6092         // fallback to the regular gather.
6093         if (UsedTEs.size() == 2)
6094           return None;
6095         UsedTEs.push_back(SavedVToTEs);
6096         Idx = UsedTEs.size() - 1;
6097       }
6098       UsedValuesEntry.try_emplace(V, Idx);
6099     }
6100   }
6101 
6102   unsigned VF = 0;
6103   if (UsedTEs.size() == 1) {
6104     // Try to find the perfect match in another gather node at first.
6105     auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) {
6106       return EntryPtr->isSame(TE->Scalars);
6107     });
6108     if (It != UsedTEs.front().end()) {
6109       Entries.push_back(*It);
6110       std::iota(Mask.begin(), Mask.end(), 0);
6111       return TargetTransformInfo::SK_PermuteSingleSrc;
6112     }
6113     // No perfect match, just shuffle, so choose the first tree node.
6114     Entries.push_back(*UsedTEs.front().begin());
6115   } else {
6116     // Try to find nodes with the same vector factor.
6117     assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries.");
6118     DenseMap<int, const TreeEntry *> VFToTE;
6119     for (const TreeEntry *TE : UsedTEs.front())
6120       VFToTE.try_emplace(TE->getVectorFactor(), TE);
6121     for (const TreeEntry *TE : UsedTEs.back()) {
6122       auto It = VFToTE.find(TE->getVectorFactor());
6123       if (It != VFToTE.end()) {
6124         VF = It->first;
6125         Entries.push_back(It->second);
6126         Entries.push_back(TE);
6127         break;
6128       }
6129     }
6130     // No 2 source vectors with the same vector factor - give up and do regular
6131     // gather.
6132     if (Entries.empty())
6133       return None;
6134   }
6135 
6136   // Build a shuffle mask for better cost estimation and vector emission.
6137   for (int I = 0, E = TE->Scalars.size(); I < E; ++I) {
6138     Value *V = TE->Scalars[I];
6139     if (isa<UndefValue>(V))
6140       continue;
6141     unsigned Idx = UsedValuesEntry.lookup(V);
6142     const TreeEntry *VTE = Entries[Idx];
6143     int FoundLane = VTE->findLaneForValue(V);
6144     Mask[I] = Idx * VF + FoundLane;
6145     // Extra check required by isSingleSourceMaskImpl function (called by
6146     // ShuffleVectorInst::isSingleSourceMask).
6147     if (Mask[I] >= 2 * E)
6148       return None;
6149   }
6150   switch (Entries.size()) {
6151   case 1:
6152     return TargetTransformInfo::SK_PermuteSingleSrc;
6153   case 2:
6154     return TargetTransformInfo::SK_PermuteTwoSrc;
6155   default:
6156     break;
6157   }
6158   return None;
6159 }
6160 
6161 InstructionCost
6162 BoUpSLP::getGatherCost(FixedVectorType *Ty,
6163                        const DenseSet<unsigned> &ShuffledIndices,
6164                        bool NeedToShuffle) const {
6165   unsigned NumElts = Ty->getNumElements();
6166   APInt DemandedElts = APInt::getZero(NumElts);
6167   for (unsigned I = 0; I < NumElts; ++I)
6168     if (!ShuffledIndices.count(I))
6169       DemandedElts.setBit(I);
6170   InstructionCost Cost =
6171       TTI->getScalarizationOverhead(Ty, DemandedElts, /*Insert*/ true,
6172                                     /*Extract*/ false);
6173   if (NeedToShuffle)
6174     Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
6175   return Cost;
6176 }
6177 
6178 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
6179   // Find the type of the operands in VL.
6180   Type *ScalarTy = VL[0]->getType();
6181   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
6182     ScalarTy = SI->getValueOperand()->getType();
6183   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
6184   bool DuplicateNonConst = false;
6185   // Find the cost of inserting/extracting values from the vector.
6186   // Check if the same elements are inserted several times and count them as
6187   // shuffle candidates.
6188   DenseSet<unsigned> ShuffledElements;
6189   DenseSet<Value *> UniqueElements;
6190   // Iterate in reverse order to consider insert elements with the high cost.
6191   for (unsigned I = VL.size(); I > 0; --I) {
6192     unsigned Idx = I - 1;
6193     // No need to shuffle duplicates for constants.
6194     if (isConstant(VL[Idx])) {
6195       ShuffledElements.insert(Idx);
6196       continue;
6197     }
6198     if (!UniqueElements.insert(VL[Idx]).second) {
6199       DuplicateNonConst = true;
6200       ShuffledElements.insert(Idx);
6201     }
6202   }
6203   return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst);
6204 }
6205 
6206 // Perform operand reordering on the instructions in VL and return the reordered
6207 // operands in Left and Right.
6208 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
6209                                              SmallVectorImpl<Value *> &Left,
6210                                              SmallVectorImpl<Value *> &Right,
6211                                              const DataLayout &DL,
6212                                              ScalarEvolution &SE,
6213                                              const BoUpSLP &R) {
6214   if (VL.empty())
6215     return;
6216   VLOperands Ops(VL, DL, SE, R);
6217   // Reorder the operands in place.
6218   Ops.reorder();
6219   Left = Ops.getVL(0);
6220   Right = Ops.getVL(1);
6221 }
6222 
6223 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) {
6224   // Get the basic block this bundle is in. All instructions in the bundle
6225   // should be in this block.
6226   auto *Front = E->getMainOp();
6227   auto *BB = Front->getParent();
6228   assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool {
6229     auto *I = cast<Instruction>(V);
6230     return !E->isOpcodeOrAlt(I) || I->getParent() == BB;
6231   }));
6232 
6233   // The last instruction in the bundle in program order.
6234   Instruction *LastInst = nullptr;
6235 
6236   // Find the last instruction. The common case should be that BB has been
6237   // scheduled, and the last instruction is VL.back(). So we start with
6238   // VL.back() and iterate over schedule data until we reach the end of the
6239   // bundle. The end of the bundle is marked by null ScheduleData.
6240   if (BlocksSchedules.count(BB)) {
6241     auto *Bundle =
6242         BlocksSchedules[BB]->getScheduleData(E->isOneOf(E->Scalars.back()));
6243     if (Bundle && Bundle->isPartOfBundle())
6244       for (; Bundle; Bundle = Bundle->NextInBundle)
6245         if (Bundle->OpValue == Bundle->Inst)
6246           LastInst = Bundle->Inst;
6247   }
6248 
6249   // LastInst can still be null at this point if there's either not an entry
6250   // for BB in BlocksSchedules or there's no ScheduleData available for
6251   // VL.back(). This can be the case if buildTree_rec aborts for various
6252   // reasons (e.g., the maximum recursion depth is reached, the maximum region
6253   // size is reached, etc.). ScheduleData is initialized in the scheduling
6254   // "dry-run".
6255   //
6256   // If this happens, we can still find the last instruction by brute force. We
6257   // iterate forwards from Front (inclusive) until we either see all
6258   // instructions in the bundle or reach the end of the block. If Front is the
6259   // last instruction in program order, LastInst will be set to Front, and we
6260   // will visit all the remaining instructions in the block.
6261   //
6262   // One of the reasons we exit early from buildTree_rec is to place an upper
6263   // bound on compile-time. Thus, taking an additional compile-time hit here is
6264   // not ideal. However, this should be exceedingly rare since it requires that
6265   // we both exit early from buildTree_rec and that the bundle be out-of-order
6266   // (causing us to iterate all the way to the end of the block).
6267   if (!LastInst) {
6268     SmallPtrSet<Value *, 16> Bundle(E->Scalars.begin(), E->Scalars.end());
6269     for (auto &I : make_range(BasicBlock::iterator(Front), BB->end())) {
6270       if (Bundle.erase(&I) && E->isOpcodeOrAlt(&I))
6271         LastInst = &I;
6272       if (Bundle.empty())
6273         break;
6274     }
6275   }
6276   assert(LastInst && "Failed to find last instruction in bundle");
6277 
6278   // Set the insertion point after the last instruction in the bundle. Set the
6279   // debug location to Front.
6280   Builder.SetInsertPoint(BB, ++LastInst->getIterator());
6281   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6282 }
6283 
6284 Value *BoUpSLP::gather(ArrayRef<Value *> VL) {
6285   // List of instructions/lanes from current block and/or the blocks which are
6286   // part of the current loop. These instructions will be inserted at the end to
6287   // make it possible to optimize loops and hoist invariant instructions out of
6288   // the loops body with better chances for success.
6289   SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts;
6290   SmallSet<int, 4> PostponedIndices;
6291   Loop *L = LI->getLoopFor(Builder.GetInsertBlock());
6292   auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) {
6293     SmallPtrSet<BasicBlock *, 4> Visited;
6294     while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second)
6295       InsertBB = InsertBB->getSinglePredecessor();
6296     return InsertBB && InsertBB == InstBB;
6297   };
6298   for (int I = 0, E = VL.size(); I < E; ++I) {
6299     if (auto *Inst = dyn_cast<Instruction>(VL[I]))
6300       if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) ||
6301            getTreeEntry(Inst) || (L && (L->contains(Inst)))) &&
6302           PostponedIndices.insert(I).second)
6303         PostponedInsts.emplace_back(Inst, I);
6304   }
6305 
6306   auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) {
6307     Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos));
6308     auto *InsElt = dyn_cast<InsertElementInst>(Vec);
6309     if (!InsElt)
6310       return Vec;
6311     GatherShuffleSeq.insert(InsElt);
6312     CSEBlocks.insert(InsElt->getParent());
6313     // Add to our 'need-to-extract' list.
6314     if (TreeEntry *Entry = getTreeEntry(V)) {
6315       // Find which lane we need to extract.
6316       unsigned FoundLane = Entry->findLaneForValue(V);
6317       ExternalUses.emplace_back(V, InsElt, FoundLane);
6318     }
6319     return Vec;
6320   };
6321   Value *Val0 =
6322       isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0];
6323   FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size());
6324   Value *Vec = PoisonValue::get(VecTy);
6325   SmallVector<int> NonConsts;
6326   // Insert constant values at first.
6327   for (int I = 0, E = VL.size(); I < E; ++I) {
6328     if (PostponedIndices.contains(I))
6329       continue;
6330     if (!isConstant(VL[I])) {
6331       NonConsts.push_back(I);
6332       continue;
6333     }
6334     Vec = CreateInsertElement(Vec, VL[I], I);
6335   }
6336   // Insert non-constant values.
6337   for (int I : NonConsts)
6338     Vec = CreateInsertElement(Vec, VL[I], I);
6339   // Append instructions, which are/may be part of the loop, in the end to make
6340   // it possible to hoist non-loop-based instructions.
6341   for (const std::pair<Value *, unsigned> &Pair : PostponedInsts)
6342     Vec = CreateInsertElement(Vec, Pair.first, Pair.second);
6343 
6344   return Vec;
6345 }
6346 
6347 namespace {
6348 /// Merges shuffle masks and emits final shuffle instruction, if required.
6349 class ShuffleInstructionBuilder {
6350   IRBuilderBase &Builder;
6351   const unsigned VF = 0;
6352   bool IsFinalized = false;
6353   SmallVector<int, 4> Mask;
6354   /// Holds all of the instructions that we gathered.
6355   SetVector<Instruction *> &GatherShuffleSeq;
6356   /// A list of blocks that we are going to CSE.
6357   SetVector<BasicBlock *> &CSEBlocks;
6358 
6359 public:
6360   ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF,
6361                             SetVector<Instruction *> &GatherShuffleSeq,
6362                             SetVector<BasicBlock *> &CSEBlocks)
6363       : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq),
6364         CSEBlocks(CSEBlocks) {}
6365 
6366   /// Adds a mask, inverting it before applying.
6367   void addInversedMask(ArrayRef<unsigned> SubMask) {
6368     if (SubMask.empty())
6369       return;
6370     SmallVector<int, 4> NewMask;
6371     inversePermutation(SubMask, NewMask);
6372     addMask(NewMask);
6373   }
6374 
6375   /// Functions adds masks, merging them into  single one.
6376   void addMask(ArrayRef<unsigned> SubMask) {
6377     SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end());
6378     addMask(NewMask);
6379   }
6380 
6381   void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); }
6382 
6383   Value *finalize(Value *V) {
6384     IsFinalized = true;
6385     unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements();
6386     if (VF == ValueVF && Mask.empty())
6387       return V;
6388     SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem);
6389     std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0);
6390     addMask(NormalizedMask);
6391 
6392     if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask))
6393       return V;
6394     Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle");
6395     if (auto *I = dyn_cast<Instruction>(Vec)) {
6396       GatherShuffleSeq.insert(I);
6397       CSEBlocks.insert(I->getParent());
6398     }
6399     return Vec;
6400   }
6401 
6402   ~ShuffleInstructionBuilder() {
6403     assert((IsFinalized || Mask.empty()) &&
6404            "Shuffle construction must be finalized.");
6405   }
6406 };
6407 } // namespace
6408 
6409 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
6410   unsigned VF = VL.size();
6411   InstructionsState S = getSameOpcode(VL);
6412   if (S.getOpcode()) {
6413     if (TreeEntry *E = getTreeEntry(S.OpValue))
6414       if (E->isSame(VL)) {
6415         Value *V = vectorizeTree(E);
6416         if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) {
6417           if (!E->ReuseShuffleIndices.empty()) {
6418             // Reshuffle to get only unique values.
6419             // If some of the scalars are duplicated in the vectorization tree
6420             // entry, we do not vectorize them but instead generate a mask for
6421             // the reuses. But if there are several users of the same entry,
6422             // they may have different vectorization factors. This is especially
6423             // important for PHI nodes. In this case, we need to adapt the
6424             // resulting instruction for the user vectorization factor and have
6425             // to reshuffle it again to take only unique elements of the vector.
6426             // Without this code the function incorrectly returns reduced vector
6427             // instruction with the same elements, not with the unique ones.
6428 
6429             // block:
6430             // %phi = phi <2 x > { .., %entry} {%shuffle, %block}
6431             // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0>
6432             // ... (use %2)
6433             // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0}
6434             // br %block
6435             SmallVector<int> UniqueIdxs(VF, UndefMaskElem);
6436             SmallSet<int, 4> UsedIdxs;
6437             int Pos = 0;
6438             int Sz = VL.size();
6439             for (int Idx : E->ReuseShuffleIndices) {
6440               if (Idx != Sz && Idx != UndefMaskElem &&
6441                   UsedIdxs.insert(Idx).second)
6442                 UniqueIdxs[Idx] = Pos;
6443               ++Pos;
6444             }
6445             assert(VF >= UsedIdxs.size() && "Expected vectorization factor "
6446                                             "less than original vector size.");
6447             UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem);
6448             V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle");
6449           } else {
6450             assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() &&
6451                    "Expected vectorization factor less "
6452                    "than original vector size.");
6453             SmallVector<int> UniformMask(VF, 0);
6454             std::iota(UniformMask.begin(), UniformMask.end(), 0);
6455             V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle");
6456           }
6457           if (auto *I = dyn_cast<Instruction>(V)) {
6458             GatherShuffleSeq.insert(I);
6459             CSEBlocks.insert(I->getParent());
6460           }
6461         }
6462         return V;
6463       }
6464   }
6465 
6466   // Check that every instruction appears once in this bundle.
6467   SmallVector<int> ReuseShuffleIndicies;
6468   SmallVector<Value *> UniqueValues;
6469   if (VL.size() > 2) {
6470     DenseMap<Value *, unsigned> UniquePositions;
6471     unsigned NumValues =
6472         std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) {
6473                                     return !isa<UndefValue>(V);
6474                                   }).base());
6475     VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues));
6476     int UniqueVals = 0;
6477     for (Value *V : VL.drop_back(VL.size() - VF)) {
6478       if (isa<UndefValue>(V)) {
6479         ReuseShuffleIndicies.emplace_back(UndefMaskElem);
6480         continue;
6481       }
6482       if (isConstant(V)) {
6483         ReuseShuffleIndicies.emplace_back(UniqueValues.size());
6484         UniqueValues.emplace_back(V);
6485         continue;
6486       }
6487       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
6488       ReuseShuffleIndicies.emplace_back(Res.first->second);
6489       if (Res.second) {
6490         UniqueValues.emplace_back(V);
6491         ++UniqueVals;
6492       }
6493     }
6494     if (UniqueVals == 1 && UniqueValues.size() == 1) {
6495       // Emit pure splat vector.
6496       ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(),
6497                                   UndefMaskElem);
6498     } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) {
6499       ReuseShuffleIndicies.clear();
6500       UniqueValues.clear();
6501       UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues));
6502     }
6503     UniqueValues.append(VF - UniqueValues.size(),
6504                         PoisonValue::get(VL[0]->getType()));
6505     VL = UniqueValues;
6506   }
6507 
6508   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6509                                            CSEBlocks);
6510   Value *Vec = gather(VL);
6511   if (!ReuseShuffleIndicies.empty()) {
6512     ShuffleBuilder.addMask(ReuseShuffleIndicies);
6513     Vec = ShuffleBuilder.finalize(Vec);
6514   }
6515   return Vec;
6516 }
6517 
6518 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
6519   IRBuilder<>::InsertPointGuard Guard(Builder);
6520 
6521   if (E->VectorizedValue) {
6522     LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
6523     return E->VectorizedValue;
6524   }
6525 
6526   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
6527   unsigned VF = E->getVectorFactor();
6528   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6529                                            CSEBlocks);
6530   if (E->State == TreeEntry::NeedToGather) {
6531     if (E->getMainOp())
6532       setInsertPointAfterBundle(E);
6533     Value *Vec;
6534     SmallVector<int> Mask;
6535     SmallVector<const TreeEntry *> Entries;
6536     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
6537         isGatherShuffledEntry(E, Mask, Entries);
6538     if (Shuffle.hasValue()) {
6539       assert((Entries.size() == 1 || Entries.size() == 2) &&
6540              "Expected shuffle of 1 or 2 entries.");
6541       Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue,
6542                                         Entries.back()->VectorizedValue, Mask);
6543       if (auto *I = dyn_cast<Instruction>(Vec)) {
6544         GatherShuffleSeq.insert(I);
6545         CSEBlocks.insert(I->getParent());
6546       }
6547     } else {
6548       Vec = gather(E->Scalars);
6549     }
6550     if (NeedToShuffleReuses) {
6551       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6552       Vec = ShuffleBuilder.finalize(Vec);
6553     }
6554     E->VectorizedValue = Vec;
6555     return Vec;
6556   }
6557 
6558   assert((E->State == TreeEntry::Vectorize ||
6559           E->State == TreeEntry::ScatterVectorize) &&
6560          "Unhandled state");
6561   unsigned ShuffleOrOp =
6562       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
6563   Instruction *VL0 = E->getMainOp();
6564   Type *ScalarTy = VL0->getType();
6565   if (auto *Store = dyn_cast<StoreInst>(VL0))
6566     ScalarTy = Store->getValueOperand()->getType();
6567   else if (auto *IE = dyn_cast<InsertElementInst>(VL0))
6568     ScalarTy = IE->getOperand(1)->getType();
6569   auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
6570   switch (ShuffleOrOp) {
6571     case Instruction::PHI: {
6572       assert(
6573           (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) &&
6574           "PHI reordering is free.");
6575       auto *PH = cast<PHINode>(VL0);
6576       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
6577       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6578       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
6579       Value *V = NewPhi;
6580       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6581       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6582       V = ShuffleBuilder.finalize(V);
6583 
6584       E->VectorizedValue = V;
6585 
6586       // PHINodes may have multiple entries from the same block. We want to
6587       // visit every block once.
6588       SmallPtrSet<BasicBlock*, 4> VisitedBBs;
6589 
6590       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
6591         ValueList Operands;
6592         BasicBlock *IBB = PH->getIncomingBlock(i);
6593 
6594         if (!VisitedBBs.insert(IBB).second) {
6595           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
6596           continue;
6597         }
6598 
6599         Builder.SetInsertPoint(IBB->getTerminator());
6600         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6601         Value *Vec = vectorizeTree(E->getOperand(i));
6602         NewPhi->addIncoming(Vec, IBB);
6603       }
6604 
6605       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
6606              "Invalid number of incoming values");
6607       return V;
6608     }
6609 
6610     case Instruction::ExtractElement: {
6611       Value *V = E->getSingleOperand(0);
6612       Builder.SetInsertPoint(VL0);
6613       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6614       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6615       V = ShuffleBuilder.finalize(V);
6616       E->VectorizedValue = V;
6617       return V;
6618     }
6619     case Instruction::ExtractValue: {
6620       auto *LI = cast<LoadInst>(E->getSingleOperand(0));
6621       Builder.SetInsertPoint(LI);
6622       auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
6623       Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
6624       LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
6625       Value *NewV = propagateMetadata(V, E->Scalars);
6626       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6627       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6628       NewV = ShuffleBuilder.finalize(NewV);
6629       E->VectorizedValue = NewV;
6630       return NewV;
6631     }
6632     case Instruction::InsertElement: {
6633       assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique");
6634       Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back()));
6635       Value *V = vectorizeTree(E->getOperand(1));
6636 
6637       // Create InsertVector shuffle if necessary
6638       auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
6639         return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0));
6640       }));
6641       const unsigned NumElts =
6642           cast<FixedVectorType>(FirstInsert->getType())->getNumElements();
6643       const unsigned NumScalars = E->Scalars.size();
6644 
6645       unsigned Offset = *getInsertIndex(VL0, 0);
6646       assert(Offset < NumElts && "Failed to find vector index offset");
6647 
6648       // Create shuffle to resize vector
6649       SmallVector<int> Mask;
6650       if (!E->ReorderIndices.empty()) {
6651         inversePermutation(E->ReorderIndices, Mask);
6652         Mask.append(NumElts - NumScalars, UndefMaskElem);
6653       } else {
6654         Mask.assign(NumElts, UndefMaskElem);
6655         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
6656       }
6657       // Create InsertVector shuffle if necessary
6658       bool IsIdentity = true;
6659       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
6660       Mask.swap(PrevMask);
6661       for (unsigned I = 0; I < NumScalars; ++I) {
6662         Value *Scalar = E->Scalars[PrevMask[I]];
6663         Optional<int> InsertIdx = getInsertIndex(Scalar, 0);
6664         if (!InsertIdx || *InsertIdx == UndefMaskElem)
6665           continue;
6666         IsIdentity &= *InsertIdx - Offset == I;
6667         Mask[*InsertIdx - Offset] = I;
6668       }
6669       if (!IsIdentity || NumElts != NumScalars) {
6670         V = Builder.CreateShuffleVector(V, Mask);
6671         if (auto *I = dyn_cast<Instruction>(V)) {
6672           GatherShuffleSeq.insert(I);
6673           CSEBlocks.insert(I->getParent());
6674         }
6675       }
6676 
6677       if ((!IsIdentity || Offset != 0 ||
6678            !isUndefVector(FirstInsert->getOperand(0))) &&
6679           NumElts != NumScalars) {
6680         SmallVector<int> InsertMask(NumElts);
6681         std::iota(InsertMask.begin(), InsertMask.end(), 0);
6682         for (unsigned I = 0; I < NumElts; I++) {
6683           if (Mask[I] != UndefMaskElem)
6684             InsertMask[Offset + I] = NumElts + I;
6685         }
6686 
6687         V = Builder.CreateShuffleVector(
6688             FirstInsert->getOperand(0), V, InsertMask,
6689             cast<Instruction>(E->Scalars.back())->getName());
6690         if (auto *I = dyn_cast<Instruction>(V)) {
6691           GatherShuffleSeq.insert(I);
6692           CSEBlocks.insert(I->getParent());
6693         }
6694       }
6695 
6696       ++NumVectorInstructions;
6697       E->VectorizedValue = V;
6698       return V;
6699     }
6700     case Instruction::ZExt:
6701     case Instruction::SExt:
6702     case Instruction::FPToUI:
6703     case Instruction::FPToSI:
6704     case Instruction::FPExt:
6705     case Instruction::PtrToInt:
6706     case Instruction::IntToPtr:
6707     case Instruction::SIToFP:
6708     case Instruction::UIToFP:
6709     case Instruction::Trunc:
6710     case Instruction::FPTrunc:
6711     case Instruction::BitCast: {
6712       setInsertPointAfterBundle(E);
6713 
6714       Value *InVec = vectorizeTree(E->getOperand(0));
6715 
6716       if (E->VectorizedValue) {
6717         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6718         return E->VectorizedValue;
6719       }
6720 
6721       auto *CI = cast<CastInst>(VL0);
6722       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
6723       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6724       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6725       V = ShuffleBuilder.finalize(V);
6726 
6727       E->VectorizedValue = V;
6728       ++NumVectorInstructions;
6729       return V;
6730     }
6731     case Instruction::FCmp:
6732     case Instruction::ICmp: {
6733       setInsertPointAfterBundle(E);
6734 
6735       Value *L = vectorizeTree(E->getOperand(0));
6736       Value *R = vectorizeTree(E->getOperand(1));
6737 
6738       if (E->VectorizedValue) {
6739         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6740         return E->VectorizedValue;
6741       }
6742 
6743       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
6744       Value *V = Builder.CreateCmp(P0, L, R);
6745       propagateIRFlags(V, E->Scalars, VL0);
6746       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6747       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6748       V = ShuffleBuilder.finalize(V);
6749 
6750       E->VectorizedValue = V;
6751       ++NumVectorInstructions;
6752       return V;
6753     }
6754     case Instruction::Select: {
6755       setInsertPointAfterBundle(E);
6756 
6757       Value *Cond = vectorizeTree(E->getOperand(0));
6758       Value *True = vectorizeTree(E->getOperand(1));
6759       Value *False = vectorizeTree(E->getOperand(2));
6760 
6761       if (E->VectorizedValue) {
6762         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6763         return E->VectorizedValue;
6764       }
6765 
6766       Value *V = Builder.CreateSelect(Cond, True, False);
6767       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6768       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6769       V = ShuffleBuilder.finalize(V);
6770 
6771       E->VectorizedValue = V;
6772       ++NumVectorInstructions;
6773       return V;
6774     }
6775     case Instruction::FNeg: {
6776       setInsertPointAfterBundle(E);
6777 
6778       Value *Op = vectorizeTree(E->getOperand(0));
6779 
6780       if (E->VectorizedValue) {
6781         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6782         return E->VectorizedValue;
6783       }
6784 
6785       Value *V = Builder.CreateUnOp(
6786           static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
6787       propagateIRFlags(V, E->Scalars, VL0);
6788       if (auto *I = dyn_cast<Instruction>(V))
6789         V = propagateMetadata(I, E->Scalars);
6790 
6791       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6792       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6793       V = ShuffleBuilder.finalize(V);
6794 
6795       E->VectorizedValue = V;
6796       ++NumVectorInstructions;
6797 
6798       return V;
6799     }
6800     case Instruction::Add:
6801     case Instruction::FAdd:
6802     case Instruction::Sub:
6803     case Instruction::FSub:
6804     case Instruction::Mul:
6805     case Instruction::FMul:
6806     case Instruction::UDiv:
6807     case Instruction::SDiv:
6808     case Instruction::FDiv:
6809     case Instruction::URem:
6810     case Instruction::SRem:
6811     case Instruction::FRem:
6812     case Instruction::Shl:
6813     case Instruction::LShr:
6814     case Instruction::AShr:
6815     case Instruction::And:
6816     case Instruction::Or:
6817     case Instruction::Xor: {
6818       setInsertPointAfterBundle(E);
6819 
6820       Value *LHS = vectorizeTree(E->getOperand(0));
6821       Value *RHS = vectorizeTree(E->getOperand(1));
6822 
6823       if (E->VectorizedValue) {
6824         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6825         return E->VectorizedValue;
6826       }
6827 
6828       Value *V = Builder.CreateBinOp(
6829           static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
6830           RHS);
6831       propagateIRFlags(V, E->Scalars, VL0);
6832       if (auto *I = dyn_cast<Instruction>(V))
6833         V = propagateMetadata(I, E->Scalars);
6834 
6835       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6836       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6837       V = ShuffleBuilder.finalize(V);
6838 
6839       E->VectorizedValue = V;
6840       ++NumVectorInstructions;
6841 
6842       return V;
6843     }
6844     case Instruction::Load: {
6845       // Loads are inserted at the head of the tree because we don't want to
6846       // sink them all the way down past store instructions.
6847       setInsertPointAfterBundle(E);
6848 
6849       LoadInst *LI = cast<LoadInst>(VL0);
6850       Instruction *NewLI;
6851       unsigned AS = LI->getPointerAddressSpace();
6852       Value *PO = LI->getPointerOperand();
6853       if (E->State == TreeEntry::Vectorize) {
6854 
6855         Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS));
6856 
6857         // The pointer operand uses an in-tree scalar so we add the new BitCast
6858         // to ExternalUses list to make sure that an extract will be generated
6859         // in the future.
6860         if (TreeEntry *Entry = getTreeEntry(PO)) {
6861           // Find which lane we need to extract.
6862           unsigned FoundLane = Entry->findLaneForValue(PO);
6863           ExternalUses.emplace_back(PO, cast<User>(VecPtr), FoundLane);
6864         }
6865 
6866         NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
6867       } else {
6868         assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state");
6869         Value *VecPtr = vectorizeTree(E->getOperand(0));
6870         // Use the minimum alignment of the gathered loads.
6871         Align CommonAlignment = LI->getAlign();
6872         for (Value *V : E->Scalars)
6873           CommonAlignment =
6874               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
6875         NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment);
6876       }
6877       Value *V = propagateMetadata(NewLI, E->Scalars);
6878 
6879       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6880       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6881       V = ShuffleBuilder.finalize(V);
6882       E->VectorizedValue = V;
6883       ++NumVectorInstructions;
6884       return V;
6885     }
6886     case Instruction::Store: {
6887       auto *SI = cast<StoreInst>(VL0);
6888       unsigned AS = SI->getPointerAddressSpace();
6889 
6890       setInsertPointAfterBundle(E);
6891 
6892       Value *VecValue = vectorizeTree(E->getOperand(0));
6893       ShuffleBuilder.addMask(E->ReorderIndices);
6894       VecValue = ShuffleBuilder.finalize(VecValue);
6895 
6896       Value *ScalarPtr = SI->getPointerOperand();
6897       Value *VecPtr = Builder.CreateBitCast(
6898           ScalarPtr, VecValue->getType()->getPointerTo(AS));
6899       StoreInst *ST = Builder.CreateAlignedStore(VecValue, VecPtr,
6900                                                  SI->getAlign());
6901 
6902       // The pointer operand uses an in-tree scalar, so add the new BitCast to
6903       // ExternalUses to make sure that an extract will be generated in the
6904       // future.
6905       if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) {
6906         // Find which lane we need to extract.
6907         unsigned FoundLane = Entry->findLaneForValue(ScalarPtr);
6908         ExternalUses.push_back(
6909             ExternalUser(ScalarPtr, cast<User>(VecPtr), FoundLane));
6910       }
6911 
6912       Value *V = propagateMetadata(ST, E->Scalars);
6913 
6914       E->VectorizedValue = V;
6915       ++NumVectorInstructions;
6916       return V;
6917     }
6918     case Instruction::GetElementPtr: {
6919       auto *GEP0 = cast<GetElementPtrInst>(VL0);
6920       setInsertPointAfterBundle(E);
6921 
6922       Value *Op0 = vectorizeTree(E->getOperand(0));
6923 
6924       SmallVector<Value *> OpVecs;
6925       for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) {
6926         Value *OpVec = vectorizeTree(E->getOperand(J));
6927         OpVecs.push_back(OpVec);
6928       }
6929 
6930       Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs);
6931       if (Instruction *I = dyn_cast<Instruction>(V))
6932         V = propagateMetadata(I, E->Scalars);
6933 
6934       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6935       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6936       V = ShuffleBuilder.finalize(V);
6937 
6938       E->VectorizedValue = V;
6939       ++NumVectorInstructions;
6940 
6941       return V;
6942     }
6943     case Instruction::Call: {
6944       CallInst *CI = cast<CallInst>(VL0);
6945       setInsertPointAfterBundle(E);
6946 
6947       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
6948       if (Function *FI = CI->getCalledFunction())
6949         IID = FI->getIntrinsicID();
6950 
6951       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
6952 
6953       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
6954       bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
6955                           VecCallCosts.first <= VecCallCosts.second;
6956 
6957       Value *ScalarArg = nullptr;
6958       std::vector<Value *> OpVecs;
6959       SmallVector<Type *, 2> TysForDecl =
6960           {FixedVectorType::get(CI->getType(), E->Scalars.size())};
6961       for (int j = 0, e = CI->arg_size(); j < e; ++j) {
6962         ValueList OpVL;
6963         // Some intrinsics have scalar arguments. This argument should not be
6964         // vectorized.
6965         if (UseIntrinsic && hasVectorInstrinsicScalarOpd(IID, j)) {
6966           CallInst *CEI = cast<CallInst>(VL0);
6967           ScalarArg = CEI->getArgOperand(j);
6968           OpVecs.push_back(CEI->getArgOperand(j));
6969           if (hasVectorInstrinsicOverloadedScalarOpd(IID, j))
6970             TysForDecl.push_back(ScalarArg->getType());
6971           continue;
6972         }
6973 
6974         Value *OpVec = vectorizeTree(E->getOperand(j));
6975         LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
6976         OpVecs.push_back(OpVec);
6977       }
6978 
6979       Function *CF;
6980       if (!UseIntrinsic) {
6981         VFShape Shape =
6982             VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
6983                                   VecTy->getNumElements())),
6984                          false /*HasGlobalPred*/);
6985         CF = VFDatabase(*CI).getVectorizedFunction(Shape);
6986       } else {
6987         CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl);
6988       }
6989 
6990       SmallVector<OperandBundleDef, 1> OpBundles;
6991       CI->getOperandBundlesAsDefs(OpBundles);
6992       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
6993 
6994       // The scalar argument uses an in-tree scalar so we add the new vectorized
6995       // call to ExternalUses list to make sure that an extract will be
6996       // generated in the future.
6997       if (ScalarArg) {
6998         if (TreeEntry *Entry = getTreeEntry(ScalarArg)) {
6999           // Find which lane we need to extract.
7000           unsigned FoundLane = Entry->findLaneForValue(ScalarArg);
7001           ExternalUses.push_back(
7002               ExternalUser(ScalarArg, cast<User>(V), FoundLane));
7003         }
7004       }
7005 
7006       propagateIRFlags(V, E->Scalars, VL0);
7007       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7008       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7009       V = ShuffleBuilder.finalize(V);
7010 
7011       E->VectorizedValue = V;
7012       ++NumVectorInstructions;
7013       return V;
7014     }
7015     case Instruction::ShuffleVector: {
7016       assert(E->isAltShuffle() &&
7017              ((Instruction::isBinaryOp(E->getOpcode()) &&
7018                Instruction::isBinaryOp(E->getAltOpcode())) ||
7019               (Instruction::isCast(E->getOpcode()) &&
7020                Instruction::isCast(E->getAltOpcode())) ||
7021               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
7022              "Invalid Shuffle Vector Operand");
7023 
7024       Value *LHS = nullptr, *RHS = nullptr;
7025       if (Instruction::isBinaryOp(E->getOpcode()) || isa<CmpInst>(VL0)) {
7026         setInsertPointAfterBundle(E);
7027         LHS = vectorizeTree(E->getOperand(0));
7028         RHS = vectorizeTree(E->getOperand(1));
7029       } else {
7030         setInsertPointAfterBundle(E);
7031         LHS = vectorizeTree(E->getOperand(0));
7032       }
7033 
7034       if (E->VectorizedValue) {
7035         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7036         return E->VectorizedValue;
7037       }
7038 
7039       Value *V0, *V1;
7040       if (Instruction::isBinaryOp(E->getOpcode())) {
7041         V0 = Builder.CreateBinOp(
7042             static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
7043         V1 = Builder.CreateBinOp(
7044             static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
7045       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
7046         V0 = Builder.CreateCmp(CI0->getPredicate(), LHS, RHS);
7047         auto *AltCI = cast<CmpInst>(E->getAltOp());
7048         CmpInst::Predicate AltPred = AltCI->getPredicate();
7049         unsigned AltIdx =
7050             std::distance(E->Scalars.begin(), find(E->Scalars, AltCI));
7051         if (AltCI->getOperand(0) != E->getOperand(0)[AltIdx])
7052           AltPred = CmpInst::getSwappedPredicate(AltPred);
7053         V1 = Builder.CreateCmp(AltPred, LHS, RHS);
7054       } else {
7055         V0 = Builder.CreateCast(
7056             static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
7057         V1 = Builder.CreateCast(
7058             static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
7059       }
7060       // Add V0 and V1 to later analysis to try to find and remove matching
7061       // instruction, if any.
7062       for (Value *V : {V0, V1}) {
7063         if (auto *I = dyn_cast<Instruction>(V)) {
7064           GatherShuffleSeq.insert(I);
7065           CSEBlocks.insert(I->getParent());
7066         }
7067       }
7068 
7069       // Create shuffle to take alternate operations from the vector.
7070       // Also, gather up main and alt scalar ops to propagate IR flags to
7071       // each vector operation.
7072       ValueList OpScalars, AltScalars;
7073       SmallVector<int> Mask;
7074       buildSuffleEntryMask(
7075           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
7076           [E](Instruction *I) {
7077             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
7078             if (auto *CI0 = dyn_cast<CmpInst>(E->getMainOp())) {
7079               auto *AltCI0 = cast<CmpInst>(E->getAltOp());
7080               auto *CI = cast<CmpInst>(I);
7081               CmpInst::Predicate P0 = CI0->getPredicate();
7082               CmpInst::Predicate AltP0 = AltCI0->getPredicate();
7083               assert(P0 != AltP0 &&
7084                      "Expected different main/alternate predicates.");
7085               CmpInst::Predicate AltP0Swapped =
7086                   CmpInst::getSwappedPredicate(AltP0);
7087               CmpInst::Predicate CurrentPred = CI->getPredicate();
7088               if (P0 == AltP0Swapped)
7089                 return (P0 == CurrentPred &&
7090                         !areCompatibleCmpOps(
7091                             CI0->getOperand(0), CI0->getOperand(1),
7092                             CI->getOperand(0), CI->getOperand(1))) ||
7093                        (AltP0 == CurrentPred &&
7094                         !areCompatibleCmpOps(
7095                             CI0->getOperand(0), CI0->getOperand(1),
7096                             CI->getOperand(1), CI->getOperand(0)));
7097               return AltP0 == CurrentPred || AltP0Swapped == CurrentPred;
7098             }
7099             return I->getOpcode() == E->getAltOpcode();
7100           },
7101           Mask, &OpScalars, &AltScalars);
7102 
7103       propagateIRFlags(V0, OpScalars);
7104       propagateIRFlags(V1, AltScalars);
7105 
7106       Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
7107       if (auto *I = dyn_cast<Instruction>(V)) {
7108         V = propagateMetadata(I, E->Scalars);
7109         GatherShuffleSeq.insert(I);
7110         CSEBlocks.insert(I->getParent());
7111       }
7112       V = ShuffleBuilder.finalize(V);
7113 
7114       E->VectorizedValue = V;
7115       ++NumVectorInstructions;
7116 
7117       return V;
7118     }
7119     default:
7120     llvm_unreachable("unknown inst");
7121   }
7122   return nullptr;
7123 }
7124 
7125 Value *BoUpSLP::vectorizeTree() {
7126   ExtraValueToDebugLocsMap ExternallyUsedValues;
7127   return vectorizeTree(ExternallyUsedValues);
7128 }
7129 
7130 Value *
7131 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
7132   // All blocks must be scheduled before any instructions are inserted.
7133   for (auto &BSIter : BlocksSchedules) {
7134     scheduleBlock(BSIter.second.get());
7135   }
7136 
7137   Builder.SetInsertPoint(&F->getEntryBlock().front());
7138   auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
7139 
7140   // If the vectorized tree can be rewritten in a smaller type, we truncate the
7141   // vectorized root. InstCombine will then rewrite the entire expression. We
7142   // sign extend the extracted values below.
7143   auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
7144   if (MinBWs.count(ScalarRoot)) {
7145     if (auto *I = dyn_cast<Instruction>(VectorRoot)) {
7146       // If current instr is a phi and not the last phi, insert it after the
7147       // last phi node.
7148       if (isa<PHINode>(I))
7149         Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt());
7150       else
7151         Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
7152     }
7153     auto BundleWidth = VectorizableTree[0]->Scalars.size();
7154     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
7155     auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
7156     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
7157     VectorizableTree[0]->VectorizedValue = Trunc;
7158   }
7159 
7160   LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
7161                     << " values .\n");
7162 
7163   // Extract all of the elements with the external uses.
7164   for (const auto &ExternalUse : ExternalUses) {
7165     Value *Scalar = ExternalUse.Scalar;
7166     llvm::User *User = ExternalUse.User;
7167 
7168     // Skip users that we already RAUW. This happens when one instruction
7169     // has multiple uses of the same value.
7170     if (User && !is_contained(Scalar->users(), User))
7171       continue;
7172     TreeEntry *E = getTreeEntry(Scalar);
7173     assert(E && "Invalid scalar");
7174     assert(E->State != TreeEntry::NeedToGather &&
7175            "Extracting from a gather list");
7176 
7177     Value *Vec = E->VectorizedValue;
7178     assert(Vec && "Can't find vectorizable value");
7179 
7180     Value *Lane = Builder.getInt32(ExternalUse.Lane);
7181     auto ExtractAndExtendIfNeeded = [&](Value *Vec) {
7182       if (Scalar->getType() != Vec->getType()) {
7183         Value *Ex;
7184         // "Reuse" the existing extract to improve final codegen.
7185         if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) {
7186           Ex = Builder.CreateExtractElement(ES->getOperand(0),
7187                                             ES->getOperand(1));
7188         } else {
7189           Ex = Builder.CreateExtractElement(Vec, Lane);
7190         }
7191         // If necessary, sign-extend or zero-extend ScalarRoot
7192         // to the larger type.
7193         if (!MinBWs.count(ScalarRoot))
7194           return Ex;
7195         if (MinBWs[ScalarRoot].second)
7196           return Builder.CreateSExt(Ex, Scalar->getType());
7197         return Builder.CreateZExt(Ex, Scalar->getType());
7198       }
7199       assert(isa<FixedVectorType>(Scalar->getType()) &&
7200              isa<InsertElementInst>(Scalar) &&
7201              "In-tree scalar of vector type is not insertelement?");
7202       return Vec;
7203     };
7204     // If User == nullptr, the Scalar is used as extra arg. Generate
7205     // ExtractElement instruction and update the record for this scalar in
7206     // ExternallyUsedValues.
7207     if (!User) {
7208       assert(ExternallyUsedValues.count(Scalar) &&
7209              "Scalar with nullptr as an external user must be registered in "
7210              "ExternallyUsedValues map");
7211       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7212         Builder.SetInsertPoint(VecI->getParent(),
7213                                std::next(VecI->getIterator()));
7214       } else {
7215         Builder.SetInsertPoint(&F->getEntryBlock().front());
7216       }
7217       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7218       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
7219       auto &NewInstLocs = ExternallyUsedValues[NewInst];
7220       auto It = ExternallyUsedValues.find(Scalar);
7221       assert(It != ExternallyUsedValues.end() &&
7222              "Externally used scalar is not found in ExternallyUsedValues");
7223       NewInstLocs.append(It->second);
7224       ExternallyUsedValues.erase(Scalar);
7225       // Required to update internally referenced instructions.
7226       Scalar->replaceAllUsesWith(NewInst);
7227       continue;
7228     }
7229 
7230     // Generate extracts for out-of-tree users.
7231     // Find the insertion point for the extractelement lane.
7232     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7233       if (PHINode *PH = dyn_cast<PHINode>(User)) {
7234         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
7235           if (PH->getIncomingValue(i) == Scalar) {
7236             Instruction *IncomingTerminator =
7237                 PH->getIncomingBlock(i)->getTerminator();
7238             if (isa<CatchSwitchInst>(IncomingTerminator)) {
7239               Builder.SetInsertPoint(VecI->getParent(),
7240                                      std::next(VecI->getIterator()));
7241             } else {
7242               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
7243             }
7244             Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7245             CSEBlocks.insert(PH->getIncomingBlock(i));
7246             PH->setOperand(i, NewInst);
7247           }
7248         }
7249       } else {
7250         Builder.SetInsertPoint(cast<Instruction>(User));
7251         Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7252         CSEBlocks.insert(cast<Instruction>(User)->getParent());
7253         User->replaceUsesOfWith(Scalar, NewInst);
7254       }
7255     } else {
7256       Builder.SetInsertPoint(&F->getEntryBlock().front());
7257       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7258       CSEBlocks.insert(&F->getEntryBlock());
7259       User->replaceUsesOfWith(Scalar, NewInst);
7260     }
7261 
7262     LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
7263   }
7264 
7265   // For each vectorized value:
7266   for (auto &TEPtr : VectorizableTree) {
7267     TreeEntry *Entry = TEPtr.get();
7268 
7269     // No need to handle users of gathered values.
7270     if (Entry->State == TreeEntry::NeedToGather)
7271       continue;
7272 
7273     assert(Entry->VectorizedValue && "Can't find vectorizable value");
7274 
7275     // For each lane:
7276     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
7277       Value *Scalar = Entry->Scalars[Lane];
7278 
7279 #ifndef NDEBUG
7280       Type *Ty = Scalar->getType();
7281       if (!Ty->isVoidTy()) {
7282         for (User *U : Scalar->users()) {
7283           LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
7284 
7285           // It is legal to delete users in the ignorelist.
7286           assert((getTreeEntry(U) || is_contained(UserIgnoreList, U) ||
7287                   (isa_and_nonnull<Instruction>(U) &&
7288                    isDeleted(cast<Instruction>(U)))) &&
7289                  "Deleting out-of-tree value");
7290         }
7291       }
7292 #endif
7293       LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
7294       eraseInstruction(cast<Instruction>(Scalar));
7295     }
7296   }
7297 
7298   Builder.ClearInsertionPoint();
7299   InstrElementSize.clear();
7300 
7301   return VectorizableTree[0]->VectorizedValue;
7302 }
7303 
7304 void BoUpSLP::optimizeGatherSequence() {
7305   LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleSeq.size()
7306                     << " gather sequences instructions.\n");
7307   // LICM InsertElementInst sequences.
7308   for (Instruction *I : GatherShuffleSeq) {
7309     if (isDeleted(I))
7310       continue;
7311 
7312     // Check if this block is inside a loop.
7313     Loop *L = LI->getLoopFor(I->getParent());
7314     if (!L)
7315       continue;
7316 
7317     // Check if it has a preheader.
7318     BasicBlock *PreHeader = L->getLoopPreheader();
7319     if (!PreHeader)
7320       continue;
7321 
7322     // If the vector or the element that we insert into it are
7323     // instructions that are defined in this basic block then we can't
7324     // hoist this instruction.
7325     if (any_of(I->operands(), [L](Value *V) {
7326           auto *OpI = dyn_cast<Instruction>(V);
7327           return OpI && L->contains(OpI);
7328         }))
7329       continue;
7330 
7331     // We can hoist this instruction. Move it to the pre-header.
7332     I->moveBefore(PreHeader->getTerminator());
7333   }
7334 
7335   // Make a list of all reachable blocks in our CSE queue.
7336   SmallVector<const DomTreeNode *, 8> CSEWorkList;
7337   CSEWorkList.reserve(CSEBlocks.size());
7338   for (BasicBlock *BB : CSEBlocks)
7339     if (DomTreeNode *N = DT->getNode(BB)) {
7340       assert(DT->isReachableFromEntry(N));
7341       CSEWorkList.push_back(N);
7342     }
7343 
7344   // Sort blocks by domination. This ensures we visit a block after all blocks
7345   // dominating it are visited.
7346   llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) {
7347     assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) &&
7348            "Different nodes should have different DFS numbers");
7349     return A->getDFSNumIn() < B->getDFSNumIn();
7350   });
7351 
7352   // Less defined shuffles can be replaced by the more defined copies.
7353   // Between two shuffles one is less defined if it has the same vector operands
7354   // and its mask indeces are the same as in the first one or undefs. E.g.
7355   // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0,
7356   // poison, <0, 0, 0, 0>.
7357   auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2,
7358                                            SmallVectorImpl<int> &NewMask) {
7359     if (I1->getType() != I2->getType())
7360       return false;
7361     auto *SI1 = dyn_cast<ShuffleVectorInst>(I1);
7362     auto *SI2 = dyn_cast<ShuffleVectorInst>(I2);
7363     if (!SI1 || !SI2)
7364       return I1->isIdenticalTo(I2);
7365     if (SI1->isIdenticalTo(SI2))
7366       return true;
7367     for (int I = 0, E = SI1->getNumOperands(); I < E; ++I)
7368       if (SI1->getOperand(I) != SI2->getOperand(I))
7369         return false;
7370     // Check if the second instruction is more defined than the first one.
7371     NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end());
7372     ArrayRef<int> SM1 = SI1->getShuffleMask();
7373     // Count trailing undefs in the mask to check the final number of used
7374     // registers.
7375     unsigned LastUndefsCnt = 0;
7376     for (int I = 0, E = NewMask.size(); I < E; ++I) {
7377       if (SM1[I] == UndefMaskElem)
7378         ++LastUndefsCnt;
7379       else
7380         LastUndefsCnt = 0;
7381       if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem &&
7382           NewMask[I] != SM1[I])
7383         return false;
7384       if (NewMask[I] == UndefMaskElem)
7385         NewMask[I] = SM1[I];
7386     }
7387     // Check if the last undefs actually change the final number of used vector
7388     // registers.
7389     return SM1.size() - LastUndefsCnt > 1 &&
7390            TTI->getNumberOfParts(SI1->getType()) ==
7391                TTI->getNumberOfParts(
7392                    FixedVectorType::get(SI1->getType()->getElementType(),
7393                                         SM1.size() - LastUndefsCnt));
7394   };
7395   // Perform O(N^2) search over the gather/shuffle sequences and merge identical
7396   // instructions. TODO: We can further optimize this scan if we split the
7397   // instructions into different buckets based on the insert lane.
7398   SmallVector<Instruction *, 16> Visited;
7399   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
7400     assert(*I &&
7401            (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
7402            "Worklist not sorted properly!");
7403     BasicBlock *BB = (*I)->getBlock();
7404     // For all instructions in blocks containing gather sequences:
7405     for (Instruction &In : llvm::make_early_inc_range(*BB)) {
7406       if (isDeleted(&In))
7407         continue;
7408       if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) &&
7409           !isa<ShuffleVectorInst>(&In) && !GatherShuffleSeq.contains(&In))
7410         continue;
7411 
7412       // Check if we can replace this instruction with any of the
7413       // visited instructions.
7414       bool Replaced = false;
7415       for (Instruction *&V : Visited) {
7416         SmallVector<int> NewMask;
7417         if (IsIdenticalOrLessDefined(&In, V, NewMask) &&
7418             DT->dominates(V->getParent(), In.getParent())) {
7419           In.replaceAllUsesWith(V);
7420           eraseInstruction(&In);
7421           if (auto *SI = dyn_cast<ShuffleVectorInst>(V))
7422             if (!NewMask.empty())
7423               SI->setShuffleMask(NewMask);
7424           Replaced = true;
7425           break;
7426         }
7427         if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) &&
7428             GatherShuffleSeq.contains(V) &&
7429             IsIdenticalOrLessDefined(V, &In, NewMask) &&
7430             DT->dominates(In.getParent(), V->getParent())) {
7431           In.moveAfter(V);
7432           V->replaceAllUsesWith(&In);
7433           eraseInstruction(V);
7434           if (auto *SI = dyn_cast<ShuffleVectorInst>(&In))
7435             if (!NewMask.empty())
7436               SI->setShuffleMask(NewMask);
7437           V = &In;
7438           Replaced = true;
7439           break;
7440         }
7441       }
7442       if (!Replaced) {
7443         assert(!is_contained(Visited, &In));
7444         Visited.push_back(&In);
7445       }
7446     }
7447   }
7448   CSEBlocks.clear();
7449   GatherShuffleSeq.clear();
7450 }
7451 
7452 BoUpSLP::ScheduleData *
7453 BoUpSLP::BlockScheduling::buildBundle(ArrayRef<Value *> VL) {
7454   ScheduleData *Bundle = nullptr;
7455   ScheduleData *PrevInBundle = nullptr;
7456   for (Value *V : VL) {
7457     ScheduleData *BundleMember = getScheduleData(V);
7458     assert(BundleMember &&
7459            "no ScheduleData for bundle member "
7460            "(maybe not in same basic block)");
7461     assert(BundleMember->isSchedulingEntity() &&
7462            "bundle member already part of other bundle");
7463     if (PrevInBundle) {
7464       PrevInBundle->NextInBundle = BundleMember;
7465     } else {
7466       Bundle = BundleMember;
7467     }
7468     BundleMember->UnscheduledDepsInBundle = 0;
7469     Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps;
7470 
7471     // Group the instructions to a bundle.
7472     BundleMember->FirstInBundle = Bundle;
7473     PrevInBundle = BundleMember;
7474   }
7475   assert(Bundle && "Failed to find schedule bundle");
7476   return Bundle;
7477 }
7478 
7479 // Groups the instructions to a bundle (which is then a single scheduling entity)
7480 // and schedules instructions until the bundle gets ready.
7481 Optional<BoUpSLP::ScheduleData *>
7482 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
7483                                             const InstructionsState &S) {
7484   // No need to schedule PHIs, insertelement, extractelement and extractvalue
7485   // instructions.
7486   if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue))
7487     return nullptr;
7488 
7489   // Initialize the instruction bundle.
7490   Instruction *OldScheduleEnd = ScheduleEnd;
7491   LLVM_DEBUG(dbgs() << "SLP:  bundle: " << *S.OpValue << "\n");
7492 
7493   auto TryScheduleBundleImpl = [this, OldScheduleEnd, SLP](bool ReSchedule,
7494                                                          ScheduleData *Bundle) {
7495     // The scheduling region got new instructions at the lower end (or it is a
7496     // new region for the first bundle). This makes it necessary to
7497     // recalculate all dependencies.
7498     // It is seldom that this needs to be done a second time after adding the
7499     // initial bundle to the region.
7500     if (ScheduleEnd != OldScheduleEnd) {
7501       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode())
7502         doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); });
7503       ReSchedule = true;
7504     }
7505     if (ReSchedule) {
7506       resetSchedule();
7507       initialFillReadyList(ReadyInsts);
7508     }
7509     if (Bundle) {
7510       LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle
7511                         << " in block " << BB->getName() << "\n");
7512       calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP);
7513     }
7514 
7515     // Now try to schedule the new bundle or (if no bundle) just calculate
7516     // dependencies. As soon as the bundle is "ready" it means that there are no
7517     // cyclic dependencies and we can schedule it. Note that's important that we
7518     // don't "schedule" the bundle yet (see cancelScheduling).
7519     while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) &&
7520            !ReadyInsts.empty()) {
7521       ScheduleData *Picked = ReadyInsts.pop_back_val();
7522       if (Picked->isSchedulingEntity() && Picked->isReady())
7523         schedule(Picked, ReadyInsts);
7524     }
7525   };
7526 
7527   // Make sure that the scheduling region contains all
7528   // instructions of the bundle.
7529   for (Value *V : VL) {
7530     if (!extendSchedulingRegion(V, S)) {
7531       // If the scheduling region got new instructions at the lower end (or it
7532       // is a new region for the first bundle). This makes it necessary to
7533       // recalculate all dependencies.
7534       // Otherwise the compiler may crash trying to incorrectly calculate
7535       // dependencies and emit instruction in the wrong order at the actual
7536       // scheduling.
7537       TryScheduleBundleImpl(/*ReSchedule=*/false, nullptr);
7538       return None;
7539     }
7540   }
7541 
7542   bool ReSchedule = false;
7543   for (Value *V : VL) {
7544     ScheduleData *BundleMember = getScheduleData(V);
7545     assert(BundleMember &&
7546            "no ScheduleData for bundle member (maybe not in same basic block)");
7547     if (!BundleMember->IsScheduled)
7548       continue;
7549     // A bundle member was scheduled as single instruction before and now
7550     // needs to be scheduled as part of the bundle. We just get rid of the
7551     // existing schedule.
7552     LLVM_DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
7553                       << " was already scheduled\n");
7554     ReSchedule = true;
7555   }
7556 
7557   auto *Bundle = buildBundle(VL);
7558   TryScheduleBundleImpl(ReSchedule, Bundle);
7559   if (!Bundle->isReady()) {
7560     cancelScheduling(VL, S.OpValue);
7561     return None;
7562   }
7563   return Bundle;
7564 }
7565 
7566 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
7567                                                 Value *OpValue) {
7568   if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue))
7569     return;
7570 
7571   ScheduleData *Bundle = getScheduleData(OpValue);
7572   LLVM_DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
7573   assert(!Bundle->IsScheduled &&
7574          "Can't cancel bundle which is already scheduled");
7575   assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
7576          "tried to unbundle something which is not a bundle");
7577 
7578   // Un-bundle: make single instructions out of the bundle.
7579   ScheduleData *BundleMember = Bundle;
7580   while (BundleMember) {
7581     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
7582     BundleMember->FirstInBundle = BundleMember;
7583     ScheduleData *Next = BundleMember->NextInBundle;
7584     BundleMember->NextInBundle = nullptr;
7585     BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps;
7586     if (BundleMember->UnscheduledDepsInBundle == 0) {
7587       ReadyInsts.insert(BundleMember);
7588     }
7589     BundleMember = Next;
7590   }
7591 }
7592 
7593 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
7594   // Allocate a new ScheduleData for the instruction.
7595   if (ChunkPos >= ChunkSize) {
7596     ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
7597     ChunkPos = 0;
7598   }
7599   return &(ScheduleDataChunks.back()[ChunkPos++]);
7600 }
7601 
7602 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
7603                                                       const InstructionsState &S) {
7604   if (getScheduleData(V, isOneOf(S, V)))
7605     return true;
7606   Instruction *I = dyn_cast<Instruction>(V);
7607   assert(I && "bundle member must be an instruction");
7608   assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) &&
7609          "phi nodes/insertelements/extractelements/extractvalues don't need to "
7610          "be scheduled");
7611   auto &&CheckSheduleForI = [this, &S](Instruction *I) -> bool {
7612     ScheduleData *ISD = getScheduleData(I);
7613     if (!ISD)
7614       return false;
7615     assert(isInSchedulingRegion(ISD) &&
7616            "ScheduleData not in scheduling region");
7617     ScheduleData *SD = allocateScheduleDataChunks();
7618     SD->Inst = I;
7619     SD->init(SchedulingRegionID, S.OpValue);
7620     ExtraScheduleDataMap[I][S.OpValue] = SD;
7621     return true;
7622   };
7623   if (CheckSheduleForI(I))
7624     return true;
7625   if (!ScheduleStart) {
7626     // It's the first instruction in the new region.
7627     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
7628     ScheduleStart = I;
7629     ScheduleEnd = I->getNextNode();
7630     if (isOneOf(S, I) != I)
7631       CheckSheduleForI(I);
7632     assert(ScheduleEnd && "tried to vectorize a terminator?");
7633     LLVM_DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
7634     return true;
7635   }
7636   // Search up and down at the same time, because we don't know if the new
7637   // instruction is above or below the existing scheduling region.
7638   BasicBlock::reverse_iterator UpIter =
7639       ++ScheduleStart->getIterator().getReverse();
7640   BasicBlock::reverse_iterator UpperEnd = BB->rend();
7641   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
7642   BasicBlock::iterator LowerEnd = BB->end();
7643   while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I &&
7644          &*DownIter != I) {
7645     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
7646       LLVM_DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
7647       return false;
7648     }
7649 
7650     ++UpIter;
7651     ++DownIter;
7652   }
7653   if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) {
7654     assert(I->getParent() == ScheduleStart->getParent() &&
7655            "Instruction is in wrong basic block.");
7656     initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
7657     ScheduleStart = I;
7658     if (isOneOf(S, I) != I)
7659       CheckSheduleForI(I);
7660     LLVM_DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I
7661                       << "\n");
7662     return true;
7663   }
7664   assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) &&
7665          "Expected to reach top of the basic block or instruction down the "
7666          "lower end.");
7667   assert(I->getParent() == ScheduleEnd->getParent() &&
7668          "Instruction is in wrong basic block.");
7669   initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
7670                    nullptr);
7671   ScheduleEnd = I->getNextNode();
7672   if (isOneOf(S, I) != I)
7673     CheckSheduleForI(I);
7674   assert(ScheduleEnd && "tried to vectorize a terminator?");
7675   LLVM_DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
7676   return true;
7677 }
7678 
7679 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
7680                                                 Instruction *ToI,
7681                                                 ScheduleData *PrevLoadStore,
7682                                                 ScheduleData *NextLoadStore) {
7683   ScheduleData *CurrentLoadStore = PrevLoadStore;
7684   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
7685     ScheduleData *SD = ScheduleDataMap[I];
7686     if (!SD) {
7687       SD = allocateScheduleDataChunks();
7688       ScheduleDataMap[I] = SD;
7689       SD->Inst = I;
7690     }
7691     assert(!isInSchedulingRegion(SD) &&
7692            "new ScheduleData already in scheduling region");
7693     SD->init(SchedulingRegionID, I);
7694 
7695     if (I->mayReadOrWriteMemory() &&
7696         (!isa<IntrinsicInst>(I) ||
7697          (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect &&
7698           cast<IntrinsicInst>(I)->getIntrinsicID() !=
7699               Intrinsic::pseudoprobe))) {
7700       // Update the linked list of memory accessing instructions.
7701       if (CurrentLoadStore) {
7702         CurrentLoadStore->NextLoadStore = SD;
7703       } else {
7704         FirstLoadStoreInRegion = SD;
7705       }
7706       CurrentLoadStore = SD;
7707     }
7708   }
7709   if (NextLoadStore) {
7710     if (CurrentLoadStore)
7711       CurrentLoadStore->NextLoadStore = NextLoadStore;
7712   } else {
7713     LastLoadStoreInRegion = CurrentLoadStore;
7714   }
7715 }
7716 
7717 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
7718                                                      bool InsertInReadyList,
7719                                                      BoUpSLP *SLP) {
7720   assert(SD->isSchedulingEntity());
7721 
7722   SmallVector<ScheduleData *, 10> WorkList;
7723   WorkList.push_back(SD);
7724 
7725   while (!WorkList.empty()) {
7726     ScheduleData *SD = WorkList.pop_back_val();
7727     for (ScheduleData *BundleMember = SD; BundleMember;
7728          BundleMember = BundleMember->NextInBundle) {
7729       assert(isInSchedulingRegion(BundleMember));
7730       if (BundleMember->hasValidDependencies())
7731         continue;
7732 
7733       LLVM_DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember
7734                  << "\n");
7735       BundleMember->Dependencies = 0;
7736       BundleMember->resetUnscheduledDeps();
7737 
7738       // Handle def-use chain dependencies.
7739       if (BundleMember->OpValue != BundleMember->Inst) {
7740         ScheduleData *UseSD = getScheduleData(BundleMember->Inst);
7741         if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
7742           BundleMember->Dependencies++;
7743           ScheduleData *DestBundle = UseSD->FirstInBundle;
7744           if (!DestBundle->IsScheduled)
7745             BundleMember->incrementUnscheduledDeps(1);
7746           if (!DestBundle->hasValidDependencies())
7747             WorkList.push_back(DestBundle);
7748         }
7749       } else {
7750         for (User *U : BundleMember->Inst->users()) {
7751           assert(isa<Instruction>(U) &&
7752                  "user of instruction must be instruction");
7753           ScheduleData *UseSD = getScheduleData(U);
7754           if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
7755             BundleMember->Dependencies++;
7756             ScheduleData *DestBundle = UseSD->FirstInBundle;
7757             if (!DestBundle->IsScheduled)
7758               BundleMember->incrementUnscheduledDeps(1);
7759             if (!DestBundle->hasValidDependencies())
7760               WorkList.push_back(DestBundle);
7761           }
7762         }
7763       }
7764 
7765       // Handle the memory dependencies (if any).
7766       ScheduleData *DepDest = BundleMember->NextLoadStore;
7767       if (!DepDest)
7768         continue;
7769       Instruction *SrcInst = BundleMember->Inst;
7770       assert(SrcInst->mayReadOrWriteMemory() &&
7771              "NextLoadStore list for non memory effecting bundle?");
7772       MemoryLocation SrcLoc = getLocation(SrcInst);
7773       bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
7774       unsigned numAliased = 0;
7775       unsigned DistToSrc = 1;
7776 
7777       for ( ; DepDest; DepDest = DepDest->NextLoadStore) {
7778         assert(isInSchedulingRegion(DepDest));
7779 
7780         // We have two limits to reduce the complexity:
7781         // 1) AliasedCheckLimit: It's a small limit to reduce calls to
7782         //    SLP->isAliased (which is the expensive part in this loop).
7783         // 2) MaxMemDepDistance: It's for very large blocks and it aborts
7784         //    the whole loop (even if the loop is fast, it's quadratic).
7785         //    It's important for the loop break condition (see below) to
7786         //    check this limit even between two read-only instructions.
7787         if (DistToSrc >= MaxMemDepDistance ||
7788             ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
7789              (numAliased >= AliasedCheckLimit ||
7790               SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
7791 
7792           // We increment the counter only if the locations are aliased
7793           // (instead of counting all alias checks). This gives a better
7794           // balance between reduced runtime and accurate dependencies.
7795           numAliased++;
7796 
7797           DepDest->MemoryDependencies.push_back(BundleMember);
7798           BundleMember->Dependencies++;
7799           ScheduleData *DestBundle = DepDest->FirstInBundle;
7800           if (!DestBundle->IsScheduled) {
7801             BundleMember->incrementUnscheduledDeps(1);
7802           }
7803           if (!DestBundle->hasValidDependencies()) {
7804             WorkList.push_back(DestBundle);
7805           }
7806         }
7807 
7808         // Example, explaining the loop break condition: Let's assume our
7809         // starting instruction is i0 and MaxMemDepDistance = 3.
7810         //
7811         //                      +--------v--v--v
7812         //             i0,i1,i2,i3,i4,i5,i6,i7,i8
7813         //             +--------^--^--^
7814         //
7815         // MaxMemDepDistance let us stop alias-checking at i3 and we add
7816         // dependencies from i0 to i3,i4,.. (even if they are not aliased).
7817         // Previously we already added dependencies from i3 to i6,i7,i8
7818         // (because of MaxMemDepDistance). As we added a dependency from
7819         // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
7820         // and we can abort this loop at i6.
7821         if (DistToSrc >= 2 * MaxMemDepDistance)
7822           break;
7823         DistToSrc++;
7824       }
7825     }
7826     if (InsertInReadyList && SD->isReady()) {
7827       ReadyInsts.push_back(SD);
7828       LLVM_DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst
7829                         << "\n");
7830     }
7831   }
7832 }
7833 
7834 void BoUpSLP::BlockScheduling::resetSchedule() {
7835   assert(ScheduleStart &&
7836          "tried to reset schedule on block which has not been scheduled");
7837   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
7838     doForAllOpcodes(I, [&](ScheduleData *SD) {
7839       assert(isInSchedulingRegion(SD) &&
7840              "ScheduleData not in scheduling region");
7841       SD->IsScheduled = false;
7842       SD->resetUnscheduledDeps();
7843     });
7844   }
7845   ReadyInsts.clear();
7846 }
7847 
7848 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
7849   if (!BS->ScheduleStart)
7850     return;
7851 
7852   LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
7853 
7854   BS->resetSchedule();
7855 
7856   // For the real scheduling we use a more sophisticated ready-list: it is
7857   // sorted by the original instruction location. This lets the final schedule
7858   // be as  close as possible to the original instruction order.
7859   struct ScheduleDataCompare {
7860     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
7861       return SD2->SchedulingPriority < SD1->SchedulingPriority;
7862     }
7863   };
7864   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
7865 
7866   // Ensure that all dependency data is updated and fill the ready-list with
7867   // initial instructions.
7868   int Idx = 0;
7869   int NumToSchedule = 0;
7870   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
7871        I = I->getNextNode()) {
7872     BS->doForAllOpcodes(I, [this, &Idx, &NumToSchedule, BS](ScheduleData *SD) {
7873       assert((isVectorLikeInstWithConstOps(SD->Inst) ||
7874               SD->isPartOfBundle() == (getTreeEntry(SD->Inst) != nullptr)) &&
7875              "scheduler and vectorizer bundle mismatch");
7876       SD->FirstInBundle->SchedulingPriority = Idx++;
7877       if (SD->isSchedulingEntity()) {
7878         BS->calculateDependencies(SD, false, this);
7879         NumToSchedule++;
7880       }
7881     });
7882   }
7883   BS->initialFillReadyList(ReadyInsts);
7884 
7885   Instruction *LastScheduledInst = BS->ScheduleEnd;
7886 
7887   // Do the "real" scheduling.
7888   while (!ReadyInsts.empty()) {
7889     ScheduleData *picked = *ReadyInsts.begin();
7890     ReadyInsts.erase(ReadyInsts.begin());
7891 
7892     // Move the scheduled instruction(s) to their dedicated places, if not
7893     // there yet.
7894     for (ScheduleData *BundleMember = picked; BundleMember;
7895          BundleMember = BundleMember->NextInBundle) {
7896       Instruction *pickedInst = BundleMember->Inst;
7897       if (pickedInst->getNextNode() != LastScheduledInst)
7898         pickedInst->moveBefore(LastScheduledInst);
7899       LastScheduledInst = pickedInst;
7900     }
7901 
7902     BS->schedule(picked, ReadyInsts);
7903     NumToSchedule--;
7904   }
7905   assert(NumToSchedule == 0 && "could not schedule all instructions");
7906 
7907   // Avoid duplicate scheduling of the block.
7908   BS->ScheduleStart = nullptr;
7909 }
7910 
7911 unsigned BoUpSLP::getVectorElementSize(Value *V) {
7912   // If V is a store, just return the width of the stored value (or value
7913   // truncated just before storing) without traversing the expression tree.
7914   // This is the common case.
7915   if (auto *Store = dyn_cast<StoreInst>(V)) {
7916     if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand()))
7917       return DL->getTypeSizeInBits(Trunc->getSrcTy());
7918     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
7919   }
7920 
7921   if (auto *IEI = dyn_cast<InsertElementInst>(V))
7922     return getVectorElementSize(IEI->getOperand(1));
7923 
7924   auto E = InstrElementSize.find(V);
7925   if (E != InstrElementSize.end())
7926     return E->second;
7927 
7928   // If V is not a store, we can traverse the expression tree to find loads
7929   // that feed it. The type of the loaded value may indicate a more suitable
7930   // width than V's type. We want to base the vector element size on the width
7931   // of memory operations where possible.
7932   SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist;
7933   SmallPtrSet<Instruction *, 16> Visited;
7934   if (auto *I = dyn_cast<Instruction>(V)) {
7935     Worklist.emplace_back(I, I->getParent());
7936     Visited.insert(I);
7937   }
7938 
7939   // Traverse the expression tree in bottom-up order looking for loads. If we
7940   // encounter an instruction we don't yet handle, we give up.
7941   auto Width = 0u;
7942   while (!Worklist.empty()) {
7943     Instruction *I;
7944     BasicBlock *Parent;
7945     std::tie(I, Parent) = Worklist.pop_back_val();
7946 
7947     // We should only be looking at scalar instructions here. If the current
7948     // instruction has a vector type, skip.
7949     auto *Ty = I->getType();
7950     if (isa<VectorType>(Ty))
7951       continue;
7952 
7953     // If the current instruction is a load, update MaxWidth to reflect the
7954     // width of the loaded value.
7955     if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) ||
7956         isa<ExtractValueInst>(I))
7957       Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty));
7958 
7959     // Otherwise, we need to visit the operands of the instruction. We only
7960     // handle the interesting cases from buildTree here. If an operand is an
7961     // instruction we haven't yet visited and from the same basic block as the
7962     // user or the use is a PHI node, we add it to the worklist.
7963     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
7964              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) ||
7965              isa<UnaryOperator>(I)) {
7966       for (Use &U : I->operands())
7967         if (auto *J = dyn_cast<Instruction>(U.get()))
7968           if (Visited.insert(J).second &&
7969               (isa<PHINode>(I) || J->getParent() == Parent))
7970             Worklist.emplace_back(J, J->getParent());
7971     } else {
7972       break;
7973     }
7974   }
7975 
7976   // If we didn't encounter a memory access in the expression tree, or if we
7977   // gave up for some reason, just return the width of V. Otherwise, return the
7978   // maximum width we found.
7979   if (!Width) {
7980     if (auto *CI = dyn_cast<CmpInst>(V))
7981       V = CI->getOperand(0);
7982     Width = DL->getTypeSizeInBits(V->getType());
7983   }
7984 
7985   for (Instruction *I : Visited)
7986     InstrElementSize[I] = Width;
7987 
7988   return Width;
7989 }
7990 
7991 // Determine if a value V in a vectorizable expression Expr can be demoted to a
7992 // smaller type with a truncation. We collect the values that will be demoted
7993 // in ToDemote and additional roots that require investigating in Roots.
7994 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
7995                                   SmallVectorImpl<Value *> &ToDemote,
7996                                   SmallVectorImpl<Value *> &Roots) {
7997   // We can always demote constants.
7998   if (isa<Constant>(V)) {
7999     ToDemote.push_back(V);
8000     return true;
8001   }
8002 
8003   // If the value is not an instruction in the expression with only one use, it
8004   // cannot be demoted.
8005   auto *I = dyn_cast<Instruction>(V);
8006   if (!I || !I->hasOneUse() || !Expr.count(I))
8007     return false;
8008 
8009   switch (I->getOpcode()) {
8010 
8011   // We can always demote truncations and extensions. Since truncations can
8012   // seed additional demotion, we save the truncated value.
8013   case Instruction::Trunc:
8014     Roots.push_back(I->getOperand(0));
8015     break;
8016   case Instruction::ZExt:
8017   case Instruction::SExt:
8018     if (isa<ExtractElementInst>(I->getOperand(0)) ||
8019         isa<InsertElementInst>(I->getOperand(0)))
8020       return false;
8021     break;
8022 
8023   // We can demote certain binary operations if we can demote both of their
8024   // operands.
8025   case Instruction::Add:
8026   case Instruction::Sub:
8027   case Instruction::Mul:
8028   case Instruction::And:
8029   case Instruction::Or:
8030   case Instruction::Xor:
8031     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
8032         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
8033       return false;
8034     break;
8035 
8036   // We can demote selects if we can demote their true and false values.
8037   case Instruction::Select: {
8038     SelectInst *SI = cast<SelectInst>(I);
8039     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
8040         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
8041       return false;
8042     break;
8043   }
8044 
8045   // We can demote phis if we can demote all their incoming operands. Note that
8046   // we don't need to worry about cycles since we ensure single use above.
8047   case Instruction::PHI: {
8048     PHINode *PN = cast<PHINode>(I);
8049     for (Value *IncValue : PN->incoming_values())
8050       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
8051         return false;
8052     break;
8053   }
8054 
8055   // Otherwise, conservatively give up.
8056   default:
8057     return false;
8058   }
8059 
8060   // Record the value that we can demote.
8061   ToDemote.push_back(V);
8062   return true;
8063 }
8064 
8065 void BoUpSLP::computeMinimumValueSizes() {
8066   // If there are no external uses, the expression tree must be rooted by a
8067   // store. We can't demote in-memory values, so there is nothing to do here.
8068   if (ExternalUses.empty())
8069     return;
8070 
8071   // We only attempt to truncate integer expressions.
8072   auto &TreeRoot = VectorizableTree[0]->Scalars;
8073   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
8074   if (!TreeRootIT)
8075     return;
8076 
8077   // If the expression is not rooted by a store, these roots should have
8078   // external uses. We will rely on InstCombine to rewrite the expression in
8079   // the narrower type. However, InstCombine only rewrites single-use values.
8080   // This means that if a tree entry other than a root is used externally, it
8081   // must have multiple uses and InstCombine will not rewrite it. The code
8082   // below ensures that only the roots are used externally.
8083   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
8084   for (auto &EU : ExternalUses)
8085     if (!Expr.erase(EU.Scalar))
8086       return;
8087   if (!Expr.empty())
8088     return;
8089 
8090   // Collect the scalar values of the vectorizable expression. We will use this
8091   // context to determine which values can be demoted. If we see a truncation,
8092   // we mark it as seeding another demotion.
8093   for (auto &EntryPtr : VectorizableTree)
8094     Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
8095 
8096   // Ensure the roots of the vectorizable tree don't form a cycle. They must
8097   // have a single external user that is not in the vectorizable tree.
8098   for (auto *Root : TreeRoot)
8099     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
8100       return;
8101 
8102   // Conservatively determine if we can actually truncate the roots of the
8103   // expression. Collect the values that can be demoted in ToDemote and
8104   // additional roots that require investigating in Roots.
8105   SmallVector<Value *, 32> ToDemote;
8106   SmallVector<Value *, 4> Roots;
8107   for (auto *Root : TreeRoot)
8108     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
8109       return;
8110 
8111   // The maximum bit width required to represent all the values that can be
8112   // demoted without loss of precision. It would be safe to truncate the roots
8113   // of the expression to this width.
8114   auto MaxBitWidth = 8u;
8115 
8116   // We first check if all the bits of the roots are demanded. If they're not,
8117   // we can truncate the roots to this narrower type.
8118   for (auto *Root : TreeRoot) {
8119     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
8120     MaxBitWidth = std::max<unsigned>(
8121         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
8122   }
8123 
8124   // True if the roots can be zero-extended back to their original type, rather
8125   // than sign-extended. We know that if the leading bits are not demanded, we
8126   // can safely zero-extend. So we initialize IsKnownPositive to True.
8127   bool IsKnownPositive = true;
8128 
8129   // If all the bits of the roots are demanded, we can try a little harder to
8130   // compute a narrower type. This can happen, for example, if the roots are
8131   // getelementptr indices. InstCombine promotes these indices to the pointer
8132   // width. Thus, all their bits are technically demanded even though the
8133   // address computation might be vectorized in a smaller type.
8134   //
8135   // We start by looking at each entry that can be demoted. We compute the
8136   // maximum bit width required to store the scalar by using ValueTracking to
8137   // compute the number of high-order bits we can truncate.
8138   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
8139       llvm::all_of(TreeRoot, [](Value *R) {
8140         assert(R->hasOneUse() && "Root should have only one use!");
8141         return isa<GetElementPtrInst>(R->user_back());
8142       })) {
8143     MaxBitWidth = 8u;
8144 
8145     // Determine if the sign bit of all the roots is known to be zero. If not,
8146     // IsKnownPositive is set to False.
8147     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
8148       KnownBits Known = computeKnownBits(R, *DL);
8149       return Known.isNonNegative();
8150     });
8151 
8152     // Determine the maximum number of bits required to store the scalar
8153     // values.
8154     for (auto *Scalar : ToDemote) {
8155       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
8156       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
8157       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
8158     }
8159 
8160     // If we can't prove that the sign bit is zero, we must add one to the
8161     // maximum bit width to account for the unknown sign bit. This preserves
8162     // the existing sign bit so we can safely sign-extend the root back to the
8163     // original type. Otherwise, if we know the sign bit is zero, we will
8164     // zero-extend the root instead.
8165     //
8166     // FIXME: This is somewhat suboptimal, as there will be cases where adding
8167     //        one to the maximum bit width will yield a larger-than-necessary
8168     //        type. In general, we need to add an extra bit only if we can't
8169     //        prove that the upper bit of the original type is equal to the
8170     //        upper bit of the proposed smaller type. If these two bits are the
8171     //        same (either zero or one) we know that sign-extending from the
8172     //        smaller type will result in the same value. Here, since we can't
8173     //        yet prove this, we are just making the proposed smaller type
8174     //        larger to ensure correctness.
8175     if (!IsKnownPositive)
8176       ++MaxBitWidth;
8177   }
8178 
8179   // Round MaxBitWidth up to the next power-of-two.
8180   if (!isPowerOf2_64(MaxBitWidth))
8181     MaxBitWidth = NextPowerOf2(MaxBitWidth);
8182 
8183   // If the maximum bit width we compute is less than the with of the roots'
8184   // type, we can proceed with the narrowing. Otherwise, do nothing.
8185   if (MaxBitWidth >= TreeRootIT->getBitWidth())
8186     return;
8187 
8188   // If we can truncate the root, we must collect additional values that might
8189   // be demoted as a result. That is, those seeded by truncations we will
8190   // modify.
8191   while (!Roots.empty())
8192     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
8193 
8194   // Finally, map the values we can demote to the maximum bit with we computed.
8195   for (auto *Scalar : ToDemote)
8196     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
8197 }
8198 
8199 namespace {
8200 
8201 /// The SLPVectorizer Pass.
8202 struct SLPVectorizer : public FunctionPass {
8203   SLPVectorizerPass Impl;
8204 
8205   /// Pass identification, replacement for typeid
8206   static char ID;
8207 
8208   explicit SLPVectorizer() : FunctionPass(ID) {
8209     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
8210   }
8211 
8212   bool doInitialization(Module &M) override { return false; }
8213 
8214   bool runOnFunction(Function &F) override {
8215     if (skipFunction(F))
8216       return false;
8217 
8218     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
8219     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
8220     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
8221     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
8222     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
8223     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
8224     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
8225     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
8226     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
8227     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
8228 
8229     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8230   }
8231 
8232   void getAnalysisUsage(AnalysisUsage &AU) const override {
8233     FunctionPass::getAnalysisUsage(AU);
8234     AU.addRequired<AssumptionCacheTracker>();
8235     AU.addRequired<ScalarEvolutionWrapperPass>();
8236     AU.addRequired<AAResultsWrapperPass>();
8237     AU.addRequired<TargetTransformInfoWrapperPass>();
8238     AU.addRequired<LoopInfoWrapperPass>();
8239     AU.addRequired<DominatorTreeWrapperPass>();
8240     AU.addRequired<DemandedBitsWrapperPass>();
8241     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
8242     AU.addRequired<InjectTLIMappingsLegacy>();
8243     AU.addPreserved<LoopInfoWrapperPass>();
8244     AU.addPreserved<DominatorTreeWrapperPass>();
8245     AU.addPreserved<AAResultsWrapperPass>();
8246     AU.addPreserved<GlobalsAAWrapperPass>();
8247     AU.setPreservesCFG();
8248   }
8249 };
8250 
8251 } // end anonymous namespace
8252 
8253 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
8254   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
8255   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
8256   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
8257   auto *AA = &AM.getResult<AAManager>(F);
8258   auto *LI = &AM.getResult<LoopAnalysis>(F);
8259   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
8260   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
8261   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
8262   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
8263 
8264   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8265   if (!Changed)
8266     return PreservedAnalyses::all();
8267 
8268   PreservedAnalyses PA;
8269   PA.preserveSet<CFGAnalyses>();
8270   return PA;
8271 }
8272 
8273 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
8274                                 TargetTransformInfo *TTI_,
8275                                 TargetLibraryInfo *TLI_, AAResults *AA_,
8276                                 LoopInfo *LI_, DominatorTree *DT_,
8277                                 AssumptionCache *AC_, DemandedBits *DB_,
8278                                 OptimizationRemarkEmitter *ORE_) {
8279   if (!RunSLPVectorization)
8280     return false;
8281   SE = SE_;
8282   TTI = TTI_;
8283   TLI = TLI_;
8284   AA = AA_;
8285   LI = LI_;
8286   DT = DT_;
8287   AC = AC_;
8288   DB = DB_;
8289   DL = &F.getParent()->getDataLayout();
8290 
8291   Stores.clear();
8292   GEPs.clear();
8293   bool Changed = false;
8294 
8295   // If the target claims to have no vector registers don't attempt
8296   // vectorization.
8297   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true))) {
8298     LLVM_DEBUG(
8299         dbgs() << "SLP: Didn't find any vector registers for target, abort.\n");
8300     return false;
8301   }
8302 
8303   // Don't vectorize when the attribute NoImplicitFloat is used.
8304   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
8305     return false;
8306 
8307   LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
8308 
8309   // Use the bottom up slp vectorizer to construct chains that start with
8310   // store instructions.
8311   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
8312 
8313   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
8314   // delete instructions.
8315 
8316   // Update DFS numbers now so that we can use them for ordering.
8317   DT->updateDFSNumbers();
8318 
8319   // Scan the blocks in the function in post order.
8320   for (auto BB : post_order(&F.getEntryBlock())) {
8321     collectSeedInstructions(BB);
8322 
8323     // Vectorize trees that end at stores.
8324     if (!Stores.empty()) {
8325       LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
8326                         << " underlying objects.\n");
8327       Changed |= vectorizeStoreChains(R);
8328     }
8329 
8330     // Vectorize trees that end at reductions.
8331     Changed |= vectorizeChainsInBlock(BB, R);
8332 
8333     // Vectorize the index computations of getelementptr instructions. This
8334     // is primarily intended to catch gather-like idioms ending at
8335     // non-consecutive loads.
8336     if (!GEPs.empty()) {
8337       LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
8338                         << " underlying objects.\n");
8339       Changed |= vectorizeGEPIndices(BB, R);
8340     }
8341   }
8342 
8343   if (Changed) {
8344     R.optimizeGatherSequence();
8345     LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
8346   }
8347   return Changed;
8348 }
8349 
8350 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
8351                                             unsigned Idx) {
8352   LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()
8353                     << "\n");
8354   const unsigned Sz = R.getVectorElementSize(Chain[0]);
8355   const unsigned MinVF = R.getMinVecRegSize() / Sz;
8356   unsigned VF = Chain.size();
8357 
8358   if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
8359     return false;
8360 
8361   LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx
8362                     << "\n");
8363 
8364   R.buildTree(Chain);
8365   if (R.isTreeTinyAndNotFullyVectorizable())
8366     return false;
8367   if (R.isLoadCombineCandidate())
8368     return false;
8369   R.reorderTopToBottom();
8370   R.reorderBottomToTop();
8371   R.buildExternalUses();
8372 
8373   R.computeMinimumValueSizes();
8374 
8375   InstructionCost Cost = R.getTreeCost();
8376 
8377   LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n");
8378   if (Cost < -SLPCostThreshold) {
8379     LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n");
8380 
8381     using namespace ore;
8382 
8383     R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
8384                                         cast<StoreInst>(Chain[0]))
8385                      << "Stores SLP vectorized with cost " << NV("Cost", Cost)
8386                      << " and with tree size "
8387                      << NV("TreeSize", R.getTreeSize()));
8388 
8389     R.vectorizeTree();
8390     return true;
8391   }
8392 
8393   return false;
8394 }
8395 
8396 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
8397                                         BoUpSLP &R) {
8398   // We may run into multiple chains that merge into a single chain. We mark the
8399   // stores that we vectorized so that we don't visit the same store twice.
8400   BoUpSLP::ValueSet VectorizedStores;
8401   bool Changed = false;
8402 
8403   int E = Stores.size();
8404   SmallBitVector Tails(E, false);
8405   int MaxIter = MaxStoreLookup.getValue();
8406   SmallVector<std::pair<int, int>, 16> ConsecutiveChain(
8407       E, std::make_pair(E, INT_MAX));
8408   SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false));
8409   int IterCnt;
8410   auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
8411                                   &CheckedPairs,
8412                                   &ConsecutiveChain](int K, int Idx) {
8413     if (IterCnt >= MaxIter)
8414       return true;
8415     if (CheckedPairs[Idx].test(K))
8416       return ConsecutiveChain[K].second == 1 &&
8417              ConsecutiveChain[K].first == Idx;
8418     ++IterCnt;
8419     CheckedPairs[Idx].set(K);
8420     CheckedPairs[K].set(Idx);
8421     Optional<int> Diff = getPointersDiff(
8422         Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(),
8423         Stores[Idx]->getValueOperand()->getType(),
8424         Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true);
8425     if (!Diff || *Diff == 0)
8426       return false;
8427     int Val = *Diff;
8428     if (Val < 0) {
8429       if (ConsecutiveChain[Idx].second > -Val) {
8430         Tails.set(K);
8431         ConsecutiveChain[Idx] = std::make_pair(K, -Val);
8432       }
8433       return false;
8434     }
8435     if (ConsecutiveChain[K].second <= Val)
8436       return false;
8437 
8438     Tails.set(Idx);
8439     ConsecutiveChain[K] = std::make_pair(Idx, Val);
8440     return Val == 1;
8441   };
8442   // Do a quadratic search on all of the given stores in reverse order and find
8443   // all of the pairs of stores that follow each other.
8444   for (int Idx = E - 1; Idx >= 0; --Idx) {
8445     // If a store has multiple consecutive store candidates, search according
8446     // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
8447     // This is because usually pairing with immediate succeeding or preceding
8448     // candidate create the best chance to find slp vectorization opportunity.
8449     const int MaxLookDepth = std::max(E - Idx, Idx + 1);
8450     IterCnt = 0;
8451     for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
8452       if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
8453           (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
8454         break;
8455   }
8456 
8457   // Tracks if we tried to vectorize stores starting from the given tail
8458   // already.
8459   SmallBitVector TriedTails(E, false);
8460   // For stores that start but don't end a link in the chain:
8461   for (int Cnt = E; Cnt > 0; --Cnt) {
8462     int I = Cnt - 1;
8463     if (ConsecutiveChain[I].first == E || Tails.test(I))
8464       continue;
8465     // We found a store instr that starts a chain. Now follow the chain and try
8466     // to vectorize it.
8467     BoUpSLP::ValueList Operands;
8468     // Collect the chain into a list.
8469     while (I != E && !VectorizedStores.count(Stores[I])) {
8470       Operands.push_back(Stores[I]);
8471       Tails.set(I);
8472       if (ConsecutiveChain[I].second != 1) {
8473         // Mark the new end in the chain and go back, if required. It might be
8474         // required if the original stores come in reversed order, for example.
8475         if (ConsecutiveChain[I].first != E &&
8476             Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) &&
8477             !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) {
8478           TriedTails.set(I);
8479           Tails.reset(ConsecutiveChain[I].first);
8480           if (Cnt < ConsecutiveChain[I].first + 2)
8481             Cnt = ConsecutiveChain[I].first + 2;
8482         }
8483         break;
8484       }
8485       // Move to the next value in the chain.
8486       I = ConsecutiveChain[I].first;
8487     }
8488     assert(!Operands.empty() && "Expected non-empty list of stores.");
8489 
8490     unsigned MaxVecRegSize = R.getMaxVecRegSize();
8491     unsigned EltSize = R.getVectorElementSize(Operands[0]);
8492     unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize);
8493 
8494     unsigned MinVF = R.getMinVF(EltSize);
8495     unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store),
8496                               MaxElts);
8497 
8498     // FIXME: Is division-by-2 the correct step? Should we assert that the
8499     // register size is a power-of-2?
8500     unsigned StartIdx = 0;
8501     for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) {
8502       for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
8503         ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size);
8504         if (!VectorizedStores.count(Slice.front()) &&
8505             !VectorizedStores.count(Slice.back()) &&
8506             vectorizeStoreChain(Slice, R, Cnt)) {
8507           // Mark the vectorized stores so that we don't vectorize them again.
8508           VectorizedStores.insert(Slice.begin(), Slice.end());
8509           Changed = true;
8510           // If we vectorized initial block, no need to try to vectorize it
8511           // again.
8512           if (Cnt == StartIdx)
8513             StartIdx += Size;
8514           Cnt += Size;
8515           continue;
8516         }
8517         ++Cnt;
8518       }
8519       // Check if the whole array was vectorized already - exit.
8520       if (StartIdx >= Operands.size())
8521         break;
8522     }
8523   }
8524 
8525   return Changed;
8526 }
8527 
8528 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
8529   // Initialize the collections. We will make a single pass over the block.
8530   Stores.clear();
8531   GEPs.clear();
8532 
8533   // Visit the store and getelementptr instructions in BB and organize them in
8534   // Stores and GEPs according to the underlying objects of their pointer
8535   // operands.
8536   for (Instruction &I : *BB) {
8537     // Ignore store instructions that are volatile or have a pointer operand
8538     // that doesn't point to a scalar type.
8539     if (auto *SI = dyn_cast<StoreInst>(&I)) {
8540       if (!SI->isSimple())
8541         continue;
8542       if (!isValidElementType(SI->getValueOperand()->getType()))
8543         continue;
8544       Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI);
8545     }
8546 
8547     // Ignore getelementptr instructions that have more than one index, a
8548     // constant index, or a pointer operand that doesn't point to a scalar
8549     // type.
8550     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
8551       auto Idx = GEP->idx_begin()->get();
8552       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
8553         continue;
8554       if (!isValidElementType(Idx->getType()))
8555         continue;
8556       if (GEP->getType()->isVectorTy())
8557         continue;
8558       GEPs[GEP->getPointerOperand()].push_back(GEP);
8559     }
8560   }
8561 }
8562 
8563 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
8564   if (!A || !B)
8565     return false;
8566   Value *VL[] = {A, B};
8567   return tryToVectorizeList(VL, R);
8568 }
8569 
8570 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
8571                                            bool LimitForRegisterSize) {
8572   if (VL.size() < 2)
8573     return false;
8574 
8575   LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
8576                     << VL.size() << ".\n");
8577 
8578   // Check that all of the parts are instructions of the same type,
8579   // we permit an alternate opcode via InstructionsState.
8580   InstructionsState S = getSameOpcode(VL);
8581   if (!S.getOpcode())
8582     return false;
8583 
8584   Instruction *I0 = cast<Instruction>(S.OpValue);
8585   // Make sure invalid types (including vector type) are rejected before
8586   // determining vectorization factor for scalar instructions.
8587   for (Value *V : VL) {
8588     Type *Ty = V->getType();
8589     if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) {
8590       // NOTE: the following will give user internal llvm type name, which may
8591       // not be useful.
8592       R.getORE()->emit([&]() {
8593         std::string type_str;
8594         llvm::raw_string_ostream rso(type_str);
8595         Ty->print(rso);
8596         return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
8597                << "Cannot SLP vectorize list: type "
8598                << rso.str() + " is unsupported by vectorizer";
8599       });
8600       return false;
8601     }
8602   }
8603 
8604   unsigned Sz = R.getVectorElementSize(I0);
8605   unsigned MinVF = R.getMinVF(Sz);
8606   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
8607   MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF);
8608   if (MaxVF < 2) {
8609     R.getORE()->emit([&]() {
8610       return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
8611              << "Cannot SLP vectorize list: vectorization factor "
8612              << "less than 2 is not supported";
8613     });
8614     return false;
8615   }
8616 
8617   bool Changed = false;
8618   bool CandidateFound = false;
8619   InstructionCost MinCost = SLPCostThreshold.getValue();
8620   Type *ScalarTy = VL[0]->getType();
8621   if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
8622     ScalarTy = IE->getOperand(1)->getType();
8623 
8624   unsigned NextInst = 0, MaxInst = VL.size();
8625   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
8626     // No actual vectorization should happen, if number of parts is the same as
8627     // provided vectorization factor (i.e. the scalar type is used for vector
8628     // code during codegen).
8629     auto *VecTy = FixedVectorType::get(ScalarTy, VF);
8630     if (TTI->getNumberOfParts(VecTy) == VF)
8631       continue;
8632     for (unsigned I = NextInst; I < MaxInst; ++I) {
8633       unsigned OpsWidth = 0;
8634 
8635       if (I + VF > MaxInst)
8636         OpsWidth = MaxInst - I;
8637       else
8638         OpsWidth = VF;
8639 
8640       if (!isPowerOf2_32(OpsWidth))
8641         continue;
8642 
8643       if ((LimitForRegisterSize && OpsWidth < MaxVF) ||
8644           (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2))
8645         break;
8646 
8647       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
8648       // Check that a previous iteration of this loop did not delete the Value.
8649       if (llvm::any_of(Ops, [&R](Value *V) {
8650             auto *I = dyn_cast<Instruction>(V);
8651             return I && R.isDeleted(I);
8652           }))
8653         continue;
8654 
8655       LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
8656                         << "\n");
8657 
8658       R.buildTree(Ops);
8659       if (R.isTreeTinyAndNotFullyVectorizable())
8660         continue;
8661       R.reorderTopToBottom();
8662       R.reorderBottomToTop(!isa<InsertElementInst>(Ops.front()));
8663       R.buildExternalUses();
8664 
8665       R.computeMinimumValueSizes();
8666       InstructionCost Cost = R.getTreeCost();
8667       CandidateFound = true;
8668       MinCost = std::min(MinCost, Cost);
8669 
8670       if (Cost < -SLPCostThreshold) {
8671         LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
8672         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
8673                                                     cast<Instruction>(Ops[0]))
8674                                  << "SLP vectorized with cost " << ore::NV("Cost", Cost)
8675                                  << " and with tree size "
8676                                  << ore::NV("TreeSize", R.getTreeSize()));
8677 
8678         R.vectorizeTree();
8679         // Move to the next bundle.
8680         I += VF - 1;
8681         NextInst = I + 1;
8682         Changed = true;
8683       }
8684     }
8685   }
8686 
8687   if (!Changed && CandidateFound) {
8688     R.getORE()->emit([&]() {
8689       return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
8690              << "List vectorization was possible but not beneficial with cost "
8691              << ore::NV("Cost", MinCost) << " >= "
8692              << ore::NV("Treshold", -SLPCostThreshold);
8693     });
8694   } else if (!Changed) {
8695     R.getORE()->emit([&]() {
8696       return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
8697              << "Cannot SLP vectorize list: vectorization was impossible"
8698              << " with available vectorization factors";
8699     });
8700   }
8701   return Changed;
8702 }
8703 
8704 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
8705   if (!I)
8706     return false;
8707 
8708   if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I))
8709     return false;
8710 
8711   Value *P = I->getParent();
8712 
8713   // Vectorize in current basic block only.
8714   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
8715   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
8716   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
8717     return false;
8718 
8719   // Try to vectorize V.
8720   if (tryToVectorizePair(Op0, Op1, R))
8721     return true;
8722 
8723   auto *A = dyn_cast<BinaryOperator>(Op0);
8724   auto *B = dyn_cast<BinaryOperator>(Op1);
8725   // Try to skip B.
8726   if (B && B->hasOneUse()) {
8727     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
8728     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
8729     if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
8730       return true;
8731     if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
8732       return true;
8733   }
8734 
8735   // Try to skip A.
8736   if (A && A->hasOneUse()) {
8737     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
8738     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
8739     if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
8740       return true;
8741     if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
8742       return true;
8743   }
8744   return false;
8745 }
8746 
8747 namespace {
8748 
8749 /// Model horizontal reductions.
8750 ///
8751 /// A horizontal reduction is a tree of reduction instructions that has values
8752 /// that can be put into a vector as its leaves. For example:
8753 ///
8754 /// mul mul mul mul
8755 ///  \  /    \  /
8756 ///   +       +
8757 ///    \     /
8758 ///       +
8759 /// This tree has "mul" as its leaf values and "+" as its reduction
8760 /// instructions. A reduction can feed into a store or a binary operation
8761 /// feeding a phi.
8762 ///    ...
8763 ///    \  /
8764 ///     +
8765 ///     |
8766 ///  phi +=
8767 ///
8768 ///  Or:
8769 ///    ...
8770 ///    \  /
8771 ///     +
8772 ///     |
8773 ///   *p =
8774 ///
8775 class HorizontalReduction {
8776   using ReductionOpsType = SmallVector<Value *, 16>;
8777   using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
8778   ReductionOpsListType ReductionOps;
8779   SmallVector<Value *, 32> ReducedVals;
8780   // Use map vector to make stable output.
8781   MapVector<Instruction *, Value *> ExtraArgs;
8782   WeakTrackingVH ReductionRoot;
8783   /// The type of reduction operation.
8784   RecurKind RdxKind;
8785 
8786   const unsigned INVALID_OPERAND_INDEX = std::numeric_limits<unsigned>::max();
8787 
8788   static bool isCmpSelMinMax(Instruction *I) {
8789     return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) &&
8790            RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I));
8791   }
8792 
8793   // And/or are potentially poison-safe logical patterns like:
8794   // select x, y, false
8795   // select x, true, y
8796   static bool isBoolLogicOp(Instruction *I) {
8797     return match(I, m_LogicalAnd(m_Value(), m_Value())) ||
8798            match(I, m_LogicalOr(m_Value(), m_Value()));
8799   }
8800 
8801   /// Checks if instruction is associative and can be vectorized.
8802   static bool isVectorizable(RecurKind Kind, Instruction *I) {
8803     if (Kind == RecurKind::None)
8804       return false;
8805 
8806     // Integer ops that map to select instructions or intrinsics are fine.
8807     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) ||
8808         isBoolLogicOp(I))
8809       return true;
8810 
8811     if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) {
8812       // FP min/max are associative except for NaN and -0.0. We do not
8813       // have to rule out -0.0 here because the intrinsic semantics do not
8814       // specify a fixed result for it.
8815       return I->getFastMathFlags().noNaNs();
8816     }
8817 
8818     return I->isAssociative();
8819   }
8820 
8821   static Value *getRdxOperand(Instruction *I, unsigned Index) {
8822     // Poison-safe 'or' takes the form: select X, true, Y
8823     // To make that work with the normal operand processing, we skip the
8824     // true value operand.
8825     // TODO: Change the code and data structures to handle this without a hack.
8826     if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1)
8827       return I->getOperand(2);
8828     return I->getOperand(Index);
8829   }
8830 
8831   /// Checks if the ParentStackElem.first should be marked as a reduction
8832   /// operation with an extra argument or as extra argument itself.
8833   void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem,
8834                     Value *ExtraArg) {
8835     if (ExtraArgs.count(ParentStackElem.first)) {
8836       ExtraArgs[ParentStackElem.first] = nullptr;
8837       // We ran into something like:
8838       // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg.
8839       // The whole ParentStackElem.first should be considered as an extra value
8840       // in this case.
8841       // Do not perform analysis of remaining operands of ParentStackElem.first
8842       // instruction, this whole instruction is an extra argument.
8843       ParentStackElem.second = INVALID_OPERAND_INDEX;
8844     } else {
8845       // We ran into something like:
8846       // ParentStackElem.first += ... + ExtraArg + ...
8847       ExtraArgs[ParentStackElem.first] = ExtraArg;
8848     }
8849   }
8850 
8851   /// Creates reduction operation with the current opcode.
8852   static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS,
8853                          Value *RHS, const Twine &Name, bool UseSelect) {
8854     unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind);
8855     switch (Kind) {
8856     case RecurKind::Or:
8857       if (UseSelect &&
8858           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
8859         return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name);
8860       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
8861                                  Name);
8862     case RecurKind::And:
8863       if (UseSelect &&
8864           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
8865         return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name);
8866       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
8867                                  Name);
8868     case RecurKind::Add:
8869     case RecurKind::Mul:
8870     case RecurKind::Xor:
8871     case RecurKind::FAdd:
8872     case RecurKind::FMul:
8873       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
8874                                  Name);
8875     case RecurKind::FMax:
8876       return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS);
8877     case RecurKind::FMin:
8878       return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS);
8879     case RecurKind::SMax:
8880       if (UseSelect) {
8881         Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name);
8882         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
8883       }
8884       return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS);
8885     case RecurKind::SMin:
8886       if (UseSelect) {
8887         Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name);
8888         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
8889       }
8890       return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS);
8891     case RecurKind::UMax:
8892       if (UseSelect) {
8893         Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name);
8894         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
8895       }
8896       return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS);
8897     case RecurKind::UMin:
8898       if (UseSelect) {
8899         Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name);
8900         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
8901       }
8902       return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS);
8903     default:
8904       llvm_unreachable("Unknown reduction operation.");
8905     }
8906   }
8907 
8908   /// Creates reduction operation with the current opcode with the IR flags
8909   /// from \p ReductionOps.
8910   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
8911                          Value *RHS, const Twine &Name,
8912                          const ReductionOpsListType &ReductionOps) {
8913     bool UseSelect = ReductionOps.size() == 2 ||
8914                      // Logical or/and.
8915                      (ReductionOps.size() == 1 &&
8916                       isa<SelectInst>(ReductionOps.front().front()));
8917     assert((!UseSelect || ReductionOps.size() != 2 ||
8918             isa<SelectInst>(ReductionOps[1][0])) &&
8919            "Expected cmp + select pairs for reduction");
8920     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect);
8921     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
8922       if (auto *Sel = dyn_cast<SelectInst>(Op)) {
8923         propagateIRFlags(Sel->getCondition(), ReductionOps[0]);
8924         propagateIRFlags(Op, ReductionOps[1]);
8925         return Op;
8926       }
8927     }
8928     propagateIRFlags(Op, ReductionOps[0]);
8929     return Op;
8930   }
8931 
8932   /// Creates reduction operation with the current opcode with the IR flags
8933   /// from \p I.
8934   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
8935                          Value *RHS, const Twine &Name, Instruction *I) {
8936     auto *SelI = dyn_cast<SelectInst>(I);
8937     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, SelI != nullptr);
8938     if (SelI && RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
8939       if (auto *Sel = dyn_cast<SelectInst>(Op))
8940         propagateIRFlags(Sel->getCondition(), SelI->getCondition());
8941     }
8942     propagateIRFlags(Op, I);
8943     return Op;
8944   }
8945 
8946   static RecurKind getRdxKind(Instruction *I) {
8947     assert(I && "Expected instruction for reduction matching");
8948     if (match(I, m_Add(m_Value(), m_Value())))
8949       return RecurKind::Add;
8950     if (match(I, m_Mul(m_Value(), m_Value())))
8951       return RecurKind::Mul;
8952     if (match(I, m_And(m_Value(), m_Value())) ||
8953         match(I, m_LogicalAnd(m_Value(), m_Value())))
8954       return RecurKind::And;
8955     if (match(I, m_Or(m_Value(), m_Value())) ||
8956         match(I, m_LogicalOr(m_Value(), m_Value())))
8957       return RecurKind::Or;
8958     if (match(I, m_Xor(m_Value(), m_Value())))
8959       return RecurKind::Xor;
8960     if (match(I, m_FAdd(m_Value(), m_Value())))
8961       return RecurKind::FAdd;
8962     if (match(I, m_FMul(m_Value(), m_Value())))
8963       return RecurKind::FMul;
8964 
8965     if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value())))
8966       return RecurKind::FMax;
8967     if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value())))
8968       return RecurKind::FMin;
8969 
8970     // This matches either cmp+select or intrinsics. SLP is expected to handle
8971     // either form.
8972     // TODO: If we are canonicalizing to intrinsics, we can remove several
8973     //       special-case paths that deal with selects.
8974     if (match(I, m_SMax(m_Value(), m_Value())))
8975       return RecurKind::SMax;
8976     if (match(I, m_SMin(m_Value(), m_Value())))
8977       return RecurKind::SMin;
8978     if (match(I, m_UMax(m_Value(), m_Value())))
8979       return RecurKind::UMax;
8980     if (match(I, m_UMin(m_Value(), m_Value())))
8981       return RecurKind::UMin;
8982 
8983     if (auto *Select = dyn_cast<SelectInst>(I)) {
8984       // Try harder: look for min/max pattern based on instructions producing
8985       // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
8986       // During the intermediate stages of SLP, it's very common to have
8987       // pattern like this (since optimizeGatherSequence is run only once
8988       // at the end):
8989       // %1 = extractelement <2 x i32> %a, i32 0
8990       // %2 = extractelement <2 x i32> %a, i32 1
8991       // %cond = icmp sgt i32 %1, %2
8992       // %3 = extractelement <2 x i32> %a, i32 0
8993       // %4 = extractelement <2 x i32> %a, i32 1
8994       // %select = select i1 %cond, i32 %3, i32 %4
8995       CmpInst::Predicate Pred;
8996       Instruction *L1;
8997       Instruction *L2;
8998 
8999       Value *LHS = Select->getTrueValue();
9000       Value *RHS = Select->getFalseValue();
9001       Value *Cond = Select->getCondition();
9002 
9003       // TODO: Support inverse predicates.
9004       if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
9005         if (!isa<ExtractElementInst>(RHS) ||
9006             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9007           return RecurKind::None;
9008       } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
9009         if (!isa<ExtractElementInst>(LHS) ||
9010             !L1->isIdenticalTo(cast<Instruction>(LHS)))
9011           return RecurKind::None;
9012       } else {
9013         if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
9014           return RecurKind::None;
9015         if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
9016             !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
9017             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9018           return RecurKind::None;
9019       }
9020 
9021       switch (Pred) {
9022       default:
9023         return RecurKind::None;
9024       case CmpInst::ICMP_SGT:
9025       case CmpInst::ICMP_SGE:
9026         return RecurKind::SMax;
9027       case CmpInst::ICMP_SLT:
9028       case CmpInst::ICMP_SLE:
9029         return RecurKind::SMin;
9030       case CmpInst::ICMP_UGT:
9031       case CmpInst::ICMP_UGE:
9032         return RecurKind::UMax;
9033       case CmpInst::ICMP_ULT:
9034       case CmpInst::ICMP_ULE:
9035         return RecurKind::UMin;
9036       }
9037     }
9038     return RecurKind::None;
9039   }
9040 
9041   /// Get the index of the first operand.
9042   static unsigned getFirstOperandIndex(Instruction *I) {
9043     return isCmpSelMinMax(I) ? 1 : 0;
9044   }
9045 
9046   /// Total number of operands in the reduction operation.
9047   static unsigned getNumberOfOperands(Instruction *I) {
9048     return isCmpSelMinMax(I) ? 3 : 2;
9049   }
9050 
9051   /// Checks if the instruction is in basic block \p BB.
9052   /// For a cmp+sel min/max reduction check that both ops are in \p BB.
9053   static bool hasSameParent(Instruction *I, BasicBlock *BB) {
9054     if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) {
9055       auto *Sel = cast<SelectInst>(I);
9056       auto *Cmp = dyn_cast<Instruction>(Sel->getCondition());
9057       return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB;
9058     }
9059     return I->getParent() == BB;
9060   }
9061 
9062   /// Expected number of uses for reduction operations/reduced values.
9063   static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) {
9064     if (IsCmpSelMinMax) {
9065       // SelectInst must be used twice while the condition op must have single
9066       // use only.
9067       if (auto *Sel = dyn_cast<SelectInst>(I))
9068         return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse();
9069       return I->hasNUses(2);
9070     }
9071 
9072     // Arithmetic reduction operation must be used once only.
9073     return I->hasOneUse();
9074   }
9075 
9076   /// Initializes the list of reduction operations.
9077   void initReductionOps(Instruction *I) {
9078     if (isCmpSelMinMax(I))
9079       ReductionOps.assign(2, ReductionOpsType());
9080     else
9081       ReductionOps.assign(1, ReductionOpsType());
9082   }
9083 
9084   /// Add all reduction operations for the reduction instruction \p I.
9085   void addReductionOps(Instruction *I) {
9086     if (isCmpSelMinMax(I)) {
9087       ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
9088       ReductionOps[1].emplace_back(I);
9089     } else {
9090       ReductionOps[0].emplace_back(I);
9091     }
9092   }
9093 
9094   static Value *getLHS(RecurKind Kind, Instruction *I) {
9095     if (Kind == RecurKind::None)
9096       return nullptr;
9097     return I->getOperand(getFirstOperandIndex(I));
9098   }
9099   static Value *getRHS(RecurKind Kind, Instruction *I) {
9100     if (Kind == RecurKind::None)
9101       return nullptr;
9102     return I->getOperand(getFirstOperandIndex(I) + 1);
9103   }
9104 
9105 public:
9106   HorizontalReduction() = default;
9107 
9108   /// Try to find a reduction tree.
9109   bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst) {
9110     assert((!Phi || is_contained(Phi->operands(), Inst)) &&
9111            "Phi needs to use the binary operator");
9112     assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) ||
9113             isa<IntrinsicInst>(Inst)) &&
9114            "Expected binop, select, or intrinsic for reduction matching");
9115     RdxKind = getRdxKind(Inst);
9116 
9117     // We could have a initial reductions that is not an add.
9118     //  r *= v1 + v2 + v3 + v4
9119     // In such a case start looking for a tree rooted in the first '+'.
9120     if (Phi) {
9121       if (getLHS(RdxKind, Inst) == Phi) {
9122         Phi = nullptr;
9123         Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst));
9124         if (!Inst)
9125           return false;
9126         RdxKind = getRdxKind(Inst);
9127       } else if (getRHS(RdxKind, Inst) == Phi) {
9128         Phi = nullptr;
9129         Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst));
9130         if (!Inst)
9131           return false;
9132         RdxKind = getRdxKind(Inst);
9133       }
9134     }
9135 
9136     if (!isVectorizable(RdxKind, Inst))
9137       return false;
9138 
9139     // Analyze "regular" integer/FP types for reductions - no target-specific
9140     // types or pointers.
9141     Type *Ty = Inst->getType();
9142     if (!isValidElementType(Ty) || Ty->isPointerTy())
9143       return false;
9144 
9145     // Though the ultimate reduction may have multiple uses, its condition must
9146     // have only single use.
9147     if (auto *Sel = dyn_cast<SelectInst>(Inst))
9148       if (!Sel->getCondition()->hasOneUse())
9149         return false;
9150 
9151     ReductionRoot = Inst;
9152 
9153     // The opcode for leaf values that we perform a reduction on.
9154     // For example: load(x) + load(y) + load(z) + fptoui(w)
9155     // The leaf opcode for 'w' does not match, so we don't include it as a
9156     // potential candidate for the reduction.
9157     unsigned LeafOpcode = 0;
9158 
9159     // Post-order traverse the reduction tree starting at Inst. We only handle
9160     // true trees containing binary operators or selects.
9161     SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
9162     Stack.push_back(std::make_pair(Inst, getFirstOperandIndex(Inst)));
9163     initReductionOps(Inst);
9164     while (!Stack.empty()) {
9165       Instruction *TreeN = Stack.back().first;
9166       unsigned EdgeToVisit = Stack.back().second++;
9167       const RecurKind TreeRdxKind = getRdxKind(TreeN);
9168       bool IsReducedValue = TreeRdxKind != RdxKind;
9169 
9170       // Postorder visit.
9171       if (IsReducedValue || EdgeToVisit >= getNumberOfOperands(TreeN)) {
9172         if (IsReducedValue)
9173           ReducedVals.push_back(TreeN);
9174         else {
9175           auto ExtraArgsIter = ExtraArgs.find(TreeN);
9176           if (ExtraArgsIter != ExtraArgs.end() && !ExtraArgsIter->second) {
9177             // Check if TreeN is an extra argument of its parent operation.
9178             if (Stack.size() <= 1) {
9179               // TreeN can't be an extra argument as it is a root reduction
9180               // operation.
9181               return false;
9182             }
9183             // Yes, TreeN is an extra argument, do not add it to a list of
9184             // reduction operations.
9185             // Stack[Stack.size() - 2] always points to the parent operation.
9186             markExtraArg(Stack[Stack.size() - 2], TreeN);
9187             ExtraArgs.erase(TreeN);
9188           } else
9189             addReductionOps(TreeN);
9190         }
9191         // Retract.
9192         Stack.pop_back();
9193         continue;
9194       }
9195 
9196       // Visit operands.
9197       Value *EdgeVal = getRdxOperand(TreeN, EdgeToVisit);
9198       auto *EdgeInst = dyn_cast<Instruction>(EdgeVal);
9199       if (!EdgeInst) {
9200         // Edge value is not a reduction instruction or a leaf instruction.
9201         // (It may be a constant, function argument, or something else.)
9202         markExtraArg(Stack.back(), EdgeVal);
9203         continue;
9204       }
9205       RecurKind EdgeRdxKind = getRdxKind(EdgeInst);
9206       // Continue analysis if the next operand is a reduction operation or
9207       // (possibly) a leaf value. If the leaf value opcode is not set,
9208       // the first met operation != reduction operation is considered as the
9209       // leaf opcode.
9210       // Only handle trees in the current basic block.
9211       // Each tree node needs to have minimal number of users except for the
9212       // ultimate reduction.
9213       const bool IsRdxInst = EdgeRdxKind == RdxKind;
9214       if (EdgeInst != Phi && EdgeInst != Inst &&
9215           hasSameParent(EdgeInst, Inst->getParent()) &&
9216           hasRequiredNumberOfUses(isCmpSelMinMax(Inst), EdgeInst) &&
9217           (!LeafOpcode || LeafOpcode == EdgeInst->getOpcode() || IsRdxInst)) {
9218         if (IsRdxInst) {
9219           // We need to be able to reassociate the reduction operations.
9220           if (!isVectorizable(EdgeRdxKind, EdgeInst)) {
9221             // I is an extra argument for TreeN (its parent operation).
9222             markExtraArg(Stack.back(), EdgeInst);
9223             continue;
9224           }
9225         } else if (!LeafOpcode) {
9226           LeafOpcode = EdgeInst->getOpcode();
9227         }
9228         Stack.push_back(
9229             std::make_pair(EdgeInst, getFirstOperandIndex(EdgeInst)));
9230         continue;
9231       }
9232       // I is an extra argument for TreeN (its parent operation).
9233       markExtraArg(Stack.back(), EdgeInst);
9234     }
9235     return true;
9236   }
9237 
9238   /// Attempt to vectorize the tree found by matchAssociativeReduction.
9239   Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
9240     // If there are a sufficient number of reduction values, reduce
9241     // to a nearby power-of-2. We can safely generate oversized
9242     // vectors and rely on the backend to split them to legal sizes.
9243     unsigned NumReducedVals = ReducedVals.size();
9244     if (NumReducedVals < 4)
9245       return nullptr;
9246 
9247     // Intersect the fast-math-flags from all reduction operations.
9248     FastMathFlags RdxFMF;
9249     RdxFMF.set();
9250     for (ReductionOpsType &RdxOp : ReductionOps) {
9251       for (Value *RdxVal : RdxOp) {
9252         if (auto *FPMO = dyn_cast<FPMathOperator>(RdxVal))
9253           RdxFMF &= FPMO->getFastMathFlags();
9254       }
9255     }
9256 
9257     IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
9258     Builder.setFastMathFlags(RdxFMF);
9259 
9260     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
9261     // The same extra argument may be used several times, so log each attempt
9262     // to use it.
9263     for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) {
9264       assert(Pair.first && "DebugLoc must be set.");
9265       ExternallyUsedValues[Pair.second].push_back(Pair.first);
9266     }
9267 
9268     // The compare instruction of a min/max is the insertion point for new
9269     // instructions and may be replaced with a new compare instruction.
9270     auto getCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
9271       assert(isa<SelectInst>(RdxRootInst) &&
9272              "Expected min/max reduction to have select root instruction");
9273       Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
9274       assert(isa<Instruction>(ScalarCond) &&
9275              "Expected min/max reduction to have compare condition");
9276       return cast<Instruction>(ScalarCond);
9277     };
9278 
9279     // The reduction root is used as the insertion point for new instructions,
9280     // so set it as externally used to prevent it from being deleted.
9281     ExternallyUsedValues[ReductionRoot];
9282     SmallVector<Value *, 16> IgnoreList;
9283     for (ReductionOpsType &RdxOp : ReductionOps)
9284       IgnoreList.append(RdxOp.begin(), RdxOp.end());
9285 
9286     unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
9287     if (NumReducedVals > ReduxWidth) {
9288       // In the loop below, we are building a tree based on a window of
9289       // 'ReduxWidth' values.
9290       // If the operands of those values have common traits (compare predicate,
9291       // constant operand, etc), then we want to group those together to
9292       // minimize the cost of the reduction.
9293 
9294       // TODO: This should be extended to count common operands for
9295       //       compares and binops.
9296 
9297       // Step 1: Count the number of times each compare predicate occurs.
9298       SmallDenseMap<unsigned, unsigned> PredCountMap;
9299       for (Value *RdxVal : ReducedVals) {
9300         CmpInst::Predicate Pred;
9301         if (match(RdxVal, m_Cmp(Pred, m_Value(), m_Value())))
9302           ++PredCountMap[Pred];
9303       }
9304       // Step 2: Sort the values so the most common predicates come first.
9305       stable_sort(ReducedVals, [&PredCountMap](Value *A, Value *B) {
9306         CmpInst::Predicate PredA, PredB;
9307         if (match(A, m_Cmp(PredA, m_Value(), m_Value())) &&
9308             match(B, m_Cmp(PredB, m_Value(), m_Value()))) {
9309           return PredCountMap[PredA] > PredCountMap[PredB];
9310         }
9311         return false;
9312       });
9313     }
9314 
9315     Value *VectorizedTree = nullptr;
9316     unsigned i = 0;
9317     while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) {
9318       ArrayRef<Value *> VL(&ReducedVals[i], ReduxWidth);
9319       V.buildTree(VL, IgnoreList);
9320       if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true))
9321         break;
9322       if (V.isLoadCombineReductionCandidate(RdxKind))
9323         break;
9324       V.reorderTopToBottom();
9325       V.reorderBottomToTop(/*IgnoreReorder=*/true);
9326       V.buildExternalUses(ExternallyUsedValues);
9327 
9328       // For a poison-safe boolean logic reduction, do not replace select
9329       // instructions with logic ops. All reduced values will be frozen (see
9330       // below) to prevent leaking poison.
9331       if (isa<SelectInst>(ReductionRoot) &&
9332           isBoolLogicOp(cast<Instruction>(ReductionRoot)) &&
9333           NumReducedVals != ReduxWidth)
9334         break;
9335 
9336       V.computeMinimumValueSizes();
9337 
9338       // Estimate cost.
9339       InstructionCost TreeCost =
9340           V.getTreeCost(makeArrayRef(&ReducedVals[i], ReduxWidth));
9341       InstructionCost ReductionCost =
9342           getReductionCost(TTI, ReducedVals[i], ReduxWidth, RdxFMF);
9343       InstructionCost Cost = TreeCost + ReductionCost;
9344       if (!Cost.isValid()) {
9345         LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n");
9346         return nullptr;
9347       }
9348       if (Cost >= -SLPCostThreshold) {
9349         V.getORE()->emit([&]() {
9350           return OptimizationRemarkMissed(SV_NAME, "HorSLPNotBeneficial",
9351                                           cast<Instruction>(VL[0]))
9352                  << "Vectorizing horizontal reduction is possible"
9353                  << "but not beneficial with cost " << ore::NV("Cost", Cost)
9354                  << " and threshold "
9355                  << ore::NV("Threshold", -SLPCostThreshold);
9356         });
9357         break;
9358       }
9359 
9360       LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
9361                         << Cost << ". (HorRdx)\n");
9362       V.getORE()->emit([&]() {
9363         return OptimizationRemark(SV_NAME, "VectorizedHorizontalReduction",
9364                                   cast<Instruction>(VL[0]))
9365                << "Vectorized horizontal reduction with cost "
9366                << ore::NV("Cost", Cost) << " and with tree size "
9367                << ore::NV("TreeSize", V.getTreeSize());
9368       });
9369 
9370       // Vectorize a tree.
9371       DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
9372       Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues);
9373 
9374       // Emit a reduction. If the root is a select (min/max idiom), the insert
9375       // point is the compare condition of that select.
9376       Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
9377       if (isCmpSelMinMax(RdxRootInst))
9378         Builder.SetInsertPoint(getCmpForMinMaxReduction(RdxRootInst));
9379       else
9380         Builder.SetInsertPoint(RdxRootInst);
9381 
9382       // To prevent poison from leaking across what used to be sequential, safe,
9383       // scalar boolean logic operations, the reduction operand must be frozen.
9384       if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst))
9385         VectorizedRoot = Builder.CreateFreeze(VectorizedRoot);
9386 
9387       Value *ReducedSubTree =
9388           emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
9389 
9390       if (!VectorizedTree) {
9391         // Initialize the final value in the reduction.
9392         VectorizedTree = ReducedSubTree;
9393       } else {
9394         // Update the final value in the reduction.
9395         Builder.SetCurrentDebugLocation(Loc);
9396         VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9397                                   ReducedSubTree, "op.rdx", ReductionOps);
9398       }
9399       i += ReduxWidth;
9400       ReduxWidth = PowerOf2Floor(NumReducedVals - i);
9401     }
9402 
9403     if (VectorizedTree) {
9404       // Finish the reduction.
9405       for (; i < NumReducedVals; ++i) {
9406         auto *I = cast<Instruction>(ReducedVals[i]);
9407         Builder.SetCurrentDebugLocation(I->getDebugLoc());
9408         VectorizedTree =
9409             createOp(Builder, RdxKind, VectorizedTree, I, "", ReductionOps);
9410       }
9411       for (auto &Pair : ExternallyUsedValues) {
9412         // Add each externally used value to the final reduction.
9413         for (auto *I : Pair.second) {
9414           Builder.SetCurrentDebugLocation(I->getDebugLoc());
9415           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9416                                     Pair.first, "op.extra", I);
9417         }
9418       }
9419 
9420       ReductionRoot->replaceAllUsesWith(VectorizedTree);
9421 
9422       // Mark all scalar reduction ops for deletion, they are replaced by the
9423       // vector reductions.
9424       V.eraseInstructions(IgnoreList);
9425     }
9426     return VectorizedTree;
9427   }
9428 
9429   unsigned numReductionValues() const { return ReducedVals.size(); }
9430 
9431 private:
9432   /// Calculate the cost of a reduction.
9433   InstructionCost getReductionCost(TargetTransformInfo *TTI,
9434                                    Value *FirstReducedVal, unsigned ReduxWidth,
9435                                    FastMathFlags FMF) {
9436     TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
9437     Type *ScalarTy = FirstReducedVal->getType();
9438     FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth);
9439     InstructionCost VectorCost, ScalarCost;
9440     switch (RdxKind) {
9441     case RecurKind::Add:
9442     case RecurKind::Mul:
9443     case RecurKind::Or:
9444     case RecurKind::And:
9445     case RecurKind::Xor:
9446     case RecurKind::FAdd:
9447     case RecurKind::FMul: {
9448       unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind);
9449       VectorCost =
9450           TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind);
9451       ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind);
9452       break;
9453     }
9454     case RecurKind::FMax:
9455     case RecurKind::FMin: {
9456       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9457       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9458       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
9459                                                /*IsUnsigned=*/false, CostKind);
9460       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9461       ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy,
9462                                            SclCondTy, RdxPred, CostKind) +
9463                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9464                                            SclCondTy, RdxPred, CostKind);
9465       break;
9466     }
9467     case RecurKind::SMax:
9468     case RecurKind::SMin:
9469     case RecurKind::UMax:
9470     case RecurKind::UMin: {
9471       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9472       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9473       bool IsUnsigned =
9474           RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin;
9475       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, IsUnsigned,
9476                                                CostKind);
9477       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9478       ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
9479                                            SclCondTy, RdxPred, CostKind) +
9480                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9481                                            SclCondTy, RdxPred, CostKind);
9482       break;
9483     }
9484     default:
9485       llvm_unreachable("Expected arithmetic or min/max reduction operation");
9486     }
9487 
9488     // Scalar cost is repeated for N-1 elements.
9489     ScalarCost *= (ReduxWidth - 1);
9490     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost
9491                       << " for reduction that starts with " << *FirstReducedVal
9492                       << " (It is a splitting reduction)\n");
9493     return VectorCost - ScalarCost;
9494   }
9495 
9496   /// Emit a horizontal reduction of the vectorized value.
9497   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
9498                        unsigned ReduxWidth, const TargetTransformInfo *TTI) {
9499     assert(VectorizedValue && "Need to have a vectorized tree node");
9500     assert(isPowerOf2_32(ReduxWidth) &&
9501            "We only handle power-of-two reductions for now");
9502     assert(RdxKind != RecurKind::FMulAdd &&
9503            "A call to the llvm.fmuladd intrinsic is not handled yet");
9504 
9505     ++NumVectorInstructions;
9506     return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind);
9507   }
9508 };
9509 
9510 } // end anonymous namespace
9511 
9512 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) {
9513   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
9514     return cast<FixedVectorType>(IE->getType())->getNumElements();
9515 
9516   unsigned AggregateSize = 1;
9517   auto *IV = cast<InsertValueInst>(InsertInst);
9518   Type *CurrentType = IV->getType();
9519   do {
9520     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
9521       for (auto *Elt : ST->elements())
9522         if (Elt != ST->getElementType(0)) // check homogeneity
9523           return None;
9524       AggregateSize *= ST->getNumElements();
9525       CurrentType = ST->getElementType(0);
9526     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
9527       AggregateSize *= AT->getNumElements();
9528       CurrentType = AT->getElementType();
9529     } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
9530       AggregateSize *= VT->getNumElements();
9531       return AggregateSize;
9532     } else if (CurrentType->isSingleValueType()) {
9533       return AggregateSize;
9534     } else {
9535       return None;
9536     }
9537   } while (true);
9538 }
9539 
9540 static bool findBuildAggregate_rec(Instruction *LastInsertInst,
9541                                    TargetTransformInfo *TTI,
9542                                    SmallVectorImpl<Value *> &BuildVectorOpds,
9543                                    SmallVectorImpl<Value *> &InsertElts,
9544                                    unsigned OperandOffset) {
9545   do {
9546     Value *InsertedOperand = LastInsertInst->getOperand(1);
9547     Optional<int> OperandIndex = getInsertIndex(LastInsertInst, OperandOffset);
9548     if (!OperandIndex)
9549       return false;
9550     if (isa<InsertElementInst>(InsertedOperand) ||
9551         isa<InsertValueInst>(InsertedOperand)) {
9552       if (!findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI,
9553                                   BuildVectorOpds, InsertElts, *OperandIndex))
9554         return false;
9555     } else {
9556       BuildVectorOpds[*OperandIndex] = InsertedOperand;
9557       InsertElts[*OperandIndex] = LastInsertInst;
9558     }
9559     LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0));
9560   } while (LastInsertInst != nullptr &&
9561            (isa<InsertValueInst>(LastInsertInst) ||
9562             isa<InsertElementInst>(LastInsertInst)) &&
9563            LastInsertInst->hasOneUse());
9564   return true;
9565 }
9566 
9567 /// Recognize construction of vectors like
9568 ///  %ra = insertelement <4 x float> poison, float %s0, i32 0
9569 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
9570 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
9571 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
9572 ///  starting from the last insertelement or insertvalue instruction.
9573 ///
9574 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>},
9575 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
9576 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
9577 ///
9578 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
9579 ///
9580 /// \return true if it matches.
9581 static bool findBuildAggregate(Instruction *LastInsertInst,
9582                                TargetTransformInfo *TTI,
9583                                SmallVectorImpl<Value *> &BuildVectorOpds,
9584                                SmallVectorImpl<Value *> &InsertElts) {
9585 
9586   assert((isa<InsertElementInst>(LastInsertInst) ||
9587           isa<InsertValueInst>(LastInsertInst)) &&
9588          "Expected insertelement or insertvalue instruction!");
9589 
9590   assert((BuildVectorOpds.empty() && InsertElts.empty()) &&
9591          "Expected empty result vectors!");
9592 
9593   Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst);
9594   if (!AggregateSize)
9595     return false;
9596   BuildVectorOpds.resize(*AggregateSize);
9597   InsertElts.resize(*AggregateSize);
9598 
9599   if (findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts,
9600                              0)) {
9601     llvm::erase_value(BuildVectorOpds, nullptr);
9602     llvm::erase_value(InsertElts, nullptr);
9603     if (BuildVectorOpds.size() >= 2)
9604       return true;
9605   }
9606 
9607   return false;
9608 }
9609 
9610 /// Try and get a reduction value from a phi node.
9611 ///
9612 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
9613 /// if they come from either \p ParentBB or a containing loop latch.
9614 ///
9615 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
9616 /// if not possible.
9617 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
9618                                 BasicBlock *ParentBB, LoopInfo *LI) {
9619   // There are situations where the reduction value is not dominated by the
9620   // reduction phi. Vectorizing such cases has been reported to cause
9621   // miscompiles. See PR25787.
9622   auto DominatedReduxValue = [&](Value *R) {
9623     return isa<Instruction>(R) &&
9624            DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
9625   };
9626 
9627   Value *Rdx = nullptr;
9628 
9629   // Return the incoming value if it comes from the same BB as the phi node.
9630   if (P->getIncomingBlock(0) == ParentBB) {
9631     Rdx = P->getIncomingValue(0);
9632   } else if (P->getIncomingBlock(1) == ParentBB) {
9633     Rdx = P->getIncomingValue(1);
9634   }
9635 
9636   if (Rdx && DominatedReduxValue(Rdx))
9637     return Rdx;
9638 
9639   // Otherwise, check whether we have a loop latch to look at.
9640   Loop *BBL = LI->getLoopFor(ParentBB);
9641   if (!BBL)
9642     return nullptr;
9643   BasicBlock *BBLatch = BBL->getLoopLatch();
9644   if (!BBLatch)
9645     return nullptr;
9646 
9647   // There is a loop latch, return the incoming value if it comes from
9648   // that. This reduction pattern occasionally turns up.
9649   if (P->getIncomingBlock(0) == BBLatch) {
9650     Rdx = P->getIncomingValue(0);
9651   } else if (P->getIncomingBlock(1) == BBLatch) {
9652     Rdx = P->getIncomingValue(1);
9653   }
9654 
9655   if (Rdx && DominatedReduxValue(Rdx))
9656     return Rdx;
9657 
9658   return nullptr;
9659 }
9660 
9661 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) {
9662   if (match(I, m_BinOp(m_Value(V0), m_Value(V1))))
9663     return true;
9664   if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1))))
9665     return true;
9666   if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1))))
9667     return true;
9668   if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1))))
9669     return true;
9670   if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1))))
9671     return true;
9672   if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1))))
9673     return true;
9674   if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1))))
9675     return true;
9676   return false;
9677 }
9678 
9679 /// Attempt to reduce a horizontal reduction.
9680 /// If it is legal to match a horizontal reduction feeding the phi node \a P
9681 /// with reduction operators \a Root (or one of its operands) in a basic block
9682 /// \a BB, then check if it can be done. If horizontal reduction is not found
9683 /// and root instruction is a binary operation, vectorization of the operands is
9684 /// attempted.
9685 /// \returns true if a horizontal reduction was matched and reduced or operands
9686 /// of one of the binary instruction were vectorized.
9687 /// \returns false if a horizontal reduction was not matched (or not possible)
9688 /// or no vectorization of any binary operation feeding \a Root instruction was
9689 /// performed.
9690 static bool tryToVectorizeHorReductionOrInstOperands(
9691     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
9692     TargetTransformInfo *TTI,
9693     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
9694   if (!ShouldVectorizeHor)
9695     return false;
9696 
9697   if (!Root)
9698     return false;
9699 
9700   if (Root->getParent() != BB || isa<PHINode>(Root))
9701     return false;
9702   // Start analysis starting from Root instruction. If horizontal reduction is
9703   // found, try to vectorize it. If it is not a horizontal reduction or
9704   // vectorization is not possible or not effective, and currently analyzed
9705   // instruction is a binary operation, try to vectorize the operands, using
9706   // pre-order DFS traversal order. If the operands were not vectorized, repeat
9707   // the same procedure considering each operand as a possible root of the
9708   // horizontal reduction.
9709   // Interrupt the process if the Root instruction itself was vectorized or all
9710   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
9711   // Skip the analysis of CmpInsts.Compiler implements postanalysis of the
9712   // CmpInsts so we can skip extra attempts in
9713   // tryToVectorizeHorReductionOrInstOperands and save compile time.
9714   std::queue<std::pair<Instruction *, unsigned>> Stack;
9715   Stack.emplace(Root, 0);
9716   SmallPtrSet<Value *, 8> VisitedInstrs;
9717   SmallVector<WeakTrackingVH> PostponedInsts;
9718   bool Res = false;
9719   auto &&TryToReduce = [TTI, &P, &R](Instruction *Inst, Value *&B0,
9720                                      Value *&B1) -> Value * {
9721     bool IsBinop = matchRdxBop(Inst, B0, B1);
9722     bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value()));
9723     if (IsBinop || IsSelect) {
9724       HorizontalReduction HorRdx;
9725       if (HorRdx.matchAssociativeReduction(P, Inst))
9726         return HorRdx.tryToReduce(R, TTI);
9727     }
9728     return nullptr;
9729   };
9730   while (!Stack.empty()) {
9731     Instruction *Inst;
9732     unsigned Level;
9733     std::tie(Inst, Level) = Stack.front();
9734     Stack.pop();
9735     // Do not try to analyze instruction that has already been vectorized.
9736     // This may happen when we vectorize instruction operands on a previous
9737     // iteration while stack was populated before that happened.
9738     if (R.isDeleted(Inst))
9739       continue;
9740     Value *B0 = nullptr, *B1 = nullptr;
9741     if (Value *V = TryToReduce(Inst, B0, B1)) {
9742       Res = true;
9743       // Set P to nullptr to avoid re-analysis of phi node in
9744       // matchAssociativeReduction function unless this is the root node.
9745       P = nullptr;
9746       if (auto *I = dyn_cast<Instruction>(V)) {
9747         // Try to find another reduction.
9748         Stack.emplace(I, Level);
9749         continue;
9750       }
9751     } else {
9752       bool IsBinop = B0 && B1;
9753       if (P && IsBinop) {
9754         Inst = dyn_cast<Instruction>(B0);
9755         if (Inst == P)
9756           Inst = dyn_cast<Instruction>(B1);
9757         if (!Inst) {
9758           // Set P to nullptr to avoid re-analysis of phi node in
9759           // matchAssociativeReduction function unless this is the root node.
9760           P = nullptr;
9761           continue;
9762         }
9763       }
9764       // Set P to nullptr to avoid re-analysis of phi node in
9765       // matchAssociativeReduction function unless this is the root node.
9766       P = nullptr;
9767       // Do not try to vectorize CmpInst operands, this is done separately.
9768       // Final attempt for binop args vectorization should happen after the loop
9769       // to try to find reductions.
9770       if (!isa<CmpInst>(Inst))
9771         PostponedInsts.push_back(Inst);
9772     }
9773 
9774     // Try to vectorize operands.
9775     // Continue analysis for the instruction from the same basic block only to
9776     // save compile time.
9777     if (++Level < RecursionMaxDepth)
9778       for (auto *Op : Inst->operand_values())
9779         if (VisitedInstrs.insert(Op).second)
9780           if (auto *I = dyn_cast<Instruction>(Op))
9781             // Do not try to vectorize CmpInst operands,  this is done
9782             // separately.
9783             if (!isa<PHINode>(I) && !isa<CmpInst>(I) && !R.isDeleted(I) &&
9784                 I->getParent() == BB)
9785               Stack.emplace(I, Level);
9786   }
9787   // Try to vectorized binops where reductions were not found.
9788   for (Value *V : PostponedInsts)
9789     if (auto *Inst = dyn_cast<Instruction>(V))
9790       if (!R.isDeleted(Inst))
9791         Res |= Vectorize(Inst, R);
9792   return Res;
9793 }
9794 
9795 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
9796                                                  BasicBlock *BB, BoUpSLP &R,
9797                                                  TargetTransformInfo *TTI) {
9798   auto *I = dyn_cast_or_null<Instruction>(V);
9799   if (!I)
9800     return false;
9801 
9802   if (!isa<BinaryOperator>(I))
9803     P = nullptr;
9804   // Try to match and vectorize a horizontal reduction.
9805   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
9806     return tryToVectorize(I, R);
9807   };
9808   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI,
9809                                                   ExtraVectorization);
9810 }
9811 
9812 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
9813                                                  BasicBlock *BB, BoUpSLP &R) {
9814   const DataLayout &DL = BB->getModule()->getDataLayout();
9815   if (!R.canMapToVector(IVI->getType(), DL))
9816     return false;
9817 
9818   SmallVector<Value *, 16> BuildVectorOpds;
9819   SmallVector<Value *, 16> BuildVectorInsts;
9820   if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts))
9821     return false;
9822 
9823   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
9824   // Aggregate value is unlikely to be processed in vector register.
9825   return tryToVectorizeList(BuildVectorOpds, R);
9826 }
9827 
9828 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
9829                                                    BasicBlock *BB, BoUpSLP &R) {
9830   SmallVector<Value *, 16> BuildVectorInsts;
9831   SmallVector<Value *, 16> BuildVectorOpds;
9832   SmallVector<int> Mask;
9833   if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
9834       (llvm::all_of(
9835            BuildVectorOpds,
9836            [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) &&
9837        isFixedVectorShuffle(BuildVectorOpds, Mask)))
9838     return false;
9839 
9840   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n");
9841   return tryToVectorizeList(BuildVectorInsts, R);
9842 }
9843 
9844 template <typename T>
9845 static bool
9846 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming,
9847                        function_ref<unsigned(T *)> Limit,
9848                        function_ref<bool(T *, T *)> Comparator,
9849                        function_ref<bool(T *, T *)> AreCompatible,
9850                        function_ref<bool(ArrayRef<T *>, bool)> TryToVectorizeHelper,
9851                        bool LimitForRegisterSize) {
9852   bool Changed = false;
9853   // Sort by type, parent, operands.
9854   stable_sort(Incoming, Comparator);
9855 
9856   // Try to vectorize elements base on their type.
9857   SmallVector<T *> Candidates;
9858   for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) {
9859     // Look for the next elements with the same type, parent and operand
9860     // kinds.
9861     auto *SameTypeIt = IncIt;
9862     while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt))
9863       ++SameTypeIt;
9864 
9865     // Try to vectorize them.
9866     unsigned NumElts = (SameTypeIt - IncIt);
9867     LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes ("
9868                       << NumElts << ")\n");
9869     // The vectorization is a 3-state attempt:
9870     // 1. Try to vectorize instructions with the same/alternate opcodes with the
9871     // size of maximal register at first.
9872     // 2. Try to vectorize remaining instructions with the same type, if
9873     // possible. This may result in the better vectorization results rather than
9874     // if we try just to vectorize instructions with the same/alternate opcodes.
9875     // 3. Final attempt to try to vectorize all instructions with the
9876     // same/alternate ops only, this may result in some extra final
9877     // vectorization.
9878     if (NumElts > 1 &&
9879         TryToVectorizeHelper(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) {
9880       // Success start over because instructions might have been changed.
9881       Changed = true;
9882     } else if (NumElts < Limit(*IncIt) &&
9883                (Candidates.empty() ||
9884                 Candidates.front()->getType() == (*IncIt)->getType())) {
9885       Candidates.append(IncIt, std::next(IncIt, NumElts));
9886     }
9887     // Final attempt to vectorize instructions with the same types.
9888     if (Candidates.size() > 1 &&
9889         (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) {
9890       if (TryToVectorizeHelper(Candidates, /*LimitForRegisterSize=*/false)) {
9891         // Success start over because instructions might have been changed.
9892         Changed = true;
9893       } else if (LimitForRegisterSize) {
9894         // Try to vectorize using small vectors.
9895         for (auto *It = Candidates.begin(), *End = Candidates.end();
9896              It != End;) {
9897           auto *SameTypeIt = It;
9898           while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It))
9899             ++SameTypeIt;
9900           unsigned NumElts = (SameTypeIt - It);
9901           if (NumElts > 1 && TryToVectorizeHelper(makeArrayRef(It, NumElts),
9902                                             /*LimitForRegisterSize=*/false))
9903             Changed = true;
9904           It = SameTypeIt;
9905         }
9906       }
9907       Candidates.clear();
9908     }
9909 
9910     // Start over at the next instruction of a different type (or the end).
9911     IncIt = SameTypeIt;
9912   }
9913   return Changed;
9914 }
9915 
9916 /// Compare two cmp instructions. If IsCompatibility is true, function returns
9917 /// true if 2 cmps have same/swapped predicates and mos compatible corresponding
9918 /// operands. If IsCompatibility is false, function implements strict weak
9919 /// ordering relation between two cmp instructions, returning true if the first
9920 /// instruction is "less" than the second, i.e. its predicate is less than the
9921 /// predicate of the second or the operands IDs are less than the operands IDs
9922 /// of the second cmp instruction.
9923 template <bool IsCompatibility>
9924 static bool compareCmp(Value *V, Value *V2,
9925                        function_ref<bool(Instruction *)> IsDeleted) {
9926   auto *CI1 = cast<CmpInst>(V);
9927   auto *CI2 = cast<CmpInst>(V2);
9928   if (IsDeleted(CI2) || !isValidElementType(CI2->getType()))
9929     return false;
9930   if (CI1->getOperand(0)->getType()->getTypeID() <
9931       CI2->getOperand(0)->getType()->getTypeID())
9932     return !IsCompatibility;
9933   if (CI1->getOperand(0)->getType()->getTypeID() >
9934       CI2->getOperand(0)->getType()->getTypeID())
9935     return false;
9936   CmpInst::Predicate Pred1 = CI1->getPredicate();
9937   CmpInst::Predicate Pred2 = CI2->getPredicate();
9938   CmpInst::Predicate SwapPred1 = CmpInst::getSwappedPredicate(Pred1);
9939   CmpInst::Predicate SwapPred2 = CmpInst::getSwappedPredicate(Pred2);
9940   CmpInst::Predicate BasePred1 = std::min(Pred1, SwapPred1);
9941   CmpInst::Predicate BasePred2 = std::min(Pred2, SwapPred2);
9942   if (BasePred1 < BasePred2)
9943     return !IsCompatibility;
9944   if (BasePred1 > BasePred2)
9945     return false;
9946   // Compare operands.
9947   bool LEPreds = Pred1 <= Pred2;
9948   bool GEPreds = Pred1 >= Pred2;
9949   for (int I = 0, E = CI1->getNumOperands(); I < E; ++I) {
9950     auto *Op1 = CI1->getOperand(LEPreds ? I : E - I - 1);
9951     auto *Op2 = CI2->getOperand(GEPreds ? I : E - I - 1);
9952     if (Op1->getValueID() < Op2->getValueID())
9953       return !IsCompatibility;
9954     if (Op1->getValueID() > Op2->getValueID())
9955       return false;
9956     if (auto *I1 = dyn_cast<Instruction>(Op1))
9957       if (auto *I2 = dyn_cast<Instruction>(Op2)) {
9958         if (I1->getParent() != I2->getParent())
9959           return false;
9960         InstructionsState S = getSameOpcode({I1, I2});
9961         if (S.getOpcode())
9962           continue;
9963         return false;
9964       }
9965   }
9966   return IsCompatibility;
9967 }
9968 
9969 bool SLPVectorizerPass::vectorizeSimpleInstructions(
9970     SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R,
9971     bool AtTerminator) {
9972   bool OpsChanged = false;
9973   SmallVector<Instruction *, 4> PostponedCmps;
9974   for (auto *I : reverse(Instructions)) {
9975     if (R.isDeleted(I))
9976       continue;
9977     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I))
9978       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
9979     else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I))
9980       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
9981     else if (isa<CmpInst>(I))
9982       PostponedCmps.push_back(I);
9983   }
9984   if (AtTerminator) {
9985     // Try to find reductions first.
9986     for (Instruction *I : PostponedCmps) {
9987       if (R.isDeleted(I))
9988         continue;
9989       for (Value *Op : I->operands())
9990         OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI);
9991     }
9992     // Try to vectorize operands as vector bundles.
9993     for (Instruction *I : PostponedCmps) {
9994       if (R.isDeleted(I))
9995         continue;
9996       OpsChanged |= tryToVectorize(I, R);
9997     }
9998     // Try to vectorize list of compares.
9999     // Sort by type, compare predicate, etc.
10000     auto &&CompareSorter = [&R](Value *V, Value *V2) {
10001       return compareCmp<false>(V, V2,
10002                                [&R](Instruction *I) { return R.isDeleted(I); });
10003     };
10004 
10005     auto &&AreCompatibleCompares = [&R](Value *V1, Value *V2) {
10006       if (V1 == V2)
10007         return true;
10008       return compareCmp<true>(V1, V2,
10009                               [&R](Instruction *I) { return R.isDeleted(I); });
10010     };
10011     auto Limit = [&R](Value *V) {
10012       unsigned EltSize = R.getVectorElementSize(V);
10013       return std::max(2U, R.getMaxVecRegSize() / EltSize);
10014     };
10015 
10016     SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end());
10017     OpsChanged |= tryToVectorizeSequence<Value>(
10018         Vals, Limit, CompareSorter, AreCompatibleCompares,
10019         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10020           // Exclude possible reductions from other blocks.
10021           bool ArePossiblyReducedInOtherBlock =
10022               any_of(Candidates, [](Value *V) {
10023                 return any_of(V->users(), [V](User *U) {
10024                   return isa<SelectInst>(U) &&
10025                          cast<SelectInst>(U)->getParent() !=
10026                              cast<Instruction>(V)->getParent();
10027                 });
10028               });
10029           if (ArePossiblyReducedInOtherBlock)
10030             return false;
10031           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10032         },
10033         /*LimitForRegisterSize=*/true);
10034     Instructions.clear();
10035   } else {
10036     // Insert in reverse order since the PostponedCmps vector was filled in
10037     // reverse order.
10038     Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend());
10039   }
10040   return OpsChanged;
10041 }
10042 
10043 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
10044   bool Changed = false;
10045   SmallVector<Value *, 4> Incoming;
10046   SmallPtrSet<Value *, 16> VisitedInstrs;
10047   // Maps phi nodes to the non-phi nodes found in the use tree for each phi
10048   // node. Allows better to identify the chains that can be vectorized in the
10049   // better way.
10050   DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes;
10051   auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) {
10052     assert(isValidElementType(V1->getType()) &&
10053            isValidElementType(V2->getType()) &&
10054            "Expected vectorizable types only.");
10055     // It is fine to compare type IDs here, since we expect only vectorizable
10056     // types, like ints, floats and pointers, we don't care about other type.
10057     if (V1->getType()->getTypeID() < V2->getType()->getTypeID())
10058       return true;
10059     if (V1->getType()->getTypeID() > V2->getType()->getTypeID())
10060       return false;
10061     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10062     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10063     if (Opcodes1.size() < Opcodes2.size())
10064       return true;
10065     if (Opcodes1.size() > Opcodes2.size())
10066       return false;
10067     Optional<bool> ConstOrder;
10068     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10069       // Undefs are compatible with any other value.
10070       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) {
10071         if (!ConstOrder)
10072           ConstOrder =
10073               !isa<UndefValue>(Opcodes1[I]) && isa<UndefValue>(Opcodes2[I]);
10074         continue;
10075       }
10076       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10077         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10078           DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent());
10079           DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent());
10080           if (!NodeI1)
10081             return NodeI2 != nullptr;
10082           if (!NodeI2)
10083             return false;
10084           assert((NodeI1 == NodeI2) ==
10085                      (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10086                  "Different nodes should have different DFS numbers");
10087           if (NodeI1 != NodeI2)
10088             return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10089           InstructionsState S = getSameOpcode({I1, I2});
10090           if (S.getOpcode())
10091             continue;
10092           return I1->getOpcode() < I2->getOpcode();
10093         }
10094       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) {
10095         if (!ConstOrder)
10096           ConstOrder = Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID();
10097         continue;
10098       }
10099       if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID())
10100         return true;
10101       if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID())
10102         return false;
10103     }
10104     return ConstOrder && *ConstOrder;
10105   };
10106   auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) {
10107     if (V1 == V2)
10108       return true;
10109     if (V1->getType() != V2->getType())
10110       return false;
10111     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10112     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10113     if (Opcodes1.size() != Opcodes2.size())
10114       return false;
10115     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10116       // Undefs are compatible with any other value.
10117       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
10118         continue;
10119       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10120         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10121           if (I1->getParent() != I2->getParent())
10122             return false;
10123           InstructionsState S = getSameOpcode({I1, I2});
10124           if (S.getOpcode())
10125             continue;
10126           return false;
10127         }
10128       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
10129         continue;
10130       if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID())
10131         return false;
10132     }
10133     return true;
10134   };
10135   auto Limit = [&R](Value *V) {
10136     unsigned EltSize = R.getVectorElementSize(V);
10137     return std::max(2U, R.getMaxVecRegSize() / EltSize);
10138   };
10139 
10140   bool HaveVectorizedPhiNodes = false;
10141   do {
10142     // Collect the incoming values from the PHIs.
10143     Incoming.clear();
10144     for (Instruction &I : *BB) {
10145       PHINode *P = dyn_cast<PHINode>(&I);
10146       if (!P)
10147         break;
10148 
10149       // No need to analyze deleted, vectorized and non-vectorizable
10150       // instructions.
10151       if (!VisitedInstrs.count(P) && !R.isDeleted(P) &&
10152           isValidElementType(P->getType()))
10153         Incoming.push_back(P);
10154     }
10155 
10156     // Find the corresponding non-phi nodes for better matching when trying to
10157     // build the tree.
10158     for (Value *V : Incoming) {
10159       SmallVectorImpl<Value *> &Opcodes =
10160           PHIToOpcodes.try_emplace(V).first->getSecond();
10161       if (!Opcodes.empty())
10162         continue;
10163       SmallVector<Value *, 4> Nodes(1, V);
10164       SmallPtrSet<Value *, 4> Visited;
10165       while (!Nodes.empty()) {
10166         auto *PHI = cast<PHINode>(Nodes.pop_back_val());
10167         if (!Visited.insert(PHI).second)
10168           continue;
10169         for (Value *V : PHI->incoming_values()) {
10170           if (auto *PHI1 = dyn_cast<PHINode>((V))) {
10171             Nodes.push_back(PHI1);
10172             continue;
10173           }
10174           Opcodes.emplace_back(V);
10175         }
10176       }
10177     }
10178 
10179     HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>(
10180         Incoming, Limit, PHICompare, AreCompatiblePHIs,
10181         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10182           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10183         },
10184         /*LimitForRegisterSize=*/true);
10185     Changed |= HaveVectorizedPhiNodes;
10186     VisitedInstrs.insert(Incoming.begin(), Incoming.end());
10187   } while (HaveVectorizedPhiNodes);
10188 
10189   VisitedInstrs.clear();
10190 
10191   SmallVector<Instruction *, 8> PostProcessInstructions;
10192   SmallDenseSet<Instruction *, 4> KeyNodes;
10193   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
10194     // Skip instructions with scalable type. The num of elements is unknown at
10195     // compile-time for scalable type.
10196     if (isa<ScalableVectorType>(it->getType()))
10197       continue;
10198 
10199     // Skip instructions marked for the deletion.
10200     if (R.isDeleted(&*it))
10201       continue;
10202     // We may go through BB multiple times so skip the one we have checked.
10203     if (!VisitedInstrs.insert(&*it).second) {
10204       if (it->use_empty() && KeyNodes.contains(&*it) &&
10205           vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10206                                       it->isTerminator())) {
10207         // We would like to start over since some instructions are deleted
10208         // and the iterator may become invalid value.
10209         Changed = true;
10210         it = BB->begin();
10211         e = BB->end();
10212       }
10213       continue;
10214     }
10215 
10216     if (isa<DbgInfoIntrinsic>(it))
10217       continue;
10218 
10219     // Try to vectorize reductions that use PHINodes.
10220     if (PHINode *P = dyn_cast<PHINode>(it)) {
10221       // Check that the PHI is a reduction PHI.
10222       if (P->getNumIncomingValues() == 2) {
10223         // Try to match and vectorize a horizontal reduction.
10224         if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
10225                                      TTI)) {
10226           Changed = true;
10227           it = BB->begin();
10228           e = BB->end();
10229           continue;
10230         }
10231       }
10232       // Try to vectorize the incoming values of the PHI, to catch reductions
10233       // that feed into PHIs.
10234       for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) {
10235         // Skip if the incoming block is the current BB for now. Also, bypass
10236         // unreachable IR for efficiency and to avoid crashing.
10237         // TODO: Collect the skipped incoming values and try to vectorize them
10238         // after processing BB.
10239         if (BB == P->getIncomingBlock(I) ||
10240             !DT->isReachableFromEntry(P->getIncomingBlock(I)))
10241           continue;
10242 
10243         Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I),
10244                                             P->getIncomingBlock(I), R, TTI);
10245       }
10246       continue;
10247     }
10248 
10249     // Ran into an instruction without users, like terminator, or function call
10250     // with ignored return value, store. Ignore unused instructions (basing on
10251     // instruction type, except for CallInst and InvokeInst).
10252     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
10253                             isa<InvokeInst>(it))) {
10254       KeyNodes.insert(&*it);
10255       bool OpsChanged = false;
10256       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
10257         for (auto *V : it->operand_values()) {
10258           // Try to match and vectorize a horizontal reduction.
10259           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
10260         }
10261       }
10262       // Start vectorization of post-process list of instructions from the
10263       // top-tree instructions to try to vectorize as many instructions as
10264       // possible.
10265       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10266                                                 it->isTerminator());
10267       if (OpsChanged) {
10268         // We would like to start over since some instructions are deleted
10269         // and the iterator may become invalid value.
10270         Changed = true;
10271         it = BB->begin();
10272         e = BB->end();
10273         continue;
10274       }
10275     }
10276 
10277     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
10278         isa<InsertValueInst>(it))
10279       PostProcessInstructions.push_back(&*it);
10280   }
10281 
10282   return Changed;
10283 }
10284 
10285 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
10286   auto Changed = false;
10287   for (auto &Entry : GEPs) {
10288     // If the getelementptr list has fewer than two elements, there's nothing
10289     // to do.
10290     if (Entry.second.size() < 2)
10291       continue;
10292 
10293     LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
10294                       << Entry.second.size() << ".\n");
10295 
10296     // Process the GEP list in chunks suitable for the target's supported
10297     // vector size. If a vector register can't hold 1 element, we are done. We
10298     // are trying to vectorize the index computations, so the maximum number of
10299     // elements is based on the size of the index expression, rather than the
10300     // size of the GEP itself (the target's pointer size).
10301     unsigned MaxVecRegSize = R.getMaxVecRegSize();
10302     unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin());
10303     if (MaxVecRegSize < EltSize)
10304       continue;
10305 
10306     unsigned MaxElts = MaxVecRegSize / EltSize;
10307     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
10308       auto Len = std::min<unsigned>(BE - BI, MaxElts);
10309       ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len);
10310 
10311       // Initialize a set a candidate getelementptrs. Note that we use a
10312       // SetVector here to preserve program order. If the index computations
10313       // are vectorizable and begin with loads, we want to minimize the chance
10314       // of having to reorder them later.
10315       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
10316 
10317       // Some of the candidates may have already been vectorized after we
10318       // initially collected them. If so, they are marked as deleted, so remove
10319       // them from the set of candidates.
10320       Candidates.remove_if(
10321           [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
10322 
10323       // Remove from the set of candidates all pairs of getelementptrs with
10324       // constant differences. Such getelementptrs are likely not good
10325       // candidates for vectorization in a bottom-up phase since one can be
10326       // computed from the other. We also ensure all candidate getelementptr
10327       // indices are unique.
10328       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
10329         auto *GEPI = GEPList[I];
10330         if (!Candidates.count(GEPI))
10331           continue;
10332         auto *SCEVI = SE->getSCEV(GEPList[I]);
10333         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
10334           auto *GEPJ = GEPList[J];
10335           auto *SCEVJ = SE->getSCEV(GEPList[J]);
10336           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
10337             Candidates.remove(GEPI);
10338             Candidates.remove(GEPJ);
10339           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
10340             Candidates.remove(GEPJ);
10341           }
10342         }
10343       }
10344 
10345       // We break out of the above computation as soon as we know there are
10346       // fewer than two candidates remaining.
10347       if (Candidates.size() < 2)
10348         continue;
10349 
10350       // Add the single, non-constant index of each candidate to the bundle. We
10351       // ensured the indices met these constraints when we originally collected
10352       // the getelementptrs.
10353       SmallVector<Value *, 16> Bundle(Candidates.size());
10354       auto BundleIndex = 0u;
10355       for (auto *V : Candidates) {
10356         auto *GEP = cast<GetElementPtrInst>(V);
10357         auto *GEPIdx = GEP->idx_begin()->get();
10358         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
10359         Bundle[BundleIndex++] = GEPIdx;
10360       }
10361 
10362       // Try and vectorize the indices. We are currently only interested in
10363       // gather-like cases of the form:
10364       //
10365       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
10366       //
10367       // where the loads of "a", the loads of "b", and the subtractions can be
10368       // performed in parallel. It's likely that detecting this pattern in a
10369       // bottom-up phase will be simpler and less costly than building a
10370       // full-blown top-down phase beginning at the consecutive loads.
10371       Changed |= tryToVectorizeList(Bundle, R);
10372     }
10373   }
10374   return Changed;
10375 }
10376 
10377 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
10378   bool Changed = false;
10379   // Sort by type, base pointers and values operand. Value operands must be
10380   // compatible (have the same opcode, same parent), otherwise it is
10381   // definitely not profitable to try to vectorize them.
10382   auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) {
10383     if (V->getPointerOperandType()->getTypeID() <
10384         V2->getPointerOperandType()->getTypeID())
10385       return true;
10386     if (V->getPointerOperandType()->getTypeID() >
10387         V2->getPointerOperandType()->getTypeID())
10388       return false;
10389     // UndefValues are compatible with all other values.
10390     if (isa<UndefValue>(V->getValueOperand()) ||
10391         isa<UndefValue>(V2->getValueOperand()))
10392       return false;
10393     if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand()))
10394       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
10395         DomTreeNodeBase<llvm::BasicBlock> *NodeI1 =
10396             DT->getNode(I1->getParent());
10397         DomTreeNodeBase<llvm::BasicBlock> *NodeI2 =
10398             DT->getNode(I2->getParent());
10399         assert(NodeI1 && "Should only process reachable instructions");
10400         assert(NodeI1 && "Should only process reachable instructions");
10401         assert((NodeI1 == NodeI2) ==
10402                    (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10403                "Different nodes should have different DFS numbers");
10404         if (NodeI1 != NodeI2)
10405           return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10406         InstructionsState S = getSameOpcode({I1, I2});
10407         if (S.getOpcode())
10408           return false;
10409         return I1->getOpcode() < I2->getOpcode();
10410       }
10411     if (isa<Constant>(V->getValueOperand()) &&
10412         isa<Constant>(V2->getValueOperand()))
10413       return false;
10414     return V->getValueOperand()->getValueID() <
10415            V2->getValueOperand()->getValueID();
10416   };
10417 
10418   auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) {
10419     if (V1 == V2)
10420       return true;
10421     if (V1->getPointerOperandType() != V2->getPointerOperandType())
10422       return false;
10423     // Undefs are compatible with any other value.
10424     if (isa<UndefValue>(V1->getValueOperand()) ||
10425         isa<UndefValue>(V2->getValueOperand()))
10426       return true;
10427     if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand()))
10428       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
10429         if (I1->getParent() != I2->getParent())
10430           return false;
10431         InstructionsState S = getSameOpcode({I1, I2});
10432         return S.getOpcode() > 0;
10433       }
10434     if (isa<Constant>(V1->getValueOperand()) &&
10435         isa<Constant>(V2->getValueOperand()))
10436       return true;
10437     return V1->getValueOperand()->getValueID() ==
10438            V2->getValueOperand()->getValueID();
10439   };
10440   auto Limit = [&R, this](StoreInst *SI) {
10441     unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
10442     return R.getMinVF(EltSize);
10443   };
10444 
10445   // Attempt to sort and vectorize each of the store-groups.
10446   for (auto &Pair : Stores) {
10447     if (Pair.second.size() < 2)
10448       continue;
10449 
10450     LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
10451                       << Pair.second.size() << ".\n");
10452 
10453     if (!isValidElementType(Pair.second.front()->getValueOperand()->getType()))
10454       continue;
10455 
10456     Changed |= tryToVectorizeSequence<StoreInst>(
10457         Pair.second, Limit, StoreSorter, AreCompatibleStores,
10458         [this, &R](ArrayRef<StoreInst *> Candidates, bool) {
10459           return vectorizeStores(Candidates, R);
10460         },
10461         /*LimitForRegisterSize=*/false);
10462   }
10463   return Changed;
10464 }
10465 
10466 char SLPVectorizer::ID = 0;
10467 
10468 static const char lv_name[] = "SLP Vectorizer";
10469 
10470 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
10471 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
10472 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
10473 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
10474 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
10475 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
10476 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
10477 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
10478 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
10479 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
10480 
10481 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
10482