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/Operator.h"
68 #include "llvm/IR/PatternMatch.h"
69 #include "llvm/IR/Type.h"
70 #include "llvm/IR/Use.h"
71 #include "llvm/IR/User.h"
72 #include "llvm/IR/Value.h"
73 #include "llvm/IR/ValueHandle.h"
74 #ifdef EXPENSIVE_CHECKS
75 #include "llvm/IR/Verifier.h"
76 #endif
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/Local.h"
91 #include "llvm/Transforms/Utils/LoopUtils.h"
92 #include "llvm/Transforms/Vectorize.h"
93 #include <algorithm>
94 #include <cassert>
95 #include <cstdint>
96 #include <iterator>
97 #include <memory>
98 #include <set>
99 #include <string>
100 #include <tuple>
101 #include <utility>
102 #include <vector>
103 
104 using namespace llvm;
105 using namespace llvm::PatternMatch;
106 using namespace slpvectorizer;
107 
108 #define SV_NAME "slp-vectorizer"
109 #define DEBUG_TYPE "SLP"
110 
111 STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
112 
113 cl::opt<bool> RunSLPVectorization("vectorize-slp", cl::init(true), cl::Hidden,
114                                   cl::desc("Run the SLP vectorization passes"));
115 
116 static cl::opt<int>
117     SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
118                      cl::desc("Only vectorize if you gain more than this "
119                               "number "));
120 
121 static cl::opt<bool>
122 ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden,
123                    cl::desc("Attempt to vectorize horizontal reductions"));
124 
125 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
126     "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
127     cl::desc(
128         "Attempt to vectorize horizontal reductions feeding into a store"));
129 
130 static cl::opt<int>
131 MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden,
132     cl::desc("Attempt to vectorize for this register size in bits"));
133 
134 static cl::opt<unsigned>
135 MaxVFOption("slp-max-vf", cl::init(0), cl::Hidden,
136     cl::desc("Maximum SLP vectorization factor (0=unlimited)"));
137 
138 static cl::opt<int>
139 MaxStoreLookup("slp-max-store-lookup", cl::init(32), cl::Hidden,
140     cl::desc("Maximum depth of the lookup for consecutive stores."));
141 
142 /// Limits the size of scheduling regions in a block.
143 /// It avoid long compile times for _very_ large blocks where vector
144 /// instructions are spread over a wide range.
145 /// This limit is way higher than needed by real-world functions.
146 static cl::opt<int>
147 ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden,
148     cl::desc("Limit the size of the SLP scheduling region per block"));
149 
150 static cl::opt<int> MinVectorRegSizeOption(
151     "slp-min-reg-size", cl::init(128), cl::Hidden,
152     cl::desc("Attempt to vectorize for this register size in bits"));
153 
154 static cl::opt<unsigned> RecursionMaxDepth(
155     "slp-recursion-max-depth", cl::init(12), cl::Hidden,
156     cl::desc("Limit the recursion depth when building a vectorizable tree"));
157 
158 static cl::opt<unsigned> MinTreeSize(
159     "slp-min-tree-size", cl::init(3), cl::Hidden,
160     cl::desc("Only vectorize small trees if they are fully vectorizable"));
161 
162 // The maximum depth that the look-ahead score heuristic will explore.
163 // The higher this value, the higher the compilation time overhead.
164 static cl::opt<int> LookAheadMaxDepth(
165     "slp-max-look-ahead-depth", cl::init(2), cl::Hidden,
166     cl::desc("The maximum look-ahead depth for operand reordering scores"));
167 
168 static cl::opt<bool>
169     ViewSLPTree("view-slp-tree", cl::Hidden,
170                 cl::desc("Display the SLP trees with Graphviz"));
171 
172 // Limit the number of alias checks. The limit is chosen so that
173 // it has no negative effect on the llvm benchmarks.
174 static const unsigned AliasedCheckLimit = 10;
175 
176 // Another limit for the alias checks: The maximum distance between load/store
177 // instructions where alias checks are done.
178 // This limit is useful for very large basic blocks.
179 static const unsigned MaxMemDepDistance = 160;
180 
181 /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
182 /// regions to be handled.
183 static const int MinScheduleRegionSize = 16;
184 
185 /// Predicate for the element types that the SLP vectorizer supports.
186 ///
187 /// The most important thing to filter here are types which are invalid in LLVM
188 /// vectors. We also filter target specific types which have absolutely no
189 /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
190 /// avoids spending time checking the cost model and realizing that they will
191 /// be inevitably scalarized.
192 static bool isValidElementType(Type *Ty) {
193   return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() &&
194          !Ty->isPPC_FP128Ty();
195 }
196 
197 /// \returns True if the value is a constant (but not globals/constant
198 /// expressions).
199 static bool isConstant(Value *V) {
200   return isa<Constant>(V) && !isa<ConstantExpr>(V) && !isa<GlobalValue>(V);
201 }
202 
203 /// Checks if \p V is one of vector-like instructions, i.e. undef,
204 /// insertelement/extractelement with constant indices for fixed vector type or
205 /// extractvalue instruction.
206 static bool isVectorLikeInstWithConstOps(Value *V) {
207   if (!isa<InsertElementInst, ExtractElementInst>(V) &&
208       !isa<ExtractValueInst, UndefValue>(V))
209     return false;
210   auto *I = dyn_cast<Instruction>(V);
211   if (!I || isa<ExtractValueInst>(I))
212     return true;
213   if (!isa<FixedVectorType>(I->getOperand(0)->getType()))
214     return false;
215   if (isa<ExtractElementInst>(I))
216     return isConstant(I->getOperand(1));
217   assert(isa<InsertElementInst>(V) && "Expected only insertelement.");
218   return isConstant(I->getOperand(2));
219 }
220 
221 /// \returns true if all of the instructions in \p VL are in the same block or
222 /// false otherwise.
223 static bool allSameBlock(ArrayRef<Value *> VL) {
224   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
225   if (!I0)
226     return false;
227   if (all_of(VL, isVectorLikeInstWithConstOps))
228     return true;
229 
230   BasicBlock *BB = I0->getParent();
231   for (int I = 1, E = VL.size(); I < E; I++) {
232     auto *II = dyn_cast<Instruction>(VL[I]);
233     if (!II)
234       return false;
235 
236     if (BB != II->getParent())
237       return false;
238   }
239   return true;
240 }
241 
242 /// \returns True if all of the values in \p VL are constants (but not
243 /// globals/constant expressions).
244 static bool allConstant(ArrayRef<Value *> VL) {
245   // Constant expressions and globals can't be vectorized like normal integer/FP
246   // constants.
247   return all_of(VL, isConstant);
248 }
249 
250 /// \returns True if all of the values in \p VL are identical or some of them
251 /// are UndefValue.
252 static bool isSplat(ArrayRef<Value *> VL) {
253   Value *FirstNonUndef = nullptr;
254   for (Value *V : VL) {
255     if (isa<UndefValue>(V))
256       continue;
257     if (!FirstNonUndef) {
258       FirstNonUndef = V;
259       continue;
260     }
261     if (V != FirstNonUndef)
262       return false;
263   }
264   return FirstNonUndef != nullptr;
265 }
266 
267 /// \returns True if \p I is commutative, handles CmpInst and BinaryOperator.
268 static bool isCommutative(Instruction *I) {
269   if (auto *Cmp = dyn_cast<CmpInst>(I))
270     return Cmp->isCommutative();
271   if (auto *BO = dyn_cast<BinaryOperator>(I))
272     return BO->isCommutative();
273   // TODO: This should check for generic Instruction::isCommutative(), but
274   //       we need to confirm that the caller code correctly handles Intrinsics
275   //       for example (does not have 2 operands).
276   return false;
277 }
278 
279 /// Checks if the given value is actually an undefined constant vector.
280 static bool isUndefVector(const Value *V) {
281   if (isa<UndefValue>(V))
282     return true;
283   auto *C = dyn_cast<Constant>(V);
284   if (!C)
285     return false;
286   if (!C->containsUndefOrPoisonElement())
287     return false;
288   auto *VecTy = dyn_cast<FixedVectorType>(C->getType());
289   if (!VecTy)
290     return false;
291   for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
292     if (Constant *Elem = C->getAggregateElement(I))
293       if (!isa<UndefValue>(Elem))
294         return false;
295   }
296   return true;
297 }
298 
299 /// Checks if the vector of instructions can be represented as a shuffle, like:
300 /// %x0 = extractelement <4 x i8> %x, i32 0
301 /// %x3 = extractelement <4 x i8> %x, i32 3
302 /// %y1 = extractelement <4 x i8> %y, i32 1
303 /// %y2 = extractelement <4 x i8> %y, i32 2
304 /// %x0x0 = mul i8 %x0, %x0
305 /// %x3x3 = mul i8 %x3, %x3
306 /// %y1y1 = mul i8 %y1, %y1
307 /// %y2y2 = mul i8 %y2, %y2
308 /// %ins1 = insertelement <4 x i8> poison, i8 %x0x0, i32 0
309 /// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1
310 /// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2
311 /// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3
312 /// ret <4 x i8> %ins4
313 /// can be transformed into:
314 /// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5,
315 ///                                                         i32 6>
316 /// %2 = mul <4 x i8> %1, %1
317 /// ret <4 x i8> %2
318 /// We convert this initially to something like:
319 /// %x0 = extractelement <4 x i8> %x, i32 0
320 /// %x3 = extractelement <4 x i8> %x, i32 3
321 /// %y1 = extractelement <4 x i8> %y, i32 1
322 /// %y2 = extractelement <4 x i8> %y, i32 2
323 /// %1 = insertelement <4 x i8> poison, i8 %x0, i32 0
324 /// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1
325 /// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2
326 /// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3
327 /// %5 = mul <4 x i8> %4, %4
328 /// %6 = extractelement <4 x i8> %5, i32 0
329 /// %ins1 = insertelement <4 x i8> poison, i8 %6, i32 0
330 /// %7 = extractelement <4 x i8> %5, i32 1
331 /// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1
332 /// %8 = extractelement <4 x i8> %5, i32 2
333 /// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2
334 /// %9 = extractelement <4 x i8> %5, i32 3
335 /// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3
336 /// ret <4 x i8> %ins4
337 /// InstCombiner transforms this into a shuffle and vector mul
338 /// Mask will return the Shuffle Mask equivalent to the extracted elements.
339 /// TODO: Can we split off and reuse the shuffle mask detection from
340 /// TargetTransformInfo::getInstructionThroughput?
341 static Optional<TargetTransformInfo::ShuffleKind>
342 isFixedVectorShuffle(ArrayRef<Value *> VL, SmallVectorImpl<int> &Mask) {
343   const auto *It =
344       find_if(VL, [](Value *V) { return isa<ExtractElementInst>(V); });
345   if (It == VL.end())
346     return None;
347   auto *EI0 = cast<ExtractElementInst>(*It);
348   if (isa<ScalableVectorType>(EI0->getVectorOperandType()))
349     return None;
350   unsigned Size =
351       cast<FixedVectorType>(EI0->getVectorOperandType())->getNumElements();
352   Value *Vec1 = nullptr;
353   Value *Vec2 = nullptr;
354   enum ShuffleMode { Unknown, Select, Permute };
355   ShuffleMode CommonShuffleMode = Unknown;
356   Mask.assign(VL.size(), UndefMaskElem);
357   for (unsigned I = 0, E = VL.size(); I < E; ++I) {
358     // Undef can be represented as an undef element in a vector.
359     if (isa<UndefValue>(VL[I]))
360       continue;
361     auto *EI = cast<ExtractElementInst>(VL[I]);
362     if (isa<ScalableVectorType>(EI->getVectorOperandType()))
363       return None;
364     auto *Vec = EI->getVectorOperand();
365     // We can extractelement from undef or poison vector.
366     if (isUndefVector(Vec))
367       continue;
368     // All vector operands must have the same number of vector elements.
369     if (cast<FixedVectorType>(Vec->getType())->getNumElements() != Size)
370       return None;
371     if (isa<UndefValue>(EI->getIndexOperand()))
372       continue;
373     auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand());
374     if (!Idx)
375       return None;
376     // Undefined behavior if Idx is negative or >= Size.
377     if (Idx->getValue().uge(Size))
378       continue;
379     unsigned IntIdx = Idx->getValue().getZExtValue();
380     Mask[I] = IntIdx;
381     // For correct shuffling we have to have at most 2 different vector operands
382     // in all extractelement instructions.
383     if (!Vec1 || Vec1 == Vec) {
384       Vec1 = Vec;
385     } else if (!Vec2 || Vec2 == Vec) {
386       Vec2 = Vec;
387       Mask[I] += Size;
388     } else {
389       return None;
390     }
391     if (CommonShuffleMode == Permute)
392       continue;
393     // If the extract index is not the same as the operation number, it is a
394     // permutation.
395     if (IntIdx != I) {
396       CommonShuffleMode = Permute;
397       continue;
398     }
399     CommonShuffleMode = Select;
400   }
401   // If we're not crossing lanes in different vectors, consider it as blending.
402   if (CommonShuffleMode == Select && Vec2)
403     return TargetTransformInfo::SK_Select;
404   // If Vec2 was never used, we have a permutation of a single vector, otherwise
405   // we have permutation of 2 vectors.
406   return Vec2 ? TargetTransformInfo::SK_PermuteTwoSrc
407               : TargetTransformInfo::SK_PermuteSingleSrc;
408 }
409 
410 namespace {
411 
412 /// Main data required for vectorization of instructions.
413 struct InstructionsState {
414   /// The very first instruction in the list with the main opcode.
415   Value *OpValue = nullptr;
416 
417   /// The main/alternate instruction.
418   Instruction *MainOp = nullptr;
419   Instruction *AltOp = nullptr;
420 
421   /// The main/alternate opcodes for the list of instructions.
422   unsigned getOpcode() const {
423     return MainOp ? MainOp->getOpcode() : 0;
424   }
425 
426   unsigned getAltOpcode() const {
427     return AltOp ? AltOp->getOpcode() : 0;
428   }
429 
430   /// Some of the instructions in the list have alternate opcodes.
431   bool isAltShuffle() const { return AltOp != MainOp; }
432 
433   bool isOpcodeOrAlt(Instruction *I) const {
434     unsigned CheckedOpcode = I->getOpcode();
435     return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode;
436   }
437 
438   InstructionsState() = delete;
439   InstructionsState(Value *OpValue, Instruction *MainOp, Instruction *AltOp)
440       : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {}
441 };
442 
443 } // end anonymous namespace
444 
445 /// Chooses the correct key for scheduling data. If \p Op has the same (or
446 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p
447 /// OpValue.
448 static Value *isOneOf(const InstructionsState &S, Value *Op) {
449   auto *I = dyn_cast<Instruction>(Op);
450   if (I && S.isOpcodeOrAlt(I))
451     return Op;
452   return S.OpValue;
453 }
454 
455 /// \returns true if \p Opcode is allowed as part of of the main/alternate
456 /// instruction for SLP vectorization.
457 ///
458 /// Example of unsupported opcode is SDIV that can potentially cause UB if the
459 /// "shuffled out" lane would result in division by zero.
460 static bool isValidForAlternation(unsigned Opcode) {
461   if (Instruction::isIntDivRem(Opcode))
462     return false;
463 
464   return true;
465 }
466 
467 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
468                                        unsigned BaseIndex = 0);
469 
470 /// Checks if the provided operands of 2 cmp instructions are compatible, i.e.
471 /// compatible instructions or constants, or just some other regular values.
472 static bool areCompatibleCmpOps(Value *BaseOp0, Value *BaseOp1, Value *Op0,
473                                 Value *Op1) {
474   return (isConstant(BaseOp0) && isConstant(Op0)) ||
475          (isConstant(BaseOp1) && isConstant(Op1)) ||
476          (!isa<Instruction>(BaseOp0) && !isa<Instruction>(Op0) &&
477           !isa<Instruction>(BaseOp1) && !isa<Instruction>(Op1)) ||
478          getSameOpcode({BaseOp0, Op0}).getOpcode() ||
479          getSameOpcode({BaseOp1, Op1}).getOpcode();
480 }
481 
482 /// \returns analysis of the Instructions in \p VL described in
483 /// InstructionsState, the Opcode that we suppose the whole list
484 /// could be vectorized even if its structure is diverse.
485 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
486                                        unsigned BaseIndex) {
487   // Make sure these are all Instructions.
488   if (llvm::any_of(VL, [](Value *V) { return !isa<Instruction>(V); }))
489     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
490 
491   bool IsCastOp = isa<CastInst>(VL[BaseIndex]);
492   bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]);
493   bool IsCmpOp = isa<CmpInst>(VL[BaseIndex]);
494   CmpInst::Predicate BasePred =
495       IsCmpOp ? cast<CmpInst>(VL[BaseIndex])->getPredicate()
496               : CmpInst::BAD_ICMP_PREDICATE;
497   unsigned Opcode = cast<Instruction>(VL[BaseIndex])->getOpcode();
498   unsigned AltOpcode = Opcode;
499   unsigned AltIndex = BaseIndex;
500 
501   // Check for one alternate opcode from another BinaryOperator.
502   // TODO - generalize to support all operators (types, calls etc.).
503   for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) {
504     unsigned InstOpcode = cast<Instruction>(VL[Cnt])->getOpcode();
505     if (IsBinOp && isa<BinaryOperator>(VL[Cnt])) {
506       if (InstOpcode == Opcode || InstOpcode == AltOpcode)
507         continue;
508       if (Opcode == AltOpcode && isValidForAlternation(InstOpcode) &&
509           isValidForAlternation(Opcode)) {
510         AltOpcode = InstOpcode;
511         AltIndex = Cnt;
512         continue;
513       }
514     } else if (IsCastOp && isa<CastInst>(VL[Cnt])) {
515       Type *Ty0 = cast<Instruction>(VL[BaseIndex])->getOperand(0)->getType();
516       Type *Ty1 = cast<Instruction>(VL[Cnt])->getOperand(0)->getType();
517       if (Ty0 == Ty1) {
518         if (InstOpcode == Opcode || InstOpcode == AltOpcode)
519           continue;
520         if (Opcode == AltOpcode) {
521           assert(isValidForAlternation(Opcode) &&
522                  isValidForAlternation(InstOpcode) &&
523                  "Cast isn't safe for alternation, logic needs to be updated!");
524           AltOpcode = InstOpcode;
525           AltIndex = Cnt;
526           continue;
527         }
528       }
529     } else if (IsCmpOp && isa<CmpInst>(VL[Cnt])) {
530       auto *BaseInst = cast<Instruction>(VL[BaseIndex]);
531       auto *Inst = cast<Instruction>(VL[Cnt]);
532       Type *Ty0 = BaseInst->getOperand(0)->getType();
533       Type *Ty1 = Inst->getOperand(0)->getType();
534       if (Ty0 == Ty1) {
535         Value *BaseOp0 = BaseInst->getOperand(0);
536         Value *BaseOp1 = BaseInst->getOperand(1);
537         Value *Op0 = Inst->getOperand(0);
538         Value *Op1 = Inst->getOperand(1);
539         CmpInst::Predicate CurrentPred =
540             cast<CmpInst>(VL[Cnt])->getPredicate();
541         CmpInst::Predicate SwappedCurrentPred =
542             CmpInst::getSwappedPredicate(CurrentPred);
543         // Check for compatible operands. If the corresponding operands are not
544         // compatible - need to perform alternate vectorization.
545         if (InstOpcode == Opcode) {
546           if (BasePred == CurrentPred &&
547               areCompatibleCmpOps(BaseOp0, BaseOp1, Op0, Op1))
548             continue;
549           if (BasePred == SwappedCurrentPred &&
550               areCompatibleCmpOps(BaseOp0, BaseOp1, Op1, Op0))
551             continue;
552           if (E == 2 &&
553               (BasePred == CurrentPred || BasePred == SwappedCurrentPred))
554             continue;
555           auto *AltInst = cast<CmpInst>(VL[AltIndex]);
556           CmpInst::Predicate AltPred = AltInst->getPredicate();
557           Value *AltOp0 = AltInst->getOperand(0);
558           Value *AltOp1 = AltInst->getOperand(1);
559           // Check if operands are compatible with alternate operands.
560           if (AltPred == CurrentPred &&
561               areCompatibleCmpOps(AltOp0, AltOp1, Op0, Op1))
562             continue;
563           if (AltPred == SwappedCurrentPred &&
564               areCompatibleCmpOps(AltOp0, AltOp1, Op1, Op0))
565             continue;
566         }
567         if (BaseIndex == AltIndex && BasePred != CurrentPred) {
568           assert(isValidForAlternation(Opcode) &&
569                  isValidForAlternation(InstOpcode) &&
570                  "Cast isn't safe for alternation, logic needs to be updated!");
571           AltIndex = Cnt;
572           continue;
573         }
574         auto *AltInst = cast<CmpInst>(VL[AltIndex]);
575         CmpInst::Predicate AltPred = AltInst->getPredicate();
576         if (BasePred == CurrentPred || BasePred == SwappedCurrentPred ||
577             AltPred == CurrentPred || AltPred == SwappedCurrentPred)
578           continue;
579       }
580     } else if (InstOpcode == Opcode || InstOpcode == AltOpcode)
581       continue;
582     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
583   }
584 
585   return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]),
586                            cast<Instruction>(VL[AltIndex]));
587 }
588 
589 /// \returns true if all of the values in \p VL have the same type or false
590 /// otherwise.
591 static bool allSameType(ArrayRef<Value *> VL) {
592   Type *Ty = VL[0]->getType();
593   for (int i = 1, e = VL.size(); i < e; i++)
594     if (VL[i]->getType() != Ty)
595       return false;
596 
597   return true;
598 }
599 
600 /// \returns True if Extract{Value,Element} instruction extracts element Idx.
601 static Optional<unsigned> getExtractIndex(Instruction *E) {
602   unsigned Opcode = E->getOpcode();
603   assert((Opcode == Instruction::ExtractElement ||
604           Opcode == Instruction::ExtractValue) &&
605          "Expected extractelement or extractvalue instruction.");
606   if (Opcode == Instruction::ExtractElement) {
607     auto *CI = dyn_cast<ConstantInt>(E->getOperand(1));
608     if (!CI)
609       return None;
610     return CI->getZExtValue();
611   }
612   ExtractValueInst *EI = cast<ExtractValueInst>(E);
613   if (EI->getNumIndices() != 1)
614     return None;
615   return *EI->idx_begin();
616 }
617 
618 /// \returns True if in-tree use also needs extract. This refers to
619 /// possible scalar operand in vectorized instruction.
620 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
621                                     TargetLibraryInfo *TLI) {
622   unsigned Opcode = UserInst->getOpcode();
623   switch (Opcode) {
624   case Instruction::Load: {
625     LoadInst *LI = cast<LoadInst>(UserInst);
626     return (LI->getPointerOperand() == Scalar);
627   }
628   case Instruction::Store: {
629     StoreInst *SI = cast<StoreInst>(UserInst);
630     return (SI->getPointerOperand() == Scalar);
631   }
632   case Instruction::Call: {
633     CallInst *CI = cast<CallInst>(UserInst);
634     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
635     for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
636       if (hasVectorInstrinsicScalarOpd(ID, i))
637         return (CI->getArgOperand(i) == Scalar);
638     }
639     LLVM_FALLTHROUGH;
640   }
641   default:
642     return false;
643   }
644 }
645 
646 /// \returns the AA location that is being access by the instruction.
647 static MemoryLocation getLocation(Instruction *I) {
648   if (StoreInst *SI = dyn_cast<StoreInst>(I))
649     return MemoryLocation::get(SI);
650   if (LoadInst *LI = dyn_cast<LoadInst>(I))
651     return MemoryLocation::get(LI);
652   return MemoryLocation();
653 }
654 
655 /// \returns True if the instruction is not a volatile or atomic load/store.
656 static bool isSimple(Instruction *I) {
657   if (LoadInst *LI = dyn_cast<LoadInst>(I))
658     return LI->isSimple();
659   if (StoreInst *SI = dyn_cast<StoreInst>(I))
660     return SI->isSimple();
661   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
662     return !MI->isVolatile();
663   return true;
664 }
665 
666 /// Shuffles \p Mask in accordance with the given \p SubMask.
667 static void addMask(SmallVectorImpl<int> &Mask, ArrayRef<int> SubMask) {
668   if (SubMask.empty())
669     return;
670   if (Mask.empty()) {
671     Mask.append(SubMask.begin(), SubMask.end());
672     return;
673   }
674   SmallVector<int> NewMask(SubMask.size(), UndefMaskElem);
675   int TermValue = std::min(Mask.size(), SubMask.size());
676   for (int I = 0, E = SubMask.size(); I < E; ++I) {
677     if (SubMask[I] >= TermValue || SubMask[I] == UndefMaskElem ||
678         Mask[SubMask[I]] >= TermValue)
679       continue;
680     NewMask[I] = Mask[SubMask[I]];
681   }
682   Mask.swap(NewMask);
683 }
684 
685 /// Order may have elements assigned special value (size) which is out of
686 /// bounds. Such indices only appear on places which correspond to undef values
687 /// (see canReuseExtract for details) and used in order to avoid undef values
688 /// have effect on operands ordering.
689 /// The first loop below simply finds all unused indices and then the next loop
690 /// nest assigns these indices for undef values positions.
691 /// As an example below Order has two undef positions and they have assigned
692 /// values 3 and 7 respectively:
693 /// before:  6 9 5 4 9 2 1 0
694 /// after:   6 3 5 4 7 2 1 0
695 static void fixupOrderingIndices(SmallVectorImpl<unsigned> &Order) {
696   const unsigned Sz = Order.size();
697   SmallBitVector UnusedIndices(Sz, /*t=*/true);
698   SmallBitVector MaskedIndices(Sz);
699   for (unsigned I = 0; I < Sz; ++I) {
700     if (Order[I] < Sz)
701       UnusedIndices.reset(Order[I]);
702     else
703       MaskedIndices.set(I);
704   }
705   if (MaskedIndices.none())
706     return;
707   assert(UnusedIndices.count() == MaskedIndices.count() &&
708          "Non-synced masked/available indices.");
709   int Idx = UnusedIndices.find_first();
710   int MIdx = MaskedIndices.find_first();
711   while (MIdx >= 0) {
712     assert(Idx >= 0 && "Indices must be synced.");
713     Order[MIdx] = Idx;
714     Idx = UnusedIndices.find_next(Idx);
715     MIdx = MaskedIndices.find_next(MIdx);
716   }
717 }
718 
719 namespace llvm {
720 
721 static void inversePermutation(ArrayRef<unsigned> Indices,
722                                SmallVectorImpl<int> &Mask) {
723   Mask.clear();
724   const unsigned E = Indices.size();
725   Mask.resize(E, UndefMaskElem);
726   for (unsigned I = 0; I < E; ++I)
727     Mask[Indices[I]] = I;
728 }
729 
730 /// \returns inserting index of InsertElement or InsertValue instruction,
731 /// using Offset as base offset for index.
732 static Optional<unsigned> getInsertIndex(Value *InsertInst,
733                                          unsigned Offset = 0) {
734   int Index = Offset;
735   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst)) {
736     if (auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2))) {
737       auto *VT = cast<FixedVectorType>(IE->getType());
738       if (CI->getValue().uge(VT->getNumElements()))
739         return None;
740       Index *= VT->getNumElements();
741       Index += CI->getZExtValue();
742       return Index;
743     }
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 Mask.
765 static void reorderScalars(SmallVectorImpl<Value *> &Scalars,
766                            ArrayRef<int> Mask) {
767   assert(!Mask.empty() && "Expected non-empty mask.");
768   SmallVector<Value *> Prev(Scalars.size(),
769                             UndefValue::get(Scalars.front()->getType()));
770   Prev.swap(Scalars);
771   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
772     if (Mask[I] != UndefMaskElem)
773       Scalars[Mask[I]] = Prev[I];
774 }
775 
776 /// Checks if the provided value does not require scheduling. It does not
777 /// require scheduling if this is not an instruction or it is an instruction
778 /// that does not read/write memory and all operands are either not instructions
779 /// or phi nodes or instructions from different blocks.
780 static bool areAllOperandsNonInsts(Value *V) {
781   auto *I = dyn_cast<Instruction>(V);
782   if (!I)
783     return true;
784   return !mayHaveNonDefUseDependency(*I) &&
785     all_of(I->operands(), [I](Value *V) {
786       auto *IO = dyn_cast<Instruction>(V);
787       if (!IO)
788         return true;
789       return isa<PHINode>(IO) || IO->getParent() != I->getParent();
790     });
791 }
792 
793 /// Checks if the provided value does not require scheduling. It does not
794 /// require scheduling if this is not an instruction or it is an instruction
795 /// that does not read/write memory and all users are phi nodes or instructions
796 /// from the different blocks.
797 static bool isUsedOutsideBlock(Value *V) {
798   auto *I = dyn_cast<Instruction>(V);
799   if (!I)
800     return true;
801   // Limits the number of uses to save compile time.
802   constexpr int UsesLimit = 8;
803   return !I->mayReadOrWriteMemory() && !I->hasNUsesOrMore(UsesLimit) &&
804          all_of(I->users(), [I](User *U) {
805            auto *IU = dyn_cast<Instruction>(U);
806            if (!IU)
807              return true;
808            return IU->getParent() != I->getParent() || isa<PHINode>(IU);
809          });
810 }
811 
812 /// Checks if the specified value does not require scheduling. It does not
813 /// require scheduling if all operands and all users do not need to be scheduled
814 /// in the current basic block.
815 static bool doesNotNeedToBeScheduled(Value *V) {
816   return areAllOperandsNonInsts(V) && isUsedOutsideBlock(V);
817 }
818 
819 /// Checks if the specified array of instructions does not require scheduling.
820 /// It is so if all either instructions have operands that do not require
821 /// scheduling or their users do not require scheduling since they are phis or
822 /// in other basic blocks.
823 static bool doesNotNeedToSchedule(ArrayRef<Value *> VL) {
824   return !VL.empty() &&
825          (all_of(VL, isUsedOutsideBlock) || all_of(VL, areAllOperandsNonInsts));
826 }
827 
828 namespace slpvectorizer {
829 
830 /// Bottom Up SLP Vectorizer.
831 class BoUpSLP {
832   struct TreeEntry;
833   struct ScheduleData;
834 
835 public:
836   using ValueList = SmallVector<Value *, 8>;
837   using InstrList = SmallVector<Instruction *, 16>;
838   using ValueSet = SmallPtrSet<Value *, 16>;
839   using StoreList = SmallVector<StoreInst *, 8>;
840   using ExtraValueToDebugLocsMap =
841       MapVector<Value *, SmallVector<Instruction *, 2>>;
842   using OrdersType = SmallVector<unsigned, 4>;
843 
844   BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
845           TargetLibraryInfo *TLi, AAResults *Aa, LoopInfo *Li,
846           DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB,
847           const DataLayout *DL, OptimizationRemarkEmitter *ORE)
848       : BatchAA(*Aa), F(Func), SE(Se), TTI(Tti), TLI(TLi), LI(Li),
849         DT(Dt), AC(AC), DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) {
850     CodeMetrics::collectEphemeralValues(F, AC, EphValues);
851     // Use the vector register size specified by the target unless overridden
852     // by a command-line option.
853     // TODO: It would be better to limit the vectorization factor based on
854     //       data type rather than just register size. For example, x86 AVX has
855     //       256-bit registers, but it does not support integer operations
856     //       at that width (that requires AVX2).
857     if (MaxVectorRegSizeOption.getNumOccurrences())
858       MaxVecRegSize = MaxVectorRegSizeOption;
859     else
860       MaxVecRegSize =
861           TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
862               .getFixedSize();
863 
864     if (MinVectorRegSizeOption.getNumOccurrences())
865       MinVecRegSize = MinVectorRegSizeOption;
866     else
867       MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
868   }
869 
870   /// Vectorize the tree that starts with the elements in \p VL.
871   /// Returns the vectorized root.
872   Value *vectorizeTree();
873 
874   /// Vectorize the tree but with the list of externally used values \p
875   /// ExternallyUsedValues. Values in this MapVector can be replaced but the
876   /// generated extractvalue instructions.
877   Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues);
878 
879   /// \returns the cost incurred by unwanted spills and fills, caused by
880   /// holding live values over call sites.
881   InstructionCost getSpillCost() const;
882 
883   /// \returns the vectorization cost of the subtree that starts at \p VL.
884   /// A negative number means that this is profitable.
885   InstructionCost getTreeCost(ArrayRef<Value *> VectorizedVals = None);
886 
887   /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
888   /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
889   void buildTree(ArrayRef<Value *> Roots,
890                  ArrayRef<Value *> UserIgnoreLst = None);
891 
892   /// Builds external uses of the vectorized scalars, i.e. the list of
893   /// vectorized scalars to be extracted, their lanes and their scalar users. \p
894   /// ExternallyUsedValues contains additional list of external uses to handle
895   /// vectorization of reductions.
896   void
897   buildExternalUses(const ExtraValueToDebugLocsMap &ExternallyUsedValues = {});
898 
899   /// Clear the internal data structures that are created by 'buildTree'.
900   void deleteTree() {
901     VectorizableTree.clear();
902     ScalarToTreeEntry.clear();
903     MustGather.clear();
904     ExternalUses.clear();
905     for (auto &Iter : BlocksSchedules) {
906       BlockScheduling *BS = Iter.second.get();
907       BS->clear();
908     }
909     MinBWs.clear();
910     InstrElementSize.clear();
911   }
912 
913   unsigned getTreeSize() const { return VectorizableTree.size(); }
914 
915   /// Perform LICM and CSE on the newly generated gather sequences.
916   void optimizeGatherSequence();
917 
918   /// Checks if the specified gather tree entry \p TE can be represented as a
919   /// shuffled vector entry + (possibly) permutation with other gathers. It
920   /// implements the checks only for possibly ordered scalars (Loads,
921   /// ExtractElement, ExtractValue), which can be part of the graph.
922   Optional<OrdersType> findReusedOrderedScalars(const TreeEntry &TE);
923 
924   /// Gets reordering data for the given tree entry. If the entry is vectorized
925   /// - just return ReorderIndices, otherwise check if the scalars can be
926   /// reordered and return the most optimal order.
927   /// \param TopToBottom If true, include the order of vectorized stores and
928   /// insertelement nodes, otherwise skip them.
929   Optional<OrdersType> getReorderingData(const TreeEntry &TE, bool TopToBottom);
930 
931   /// Reorders the current graph to the most profitable order starting from the
932   /// root node to the leaf nodes. The best order is chosen only from the nodes
933   /// of the same size (vectorization factor). Smaller nodes are considered
934   /// parts of subgraph with smaller VF and they are reordered independently. We
935   /// can make it because we still need to extend smaller nodes to the wider VF
936   /// and we can merge reordering shuffles with the widening shuffles.
937   void reorderTopToBottom();
938 
939   /// Reorders the current graph to the most profitable order starting from
940   /// leaves to the root. It allows to rotate small subgraphs and reduce the
941   /// number of reshuffles if the leaf nodes use the same order. In this case we
942   /// can merge the orders and just shuffle user node instead of shuffling its
943   /// operands. Plus, even the leaf nodes have different orders, it allows to
944   /// sink reordering in the graph closer to the root node and merge it later
945   /// during analysis.
946   void reorderBottomToTop(bool IgnoreReorder = false);
947 
948   /// \return The vector element size in bits to use when vectorizing the
949   /// expression tree ending at \p V. If V is a store, the size is the width of
950   /// the stored value. Otherwise, the size is the width of the largest loaded
951   /// value reaching V. This method is used by the vectorizer to calculate
952   /// vectorization factors.
953   unsigned getVectorElementSize(Value *V);
954 
955   /// Compute the minimum type sizes required to represent the entries in a
956   /// vectorizable tree.
957   void computeMinimumValueSizes();
958 
959   // \returns maximum vector register size as set by TTI or overridden by cl::opt.
960   unsigned getMaxVecRegSize() const {
961     return MaxVecRegSize;
962   }
963 
964   // \returns minimum vector register size as set by cl::opt.
965   unsigned getMinVecRegSize() const {
966     return MinVecRegSize;
967   }
968 
969   unsigned getMinVF(unsigned Sz) const {
970     return std::max(2U, getMinVecRegSize() / Sz);
971   }
972 
973   unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const {
974     unsigned MaxVF = MaxVFOption.getNumOccurrences() ?
975       MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode);
976     return MaxVF ? MaxVF : UINT_MAX;
977   }
978 
979   /// Check if homogeneous aggregate is isomorphic to some VectorType.
980   /// Accepts homogeneous multidimensional aggregate of scalars/vectors like
981   /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> },
982   /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on.
983   ///
984   /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
985   unsigned canMapToVector(Type *T, const DataLayout &DL) const;
986 
987   /// \returns True if the VectorizableTree is both tiny and not fully
988   /// vectorizable. We do not vectorize such trees.
989   bool isTreeTinyAndNotFullyVectorizable(bool ForReduction = false) const;
990 
991   /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values
992   /// can be load combined in the backend. Load combining may not be allowed in
993   /// the IR optimizer, so we do not want to alter the pattern. For example,
994   /// partially transforming a scalar bswap() pattern into vector code is
995   /// effectively impossible for the backend to undo.
996   /// TODO: If load combining is allowed in the IR optimizer, this analysis
997   ///       may not be necessary.
998   bool isLoadCombineReductionCandidate(RecurKind RdxKind) const;
999 
1000   /// Assume that a vector of stores of bitwise-or/shifted/zexted loaded values
1001   /// can be load combined in the backend. Load combining may not be allowed in
1002   /// the IR optimizer, so we do not want to alter the pattern. For example,
1003   /// partially transforming a scalar bswap() pattern into vector code is
1004   /// effectively impossible for the backend to undo.
1005   /// TODO: If load combining is allowed in the IR optimizer, this analysis
1006   ///       may not be necessary.
1007   bool isLoadCombineCandidate() const;
1008 
1009   OptimizationRemarkEmitter *getORE() { return ORE; }
1010 
1011   /// This structure holds any data we need about the edges being traversed
1012   /// during buildTree_rec(). We keep track of:
1013   /// (i) the user TreeEntry index, and
1014   /// (ii) the index of the edge.
1015   struct EdgeInfo {
1016     EdgeInfo() = default;
1017     EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx)
1018         : UserTE(UserTE), EdgeIdx(EdgeIdx) {}
1019     /// The user TreeEntry.
1020     TreeEntry *UserTE = nullptr;
1021     /// The operand index of the use.
1022     unsigned EdgeIdx = UINT_MAX;
1023 #ifndef NDEBUG
1024     friend inline raw_ostream &operator<<(raw_ostream &OS,
1025                                           const BoUpSLP::EdgeInfo &EI) {
1026       EI.dump(OS);
1027       return OS;
1028     }
1029     /// Debug print.
1030     void dump(raw_ostream &OS) const {
1031       OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null")
1032          << " EdgeIdx:" << EdgeIdx << "}";
1033     }
1034     LLVM_DUMP_METHOD void dump() const { dump(dbgs()); }
1035 #endif
1036   };
1037 
1038   /// A helper data structure to hold the operands of a vector of instructions.
1039   /// This supports a fixed vector length for all operand vectors.
1040   class VLOperands {
1041     /// For each operand we need (i) the value, and (ii) the opcode that it
1042     /// would be attached to if the expression was in a left-linearized form.
1043     /// This is required to avoid illegal operand reordering.
1044     /// For example:
1045     /// \verbatim
1046     ///                         0 Op1
1047     ///                         |/
1048     /// Op1 Op2   Linearized    + Op2
1049     ///   \ /     ---------->   |/
1050     ///    -                    -
1051     ///
1052     /// Op1 - Op2            (0 + Op1) - Op2
1053     /// \endverbatim
1054     ///
1055     /// Value Op1 is attached to a '+' operation, and Op2 to a '-'.
1056     ///
1057     /// Another way to think of this is to track all the operations across the
1058     /// path from the operand all the way to the root of the tree and to
1059     /// calculate the operation that corresponds to this path. For example, the
1060     /// path from Op2 to the root crosses the RHS of the '-', therefore the
1061     /// corresponding operation is a '-' (which matches the one in the
1062     /// linearized tree, as shown above).
1063     ///
1064     /// For lack of a better term, we refer to this operation as Accumulated
1065     /// Path Operation (APO).
1066     struct OperandData {
1067       OperandData() = default;
1068       OperandData(Value *V, bool APO, bool IsUsed)
1069           : V(V), APO(APO), IsUsed(IsUsed) {}
1070       /// The operand value.
1071       Value *V = nullptr;
1072       /// TreeEntries only allow a single opcode, or an alternate sequence of
1073       /// them (e.g, +, -). Therefore, we can safely use a boolean value for the
1074       /// APO. It is set to 'true' if 'V' is attached to an inverse operation
1075       /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise
1076       /// (e.g., Add/Mul)
1077       bool APO = false;
1078       /// Helper data for the reordering function.
1079       bool IsUsed = false;
1080     };
1081 
1082     /// During operand reordering, we are trying to select the operand at lane
1083     /// that matches best with the operand at the neighboring lane. Our
1084     /// selection is based on the type of value we are looking for. For example,
1085     /// if the neighboring lane has a load, we need to look for a load that is
1086     /// accessing a consecutive address. These strategies are summarized in the
1087     /// 'ReorderingMode' enumerator.
1088     enum class ReorderingMode {
1089       Load,     ///< Matching loads to consecutive memory addresses
1090       Opcode,   ///< Matching instructions based on opcode (same or alternate)
1091       Constant, ///< Matching constants
1092       Splat,    ///< Matching the same instruction multiple times (broadcast)
1093       Failed,   ///< We failed to create a vectorizable group
1094     };
1095 
1096     using OperandDataVec = SmallVector<OperandData, 2>;
1097 
1098     /// A vector of operand vectors.
1099     SmallVector<OperandDataVec, 4> OpsVec;
1100 
1101     const DataLayout &DL;
1102     ScalarEvolution &SE;
1103     const BoUpSLP &R;
1104 
1105     /// \returns the operand data at \p OpIdx and \p Lane.
1106     OperandData &getData(unsigned OpIdx, unsigned Lane) {
1107       return OpsVec[OpIdx][Lane];
1108     }
1109 
1110     /// \returns the operand data at \p OpIdx and \p Lane. Const version.
1111     const OperandData &getData(unsigned OpIdx, unsigned Lane) const {
1112       return OpsVec[OpIdx][Lane];
1113     }
1114 
1115     /// Clears the used flag for all entries.
1116     void clearUsed() {
1117       for (unsigned OpIdx = 0, NumOperands = getNumOperands();
1118            OpIdx != NumOperands; ++OpIdx)
1119         for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
1120              ++Lane)
1121           OpsVec[OpIdx][Lane].IsUsed = false;
1122     }
1123 
1124     /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2.
1125     void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) {
1126       std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]);
1127     }
1128 
1129     // The hard-coded scores listed here are not very important, though it shall
1130     // be higher for better matches to improve the resulting cost. When
1131     // computing the scores of matching one sub-tree with another, we are
1132     // basically counting the number of values that are matching. So even if all
1133     // scores are set to 1, we would still get a decent matching result.
1134     // However, sometimes we have to break ties. For example we may have to
1135     // choose between matching loads vs matching opcodes. This is what these
1136     // scores are helping us with: they provide the order of preference. Also,
1137     // this is important if the scalar is externally used or used in another
1138     // tree entry node in the different lane.
1139 
1140     /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]).
1141     static const int ScoreConsecutiveLoads = 4;
1142     /// The same load multiple times. This should have a better score than
1143     /// `ScoreSplat` because it in x86 for a 2-lane vector we can represent it
1144     /// with `movddup (%reg), xmm0` which has a throughput of 0.5 versus 0.5 for
1145     /// a vector load and 1.0 for a broadcast.
1146     static const int ScoreSplatLoads = 3;
1147     /// Loads from reversed memory addresses, e.g. load(A[i+1]), load(A[i]).
1148     static const int ScoreReversedLoads = 3;
1149     /// ExtractElementInst from same vector and consecutive indexes.
1150     static const int ScoreConsecutiveExtracts = 4;
1151     /// ExtractElementInst from same vector and reversed indices.
1152     static const int ScoreReversedExtracts = 3;
1153     /// Constants.
1154     static const int ScoreConstants = 2;
1155     /// Instructions with the same opcode.
1156     static const int ScoreSameOpcode = 2;
1157     /// Instructions with alt opcodes (e.g, add + sub).
1158     static const int ScoreAltOpcodes = 1;
1159     /// Identical instructions (a.k.a. splat or broadcast).
1160     static const int ScoreSplat = 1;
1161     /// Matching with an undef is preferable to failing.
1162     static const int ScoreUndef = 1;
1163     /// Score for failing to find a decent match.
1164     static const int ScoreFail = 0;
1165     /// Score if all users are vectorized.
1166     static const int ScoreAllUserVectorized = 1;
1167 
1168     /// \returns the score of placing \p V1 and \p V2 in consecutive lanes.
1169     /// Also, checks if \p V1 and \p V2 are compatible with instructions in \p
1170     /// MainAltOps.
1171     static int getShallowScore(Value *V1, Value *V2, const DataLayout &DL,
1172                                ScalarEvolution &SE, int NumLanes,
1173                                ArrayRef<Value *> MainAltOps,
1174                                const TargetTransformInfo *TTI) {
1175       if (V1 == V2) {
1176         if (isa<LoadInst>(V1)) {
1177           // A broadcast of a load can be cheaper on some targets.
1178           // TODO: For now accept a broadcast load with no other internal uses.
1179           if (TTI->isLegalBroadcastLoad(V1->getType(), NumLanes) &&
1180               (int)V1->getNumUses() == NumLanes)
1181             return VLOperands::ScoreSplatLoads;
1182         }
1183         return VLOperands::ScoreSplat;
1184       }
1185 
1186       auto *LI1 = dyn_cast<LoadInst>(V1);
1187       auto *LI2 = dyn_cast<LoadInst>(V2);
1188       if (LI1 && LI2) {
1189         if (LI1->getParent() != LI2->getParent())
1190           return VLOperands::ScoreFail;
1191 
1192         Optional<int> Dist = getPointersDiff(
1193             LI1->getType(), LI1->getPointerOperand(), LI2->getType(),
1194             LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true);
1195         if (!Dist || *Dist == 0)
1196           return VLOperands::ScoreFail;
1197         // The distance is too large - still may be profitable to use masked
1198         // loads/gathers.
1199         if (std::abs(*Dist) > NumLanes / 2)
1200           return VLOperands::ScoreAltOpcodes;
1201         // This still will detect consecutive loads, but we might have "holes"
1202         // in some cases. It is ok for non-power-2 vectorization and may produce
1203         // better results. It should not affect current vectorization.
1204         return (*Dist > 0) ? VLOperands::ScoreConsecutiveLoads
1205                            : VLOperands::ScoreReversedLoads;
1206       }
1207 
1208       auto *C1 = dyn_cast<Constant>(V1);
1209       auto *C2 = dyn_cast<Constant>(V2);
1210       if (C1 && C2)
1211         return VLOperands::ScoreConstants;
1212 
1213       // Extracts from consecutive indexes of the same vector better score as
1214       // the extracts could be optimized away.
1215       Value *EV1;
1216       ConstantInt *Ex1Idx;
1217       if (match(V1, m_ExtractElt(m_Value(EV1), m_ConstantInt(Ex1Idx)))) {
1218         // Undefs are always profitable for extractelements.
1219         if (isa<UndefValue>(V2))
1220           return VLOperands::ScoreConsecutiveExtracts;
1221         Value *EV2 = nullptr;
1222         ConstantInt *Ex2Idx = nullptr;
1223         if (match(V2,
1224                   m_ExtractElt(m_Value(EV2), m_CombineOr(m_ConstantInt(Ex2Idx),
1225                                                          m_Undef())))) {
1226           // Undefs are always profitable for extractelements.
1227           if (!Ex2Idx)
1228             return VLOperands::ScoreConsecutiveExtracts;
1229           if (isUndefVector(EV2) && EV2->getType() == EV1->getType())
1230             return VLOperands::ScoreConsecutiveExtracts;
1231           if (EV2 == EV1) {
1232             int Idx1 = Ex1Idx->getZExtValue();
1233             int Idx2 = Ex2Idx->getZExtValue();
1234             int Dist = Idx2 - Idx1;
1235             // The distance is too large - still may be profitable to use
1236             // shuffles.
1237             if (std::abs(Dist) == 0)
1238               return VLOperands::ScoreSplat;
1239             if (std::abs(Dist) > NumLanes / 2)
1240               return VLOperands::ScoreSameOpcode;
1241             return (Dist > 0) ? VLOperands::ScoreConsecutiveExtracts
1242                               : VLOperands::ScoreReversedExtracts;
1243           }
1244           return VLOperands::ScoreAltOpcodes;
1245         }
1246         return VLOperands::ScoreFail;
1247       }
1248 
1249       auto *I1 = dyn_cast<Instruction>(V1);
1250       auto *I2 = dyn_cast<Instruction>(V2);
1251       if (I1 && I2) {
1252         if (I1->getParent() != I2->getParent())
1253           return VLOperands::ScoreFail;
1254         SmallVector<Value *, 4> Ops(MainAltOps.begin(), MainAltOps.end());
1255         Ops.push_back(I1);
1256         Ops.push_back(I2);
1257         InstructionsState S = getSameOpcode(Ops);
1258         // Note: Only consider instructions with <= 2 operands to avoid
1259         // complexity explosion.
1260         if (S.getOpcode() &&
1261             (S.MainOp->getNumOperands() <= 2 || !MainAltOps.empty() ||
1262              !S.isAltShuffle()) &&
1263             all_of(Ops, [&S](Value *V) {
1264               return cast<Instruction>(V)->getNumOperands() ==
1265                      S.MainOp->getNumOperands();
1266             }))
1267           return S.isAltShuffle() ? VLOperands::ScoreAltOpcodes
1268                                   : VLOperands::ScoreSameOpcode;
1269       }
1270 
1271       if (isa<UndefValue>(V2))
1272         return VLOperands::ScoreUndef;
1273 
1274       return VLOperands::ScoreFail;
1275     }
1276 
1277     /// \param Lane lane of the operands under analysis.
1278     /// \param OpIdx operand index in \p Lane lane we're looking the best
1279     /// candidate for.
1280     /// \param Idx operand index of the current candidate value.
1281     /// \returns The additional score due to possible broadcasting of the
1282     /// elements in the lane. It is more profitable to have power-of-2 unique
1283     /// elements in the lane, it will be vectorized with higher probability
1284     /// after removing duplicates. Currently the SLP vectorizer supports only
1285     /// vectorization of the power-of-2 number of unique scalars.
1286     int getSplatScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1287       Value *IdxLaneV = getData(Idx, Lane).V;
1288       if (!isa<Instruction>(IdxLaneV) || IdxLaneV == getData(OpIdx, Lane).V)
1289         return 0;
1290       SmallPtrSet<Value *, 4> Uniques;
1291       for (unsigned Ln = 0, E = getNumLanes(); Ln < E; ++Ln) {
1292         if (Ln == Lane)
1293           continue;
1294         Value *OpIdxLnV = getData(OpIdx, Ln).V;
1295         if (!isa<Instruction>(OpIdxLnV))
1296           return 0;
1297         Uniques.insert(OpIdxLnV);
1298       }
1299       int UniquesCount = Uniques.size();
1300       int UniquesCntWithIdxLaneV =
1301           Uniques.contains(IdxLaneV) ? UniquesCount : UniquesCount + 1;
1302       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1303       int UniquesCntWithOpIdxLaneV =
1304           Uniques.contains(OpIdxLaneV) ? UniquesCount : UniquesCount + 1;
1305       if (UniquesCntWithIdxLaneV == UniquesCntWithOpIdxLaneV)
1306         return 0;
1307       return (PowerOf2Ceil(UniquesCntWithOpIdxLaneV) -
1308               UniquesCntWithOpIdxLaneV) -
1309              (PowerOf2Ceil(UniquesCntWithIdxLaneV) - UniquesCntWithIdxLaneV);
1310     }
1311 
1312     /// \param Lane lane of the operands under analysis.
1313     /// \param OpIdx operand index in \p Lane lane we're looking the best
1314     /// candidate for.
1315     /// \param Idx operand index of the current candidate value.
1316     /// \returns The additional score for the scalar which users are all
1317     /// vectorized.
1318     int getExternalUseScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1319       Value *IdxLaneV = getData(Idx, Lane).V;
1320       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1321       // Do not care about number of uses for vector-like instructions
1322       // (extractelement/extractvalue with constant indices), they are extracts
1323       // themselves and already externally used. Vectorization of such
1324       // instructions does not add extra extractelement instruction, just may
1325       // remove it.
1326       if (isVectorLikeInstWithConstOps(IdxLaneV) &&
1327           isVectorLikeInstWithConstOps(OpIdxLaneV))
1328         return VLOperands::ScoreAllUserVectorized;
1329       auto *IdxLaneI = dyn_cast<Instruction>(IdxLaneV);
1330       if (!IdxLaneI || !isa<Instruction>(OpIdxLaneV))
1331         return 0;
1332       return R.areAllUsersVectorized(IdxLaneI, None)
1333                  ? VLOperands::ScoreAllUserVectorized
1334                  : 0;
1335     }
1336 
1337     /// Go through the operands of \p LHS and \p RHS recursively until \p
1338     /// MaxLevel, and return the cummulative score. For example:
1339     /// \verbatim
1340     ///  A[0]  B[0]  A[1]  B[1]  C[0] D[0]  B[1] A[1]
1341     ///     \ /         \ /         \ /        \ /
1342     ///      +           +           +          +
1343     ///     G1          G2          G3         G4
1344     /// \endverbatim
1345     /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at
1346     /// each level recursively, accumulating the score. It starts from matching
1347     /// the additions at level 0, then moves on to the loads (level 1). The
1348     /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and
1349     /// {B[0],B[1]} match with VLOperands::ScoreConsecutiveLoads, while
1350     /// {A[0],C[0]} has a score of VLOperands::ScoreFail.
1351     /// Please note that the order of the operands does not matter, as we
1352     /// evaluate the score of all profitable combinations of operands. In
1353     /// other words the score of G1 and G4 is the same as G1 and G2. This
1354     /// heuristic is based on ideas described in:
1355     ///   Look-ahead SLP: Auto-vectorization in the presence of commutative
1356     ///   operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha,
1357     ///   Luís F. W. Góes
1358     int getScoreAtLevelRec(Value *LHS, Value *RHS, int CurrLevel, int MaxLevel,
1359                            ArrayRef<Value *> MainAltOps) {
1360 
1361       // Get the shallow score of V1 and V2.
1362       int ShallowScoreAtThisLevel =
1363           getShallowScore(LHS, RHS, DL, SE, getNumLanes(), MainAltOps, R.TTI);
1364 
1365       // If reached MaxLevel,
1366       //  or if V1 and V2 are not instructions,
1367       //  or if they are SPLAT,
1368       //  or if they are not consecutive,
1369       //  or if profitable to vectorize loads or extractelements, early return
1370       //  the current cost.
1371       auto *I1 = dyn_cast<Instruction>(LHS);
1372       auto *I2 = dyn_cast<Instruction>(RHS);
1373       if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 ||
1374           ShallowScoreAtThisLevel == VLOperands::ScoreFail ||
1375           (((isa<LoadInst>(I1) && isa<LoadInst>(I2)) ||
1376             (I1->getNumOperands() > 2 && I2->getNumOperands() > 2) ||
1377             (isa<ExtractElementInst>(I1) && isa<ExtractElementInst>(I2))) &&
1378            ShallowScoreAtThisLevel))
1379         return ShallowScoreAtThisLevel;
1380       assert(I1 && I2 && "Should have early exited.");
1381 
1382       // Contains the I2 operand indexes that got matched with I1 operands.
1383       SmallSet<unsigned, 4> Op2Used;
1384 
1385       // Recursion towards the operands of I1 and I2. We are trying all possible
1386       // operand pairs, and keeping track of the best score.
1387       for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands();
1388            OpIdx1 != NumOperands1; ++OpIdx1) {
1389         // Try to pair op1I with the best operand of I2.
1390         int MaxTmpScore = 0;
1391         unsigned MaxOpIdx2 = 0;
1392         bool FoundBest = false;
1393         // If I2 is commutative try all combinations.
1394         unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1;
1395         unsigned ToIdx = isCommutative(I2)
1396                              ? I2->getNumOperands()
1397                              : std::min(I2->getNumOperands(), OpIdx1 + 1);
1398         assert(FromIdx <= ToIdx && "Bad index");
1399         for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) {
1400           // Skip operands already paired with OpIdx1.
1401           if (Op2Used.count(OpIdx2))
1402             continue;
1403           // Recursively calculate the cost at each level
1404           int TmpScore =
1405               getScoreAtLevelRec(I1->getOperand(OpIdx1), I2->getOperand(OpIdx2),
1406                                  CurrLevel + 1, MaxLevel, None);
1407           // Look for the best score.
1408           if (TmpScore > VLOperands::ScoreFail && TmpScore > MaxTmpScore) {
1409             MaxTmpScore = TmpScore;
1410             MaxOpIdx2 = OpIdx2;
1411             FoundBest = true;
1412           }
1413         }
1414         if (FoundBest) {
1415           // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it.
1416           Op2Used.insert(MaxOpIdx2);
1417           ShallowScoreAtThisLevel += MaxTmpScore;
1418         }
1419       }
1420       return ShallowScoreAtThisLevel;
1421     }
1422 
1423     /// Score scaling factor for fully compatible instructions but with
1424     /// different number of external uses. Allows better selection of the
1425     /// instructions with less external uses.
1426     static const int ScoreScaleFactor = 10;
1427 
1428     /// \Returns the look-ahead score, which tells us how much the sub-trees
1429     /// rooted at \p LHS and \p RHS match, the more they match the higher the
1430     /// score. This helps break ties in an informed way when we cannot decide on
1431     /// the order of the operands by just considering the immediate
1432     /// predecessors.
1433     int getLookAheadScore(Value *LHS, Value *RHS, ArrayRef<Value *> MainAltOps,
1434                           int Lane, unsigned OpIdx, unsigned Idx,
1435                           bool &IsUsed) {
1436       int Score =
1437           getScoreAtLevelRec(LHS, RHS, 1, LookAheadMaxDepth, MainAltOps);
1438       if (Score) {
1439         int SplatScore = getSplatScore(Lane, OpIdx, Idx);
1440         if (Score <= -SplatScore) {
1441           // Set the minimum score for splat-like sequence to avoid setting
1442           // failed state.
1443           Score = 1;
1444         } else {
1445           Score += SplatScore;
1446           // Scale score to see the difference between different operands
1447           // and similar operands but all vectorized/not all vectorized
1448           // uses. It does not affect actual selection of the best
1449           // compatible operand in general, just allows to select the
1450           // operand with all vectorized uses.
1451           Score *= ScoreScaleFactor;
1452           Score += getExternalUseScore(Lane, OpIdx, Idx);
1453           IsUsed = true;
1454         }
1455       }
1456       return Score;
1457     }
1458 
1459     /// Best defined scores per lanes between the passes. Used to choose the
1460     /// best operand (with the highest score) between the passes.
1461     /// The key - {Operand Index, Lane}.
1462     /// The value - the best score between the passes for the lane and the
1463     /// operand.
1464     SmallDenseMap<std::pair<unsigned, unsigned>, unsigned, 8>
1465         BestScoresPerLanes;
1466 
1467     // Search all operands in Ops[*][Lane] for the one that matches best
1468     // Ops[OpIdx][LastLane] and return its opreand index.
1469     // If no good match can be found, return None.
1470     Optional<unsigned> getBestOperand(unsigned OpIdx, int Lane, int LastLane,
1471                                       ArrayRef<ReorderingMode> ReorderingModes,
1472                                       ArrayRef<Value *> MainAltOps) {
1473       unsigned NumOperands = getNumOperands();
1474 
1475       // The operand of the previous lane at OpIdx.
1476       Value *OpLastLane = getData(OpIdx, LastLane).V;
1477 
1478       // Our strategy mode for OpIdx.
1479       ReorderingMode RMode = ReorderingModes[OpIdx];
1480       if (RMode == ReorderingMode::Failed)
1481         return None;
1482 
1483       // The linearized opcode of the operand at OpIdx, Lane.
1484       bool OpIdxAPO = getData(OpIdx, Lane).APO;
1485 
1486       // The best operand index and its score.
1487       // Sometimes we have more than one option (e.g., Opcode and Undefs), so we
1488       // are using the score to differentiate between the two.
1489       struct BestOpData {
1490         Optional<unsigned> Idx = None;
1491         unsigned Score = 0;
1492       } BestOp;
1493       BestOp.Score =
1494           BestScoresPerLanes.try_emplace(std::make_pair(OpIdx, Lane), 0)
1495               .first->second;
1496 
1497       // Track if the operand must be marked as used. If the operand is set to
1498       // Score 1 explicitly (because of non power-of-2 unique scalars, we may
1499       // want to reestimate the operands again on the following iterations).
1500       bool IsUsed =
1501           RMode == ReorderingMode::Splat || RMode == ReorderingMode::Constant;
1502       // Iterate through all unused operands and look for the best.
1503       for (unsigned Idx = 0; Idx != NumOperands; ++Idx) {
1504         // Get the operand at Idx and Lane.
1505         OperandData &OpData = getData(Idx, Lane);
1506         Value *Op = OpData.V;
1507         bool OpAPO = OpData.APO;
1508 
1509         // Skip already selected operands.
1510         if (OpData.IsUsed)
1511           continue;
1512 
1513         // Skip if we are trying to move the operand to a position with a
1514         // different opcode in the linearized tree form. This would break the
1515         // semantics.
1516         if (OpAPO != OpIdxAPO)
1517           continue;
1518 
1519         // Look for an operand that matches the current mode.
1520         switch (RMode) {
1521         case ReorderingMode::Load:
1522         case ReorderingMode::Constant:
1523         case ReorderingMode::Opcode: {
1524           bool LeftToRight = Lane > LastLane;
1525           Value *OpLeft = (LeftToRight) ? OpLastLane : Op;
1526           Value *OpRight = (LeftToRight) ? Op : OpLastLane;
1527           int Score = getLookAheadScore(OpLeft, OpRight, MainAltOps, Lane,
1528                                         OpIdx, Idx, IsUsed);
1529           if (Score > static_cast<int>(BestOp.Score)) {
1530             BestOp.Idx = Idx;
1531             BestOp.Score = Score;
1532             BestScoresPerLanes[std::make_pair(OpIdx, Lane)] = Score;
1533           }
1534           break;
1535         }
1536         case ReorderingMode::Splat:
1537           if (Op == OpLastLane)
1538             BestOp.Idx = Idx;
1539           break;
1540         case ReorderingMode::Failed:
1541           llvm_unreachable("Not expected Failed reordering mode.");
1542         }
1543       }
1544 
1545       if (BestOp.Idx) {
1546         getData(BestOp.Idx.getValue(), Lane).IsUsed = IsUsed;
1547         return BestOp.Idx;
1548       }
1549       // If we could not find a good match return None.
1550       return None;
1551     }
1552 
1553     /// Helper for reorderOperandVecs.
1554     /// \returns the lane that we should start reordering from. This is the one
1555     /// which has the least number of operands that can freely move about or
1556     /// less profitable because it already has the most optimal set of operands.
1557     unsigned getBestLaneToStartReordering() const {
1558       unsigned Min = UINT_MAX;
1559       unsigned SameOpNumber = 0;
1560       // std::pair<unsigned, unsigned> is used to implement a simple voting
1561       // algorithm and choose the lane with the least number of operands that
1562       // can freely move about or less profitable because it already has the
1563       // most optimal set of operands. The first unsigned is a counter for
1564       // voting, the second unsigned is the counter of lanes with instructions
1565       // with same/alternate opcodes and same parent basic block.
1566       MapVector<unsigned, std::pair<unsigned, unsigned>> HashMap;
1567       // Try to be closer to the original results, if we have multiple lanes
1568       // with same cost. If 2 lanes have the same cost, use the one with the
1569       // lowest index.
1570       for (int I = getNumLanes(); I > 0; --I) {
1571         unsigned Lane = I - 1;
1572         OperandsOrderData NumFreeOpsHash =
1573             getMaxNumOperandsThatCanBeReordered(Lane);
1574         // Compare the number of operands that can move and choose the one with
1575         // the least number.
1576         if (NumFreeOpsHash.NumOfAPOs < Min) {
1577           Min = NumFreeOpsHash.NumOfAPOs;
1578           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1579           HashMap.clear();
1580           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1581         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1582                    NumFreeOpsHash.NumOpsWithSameOpcodeParent < SameOpNumber) {
1583           // Select the most optimal lane in terms of number of operands that
1584           // should be moved around.
1585           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1586           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1587         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1588                    NumFreeOpsHash.NumOpsWithSameOpcodeParent == SameOpNumber) {
1589           auto It = HashMap.find(NumFreeOpsHash.Hash);
1590           if (It == HashMap.end())
1591             HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1592           else
1593             ++It->second.first;
1594         }
1595       }
1596       // Select the lane with the minimum counter.
1597       unsigned BestLane = 0;
1598       unsigned CntMin = UINT_MAX;
1599       for (const auto &Data : reverse(HashMap)) {
1600         if (Data.second.first < CntMin) {
1601           CntMin = Data.second.first;
1602           BestLane = Data.second.second;
1603         }
1604       }
1605       return BestLane;
1606     }
1607 
1608     /// Data structure that helps to reorder operands.
1609     struct OperandsOrderData {
1610       /// The best number of operands with the same APOs, which can be
1611       /// reordered.
1612       unsigned NumOfAPOs = UINT_MAX;
1613       /// Number of operands with the same/alternate instruction opcode and
1614       /// parent.
1615       unsigned NumOpsWithSameOpcodeParent = 0;
1616       /// Hash for the actual operands ordering.
1617       /// Used to count operands, actually their position id and opcode
1618       /// value. It is used in the voting mechanism to find the lane with the
1619       /// least number of operands that can freely move about or less profitable
1620       /// because it already has the most optimal set of operands. Can be
1621       /// replaced with SmallVector<unsigned> instead but hash code is faster
1622       /// and requires less memory.
1623       unsigned Hash = 0;
1624     };
1625     /// \returns the maximum number of operands that are allowed to be reordered
1626     /// for \p Lane and the number of compatible instructions(with the same
1627     /// parent/opcode). This is used as a heuristic for selecting the first lane
1628     /// to start operand reordering.
1629     OperandsOrderData getMaxNumOperandsThatCanBeReordered(unsigned Lane) const {
1630       unsigned CntTrue = 0;
1631       unsigned NumOperands = getNumOperands();
1632       // Operands with the same APO can be reordered. We therefore need to count
1633       // how many of them we have for each APO, like this: Cnt[APO] = x.
1634       // Since we only have two APOs, namely true and false, we can avoid using
1635       // a map. Instead we can simply count the number of operands that
1636       // correspond to one of them (in this case the 'true' APO), and calculate
1637       // the other by subtracting it from the total number of operands.
1638       // Operands with the same instruction opcode and parent are more
1639       // profitable since we don't need to move them in many cases, with a high
1640       // probability such lane already can be vectorized effectively.
1641       bool AllUndefs = true;
1642       unsigned NumOpsWithSameOpcodeParent = 0;
1643       Instruction *OpcodeI = nullptr;
1644       BasicBlock *Parent = nullptr;
1645       unsigned Hash = 0;
1646       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1647         const OperandData &OpData = getData(OpIdx, Lane);
1648         if (OpData.APO)
1649           ++CntTrue;
1650         // Use Boyer-Moore majority voting for finding the majority opcode and
1651         // the number of times it occurs.
1652         if (auto *I = dyn_cast<Instruction>(OpData.V)) {
1653           if (!OpcodeI || !getSameOpcode({OpcodeI, I}).getOpcode() ||
1654               I->getParent() != Parent) {
1655             if (NumOpsWithSameOpcodeParent == 0) {
1656               NumOpsWithSameOpcodeParent = 1;
1657               OpcodeI = I;
1658               Parent = I->getParent();
1659             } else {
1660               --NumOpsWithSameOpcodeParent;
1661             }
1662           } else {
1663             ++NumOpsWithSameOpcodeParent;
1664           }
1665         }
1666         Hash = hash_combine(
1667             Hash, hash_value((OpIdx + 1) * (OpData.V->getValueID() + 1)));
1668         AllUndefs = AllUndefs && isa<UndefValue>(OpData.V);
1669       }
1670       if (AllUndefs)
1671         return {};
1672       OperandsOrderData Data;
1673       Data.NumOfAPOs = std::max(CntTrue, NumOperands - CntTrue);
1674       Data.NumOpsWithSameOpcodeParent = NumOpsWithSameOpcodeParent;
1675       Data.Hash = Hash;
1676       return Data;
1677     }
1678 
1679     /// Go through the instructions in VL and append their operands.
1680     void appendOperandsOfVL(ArrayRef<Value *> VL) {
1681       assert(!VL.empty() && "Bad VL");
1682       assert((empty() || VL.size() == getNumLanes()) &&
1683              "Expected same number of lanes");
1684       assert(isa<Instruction>(VL[0]) && "Expected instruction");
1685       unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands();
1686       OpsVec.resize(NumOperands);
1687       unsigned NumLanes = VL.size();
1688       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1689         OpsVec[OpIdx].resize(NumLanes);
1690         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1691           assert(isa<Instruction>(VL[Lane]) && "Expected instruction");
1692           // Our tree has just 3 nodes: the root and two operands.
1693           // It is therefore trivial to get the APO. We only need to check the
1694           // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or
1695           // RHS operand. The LHS operand of both add and sub is never attached
1696           // to an inversese operation in the linearized form, therefore its APO
1697           // is false. The RHS is true only if VL[Lane] is an inverse operation.
1698 
1699           // Since operand reordering is performed on groups of commutative
1700           // operations or alternating sequences (e.g., +, -), we can safely
1701           // tell the inverse operations by checking commutativity.
1702           bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane]));
1703           bool APO = (OpIdx == 0) ? false : IsInverseOperation;
1704           OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx),
1705                                  APO, false};
1706         }
1707       }
1708     }
1709 
1710     /// \returns the number of operands.
1711     unsigned getNumOperands() const { return OpsVec.size(); }
1712 
1713     /// \returns the number of lanes.
1714     unsigned getNumLanes() const { return OpsVec[0].size(); }
1715 
1716     /// \returns the operand value at \p OpIdx and \p Lane.
1717     Value *getValue(unsigned OpIdx, unsigned Lane) const {
1718       return getData(OpIdx, Lane).V;
1719     }
1720 
1721     /// \returns true if the data structure is empty.
1722     bool empty() const { return OpsVec.empty(); }
1723 
1724     /// Clears the data.
1725     void clear() { OpsVec.clear(); }
1726 
1727     /// \Returns true if there are enough operands identical to \p Op to fill
1728     /// the whole vector.
1729     /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow.
1730     bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) {
1731       bool OpAPO = getData(OpIdx, Lane).APO;
1732       for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) {
1733         if (Ln == Lane)
1734           continue;
1735         // This is set to true if we found a candidate for broadcast at Lane.
1736         bool FoundCandidate = false;
1737         for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) {
1738           OperandData &Data = getData(OpI, Ln);
1739           if (Data.APO != OpAPO || Data.IsUsed)
1740             continue;
1741           if (Data.V == Op) {
1742             FoundCandidate = true;
1743             Data.IsUsed = true;
1744             break;
1745           }
1746         }
1747         if (!FoundCandidate)
1748           return false;
1749       }
1750       return true;
1751     }
1752 
1753   public:
1754     /// Initialize with all the operands of the instruction vector \p RootVL.
1755     VLOperands(ArrayRef<Value *> RootVL, const DataLayout &DL,
1756                ScalarEvolution &SE, const BoUpSLP &R)
1757         : DL(DL), SE(SE), R(R) {
1758       // Append all the operands of RootVL.
1759       appendOperandsOfVL(RootVL);
1760     }
1761 
1762     /// \Returns a value vector with the operands across all lanes for the
1763     /// opearnd at \p OpIdx.
1764     ValueList getVL(unsigned OpIdx) const {
1765       ValueList OpVL(OpsVec[OpIdx].size());
1766       assert(OpsVec[OpIdx].size() == getNumLanes() &&
1767              "Expected same num of lanes across all operands");
1768       for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane)
1769         OpVL[Lane] = OpsVec[OpIdx][Lane].V;
1770       return OpVL;
1771     }
1772 
1773     // Performs operand reordering for 2 or more operands.
1774     // The original operands are in OrigOps[OpIdx][Lane].
1775     // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'.
1776     void reorder() {
1777       unsigned NumOperands = getNumOperands();
1778       unsigned NumLanes = getNumLanes();
1779       // Each operand has its own mode. We are using this mode to help us select
1780       // the instructions for each lane, so that they match best with the ones
1781       // we have selected so far.
1782       SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands);
1783 
1784       // This is a greedy single-pass algorithm. We are going over each lane
1785       // once and deciding on the best order right away with no back-tracking.
1786       // However, in order to increase its effectiveness, we start with the lane
1787       // that has operands that can move the least. For example, given the
1788       // following lanes:
1789       //  Lane 0 : A[0] = B[0] + C[0]   // Visited 3rd
1790       //  Lane 1 : A[1] = C[1] - B[1]   // Visited 1st
1791       //  Lane 2 : A[2] = B[2] + C[2]   // Visited 2nd
1792       //  Lane 3 : A[3] = C[3] - B[3]   // Visited 4th
1793       // we will start at Lane 1, since the operands of the subtraction cannot
1794       // be reordered. Then we will visit the rest of the lanes in a circular
1795       // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3.
1796 
1797       // Find the first lane that we will start our search from.
1798       unsigned FirstLane = getBestLaneToStartReordering();
1799 
1800       // Initialize the modes.
1801       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1802         Value *OpLane0 = getValue(OpIdx, FirstLane);
1803         // Keep track if we have instructions with all the same opcode on one
1804         // side.
1805         if (isa<LoadInst>(OpLane0))
1806           ReorderingModes[OpIdx] = ReorderingMode::Load;
1807         else if (isa<Instruction>(OpLane0)) {
1808           // Check if OpLane0 should be broadcast.
1809           if (shouldBroadcast(OpLane0, OpIdx, FirstLane))
1810             ReorderingModes[OpIdx] = ReorderingMode::Splat;
1811           else
1812             ReorderingModes[OpIdx] = ReorderingMode::Opcode;
1813         }
1814         else if (isa<Constant>(OpLane0))
1815           ReorderingModes[OpIdx] = ReorderingMode::Constant;
1816         else if (isa<Argument>(OpLane0))
1817           // Our best hope is a Splat. It may save some cost in some cases.
1818           ReorderingModes[OpIdx] = ReorderingMode::Splat;
1819         else
1820           // NOTE: This should be unreachable.
1821           ReorderingModes[OpIdx] = ReorderingMode::Failed;
1822       }
1823 
1824       // Check that we don't have same operands. No need to reorder if operands
1825       // are just perfect diamond or shuffled diamond match. Do not do it only
1826       // for possible broadcasts or non-power of 2 number of scalars (just for
1827       // now).
1828       auto &&SkipReordering = [this]() {
1829         SmallPtrSet<Value *, 4> UniqueValues;
1830         ArrayRef<OperandData> Op0 = OpsVec.front();
1831         for (const OperandData &Data : Op0)
1832           UniqueValues.insert(Data.V);
1833         for (ArrayRef<OperandData> Op : drop_begin(OpsVec, 1)) {
1834           if (any_of(Op, [&UniqueValues](const OperandData &Data) {
1835                 return !UniqueValues.contains(Data.V);
1836               }))
1837             return false;
1838         }
1839         // TODO: Check if we can remove a check for non-power-2 number of
1840         // scalars after full support of non-power-2 vectorization.
1841         return UniqueValues.size() != 2 && isPowerOf2_32(UniqueValues.size());
1842       };
1843 
1844       // If the initial strategy fails for any of the operand indexes, then we
1845       // perform reordering again in a second pass. This helps avoid assigning
1846       // high priority to the failed strategy, and should improve reordering for
1847       // the non-failed operand indexes.
1848       for (int Pass = 0; Pass != 2; ++Pass) {
1849         // Check if no need to reorder operands since they're are perfect or
1850         // shuffled diamond match.
1851         // Need to to do it to avoid extra external use cost counting for
1852         // shuffled matches, which may cause regressions.
1853         if (SkipReordering())
1854           break;
1855         // Skip the second pass if the first pass did not fail.
1856         bool StrategyFailed = false;
1857         // Mark all operand data as free to use.
1858         clearUsed();
1859         // We keep the original operand order for the FirstLane, so reorder the
1860         // rest of the lanes. We are visiting the nodes in a circular fashion,
1861         // using FirstLane as the center point and increasing the radius
1862         // distance.
1863         SmallVector<SmallVector<Value *, 2>> MainAltOps(NumOperands);
1864         for (unsigned I = 0; I < NumOperands; ++I)
1865           MainAltOps[I].push_back(getData(I, FirstLane).V);
1866 
1867         for (unsigned Distance = 1; Distance != NumLanes; ++Distance) {
1868           // Visit the lane on the right and then the lane on the left.
1869           for (int Direction : {+1, -1}) {
1870             int Lane = FirstLane + Direction * Distance;
1871             if (Lane < 0 || Lane >= (int)NumLanes)
1872               continue;
1873             int LastLane = Lane - Direction;
1874             assert(LastLane >= 0 && LastLane < (int)NumLanes &&
1875                    "Out of bounds");
1876             // Look for a good match for each operand.
1877             for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1878               // Search for the operand that matches SortedOps[OpIdx][Lane-1].
1879               Optional<unsigned> BestIdx = getBestOperand(
1880                   OpIdx, Lane, LastLane, ReorderingModes, MainAltOps[OpIdx]);
1881               // By not selecting a value, we allow the operands that follow to
1882               // select a better matching value. We will get a non-null value in
1883               // the next run of getBestOperand().
1884               if (BestIdx) {
1885                 // Swap the current operand with the one returned by
1886                 // getBestOperand().
1887                 swap(OpIdx, BestIdx.getValue(), Lane);
1888               } else {
1889                 // We failed to find a best operand, set mode to 'Failed'.
1890                 ReorderingModes[OpIdx] = ReorderingMode::Failed;
1891                 // Enable the second pass.
1892                 StrategyFailed = true;
1893               }
1894               // Try to get the alternate opcode and follow it during analysis.
1895               if (MainAltOps[OpIdx].size() != 2) {
1896                 OperandData &AltOp = getData(OpIdx, Lane);
1897                 InstructionsState OpS =
1898                     getSameOpcode({MainAltOps[OpIdx].front(), AltOp.V});
1899                 if (OpS.getOpcode() && OpS.isAltShuffle())
1900                   MainAltOps[OpIdx].push_back(AltOp.V);
1901               }
1902             }
1903           }
1904         }
1905         // Skip second pass if the strategy did not fail.
1906         if (!StrategyFailed)
1907           break;
1908       }
1909     }
1910 
1911 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1912     LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) {
1913       switch (RMode) {
1914       case ReorderingMode::Load:
1915         return "Load";
1916       case ReorderingMode::Opcode:
1917         return "Opcode";
1918       case ReorderingMode::Constant:
1919         return "Constant";
1920       case ReorderingMode::Splat:
1921         return "Splat";
1922       case ReorderingMode::Failed:
1923         return "Failed";
1924       }
1925       llvm_unreachable("Unimplemented Reordering Type");
1926     }
1927 
1928     LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode,
1929                                                    raw_ostream &OS) {
1930       return OS << getModeStr(RMode);
1931     }
1932 
1933     /// Debug print.
1934     LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) {
1935       printMode(RMode, dbgs());
1936     }
1937 
1938     friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) {
1939       return printMode(RMode, OS);
1940     }
1941 
1942     LLVM_DUMP_METHOD raw_ostream &print(raw_ostream &OS) const {
1943       const unsigned Indent = 2;
1944       unsigned Cnt = 0;
1945       for (const OperandDataVec &OpDataVec : OpsVec) {
1946         OS << "Operand " << Cnt++ << "\n";
1947         for (const OperandData &OpData : OpDataVec) {
1948           OS.indent(Indent) << "{";
1949           if (Value *V = OpData.V)
1950             OS << *V;
1951           else
1952             OS << "null";
1953           OS << ", APO:" << OpData.APO << "}\n";
1954         }
1955         OS << "\n";
1956       }
1957       return OS;
1958     }
1959 
1960     /// Debug print.
1961     LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
1962 #endif
1963   };
1964 
1965   /// Checks if the instruction is marked for deletion.
1966   bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); }
1967 
1968   /// Removes an instruction from its block and eventually deletes it.
1969   /// It's like Instruction::eraseFromParent() except that the actual deletion
1970   /// is delayed until BoUpSLP is destructed.
1971   void eraseInstruction(Instruction *I) {
1972     DeletedInstructions.insert(I);
1973   }
1974 
1975   ~BoUpSLP();
1976 
1977 private:
1978   /// Check if the operands on the edges \p Edges of the \p UserTE allows
1979   /// reordering (i.e. the operands can be reordered because they have only one
1980   /// user and reordarable).
1981   /// \param ReorderableGathers List of all gather nodes that require reordering
1982   /// (e.g., gather of extractlements or partially vectorizable loads).
1983   /// \param GatherOps List of gather operand nodes for \p UserTE that require
1984   /// reordering, subset of \p NonVectorized.
1985   bool
1986   canReorderOperands(TreeEntry *UserTE,
1987                      SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
1988                      ArrayRef<TreeEntry *> ReorderableGathers,
1989                      SmallVectorImpl<TreeEntry *> &GatherOps);
1990 
1991   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
1992   /// if any. If it is not vectorized (gather node), returns nullptr.
1993   TreeEntry *getVectorizedOperand(TreeEntry *UserTE, unsigned OpIdx) {
1994     ArrayRef<Value *> VL = UserTE->getOperand(OpIdx);
1995     TreeEntry *TE = nullptr;
1996     const auto *It = find_if(VL, [this, &TE](Value *V) {
1997       TE = getTreeEntry(V);
1998       return TE;
1999     });
2000     if (It != VL.end() && TE->isSame(VL))
2001       return TE;
2002     return nullptr;
2003   }
2004 
2005   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
2006   /// if any. If it is not vectorized (gather node), returns nullptr.
2007   const TreeEntry *getVectorizedOperand(const TreeEntry *UserTE,
2008                                         unsigned OpIdx) const {
2009     return const_cast<BoUpSLP *>(this)->getVectorizedOperand(
2010         const_cast<TreeEntry *>(UserTE), OpIdx);
2011   }
2012 
2013   /// Checks if all users of \p I are the part of the vectorization tree.
2014   bool areAllUsersVectorized(Instruction *I,
2015                              ArrayRef<Value *> VectorizedVals) const;
2016 
2017   /// \returns the cost of the vectorizable entry.
2018   InstructionCost getEntryCost(const TreeEntry *E,
2019                                ArrayRef<Value *> VectorizedVals);
2020 
2021   /// This is the recursive part of buildTree.
2022   void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth,
2023                      const EdgeInfo &EI);
2024 
2025   /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
2026   /// be vectorized to use the original vector (or aggregate "bitcast" to a
2027   /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
2028   /// returns false, setting \p CurrentOrder to either an empty vector or a
2029   /// non-identity permutation that allows to reuse extract instructions.
2030   bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
2031                        SmallVectorImpl<unsigned> &CurrentOrder) const;
2032 
2033   /// Vectorize a single entry in the tree.
2034   Value *vectorizeTree(TreeEntry *E);
2035 
2036   /// Vectorize a single entry in the tree, starting in \p VL.
2037   Value *vectorizeTree(ArrayRef<Value *> VL);
2038 
2039   /// Create a new vector from a list of scalar values.  Produces a sequence
2040   /// which exploits values reused across lanes, and arranges the inserts
2041   /// for ease of later optimization.
2042   Value *createBuildVector(ArrayRef<Value *> VL);
2043 
2044   /// \returns the scalarization cost for this type. Scalarization in this
2045   /// context means the creation of vectors from a group of scalars. If \p
2046   /// NeedToShuffle is true, need to add a cost of reshuffling some of the
2047   /// vector elements.
2048   InstructionCost getGatherCost(FixedVectorType *Ty,
2049                                 const APInt &ShuffledIndices,
2050                                 bool NeedToShuffle) const;
2051 
2052   /// Checks if the gathered \p VL can be represented as shuffle(s) of previous
2053   /// tree entries.
2054   /// \returns ShuffleKind, if gathered values can be represented as shuffles of
2055   /// previous tree entries. \p Mask is filled with the shuffle mask.
2056   Optional<TargetTransformInfo::ShuffleKind>
2057   isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
2058                         SmallVectorImpl<const TreeEntry *> &Entries);
2059 
2060   /// \returns the scalarization cost for this list of values. Assuming that
2061   /// this subtree gets vectorized, we may need to extract the values from the
2062   /// roots. This method calculates the cost of extracting the values.
2063   InstructionCost getGatherCost(ArrayRef<Value *> VL) const;
2064 
2065   /// Set the Builder insert point to one after the last instruction in
2066   /// the bundle
2067   void setInsertPointAfterBundle(const TreeEntry *E);
2068 
2069   /// \returns a vector from a collection of scalars in \p VL.
2070   Value *gather(ArrayRef<Value *> VL);
2071 
2072   /// \returns whether the VectorizableTree is fully vectorizable and will
2073   /// be beneficial even the tree height is tiny.
2074   bool isFullyVectorizableTinyTree(bool ForReduction) const;
2075 
2076   /// Reorder commutative or alt operands to get better probability of
2077   /// generating vectorized code.
2078   static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
2079                                              SmallVectorImpl<Value *> &Left,
2080                                              SmallVectorImpl<Value *> &Right,
2081                                              const DataLayout &DL,
2082                                              ScalarEvolution &SE,
2083                                              const BoUpSLP &R);
2084   struct TreeEntry {
2085     using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>;
2086     TreeEntry(VecTreeTy &Container) : Container(Container) {}
2087 
2088     /// \returns true if the scalars in VL are equal to this entry.
2089     bool isSame(ArrayRef<Value *> VL) const {
2090       auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) {
2091         if (Mask.size() != VL.size() && VL.size() == Scalars.size())
2092           return std::equal(VL.begin(), VL.end(), Scalars.begin());
2093         return VL.size() == Mask.size() &&
2094                std::equal(VL.begin(), VL.end(), Mask.begin(),
2095                           [Scalars](Value *V, int Idx) {
2096                             return (isa<UndefValue>(V) &&
2097                                     Idx == UndefMaskElem) ||
2098                                    (Idx != UndefMaskElem && V == Scalars[Idx]);
2099                           });
2100       };
2101       if (!ReorderIndices.empty()) {
2102         // TODO: implement matching if the nodes are just reordered, still can
2103         // treat the vector as the same if the list of scalars matches VL
2104         // directly, without reordering.
2105         SmallVector<int> Mask;
2106         inversePermutation(ReorderIndices, Mask);
2107         if (VL.size() == Scalars.size())
2108           return IsSame(Scalars, Mask);
2109         if (VL.size() == ReuseShuffleIndices.size()) {
2110           ::addMask(Mask, ReuseShuffleIndices);
2111           return IsSame(Scalars, Mask);
2112         }
2113         return false;
2114       }
2115       return IsSame(Scalars, ReuseShuffleIndices);
2116     }
2117 
2118     /// \returns true if current entry has same operands as \p TE.
2119     bool hasEqualOperands(const TreeEntry &TE) const {
2120       if (TE.getNumOperands() != getNumOperands())
2121         return false;
2122       SmallBitVector Used(getNumOperands());
2123       for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
2124         unsigned PrevCount = Used.count();
2125         for (unsigned K = 0; K < E; ++K) {
2126           if (Used.test(K))
2127             continue;
2128           if (getOperand(K) == TE.getOperand(I)) {
2129             Used.set(K);
2130             break;
2131           }
2132         }
2133         // Check if we actually found the matching operand.
2134         if (PrevCount == Used.count())
2135           return false;
2136       }
2137       return true;
2138     }
2139 
2140     /// \return Final vectorization factor for the node. Defined by the total
2141     /// number of vectorized scalars, including those, used several times in the
2142     /// entry and counted in the \a ReuseShuffleIndices, if any.
2143     unsigned getVectorFactor() const {
2144       if (!ReuseShuffleIndices.empty())
2145         return ReuseShuffleIndices.size();
2146       return Scalars.size();
2147     };
2148 
2149     /// A vector of scalars.
2150     ValueList Scalars;
2151 
2152     /// The Scalars are vectorized into this value. It is initialized to Null.
2153     Value *VectorizedValue = nullptr;
2154 
2155     /// Do we need to gather this sequence or vectorize it
2156     /// (either with vector instruction or with scatter/gather
2157     /// intrinsics for store/load)?
2158     enum EntryState { Vectorize, ScatterVectorize, NeedToGather };
2159     EntryState State;
2160 
2161     /// Does this sequence require some shuffling?
2162     SmallVector<int, 4> ReuseShuffleIndices;
2163 
2164     /// Does this entry require reordering?
2165     SmallVector<unsigned, 4> ReorderIndices;
2166 
2167     /// Points back to the VectorizableTree.
2168     ///
2169     /// Only used for Graphviz right now.  Unfortunately GraphTrait::NodeRef has
2170     /// to be a pointer and needs to be able to initialize the child iterator.
2171     /// Thus we need a reference back to the container to translate the indices
2172     /// to entries.
2173     VecTreeTy &Container;
2174 
2175     /// The TreeEntry index containing the user of this entry.  We can actually
2176     /// have multiple users so the data structure is not truly a tree.
2177     SmallVector<EdgeInfo, 1> UserTreeIndices;
2178 
2179     /// The index of this treeEntry in VectorizableTree.
2180     int Idx = -1;
2181 
2182   private:
2183     /// The operands of each instruction in each lane Operands[op_index][lane].
2184     /// Note: This helps avoid the replication of the code that performs the
2185     /// reordering of operands during buildTree_rec() and vectorizeTree().
2186     SmallVector<ValueList, 2> Operands;
2187 
2188     /// The main/alternate instruction.
2189     Instruction *MainOp = nullptr;
2190     Instruction *AltOp = nullptr;
2191 
2192   public:
2193     /// Set this bundle's \p OpIdx'th operand to \p OpVL.
2194     void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) {
2195       if (Operands.size() < OpIdx + 1)
2196         Operands.resize(OpIdx + 1);
2197       assert(Operands[OpIdx].empty() && "Already resized?");
2198       assert(OpVL.size() <= Scalars.size() &&
2199              "Number of operands is greater than the number of scalars.");
2200       Operands[OpIdx].resize(OpVL.size());
2201       copy(OpVL, Operands[OpIdx].begin());
2202     }
2203 
2204     /// Set the operands of this bundle in their original order.
2205     void setOperandsInOrder() {
2206       assert(Operands.empty() && "Already initialized?");
2207       auto *I0 = cast<Instruction>(Scalars[0]);
2208       Operands.resize(I0->getNumOperands());
2209       unsigned NumLanes = Scalars.size();
2210       for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands();
2211            OpIdx != NumOperands; ++OpIdx) {
2212         Operands[OpIdx].resize(NumLanes);
2213         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
2214           auto *I = cast<Instruction>(Scalars[Lane]);
2215           assert(I->getNumOperands() == NumOperands &&
2216                  "Expected same number of operands");
2217           Operands[OpIdx][Lane] = I->getOperand(OpIdx);
2218         }
2219       }
2220     }
2221 
2222     /// Reorders operands of the node to the given mask \p Mask.
2223     void reorderOperands(ArrayRef<int> Mask) {
2224       for (ValueList &Operand : Operands)
2225         reorderScalars(Operand, Mask);
2226     }
2227 
2228     /// \returns the \p OpIdx operand of this TreeEntry.
2229     ValueList &getOperand(unsigned OpIdx) {
2230       assert(OpIdx < Operands.size() && "Off bounds");
2231       return Operands[OpIdx];
2232     }
2233 
2234     /// \returns the \p OpIdx operand of this TreeEntry.
2235     ArrayRef<Value *> getOperand(unsigned OpIdx) const {
2236       assert(OpIdx < Operands.size() && "Off bounds");
2237       return Operands[OpIdx];
2238     }
2239 
2240     /// \returns the number of operands.
2241     unsigned getNumOperands() const { return Operands.size(); }
2242 
2243     /// \return the single \p OpIdx operand.
2244     Value *getSingleOperand(unsigned OpIdx) const {
2245       assert(OpIdx < Operands.size() && "Off bounds");
2246       assert(!Operands[OpIdx].empty() && "No operand available");
2247       return Operands[OpIdx][0];
2248     }
2249 
2250     /// Some of the instructions in the list have alternate opcodes.
2251     bool isAltShuffle() const { return MainOp != AltOp; }
2252 
2253     bool isOpcodeOrAlt(Instruction *I) const {
2254       unsigned CheckedOpcode = I->getOpcode();
2255       return (getOpcode() == CheckedOpcode ||
2256               getAltOpcode() == CheckedOpcode);
2257     }
2258 
2259     /// Chooses the correct key for scheduling data. If \p Op has the same (or
2260     /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is
2261     /// \p OpValue.
2262     Value *isOneOf(Value *Op) const {
2263       auto *I = dyn_cast<Instruction>(Op);
2264       if (I && isOpcodeOrAlt(I))
2265         return Op;
2266       return MainOp;
2267     }
2268 
2269     void setOperations(const InstructionsState &S) {
2270       MainOp = S.MainOp;
2271       AltOp = S.AltOp;
2272     }
2273 
2274     Instruction *getMainOp() const {
2275       return MainOp;
2276     }
2277 
2278     Instruction *getAltOp() const {
2279       return AltOp;
2280     }
2281 
2282     /// The main/alternate opcodes for the list of instructions.
2283     unsigned getOpcode() const {
2284       return MainOp ? MainOp->getOpcode() : 0;
2285     }
2286 
2287     unsigned getAltOpcode() const {
2288       return AltOp ? AltOp->getOpcode() : 0;
2289     }
2290 
2291     /// When ReuseReorderShuffleIndices is empty it just returns position of \p
2292     /// V within vector of Scalars. Otherwise, try to remap on its reuse index.
2293     int findLaneForValue(Value *V) const {
2294       unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V));
2295       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2296       if (!ReorderIndices.empty())
2297         FoundLane = ReorderIndices[FoundLane];
2298       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2299       if (!ReuseShuffleIndices.empty()) {
2300         FoundLane = std::distance(ReuseShuffleIndices.begin(),
2301                                   find(ReuseShuffleIndices, FoundLane));
2302       }
2303       return FoundLane;
2304     }
2305 
2306 #ifndef NDEBUG
2307     /// Debug printer.
2308     LLVM_DUMP_METHOD void dump() const {
2309       dbgs() << Idx << ".\n";
2310       for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) {
2311         dbgs() << "Operand " << OpI << ":\n";
2312         for (const Value *V : Operands[OpI])
2313           dbgs().indent(2) << *V << "\n";
2314       }
2315       dbgs() << "Scalars: \n";
2316       for (Value *V : Scalars)
2317         dbgs().indent(2) << *V << "\n";
2318       dbgs() << "State: ";
2319       switch (State) {
2320       case Vectorize:
2321         dbgs() << "Vectorize\n";
2322         break;
2323       case ScatterVectorize:
2324         dbgs() << "ScatterVectorize\n";
2325         break;
2326       case NeedToGather:
2327         dbgs() << "NeedToGather\n";
2328         break;
2329       }
2330       dbgs() << "MainOp: ";
2331       if (MainOp)
2332         dbgs() << *MainOp << "\n";
2333       else
2334         dbgs() << "NULL\n";
2335       dbgs() << "AltOp: ";
2336       if (AltOp)
2337         dbgs() << *AltOp << "\n";
2338       else
2339         dbgs() << "NULL\n";
2340       dbgs() << "VectorizedValue: ";
2341       if (VectorizedValue)
2342         dbgs() << *VectorizedValue << "\n";
2343       else
2344         dbgs() << "NULL\n";
2345       dbgs() << "ReuseShuffleIndices: ";
2346       if (ReuseShuffleIndices.empty())
2347         dbgs() << "Empty";
2348       else
2349         for (int ReuseIdx : ReuseShuffleIndices)
2350           dbgs() << ReuseIdx << ", ";
2351       dbgs() << "\n";
2352       dbgs() << "ReorderIndices: ";
2353       for (unsigned ReorderIdx : ReorderIndices)
2354         dbgs() << ReorderIdx << ", ";
2355       dbgs() << "\n";
2356       dbgs() << "UserTreeIndices: ";
2357       for (const auto &EInfo : UserTreeIndices)
2358         dbgs() << EInfo << ", ";
2359       dbgs() << "\n";
2360     }
2361 #endif
2362   };
2363 
2364 #ifndef NDEBUG
2365   void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost,
2366                      InstructionCost VecCost,
2367                      InstructionCost ScalarCost) const {
2368     dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump();
2369     dbgs() << "SLP: Costs:\n";
2370     dbgs() << "SLP:     ReuseShuffleCost = " << ReuseShuffleCost << "\n";
2371     dbgs() << "SLP:     VectorCost = " << VecCost << "\n";
2372     dbgs() << "SLP:     ScalarCost = " << ScalarCost << "\n";
2373     dbgs() << "SLP:     ReuseShuffleCost + VecCost - ScalarCost = " <<
2374                ReuseShuffleCost + VecCost - ScalarCost << "\n";
2375   }
2376 #endif
2377 
2378   /// Create a new VectorizableTree entry.
2379   TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle,
2380                           const InstructionsState &S,
2381                           const EdgeInfo &UserTreeIdx,
2382                           ArrayRef<int> ReuseShuffleIndices = None,
2383                           ArrayRef<unsigned> ReorderIndices = None) {
2384     TreeEntry::EntryState EntryState =
2385         Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather;
2386     return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx,
2387                         ReuseShuffleIndices, ReorderIndices);
2388   }
2389 
2390   TreeEntry *newTreeEntry(ArrayRef<Value *> VL,
2391                           TreeEntry::EntryState EntryState,
2392                           Optional<ScheduleData *> Bundle,
2393                           const InstructionsState &S,
2394                           const EdgeInfo &UserTreeIdx,
2395                           ArrayRef<int> ReuseShuffleIndices = None,
2396                           ArrayRef<unsigned> ReorderIndices = None) {
2397     assert(((!Bundle && EntryState == TreeEntry::NeedToGather) ||
2398             (Bundle && EntryState != TreeEntry::NeedToGather)) &&
2399            "Need to vectorize gather entry?");
2400     VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree));
2401     TreeEntry *Last = VectorizableTree.back().get();
2402     Last->Idx = VectorizableTree.size() - 1;
2403     Last->State = EntryState;
2404     Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
2405                                      ReuseShuffleIndices.end());
2406     if (ReorderIndices.empty()) {
2407       Last->Scalars.assign(VL.begin(), VL.end());
2408       Last->setOperations(S);
2409     } else {
2410       // Reorder scalars and build final mask.
2411       Last->Scalars.assign(VL.size(), nullptr);
2412       transform(ReorderIndices, Last->Scalars.begin(),
2413                 [VL](unsigned Idx) -> Value * {
2414                   if (Idx >= VL.size())
2415                     return UndefValue::get(VL.front()->getType());
2416                   return VL[Idx];
2417                 });
2418       InstructionsState S = getSameOpcode(Last->Scalars);
2419       Last->setOperations(S);
2420       Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end());
2421     }
2422     if (Last->State != TreeEntry::NeedToGather) {
2423       for (Value *V : VL) {
2424         assert(!getTreeEntry(V) && "Scalar already in tree!");
2425         ScalarToTreeEntry[V] = Last;
2426       }
2427       // Update the scheduler bundle to point to this TreeEntry.
2428       ScheduleData *BundleMember = Bundle.getValue();
2429       assert((BundleMember || isa<PHINode>(S.MainOp) ||
2430               isVectorLikeInstWithConstOps(S.MainOp) ||
2431               doesNotNeedToSchedule(VL)) &&
2432              "Bundle and VL out of sync");
2433       if (BundleMember) {
2434         for (Value *V : VL) {
2435           if (doesNotNeedToBeScheduled(V))
2436             continue;
2437           assert(BundleMember && "Unexpected end of bundle.");
2438           BundleMember->TE = Last;
2439           BundleMember = BundleMember->NextInBundle;
2440         }
2441       }
2442       assert(!BundleMember && "Bundle and VL out of sync");
2443     } else {
2444       MustGather.insert(VL.begin(), VL.end());
2445     }
2446 
2447     if (UserTreeIdx.UserTE)
2448       Last->UserTreeIndices.push_back(UserTreeIdx);
2449 
2450     return Last;
2451   }
2452 
2453   /// -- Vectorization State --
2454   /// Holds all of the tree entries.
2455   TreeEntry::VecTreeTy VectorizableTree;
2456 
2457 #ifndef NDEBUG
2458   /// Debug printer.
2459   LLVM_DUMP_METHOD void dumpVectorizableTree() const {
2460     for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) {
2461       VectorizableTree[Id]->dump();
2462       dbgs() << "\n";
2463     }
2464   }
2465 #endif
2466 
2467   TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); }
2468 
2469   const TreeEntry *getTreeEntry(Value *V) const {
2470     return ScalarToTreeEntry.lookup(V);
2471   }
2472 
2473   /// Maps a specific scalar to its tree entry.
2474   SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry;
2475 
2476   /// Maps a value to the proposed vectorizable size.
2477   SmallDenseMap<Value *, unsigned> InstrElementSize;
2478 
2479   /// A list of scalars that we found that we need to keep as scalars.
2480   ValueSet MustGather;
2481 
2482   /// This POD struct describes one external user in the vectorized tree.
2483   struct ExternalUser {
2484     ExternalUser(Value *S, llvm::User *U, int L)
2485         : Scalar(S), User(U), Lane(L) {}
2486 
2487     // Which scalar in our function.
2488     Value *Scalar;
2489 
2490     // Which user that uses the scalar.
2491     llvm::User *User;
2492 
2493     // Which lane does the scalar belong to.
2494     int Lane;
2495   };
2496   using UserList = SmallVector<ExternalUser, 16>;
2497 
2498   /// Checks if two instructions may access the same memory.
2499   ///
2500   /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
2501   /// is invariant in the calling loop.
2502   bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
2503                  Instruction *Inst2) {
2504     // First check if the result is already in the cache.
2505     AliasCacheKey key = std::make_pair(Inst1, Inst2);
2506     Optional<bool> &result = AliasCache[key];
2507     if (result.hasValue()) {
2508       return result.getValue();
2509     }
2510     bool aliased = true;
2511     if (Loc1.Ptr && isSimple(Inst1))
2512       aliased = isModOrRefSet(BatchAA.getModRefInfo(Inst2, Loc1));
2513     // Store the result in the cache.
2514     result = aliased;
2515     return aliased;
2516   }
2517 
2518   using AliasCacheKey = std::pair<Instruction *, Instruction *>;
2519 
2520   /// Cache for alias results.
2521   /// TODO: consider moving this to the AliasAnalysis itself.
2522   DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
2523 
2524   // Cache for pointerMayBeCaptured calls inside AA.  This is preserved
2525   // globally through SLP because we don't perform any action which
2526   // invalidates capture results.
2527   BatchAAResults BatchAA;
2528 
2529   /// Temporary store for deleted instructions. Instructions will be deleted
2530   /// eventually when the BoUpSLP is destructed.  The deferral is required to
2531   /// ensure that there are no incorrect collisions in the AliasCache, which
2532   /// can happen if a new instruction is allocated at the same address as a
2533   /// previously deleted instruction.
2534   DenseSet<Instruction *> DeletedInstructions;
2535 
2536   /// A list of values that need to extracted out of the tree.
2537   /// This list holds pairs of (Internal Scalar : External User). External User
2538   /// can be nullptr, it means that this Internal Scalar will be used later,
2539   /// after vectorization.
2540   UserList ExternalUses;
2541 
2542   /// Values used only by @llvm.assume calls.
2543   SmallPtrSet<const Value *, 32> EphValues;
2544 
2545   /// Holds all of the instructions that we gathered.
2546   SetVector<Instruction *> GatherShuffleSeq;
2547 
2548   /// A list of blocks that we are going to CSE.
2549   SetVector<BasicBlock *> CSEBlocks;
2550 
2551   /// Contains all scheduling relevant data for an instruction.
2552   /// A ScheduleData either represents a single instruction or a member of an
2553   /// instruction bundle (= a group of instructions which is combined into a
2554   /// vector instruction).
2555   struct ScheduleData {
2556     // The initial value for the dependency counters. It means that the
2557     // dependencies are not calculated yet.
2558     enum { InvalidDeps = -1 };
2559 
2560     ScheduleData() = default;
2561 
2562     void init(int BlockSchedulingRegionID, Value *OpVal) {
2563       FirstInBundle = this;
2564       NextInBundle = nullptr;
2565       NextLoadStore = nullptr;
2566       IsScheduled = false;
2567       SchedulingRegionID = BlockSchedulingRegionID;
2568       clearDependencies();
2569       OpValue = OpVal;
2570       TE = nullptr;
2571     }
2572 
2573     /// Verify basic self consistency properties
2574     void verify() {
2575       if (hasValidDependencies()) {
2576         assert(UnscheduledDeps <= Dependencies && "invariant");
2577       } else {
2578         assert(UnscheduledDeps == Dependencies && "invariant");
2579       }
2580 
2581       if (IsScheduled) {
2582         assert(isSchedulingEntity() &&
2583                 "unexpected scheduled state");
2584         for (const ScheduleData *BundleMember = this; BundleMember;
2585              BundleMember = BundleMember->NextInBundle) {
2586           assert(BundleMember->hasValidDependencies() &&
2587                  BundleMember->UnscheduledDeps == 0 &&
2588                  "unexpected scheduled state");
2589           assert((BundleMember == this || !BundleMember->IsScheduled) &&
2590                  "only bundle is marked scheduled");
2591         }
2592       }
2593 
2594       assert(Inst->getParent() == FirstInBundle->Inst->getParent() &&
2595              "all bundle members must be in same basic block");
2596     }
2597 
2598     /// Returns true if the dependency information has been calculated.
2599     /// Note that depenendency validity can vary between instructions within
2600     /// a single bundle.
2601     bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
2602 
2603     /// Returns true for single instructions and for bundle representatives
2604     /// (= the head of a bundle).
2605     bool isSchedulingEntity() const { return FirstInBundle == this; }
2606 
2607     /// Returns true if it represents an instruction bundle and not only a
2608     /// single instruction.
2609     bool isPartOfBundle() const {
2610       return NextInBundle != nullptr || FirstInBundle != this || TE;
2611     }
2612 
2613     /// Returns true if it is ready for scheduling, i.e. it has no more
2614     /// unscheduled depending instructions/bundles.
2615     bool isReady() const {
2616       assert(isSchedulingEntity() &&
2617              "can't consider non-scheduling entity for ready list");
2618       return unscheduledDepsInBundle() == 0 && !IsScheduled;
2619     }
2620 
2621     /// Modifies the number of unscheduled dependencies for this instruction,
2622     /// and returns the number of remaining dependencies for the containing
2623     /// bundle.
2624     int incrementUnscheduledDeps(int Incr) {
2625       assert(hasValidDependencies() &&
2626              "increment of unscheduled deps would be meaningless");
2627       UnscheduledDeps += Incr;
2628       return FirstInBundle->unscheduledDepsInBundle();
2629     }
2630 
2631     /// Sets the number of unscheduled dependencies to the number of
2632     /// dependencies.
2633     void resetUnscheduledDeps() {
2634       UnscheduledDeps = Dependencies;
2635     }
2636 
2637     /// Clears all dependency information.
2638     void clearDependencies() {
2639       Dependencies = InvalidDeps;
2640       resetUnscheduledDeps();
2641       MemoryDependencies.clear();
2642       ControlDependencies.clear();
2643     }
2644 
2645     int unscheduledDepsInBundle() const {
2646       assert(isSchedulingEntity() && "only meaningful on the bundle");
2647       int Sum = 0;
2648       for (const ScheduleData *BundleMember = this; BundleMember;
2649            BundleMember = BundleMember->NextInBundle) {
2650         if (BundleMember->UnscheduledDeps == InvalidDeps)
2651           return InvalidDeps;
2652         Sum += BundleMember->UnscheduledDeps;
2653       }
2654       return Sum;
2655     }
2656 
2657     void dump(raw_ostream &os) const {
2658       if (!isSchedulingEntity()) {
2659         os << "/ " << *Inst;
2660       } else if (NextInBundle) {
2661         os << '[' << *Inst;
2662         ScheduleData *SD = NextInBundle;
2663         while (SD) {
2664           os << ';' << *SD->Inst;
2665           SD = SD->NextInBundle;
2666         }
2667         os << ']';
2668       } else {
2669         os << *Inst;
2670       }
2671     }
2672 
2673     Instruction *Inst = nullptr;
2674 
2675     /// Opcode of the current instruction in the schedule data.
2676     Value *OpValue = nullptr;
2677 
2678     /// The TreeEntry that this instruction corresponds to.
2679     TreeEntry *TE = nullptr;
2680 
2681     /// Points to the head in an instruction bundle (and always to this for
2682     /// single instructions).
2683     ScheduleData *FirstInBundle = nullptr;
2684 
2685     /// Single linked list of all instructions in a bundle. Null if it is a
2686     /// single instruction.
2687     ScheduleData *NextInBundle = nullptr;
2688 
2689     /// Single linked list of all memory instructions (e.g. load, store, call)
2690     /// in the block - until the end of the scheduling region.
2691     ScheduleData *NextLoadStore = nullptr;
2692 
2693     /// The dependent memory instructions.
2694     /// This list is derived on demand in calculateDependencies().
2695     SmallVector<ScheduleData *, 4> MemoryDependencies;
2696 
2697     /// List of instructions which this instruction could be control dependent
2698     /// on.  Allowing such nodes to be scheduled below this one could introduce
2699     /// a runtime fault which didn't exist in the original program.
2700     /// ex: this is a load or udiv following a readonly call which inf loops
2701     SmallVector<ScheduleData *, 4> ControlDependencies;
2702 
2703     /// This ScheduleData is in the current scheduling region if this matches
2704     /// the current SchedulingRegionID of BlockScheduling.
2705     int SchedulingRegionID = 0;
2706 
2707     /// Used for getting a "good" final ordering of instructions.
2708     int SchedulingPriority = 0;
2709 
2710     /// The number of dependencies. Constitutes of the number of users of the
2711     /// instruction plus the number of dependent memory instructions (if any).
2712     /// This value is calculated on demand.
2713     /// If InvalidDeps, the number of dependencies is not calculated yet.
2714     int Dependencies = InvalidDeps;
2715 
2716     /// The number of dependencies minus the number of dependencies of scheduled
2717     /// instructions. As soon as this is zero, the instruction/bundle gets ready
2718     /// for scheduling.
2719     /// Note that this is negative as long as Dependencies is not calculated.
2720     int UnscheduledDeps = InvalidDeps;
2721 
2722     /// True if this instruction is scheduled (or considered as scheduled in the
2723     /// dry-run).
2724     bool IsScheduled = false;
2725   };
2726 
2727 #ifndef NDEBUG
2728   friend inline raw_ostream &operator<<(raw_ostream &os,
2729                                         const BoUpSLP::ScheduleData &SD) {
2730     SD.dump(os);
2731     return os;
2732   }
2733 #endif
2734 
2735   friend struct GraphTraits<BoUpSLP *>;
2736   friend struct DOTGraphTraits<BoUpSLP *>;
2737 
2738   /// Contains all scheduling data for a basic block.
2739   /// It does not schedules instructions, which are not memory read/write
2740   /// instructions and their operands are either constants, or arguments, or
2741   /// phis, or instructions from others blocks, or their users are phis or from
2742   /// the other blocks. The resulting vector instructions can be placed at the
2743   /// beginning of the basic block without scheduling (if operands does not need
2744   /// to be scheduled) or at the end of the block (if users are outside of the
2745   /// block). It allows to save some compile time and memory used by the
2746   /// compiler.
2747   /// ScheduleData is assigned for each instruction in between the boundaries of
2748   /// the tree entry, even for those, which are not part of the graph. It is
2749   /// required to correctly follow the dependencies between the instructions and
2750   /// their correct scheduling. The ScheduleData is not allocated for the
2751   /// instructions, which do not require scheduling, like phis, nodes with
2752   /// extractelements/insertelements only or nodes with instructions, with
2753   /// uses/operands outside of the block.
2754   struct BlockScheduling {
2755     BlockScheduling(BasicBlock *BB)
2756         : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
2757 
2758     void clear() {
2759       ReadyInsts.clear();
2760       ScheduleStart = nullptr;
2761       ScheduleEnd = nullptr;
2762       FirstLoadStoreInRegion = nullptr;
2763       LastLoadStoreInRegion = nullptr;
2764       RegionHasStackSave = false;
2765 
2766       // Reduce the maximum schedule region size by the size of the
2767       // previous scheduling run.
2768       ScheduleRegionSizeLimit -= ScheduleRegionSize;
2769       if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
2770         ScheduleRegionSizeLimit = MinScheduleRegionSize;
2771       ScheduleRegionSize = 0;
2772 
2773       // Make a new scheduling region, i.e. all existing ScheduleData is not
2774       // in the new region yet.
2775       ++SchedulingRegionID;
2776     }
2777 
2778     ScheduleData *getScheduleData(Instruction *I) {
2779       if (BB != I->getParent())
2780         // Avoid lookup if can't possibly be in map.
2781         return nullptr;
2782       ScheduleData *SD = ScheduleDataMap.lookup(I);
2783       if (SD && isInSchedulingRegion(SD))
2784         return SD;
2785       return nullptr;
2786     }
2787 
2788     ScheduleData *getScheduleData(Value *V) {
2789       if (auto *I = dyn_cast<Instruction>(V))
2790         return getScheduleData(I);
2791       return nullptr;
2792     }
2793 
2794     ScheduleData *getScheduleData(Value *V, Value *Key) {
2795       if (V == Key)
2796         return getScheduleData(V);
2797       auto I = ExtraScheduleDataMap.find(V);
2798       if (I != ExtraScheduleDataMap.end()) {
2799         ScheduleData *SD = I->second.lookup(Key);
2800         if (SD && isInSchedulingRegion(SD))
2801           return SD;
2802       }
2803       return nullptr;
2804     }
2805 
2806     bool isInSchedulingRegion(ScheduleData *SD) const {
2807       return SD->SchedulingRegionID == SchedulingRegionID;
2808     }
2809 
2810     /// Marks an instruction as scheduled and puts all dependent ready
2811     /// instructions into the ready-list.
2812     template <typename ReadyListType>
2813     void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
2814       SD->IsScheduled = true;
2815       LLVM_DEBUG(dbgs() << "SLP:   schedule " << *SD << "\n");
2816 
2817       for (ScheduleData *BundleMember = SD; BundleMember;
2818            BundleMember = BundleMember->NextInBundle) {
2819         if (BundleMember->Inst != BundleMember->OpValue)
2820           continue;
2821 
2822         // Handle the def-use chain dependencies.
2823 
2824         // Decrement the unscheduled counter and insert to ready list if ready.
2825         auto &&DecrUnsched = [this, &ReadyList](Instruction *I) {
2826           doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
2827             if (OpDef && OpDef->hasValidDependencies() &&
2828                 OpDef->incrementUnscheduledDeps(-1) == 0) {
2829               // There are no more unscheduled dependencies after
2830               // decrementing, so we can put the dependent instruction
2831               // into the ready list.
2832               ScheduleData *DepBundle = OpDef->FirstInBundle;
2833               assert(!DepBundle->IsScheduled &&
2834                      "already scheduled bundle gets ready");
2835               ReadyList.insert(DepBundle);
2836               LLVM_DEBUG(dbgs()
2837                          << "SLP:    gets ready (def): " << *DepBundle << "\n");
2838             }
2839           });
2840         };
2841 
2842         // If BundleMember is a vector bundle, its operands may have been
2843         // reordered during buildTree(). We therefore need to get its operands
2844         // through the TreeEntry.
2845         if (TreeEntry *TE = BundleMember->TE) {
2846           // Need to search for the lane since the tree entry can be reordered.
2847           int Lane = std::distance(TE->Scalars.begin(),
2848                                    find(TE->Scalars, BundleMember->Inst));
2849           assert(Lane >= 0 && "Lane not set");
2850 
2851           // Since vectorization tree is being built recursively this assertion
2852           // ensures that the tree entry has all operands set before reaching
2853           // this code. Couple of exceptions known at the moment are extracts
2854           // where their second (immediate) operand is not added. Since
2855           // immediates do not affect scheduler behavior this is considered
2856           // okay.
2857           auto *In = BundleMember->Inst;
2858           assert(In &&
2859                  (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) ||
2860                   In->getNumOperands() == TE->getNumOperands()) &&
2861                  "Missed TreeEntry operands?");
2862           (void)In; // fake use to avoid build failure when assertions disabled
2863 
2864           for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands();
2865                OpIdx != NumOperands; ++OpIdx)
2866             if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane]))
2867               DecrUnsched(I);
2868         } else {
2869           // If BundleMember is a stand-alone instruction, no operand reordering
2870           // has taken place, so we directly access its operands.
2871           for (Use &U : BundleMember->Inst->operands())
2872             if (auto *I = dyn_cast<Instruction>(U.get()))
2873               DecrUnsched(I);
2874         }
2875         // Handle the memory dependencies.
2876         for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
2877           if (MemoryDepSD->hasValidDependencies() &&
2878               MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
2879             // There are no more unscheduled dependencies after decrementing,
2880             // so we can put the dependent instruction into the ready list.
2881             ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
2882             assert(!DepBundle->IsScheduled &&
2883                    "already scheduled bundle gets ready");
2884             ReadyList.insert(DepBundle);
2885             LLVM_DEBUG(dbgs()
2886                        << "SLP:    gets ready (mem): " << *DepBundle << "\n");
2887           }
2888         }
2889         // Handle the control dependencies.
2890         for (ScheduleData *DepSD : BundleMember->ControlDependencies) {
2891           if (DepSD->incrementUnscheduledDeps(-1) == 0) {
2892             // There are no more unscheduled dependencies after decrementing,
2893             // so we can put the dependent instruction into the ready list.
2894             ScheduleData *DepBundle = DepSD->FirstInBundle;
2895             assert(!DepBundle->IsScheduled &&
2896                    "already scheduled bundle gets ready");
2897             ReadyList.insert(DepBundle);
2898             LLVM_DEBUG(dbgs()
2899                        << "SLP:    gets ready (ctl): " << *DepBundle << "\n");
2900           }
2901         }
2902 
2903       }
2904     }
2905 
2906     /// Verify basic self consistency properties of the data structure.
2907     void verify() {
2908       if (!ScheduleStart)
2909         return;
2910 
2911       assert(ScheduleStart->getParent() == ScheduleEnd->getParent() &&
2912              ScheduleStart->comesBefore(ScheduleEnd) &&
2913              "Not a valid scheduling region?");
2914 
2915       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2916         auto *SD = getScheduleData(I);
2917         if (!SD)
2918           continue;
2919         assert(isInSchedulingRegion(SD) &&
2920                "primary schedule data not in window?");
2921         assert(isInSchedulingRegion(SD->FirstInBundle) &&
2922                "entire bundle in window!");
2923         (void)SD;
2924         doForAllOpcodes(I, [](ScheduleData *SD) { SD->verify(); });
2925       }
2926 
2927       for (auto *SD : ReadyInsts) {
2928         assert(SD->isSchedulingEntity() && SD->isReady() &&
2929                "item in ready list not ready?");
2930         (void)SD;
2931       }
2932     }
2933 
2934     void doForAllOpcodes(Value *V,
2935                          function_ref<void(ScheduleData *SD)> Action) {
2936       if (ScheduleData *SD = getScheduleData(V))
2937         Action(SD);
2938       auto I = ExtraScheduleDataMap.find(V);
2939       if (I != ExtraScheduleDataMap.end())
2940         for (auto &P : I->second)
2941           if (isInSchedulingRegion(P.second))
2942             Action(P.second);
2943     }
2944 
2945     /// Put all instructions into the ReadyList which are ready for scheduling.
2946     template <typename ReadyListType>
2947     void initialFillReadyList(ReadyListType &ReadyList) {
2948       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2949         doForAllOpcodes(I, [&](ScheduleData *SD) {
2950           if (SD->isSchedulingEntity() && SD->hasValidDependencies() &&
2951               SD->isReady()) {
2952             ReadyList.insert(SD);
2953             LLVM_DEBUG(dbgs()
2954                        << "SLP:    initially in ready list: " << *SD << "\n");
2955           }
2956         });
2957       }
2958     }
2959 
2960     /// Build a bundle from the ScheduleData nodes corresponding to the
2961     /// scalar instruction for each lane.
2962     ScheduleData *buildBundle(ArrayRef<Value *> VL);
2963 
2964     /// Checks if a bundle of instructions can be scheduled, i.e. has no
2965     /// cyclic dependencies. This is only a dry-run, no instructions are
2966     /// actually moved at this stage.
2967     /// \returns the scheduling bundle. The returned Optional value is non-None
2968     /// if \p VL is allowed to be scheduled.
2969     Optional<ScheduleData *>
2970     tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
2971                       const InstructionsState &S);
2972 
2973     /// Un-bundles a group of instructions.
2974     void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
2975 
2976     /// Allocates schedule data chunk.
2977     ScheduleData *allocateScheduleDataChunks();
2978 
2979     /// Extends the scheduling region so that V is inside the region.
2980     /// \returns true if the region size is within the limit.
2981     bool extendSchedulingRegion(Value *V, const InstructionsState &S);
2982 
2983     /// Initialize the ScheduleData structures for new instructions in the
2984     /// scheduling region.
2985     void initScheduleData(Instruction *FromI, Instruction *ToI,
2986                           ScheduleData *PrevLoadStore,
2987                           ScheduleData *NextLoadStore);
2988 
2989     /// Updates the dependency information of a bundle and of all instructions/
2990     /// bundles which depend on the original bundle.
2991     void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
2992                                BoUpSLP *SLP);
2993 
2994     /// Sets all instruction in the scheduling region to un-scheduled.
2995     void resetSchedule();
2996 
2997     BasicBlock *BB;
2998 
2999     /// Simple memory allocation for ScheduleData.
3000     std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
3001 
3002     /// The size of a ScheduleData array in ScheduleDataChunks.
3003     int ChunkSize;
3004 
3005     /// The allocator position in the current chunk, which is the last entry
3006     /// of ScheduleDataChunks.
3007     int ChunkPos;
3008 
3009     /// Attaches ScheduleData to Instruction.
3010     /// Note that the mapping survives during all vectorization iterations, i.e.
3011     /// ScheduleData structures are recycled.
3012     DenseMap<Instruction *, ScheduleData *> ScheduleDataMap;
3013 
3014     /// Attaches ScheduleData to Instruction with the leading key.
3015     DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
3016         ExtraScheduleDataMap;
3017 
3018     /// The ready-list for scheduling (only used for the dry-run).
3019     SetVector<ScheduleData *> ReadyInsts;
3020 
3021     /// The first instruction of the scheduling region.
3022     Instruction *ScheduleStart = nullptr;
3023 
3024     /// The first instruction _after_ the scheduling region.
3025     Instruction *ScheduleEnd = nullptr;
3026 
3027     /// The first memory accessing instruction in the scheduling region
3028     /// (can be null).
3029     ScheduleData *FirstLoadStoreInRegion = nullptr;
3030 
3031     /// The last memory accessing instruction in the scheduling region
3032     /// (can be null).
3033     ScheduleData *LastLoadStoreInRegion = nullptr;
3034 
3035     /// Is there an llvm.stacksave or llvm.stackrestore in the scheduling
3036     /// region?  Used to optimize the dependence calculation for the
3037     /// common case where there isn't.
3038     bool RegionHasStackSave = false;
3039 
3040     /// The current size of the scheduling region.
3041     int ScheduleRegionSize = 0;
3042 
3043     /// The maximum size allowed for the scheduling region.
3044     int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
3045 
3046     /// The ID of the scheduling region. For a new vectorization iteration this
3047     /// is incremented which "removes" all ScheduleData from the region.
3048     /// Make sure that the initial SchedulingRegionID is greater than the
3049     /// initial SchedulingRegionID in ScheduleData (which is 0).
3050     int SchedulingRegionID = 1;
3051   };
3052 
3053   /// Attaches the BlockScheduling structures to basic blocks.
3054   MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
3055 
3056   /// Performs the "real" scheduling. Done before vectorization is actually
3057   /// performed in a basic block.
3058   void scheduleBlock(BlockScheduling *BS);
3059 
3060   /// List of users to ignore during scheduling and that don't need extracting.
3061   ArrayRef<Value *> UserIgnoreList;
3062 
3063   /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
3064   /// sorted SmallVectors of unsigned.
3065   struct OrdersTypeDenseMapInfo {
3066     static OrdersType getEmptyKey() {
3067       OrdersType V;
3068       V.push_back(~1U);
3069       return V;
3070     }
3071 
3072     static OrdersType getTombstoneKey() {
3073       OrdersType V;
3074       V.push_back(~2U);
3075       return V;
3076     }
3077 
3078     static unsigned getHashValue(const OrdersType &V) {
3079       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
3080     }
3081 
3082     static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
3083       return LHS == RHS;
3084     }
3085   };
3086 
3087   // Analysis and block reference.
3088   Function *F;
3089   ScalarEvolution *SE;
3090   TargetTransformInfo *TTI;
3091   TargetLibraryInfo *TLI;
3092   LoopInfo *LI;
3093   DominatorTree *DT;
3094   AssumptionCache *AC;
3095   DemandedBits *DB;
3096   const DataLayout *DL;
3097   OptimizationRemarkEmitter *ORE;
3098 
3099   unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
3100   unsigned MinVecRegSize; // Set by cl::opt (default: 128).
3101 
3102   /// Instruction builder to construct the vectorized tree.
3103   IRBuilder<> Builder;
3104 
3105   /// A map of scalar integer values to the smallest bit width with which they
3106   /// can legally be represented. The values map to (width, signed) pairs,
3107   /// where "width" indicates the minimum bit width and "signed" is True if the
3108   /// value must be signed-extended, rather than zero-extended, back to its
3109   /// original width.
3110   MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
3111 };
3112 
3113 } // end namespace slpvectorizer
3114 
3115 template <> struct GraphTraits<BoUpSLP *> {
3116   using TreeEntry = BoUpSLP::TreeEntry;
3117 
3118   /// NodeRef has to be a pointer per the GraphWriter.
3119   using NodeRef = TreeEntry *;
3120 
3121   using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy;
3122 
3123   /// Add the VectorizableTree to the index iterator to be able to return
3124   /// TreeEntry pointers.
3125   struct ChildIteratorType
3126       : public iterator_adaptor_base<
3127             ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
3128     ContainerTy &VectorizableTree;
3129 
3130     ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W,
3131                       ContainerTy &VT)
3132         : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
3133 
3134     NodeRef operator*() { return I->UserTE; }
3135   };
3136 
3137   static NodeRef getEntryNode(BoUpSLP &R) {
3138     return R.VectorizableTree[0].get();
3139   }
3140 
3141   static ChildIteratorType child_begin(NodeRef N) {
3142     return {N->UserTreeIndices.begin(), N->Container};
3143   }
3144 
3145   static ChildIteratorType child_end(NodeRef N) {
3146     return {N->UserTreeIndices.end(), N->Container};
3147   }
3148 
3149   /// For the node iterator we just need to turn the TreeEntry iterator into a
3150   /// TreeEntry* iterator so that it dereferences to NodeRef.
3151   class nodes_iterator {
3152     using ItTy = ContainerTy::iterator;
3153     ItTy It;
3154 
3155   public:
3156     nodes_iterator(const ItTy &It2) : It(It2) {}
3157     NodeRef operator*() { return It->get(); }
3158     nodes_iterator operator++() {
3159       ++It;
3160       return *this;
3161     }
3162     bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
3163   };
3164 
3165   static nodes_iterator nodes_begin(BoUpSLP *R) {
3166     return nodes_iterator(R->VectorizableTree.begin());
3167   }
3168 
3169   static nodes_iterator nodes_end(BoUpSLP *R) {
3170     return nodes_iterator(R->VectorizableTree.end());
3171   }
3172 
3173   static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
3174 };
3175 
3176 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
3177   using TreeEntry = BoUpSLP::TreeEntry;
3178 
3179   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
3180 
3181   std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
3182     std::string Str;
3183     raw_string_ostream OS(Str);
3184     if (isSplat(Entry->Scalars))
3185       OS << "<splat> ";
3186     for (auto V : Entry->Scalars) {
3187       OS << *V;
3188       if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) {
3189             return EU.Scalar == V;
3190           }))
3191         OS << " <extract>";
3192       OS << "\n";
3193     }
3194     return Str;
3195   }
3196 
3197   static std::string getNodeAttributes(const TreeEntry *Entry,
3198                                        const BoUpSLP *) {
3199     if (Entry->State == TreeEntry::NeedToGather)
3200       return "color=red";
3201     return "";
3202   }
3203 };
3204 
3205 } // end namespace llvm
3206 
3207 BoUpSLP::~BoUpSLP() {
3208   SmallVector<WeakTrackingVH> DeadInsts;
3209   for (auto *I : DeletedInstructions) {
3210     for (Use &U : I->operands()) {
3211       auto *Op = dyn_cast<Instruction>(U.get());
3212       if (Op && !DeletedInstructions.count(Op) && Op->hasOneUser() &&
3213           wouldInstructionBeTriviallyDead(Op, TLI))
3214         DeadInsts.emplace_back(Op);
3215     }
3216     I->dropAllReferences();
3217   }
3218   for (auto *I : DeletedInstructions) {
3219     assert(I->use_empty() &&
3220            "trying to erase instruction with users.");
3221     I->eraseFromParent();
3222   }
3223 
3224   // Cleanup any dead scalar code feeding the vectorized instructions
3225   RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI);
3226 
3227 #ifdef EXPENSIVE_CHECKS
3228   // If we could guarantee that this call is not extremely slow, we could
3229   // remove the ifdef limitation (see PR47712).
3230   assert(!verifyFunction(*F, &dbgs()));
3231 #endif
3232 }
3233 
3234 /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses
3235 /// contains original mask for the scalars reused in the node. Procedure
3236 /// transform this mask in accordance with the given \p Mask.
3237 static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) {
3238   assert(!Mask.empty() && Reuses.size() == Mask.size() &&
3239          "Expected non-empty mask.");
3240   SmallVector<int> Prev(Reuses.begin(), Reuses.end());
3241   Prev.swap(Reuses);
3242   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
3243     if (Mask[I] != UndefMaskElem)
3244       Reuses[Mask[I]] = Prev[I];
3245 }
3246 
3247 /// Reorders the given \p Order according to the given \p Mask. \p Order - is
3248 /// the original order of the scalars. Procedure transforms the provided order
3249 /// in accordance with the given \p Mask. If the resulting \p Order is just an
3250 /// identity order, \p Order is cleared.
3251 static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) {
3252   assert(!Mask.empty() && "Expected non-empty mask.");
3253   SmallVector<int> MaskOrder;
3254   if (Order.empty()) {
3255     MaskOrder.resize(Mask.size());
3256     std::iota(MaskOrder.begin(), MaskOrder.end(), 0);
3257   } else {
3258     inversePermutation(Order, MaskOrder);
3259   }
3260   reorderReuses(MaskOrder, Mask);
3261   if (ShuffleVectorInst::isIdentityMask(MaskOrder)) {
3262     Order.clear();
3263     return;
3264   }
3265   Order.assign(Mask.size(), Mask.size());
3266   for (unsigned I = 0, E = Mask.size(); I < E; ++I)
3267     if (MaskOrder[I] != UndefMaskElem)
3268       Order[MaskOrder[I]] = I;
3269   fixupOrderingIndices(Order);
3270 }
3271 
3272 Optional<BoUpSLP::OrdersType>
3273 BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) {
3274   assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
3275   unsigned NumScalars = TE.Scalars.size();
3276   OrdersType CurrentOrder(NumScalars, NumScalars);
3277   SmallVector<int> Positions;
3278   SmallBitVector UsedPositions(NumScalars);
3279   const TreeEntry *STE = nullptr;
3280   // Try to find all gathered scalars that are gets vectorized in other
3281   // vectorize node. Here we can have only one single tree vector node to
3282   // correctly identify order of the gathered scalars.
3283   for (unsigned I = 0; I < NumScalars; ++I) {
3284     Value *V = TE.Scalars[I];
3285     if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V))
3286       continue;
3287     if (const auto *LocalSTE = getTreeEntry(V)) {
3288       if (!STE)
3289         STE = LocalSTE;
3290       else if (STE != LocalSTE)
3291         // Take the order only from the single vector node.
3292         return None;
3293       unsigned Lane =
3294           std::distance(STE->Scalars.begin(), find(STE->Scalars, V));
3295       if (Lane >= NumScalars)
3296         return None;
3297       if (CurrentOrder[Lane] != NumScalars) {
3298         if (Lane != I)
3299           continue;
3300         UsedPositions.reset(CurrentOrder[Lane]);
3301       }
3302       // The partial identity (where only some elements of the gather node are
3303       // in the identity order) is good.
3304       CurrentOrder[Lane] = I;
3305       UsedPositions.set(I);
3306     }
3307   }
3308   // Need to keep the order if we have a vector entry and at least 2 scalars or
3309   // the vectorized entry has just 2 scalars.
3310   if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) {
3311     auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) {
3312       for (unsigned I = 0; I < NumScalars; ++I)
3313         if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars)
3314           return false;
3315       return true;
3316     };
3317     if (IsIdentityOrder(CurrentOrder)) {
3318       CurrentOrder.clear();
3319       return CurrentOrder;
3320     }
3321     auto *It = CurrentOrder.begin();
3322     for (unsigned I = 0; I < NumScalars;) {
3323       if (UsedPositions.test(I)) {
3324         ++I;
3325         continue;
3326       }
3327       if (*It == NumScalars) {
3328         *It = I;
3329         ++I;
3330       }
3331       ++It;
3332     }
3333     return CurrentOrder;
3334   }
3335   return None;
3336 }
3337 
3338 Optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE,
3339                                                          bool TopToBottom) {
3340   // No need to reorder if need to shuffle reuses, still need to shuffle the
3341   // node.
3342   if (!TE.ReuseShuffleIndices.empty())
3343     return None;
3344   if (TE.State == TreeEntry::Vectorize &&
3345       (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) ||
3346        (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) &&
3347       !TE.isAltShuffle())
3348     return TE.ReorderIndices;
3349   if (TE.State == TreeEntry::NeedToGather) {
3350     // TODO: add analysis of other gather nodes with extractelement
3351     // instructions and other values/instructions, not only undefs.
3352     if (((TE.getOpcode() == Instruction::ExtractElement &&
3353           !TE.isAltShuffle()) ||
3354          (all_of(TE.Scalars,
3355                  [](Value *V) {
3356                    return isa<UndefValue, ExtractElementInst>(V);
3357                  }) &&
3358           any_of(TE.Scalars,
3359                  [](Value *V) { return isa<ExtractElementInst>(V); }))) &&
3360         all_of(TE.Scalars,
3361                [](Value *V) {
3362                  auto *EE = dyn_cast<ExtractElementInst>(V);
3363                  return !EE || isa<FixedVectorType>(EE->getVectorOperandType());
3364                }) &&
3365         allSameType(TE.Scalars)) {
3366       // Check that gather of extractelements can be represented as
3367       // just a shuffle of a single vector.
3368       OrdersType CurrentOrder;
3369       bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder);
3370       if (Reuse || !CurrentOrder.empty()) {
3371         if (!CurrentOrder.empty())
3372           fixupOrderingIndices(CurrentOrder);
3373         return CurrentOrder;
3374       }
3375     }
3376     if (Optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE))
3377       return CurrentOrder;
3378   }
3379   return None;
3380 }
3381 
3382 void BoUpSLP::reorderTopToBottom() {
3383   // Maps VF to the graph nodes.
3384   DenseMap<unsigned, SetVector<TreeEntry *>> VFToOrderedEntries;
3385   // ExtractElement gather nodes which can be vectorized and need to handle
3386   // their ordering.
3387   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3388   // Find all reorderable nodes with the given VF.
3389   // Currently the are vectorized stores,loads,extracts + some gathering of
3390   // extracts.
3391   for_each(VectorizableTree, [this, &VFToOrderedEntries, &GathersToOrders](
3392                                  const std::unique_ptr<TreeEntry> &TE) {
3393     if (Optional<OrdersType> CurrentOrder =
3394             getReorderingData(*TE, /*TopToBottom=*/true)) {
3395       // Do not include ordering for nodes used in the alt opcode vectorization,
3396       // better to reorder them during bottom-to-top stage. If follow the order
3397       // here, it causes reordering of the whole graph though actually it is
3398       // profitable just to reorder the subgraph that starts from the alternate
3399       // opcode vectorization node. Such nodes already end-up with the shuffle
3400       // instruction and it is just enough to change this shuffle rather than
3401       // rotate the scalars for the whole graph.
3402       unsigned Cnt = 0;
3403       const TreeEntry *UserTE = TE.get();
3404       while (UserTE && Cnt < RecursionMaxDepth) {
3405         if (UserTE->UserTreeIndices.size() != 1)
3406           break;
3407         if (all_of(UserTE->UserTreeIndices, [](const EdgeInfo &EI) {
3408               return EI.UserTE->State == TreeEntry::Vectorize &&
3409                      EI.UserTE->isAltShuffle() && EI.UserTE->Idx != 0;
3410             }))
3411           return;
3412         if (UserTE->UserTreeIndices.empty())
3413           UserTE = nullptr;
3414         else
3415           UserTE = UserTE->UserTreeIndices.back().UserTE;
3416         ++Cnt;
3417       }
3418       VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
3419       if (TE->State != TreeEntry::Vectorize)
3420         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3421     }
3422   });
3423 
3424   // Reorder the graph nodes according to their vectorization factor.
3425   for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1;
3426        VF /= 2) {
3427     auto It = VFToOrderedEntries.find(VF);
3428     if (It == VFToOrderedEntries.end())
3429       continue;
3430     // Try to find the most profitable order. We just are looking for the most
3431     // used order and reorder scalar elements in the nodes according to this
3432     // mostly used order.
3433     ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef();
3434     // All operands are reordered and used only in this node - propagate the
3435     // most used order to the user node.
3436     MapVector<OrdersType, unsigned,
3437               DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3438         OrdersUses;
3439     SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3440     for (const TreeEntry *OpTE : OrderedEntries) {
3441       // No need to reorder this nodes, still need to extend and to use shuffle,
3442       // just need to merge reordering shuffle and the reuse shuffle.
3443       if (!OpTE->ReuseShuffleIndices.empty())
3444         continue;
3445       // Count number of orders uses.
3446       const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3447         if (OpTE->State == TreeEntry::NeedToGather)
3448           return GathersToOrders.find(OpTE)->second;
3449         return OpTE->ReorderIndices;
3450       }();
3451       // Stores actually store the mask, not the order, need to invert.
3452       if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3453           OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3454         SmallVector<int> Mask;
3455         inversePermutation(Order, Mask);
3456         unsigned E = Order.size();
3457         OrdersType CurrentOrder(E, E);
3458         transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3459           return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3460         });
3461         fixupOrderingIndices(CurrentOrder);
3462         ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
3463       } else {
3464         ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
3465       }
3466     }
3467     // Set order of the user node.
3468     if (OrdersUses.empty())
3469       continue;
3470     // Choose the most used order.
3471     ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3472     unsigned Cnt = OrdersUses.front().second;
3473     for (const auto &Pair : drop_begin(OrdersUses)) {
3474       if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3475         BestOrder = Pair.first;
3476         Cnt = Pair.second;
3477       }
3478     }
3479     // Set order of the user node.
3480     if (BestOrder.empty())
3481       continue;
3482     SmallVector<int> Mask;
3483     inversePermutation(BestOrder, Mask);
3484     SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3485     unsigned E = BestOrder.size();
3486     transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3487       return I < E ? static_cast<int>(I) : UndefMaskElem;
3488     });
3489     // Do an actual reordering, if profitable.
3490     for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
3491       // Just do the reordering for the nodes with the given VF.
3492       if (TE->Scalars.size() != VF) {
3493         if (TE->ReuseShuffleIndices.size() == VF) {
3494           // Need to reorder the reuses masks of the operands with smaller VF to
3495           // be able to find the match between the graph nodes and scalar
3496           // operands of the given node during vectorization/cost estimation.
3497           assert(all_of(TE->UserTreeIndices,
3498                         [VF, &TE](const EdgeInfo &EI) {
3499                           return EI.UserTE->Scalars.size() == VF ||
3500                                  EI.UserTE->Scalars.size() ==
3501                                      TE->Scalars.size();
3502                         }) &&
3503                  "All users must be of VF size.");
3504           // Update ordering of the operands with the smaller VF than the given
3505           // one.
3506           reorderReuses(TE->ReuseShuffleIndices, Mask);
3507         }
3508         continue;
3509       }
3510       if (TE->State == TreeEntry::Vectorize &&
3511           isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst,
3512               InsertElementInst>(TE->getMainOp()) &&
3513           !TE->isAltShuffle()) {
3514         // Build correct orders for extract{element,value}, loads and
3515         // stores.
3516         reorderOrder(TE->ReorderIndices, Mask);
3517         if (isa<InsertElementInst, StoreInst>(TE->getMainOp()))
3518           TE->reorderOperands(Mask);
3519       } else {
3520         // Reorder the node and its operands.
3521         TE->reorderOperands(Mask);
3522         assert(TE->ReorderIndices.empty() &&
3523                "Expected empty reorder sequence.");
3524         reorderScalars(TE->Scalars, Mask);
3525       }
3526       if (!TE->ReuseShuffleIndices.empty()) {
3527         // Apply reversed order to keep the original ordering of the reused
3528         // elements to avoid extra reorder indices shuffling.
3529         OrdersType CurrentOrder;
3530         reorderOrder(CurrentOrder, MaskOrder);
3531         SmallVector<int> NewReuses;
3532         inversePermutation(CurrentOrder, NewReuses);
3533         addMask(NewReuses, TE->ReuseShuffleIndices);
3534         TE->ReuseShuffleIndices.swap(NewReuses);
3535       }
3536     }
3537   }
3538 }
3539 
3540 bool BoUpSLP::canReorderOperands(
3541     TreeEntry *UserTE, SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
3542     ArrayRef<TreeEntry *> ReorderableGathers,
3543     SmallVectorImpl<TreeEntry *> &GatherOps) {
3544   for (unsigned I = 0, E = UserTE->getNumOperands(); I < E; ++I) {
3545     if (any_of(Edges, [I](const std::pair<unsigned, TreeEntry *> &OpData) {
3546           return OpData.first == I &&
3547                  OpData.second->State == TreeEntry::Vectorize;
3548         }))
3549       continue;
3550     if (TreeEntry *TE = getVectorizedOperand(UserTE, I)) {
3551       // Do not reorder if operand node is used by many user nodes.
3552       if (any_of(TE->UserTreeIndices,
3553                  [UserTE](const EdgeInfo &EI) { return EI.UserTE != UserTE; }))
3554         return false;
3555       // Add the node to the list of the ordered nodes with the identity
3556       // order.
3557       Edges.emplace_back(I, TE);
3558       continue;
3559     }
3560     ArrayRef<Value *> VL = UserTE->getOperand(I);
3561     TreeEntry *Gather = nullptr;
3562     if (count_if(ReorderableGathers, [VL, &Gather](TreeEntry *TE) {
3563           assert(TE->State != TreeEntry::Vectorize &&
3564                  "Only non-vectorized nodes are expected.");
3565           if (TE->isSame(VL)) {
3566             Gather = TE;
3567             return true;
3568           }
3569           return false;
3570         }) > 1)
3571       return false;
3572     if (Gather)
3573       GatherOps.push_back(Gather);
3574   }
3575   return true;
3576 }
3577 
3578 void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) {
3579   SetVector<TreeEntry *> OrderedEntries;
3580   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3581   // Find all reorderable leaf nodes with the given VF.
3582   // Currently the are vectorized loads,extracts without alternate operands +
3583   // some gathering of extracts.
3584   SmallVector<TreeEntry *> NonVectorized;
3585   for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders,
3586                               &NonVectorized](
3587                                  const std::unique_ptr<TreeEntry> &TE) {
3588     if (TE->State != TreeEntry::Vectorize)
3589       NonVectorized.push_back(TE.get());
3590     if (Optional<OrdersType> CurrentOrder =
3591             getReorderingData(*TE, /*TopToBottom=*/false)) {
3592       OrderedEntries.insert(TE.get());
3593       if (TE->State != TreeEntry::Vectorize)
3594         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3595     }
3596   });
3597 
3598   // 1. Propagate order to the graph nodes, which use only reordered nodes.
3599   // I.e., if the node has operands, that are reordered, try to make at least
3600   // one operand order in the natural order and reorder others + reorder the
3601   // user node itself.
3602   SmallPtrSet<const TreeEntry *, 4> Visited;
3603   while (!OrderedEntries.empty()) {
3604     // 1. Filter out only reordered nodes.
3605     // 2. If the entry has multiple uses - skip it and jump to the next node.
3606     MapVector<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users;
3607     SmallVector<TreeEntry *> Filtered;
3608     for (TreeEntry *TE : OrderedEntries) {
3609       if (!(TE->State == TreeEntry::Vectorize ||
3610             (TE->State == TreeEntry::NeedToGather &&
3611              GathersToOrders.count(TE))) ||
3612           TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3613           !all_of(drop_begin(TE->UserTreeIndices),
3614                   [TE](const EdgeInfo &EI) {
3615                     return EI.UserTE == TE->UserTreeIndices.front().UserTE;
3616                   }) ||
3617           !Visited.insert(TE).second) {
3618         Filtered.push_back(TE);
3619         continue;
3620       }
3621       // Build a map between user nodes and their operands order to speedup
3622       // search. The graph currently does not provide this dependency directly.
3623       for (EdgeInfo &EI : TE->UserTreeIndices) {
3624         TreeEntry *UserTE = EI.UserTE;
3625         auto It = Users.find(UserTE);
3626         if (It == Users.end())
3627           It = Users.insert({UserTE, {}}).first;
3628         It->second.emplace_back(EI.EdgeIdx, TE);
3629       }
3630     }
3631     // Erase filtered entries.
3632     for_each(Filtered,
3633              [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); });
3634     for (auto &Data : Users) {
3635       // Check that operands are used only in the User node.
3636       SmallVector<TreeEntry *> GatherOps;
3637       if (!canReorderOperands(Data.first, Data.second, NonVectorized,
3638                               GatherOps)) {
3639         for_each(Data.second,
3640                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3641                    OrderedEntries.remove(Op.second);
3642                  });
3643         continue;
3644       }
3645       // All operands are reordered and used only in this node - propagate the
3646       // most used order to the user node.
3647       MapVector<OrdersType, unsigned,
3648                 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3649           OrdersUses;
3650       // Do the analysis for each tree entry only once, otherwise the order of
3651       // the same node my be considered several times, though might be not
3652       // profitable.
3653       SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3654       SmallPtrSet<const TreeEntry *, 4> VisitedUsers;
3655       for (const auto &Op : Data.second) {
3656         TreeEntry *OpTE = Op.second;
3657         if (!VisitedOps.insert(OpTE).second)
3658           continue;
3659         if (!OpTE->ReuseShuffleIndices.empty() ||
3660             (IgnoreReorder && OpTE == VectorizableTree.front().get()))
3661           continue;
3662         const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3663           if (OpTE->State == TreeEntry::NeedToGather)
3664             return GathersToOrders.find(OpTE)->second;
3665           return OpTE->ReorderIndices;
3666         }();
3667         unsigned NumOps = count_if(
3668             Data.second, [OpTE](const std::pair<unsigned, TreeEntry *> &P) {
3669               return P.second == OpTE;
3670             });
3671         // Stores actually store the mask, not the order, need to invert.
3672         if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3673             OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3674           SmallVector<int> Mask;
3675           inversePermutation(Order, Mask);
3676           unsigned E = Order.size();
3677           OrdersType CurrentOrder(E, E);
3678           transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3679             return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3680           });
3681           fixupOrderingIndices(CurrentOrder);
3682           OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second +=
3683               NumOps;
3684         } else {
3685           OrdersUses.insert(std::make_pair(Order, 0)).first->second += NumOps;
3686         }
3687         auto Res = OrdersUses.insert(std::make_pair(OrdersType(), 0));
3688         const auto &&AllowsReordering = [IgnoreReorder, &GathersToOrders](
3689                                             const TreeEntry *TE) {
3690           if (!TE->ReorderIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3691               (TE->State == TreeEntry::Vectorize && TE->isAltShuffle()) ||
3692               (IgnoreReorder && TE->Idx == 0))
3693             return true;
3694           if (TE->State == TreeEntry::NeedToGather) {
3695             auto It = GathersToOrders.find(TE);
3696             if (It != GathersToOrders.end())
3697               return !It->second.empty();
3698             return true;
3699           }
3700           return false;
3701         };
3702         for (const EdgeInfo &EI : OpTE->UserTreeIndices) {
3703           TreeEntry *UserTE = EI.UserTE;
3704           if (!VisitedUsers.insert(UserTE).second)
3705             continue;
3706           // May reorder user node if it requires reordering, has reused
3707           // scalars, is an alternate op vectorize node or its op nodes require
3708           // reordering.
3709           if (AllowsReordering(UserTE))
3710             continue;
3711           // Check if users allow reordering.
3712           // Currently look up just 1 level of operands to avoid increase of
3713           // the compile time.
3714           // Profitable to reorder if definitely more operands allow
3715           // reordering rather than those with natural order.
3716           ArrayRef<std::pair<unsigned, TreeEntry *>> Ops = Users[UserTE];
3717           if (static_cast<unsigned>(count_if(
3718                   Ops, [UserTE, &AllowsReordering](
3719                            const std::pair<unsigned, TreeEntry *> &Op) {
3720                     return AllowsReordering(Op.second) &&
3721                            all_of(Op.second->UserTreeIndices,
3722                                   [UserTE](const EdgeInfo &EI) {
3723                                     return EI.UserTE == UserTE;
3724                                   });
3725                   })) <= Ops.size() / 2)
3726             ++Res.first->second;
3727         }
3728       }
3729       // If no orders - skip current nodes and jump to the next one, if any.
3730       if (OrdersUses.empty()) {
3731         for_each(Data.second,
3732                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3733                    OrderedEntries.remove(Op.second);
3734                  });
3735         continue;
3736       }
3737       // Choose the best order.
3738       ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3739       unsigned Cnt = OrdersUses.front().second;
3740       for (const auto &Pair : drop_begin(OrdersUses)) {
3741         if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3742           BestOrder = Pair.first;
3743           Cnt = Pair.second;
3744         }
3745       }
3746       // Set order of the user node (reordering of operands and user nodes).
3747       if (BestOrder.empty()) {
3748         for_each(Data.second,
3749                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3750                    OrderedEntries.remove(Op.second);
3751                  });
3752         continue;
3753       }
3754       // Erase operands from OrderedEntries list and adjust their orders.
3755       VisitedOps.clear();
3756       SmallVector<int> Mask;
3757       inversePermutation(BestOrder, Mask);
3758       SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3759       unsigned E = BestOrder.size();
3760       transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3761         return I < E ? static_cast<int>(I) : UndefMaskElem;
3762       });
3763       for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) {
3764         TreeEntry *TE = Op.second;
3765         OrderedEntries.remove(TE);
3766         if (!VisitedOps.insert(TE).second)
3767           continue;
3768         if (TE->ReuseShuffleIndices.size() == BestOrder.size()) {
3769           // Just reorder reuses indices.
3770           reorderReuses(TE->ReuseShuffleIndices, Mask);
3771           continue;
3772         }
3773         // Gathers are processed separately.
3774         if (TE->State != TreeEntry::Vectorize)
3775           continue;
3776         assert((BestOrder.size() == TE->ReorderIndices.size() ||
3777                 TE->ReorderIndices.empty()) &&
3778                "Non-matching sizes of user/operand entries.");
3779         reorderOrder(TE->ReorderIndices, Mask);
3780       }
3781       // For gathers just need to reorder its scalars.
3782       for (TreeEntry *Gather : GatherOps) {
3783         assert(Gather->ReorderIndices.empty() &&
3784                "Unexpected reordering of gathers.");
3785         if (!Gather->ReuseShuffleIndices.empty()) {
3786           // Just reorder reuses indices.
3787           reorderReuses(Gather->ReuseShuffleIndices, Mask);
3788           continue;
3789         }
3790         reorderScalars(Gather->Scalars, Mask);
3791         OrderedEntries.remove(Gather);
3792       }
3793       // Reorder operands of the user node and set the ordering for the user
3794       // node itself.
3795       if (Data.first->State != TreeEntry::Vectorize ||
3796           !isa<ExtractElementInst, ExtractValueInst, LoadInst>(
3797               Data.first->getMainOp()) ||
3798           Data.first->isAltShuffle())
3799         Data.first->reorderOperands(Mask);
3800       if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) ||
3801           Data.first->isAltShuffle()) {
3802         reorderScalars(Data.first->Scalars, Mask);
3803         reorderOrder(Data.first->ReorderIndices, MaskOrder);
3804         if (Data.first->ReuseShuffleIndices.empty() &&
3805             !Data.first->ReorderIndices.empty() &&
3806             !Data.first->isAltShuffle()) {
3807           // Insert user node to the list to try to sink reordering deeper in
3808           // the graph.
3809           OrderedEntries.insert(Data.first);
3810         }
3811       } else {
3812         reorderOrder(Data.first->ReorderIndices, Mask);
3813       }
3814     }
3815   }
3816   // If the reordering is unnecessary, just remove the reorder.
3817   if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() &&
3818       VectorizableTree.front()->ReuseShuffleIndices.empty())
3819     VectorizableTree.front()->ReorderIndices.clear();
3820 }
3821 
3822 void BoUpSLP::buildExternalUses(
3823     const ExtraValueToDebugLocsMap &ExternallyUsedValues) {
3824   // Collect the values that we need to extract from the tree.
3825   for (auto &TEPtr : VectorizableTree) {
3826     TreeEntry *Entry = TEPtr.get();
3827 
3828     // No need to handle users of gathered values.
3829     if (Entry->State == TreeEntry::NeedToGather)
3830       continue;
3831 
3832     // For each lane:
3833     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
3834       Value *Scalar = Entry->Scalars[Lane];
3835       int FoundLane = Entry->findLaneForValue(Scalar);
3836 
3837       // Check if the scalar is externally used as an extra arg.
3838       auto ExtI = ExternallyUsedValues.find(Scalar);
3839       if (ExtI != ExternallyUsedValues.end()) {
3840         LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
3841                           << Lane << " from " << *Scalar << ".\n");
3842         ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
3843       }
3844       for (User *U : Scalar->users()) {
3845         LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
3846 
3847         Instruction *UserInst = dyn_cast<Instruction>(U);
3848         if (!UserInst)
3849           continue;
3850 
3851         if (isDeleted(UserInst))
3852           continue;
3853 
3854         // Skip in-tree scalars that become vectors
3855         if (TreeEntry *UseEntry = getTreeEntry(U)) {
3856           Value *UseScalar = UseEntry->Scalars[0];
3857           // Some in-tree scalars will remain as scalar in vectorized
3858           // instructions. If that is the case, the one in Lane 0 will
3859           // be used.
3860           if (UseScalar != U ||
3861               UseEntry->State == TreeEntry::ScatterVectorize ||
3862               !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
3863             LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
3864                               << ".\n");
3865             assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state");
3866             continue;
3867           }
3868         }
3869 
3870         // Ignore users in the user ignore list.
3871         if (is_contained(UserIgnoreList, UserInst))
3872           continue;
3873 
3874         LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
3875                           << Lane << " from " << *Scalar << ".\n");
3876         ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
3877       }
3878     }
3879   }
3880 }
3881 
3882 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
3883                         ArrayRef<Value *> UserIgnoreLst) {
3884   deleteTree();
3885   UserIgnoreList = UserIgnoreLst;
3886   if (!allSameType(Roots))
3887     return;
3888   buildTree_rec(Roots, 0, EdgeInfo());
3889 }
3890 
3891 namespace {
3892 /// Tracks the state we can represent the loads in the given sequence.
3893 enum class LoadsState { Gather, Vectorize, ScatterVectorize };
3894 } // anonymous namespace
3895 
3896 /// Checks if the given array of loads can be represented as a vectorized,
3897 /// scatter or just simple gather.
3898 static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0,
3899                                     const TargetTransformInfo &TTI,
3900                                     const DataLayout &DL, ScalarEvolution &SE,
3901                                     SmallVectorImpl<unsigned> &Order,
3902                                     SmallVectorImpl<Value *> &PointerOps) {
3903   // Check that a vectorized load would load the same memory as a scalar
3904   // load. For example, we don't want to vectorize loads that are smaller
3905   // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
3906   // treats loading/storing it as an i8 struct. If we vectorize loads/stores
3907   // from such a struct, we read/write packed bits disagreeing with the
3908   // unvectorized version.
3909   Type *ScalarTy = VL0->getType();
3910 
3911   if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy))
3912     return LoadsState::Gather;
3913 
3914   // Make sure all loads in the bundle are simple - we can't vectorize
3915   // atomic or volatile loads.
3916   PointerOps.clear();
3917   PointerOps.resize(VL.size());
3918   auto *POIter = PointerOps.begin();
3919   for (Value *V : VL) {
3920     auto *L = cast<LoadInst>(V);
3921     if (!L->isSimple())
3922       return LoadsState::Gather;
3923     *POIter = L->getPointerOperand();
3924     ++POIter;
3925   }
3926 
3927   Order.clear();
3928   // Check the order of pointer operands.
3929   if (llvm::sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order)) {
3930     Value *Ptr0;
3931     Value *PtrN;
3932     if (Order.empty()) {
3933       Ptr0 = PointerOps.front();
3934       PtrN = PointerOps.back();
3935     } else {
3936       Ptr0 = PointerOps[Order.front()];
3937       PtrN = PointerOps[Order.back()];
3938     }
3939     Optional<int> Diff =
3940         getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE);
3941     // Check that the sorted loads are consecutive.
3942     if (static_cast<unsigned>(*Diff) == VL.size() - 1)
3943       return LoadsState::Vectorize;
3944     Align CommonAlignment = cast<LoadInst>(VL0)->getAlign();
3945     for (Value *V : VL)
3946       CommonAlignment =
3947           commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
3948     if (TTI.isLegalMaskedGather(FixedVectorType::get(ScalarTy, VL.size()),
3949                                 CommonAlignment))
3950       return LoadsState::ScatterVectorize;
3951   }
3952 
3953   return LoadsState::Gather;
3954 }
3955 
3956 /// \return true if the specified list of values has only one instruction that
3957 /// requires scheduling, false otherwise.
3958 #ifndef NDEBUG
3959 static bool needToScheduleSingleInstruction(ArrayRef<Value *> VL) {
3960   Value *NeedsScheduling = nullptr;
3961   for (Value *V : VL) {
3962     if (doesNotNeedToBeScheduled(V))
3963       continue;
3964     if (!NeedsScheduling) {
3965       NeedsScheduling = V;
3966       continue;
3967     }
3968     return false;
3969   }
3970   return NeedsScheduling;
3971 }
3972 #endif
3973 
3974 /// Generates key/subkey pair for the given value to provide effective sorting
3975 /// of the values and better detection of the vectorizable values sequences. The
3976 /// keys/subkeys can be used for better sorting of the values themselves (keys)
3977 /// and in values subgroups (subkeys).
3978 static std::pair<size_t, size_t> generateKeySubkey(
3979     Value *V, const TargetLibraryInfo *TLI,
3980     function_ref<hash_code(size_t, LoadInst *)> LoadsSubkeyGenerator,
3981     bool AllowAlternate) {
3982   hash_code Key = hash_value(V->getValueID() + 2);
3983   hash_code SubKey = hash_value(0);
3984   // Sort the loads by the distance between the pointers.
3985   if (auto *LI = dyn_cast<LoadInst>(V)) {
3986     Key = hash_combine(hash_value(LI->getParent()), Key);
3987     if (LI->isSimple())
3988       SubKey = hash_value(LoadsSubkeyGenerator(Key, LI));
3989     else
3990       SubKey = hash_value(LI);
3991   } else if (isVectorLikeInstWithConstOps(V)) {
3992     // Sort extracts by the vector operands.
3993     if (isa<ExtractElementInst, UndefValue>(V))
3994       Key = hash_value(Value::UndefValueVal + 1);
3995     if (auto *EI = dyn_cast<ExtractElementInst>(V)) {
3996       if (!isUndefVector(EI->getVectorOperand()) &&
3997           !isa<UndefValue>(EI->getIndexOperand()))
3998         SubKey = hash_value(EI->getVectorOperand());
3999     }
4000   } else if (auto *I = dyn_cast<Instruction>(V)) {
4001     // Sort other instructions just by the opcodes except for CMPInst.
4002     // For CMP also sort by the predicate kind.
4003     if ((isa<BinaryOperator>(I) || isa<CastInst>(I)) &&
4004         isValidForAlternation(I->getOpcode())) {
4005       if (AllowAlternate)
4006         Key = hash_value(isa<BinaryOperator>(I) ? 1 : 0);
4007       else
4008         Key = hash_combine(hash_value(I->getOpcode()), Key);
4009       SubKey = hash_combine(
4010           hash_value(I->getOpcode()), hash_value(I->getType()),
4011           hash_value(isa<BinaryOperator>(I)
4012                          ? I->getType()
4013                          : cast<CastInst>(I)->getOperand(0)->getType()));
4014     } else if (auto *CI = dyn_cast<CmpInst>(I)) {
4015       CmpInst::Predicate Pred = CI->getPredicate();
4016       if (CI->isCommutative())
4017         Pred = std::min(Pred, CmpInst::getInversePredicate(Pred));
4018       CmpInst::Predicate SwapPred = CmpInst::getSwappedPredicate(Pred);
4019       SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(Pred),
4020                             hash_value(SwapPred),
4021                             hash_value(CI->getOperand(0)->getType()));
4022     } else if (auto *Call = dyn_cast<CallInst>(I)) {
4023       Intrinsic::ID ID = getVectorIntrinsicIDForCall(Call, TLI);
4024       if (isTriviallyVectorizable(ID))
4025         SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(ID));
4026       else if (!VFDatabase(*Call).getMappings(*Call).empty())
4027         SubKey = hash_combine(hash_value(I->getOpcode()),
4028                               hash_value(Call->getCalledFunction()));
4029       else
4030         SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(Call));
4031       for (const CallBase::BundleOpInfo &Op : Call->bundle_op_infos())
4032         SubKey = hash_combine(hash_value(Op.Begin), hash_value(Op.End),
4033                               hash_value(Op.Tag), SubKey);
4034     } else if (auto *Gep = dyn_cast<GetElementPtrInst>(I)) {
4035       if (Gep->getNumOperands() == 2 && isa<ConstantInt>(Gep->getOperand(1)))
4036         SubKey = hash_value(Gep->getPointerOperand());
4037       else
4038         SubKey = hash_value(Gep);
4039     } else if (BinaryOperator::isIntDivRem(I->getOpcode()) &&
4040                !isa<ConstantInt>(I->getOperand(1))) {
4041       // Do not try to vectorize instructions with potentially high cost.
4042       SubKey = hash_value(I);
4043     } else {
4044       SubKey = hash_value(I->getOpcode());
4045     }
4046     Key = hash_combine(hash_value(I->getParent()), Key);
4047   }
4048   return std::make_pair(Key, SubKey);
4049 }
4050 
4051 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
4052                             const EdgeInfo &UserTreeIdx) {
4053   assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
4054 
4055   SmallVector<int> ReuseShuffleIndicies;
4056   SmallVector<Value *> UniqueValues;
4057   auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues,
4058                                 &UserTreeIdx,
4059                                 this](const InstructionsState &S) {
4060     // Check that every instruction appears once in this bundle.
4061     DenseMap<Value *, unsigned> UniquePositions;
4062     for (Value *V : VL) {
4063       if (isConstant(V)) {
4064         ReuseShuffleIndicies.emplace_back(
4065             isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size());
4066         UniqueValues.emplace_back(V);
4067         continue;
4068       }
4069       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
4070       ReuseShuffleIndicies.emplace_back(Res.first->second);
4071       if (Res.second)
4072         UniqueValues.emplace_back(V);
4073     }
4074     size_t NumUniqueScalarValues = UniqueValues.size();
4075     if (NumUniqueScalarValues == VL.size()) {
4076       ReuseShuffleIndicies.clear();
4077     } else {
4078       LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
4079       if (NumUniqueScalarValues <= 1 ||
4080           (UniquePositions.size() == 1 && all_of(UniqueValues,
4081                                                  [](Value *V) {
4082                                                    return isa<UndefValue>(V) ||
4083                                                           !isConstant(V);
4084                                                  })) ||
4085           !llvm::isPowerOf2_32(NumUniqueScalarValues)) {
4086         LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
4087         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4088         return false;
4089       }
4090       VL = UniqueValues;
4091     }
4092     return true;
4093   };
4094 
4095   InstructionsState S = getSameOpcode(VL);
4096   if (Depth == RecursionMaxDepth) {
4097     LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
4098     if (TryToFindDuplicates(S))
4099       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4100                    ReuseShuffleIndicies);
4101     return;
4102   }
4103 
4104   // Don't handle scalable vectors
4105   if (S.getOpcode() == Instruction::ExtractElement &&
4106       isa<ScalableVectorType>(
4107           cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) {
4108     LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n");
4109     if (TryToFindDuplicates(S))
4110       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4111                    ReuseShuffleIndicies);
4112     return;
4113   }
4114 
4115   // Don't handle vectors.
4116   if (S.OpValue->getType()->isVectorTy() &&
4117       !isa<InsertElementInst>(S.OpValue)) {
4118     LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
4119     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4120     return;
4121   }
4122 
4123   if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
4124     if (SI->getValueOperand()->getType()->isVectorTy()) {
4125       LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
4126       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4127       return;
4128     }
4129 
4130   // If all of the operands are identical or constant we have a simple solution.
4131   // If we deal with insert/extract instructions, they all must have constant
4132   // indices, otherwise we should gather them, not try to vectorize.
4133   if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode() ||
4134       (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(S.MainOp) &&
4135        !all_of(VL, isVectorLikeInstWithConstOps))) {
4136     LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
4137     if (TryToFindDuplicates(S))
4138       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4139                    ReuseShuffleIndicies);
4140     return;
4141   }
4142 
4143   // We now know that this is a vector of instructions of the same type from
4144   // the same block.
4145 
4146   // Don't vectorize ephemeral values.
4147   for (Value *V : VL) {
4148     if (EphValues.count(V)) {
4149       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
4150                         << ") is ephemeral.\n");
4151       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4152       return;
4153     }
4154   }
4155 
4156   // Check if this is a duplicate of another entry.
4157   if (TreeEntry *E = getTreeEntry(S.OpValue)) {
4158     LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n");
4159     if (!E->isSame(VL)) {
4160       LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
4161       if (TryToFindDuplicates(S))
4162         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4163                      ReuseShuffleIndicies);
4164       return;
4165     }
4166     // Record the reuse of the tree node.  FIXME, currently this is only used to
4167     // properly draw the graph rather than for the actual vectorization.
4168     E->UserTreeIndices.push_back(UserTreeIdx);
4169     LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue
4170                       << ".\n");
4171     return;
4172   }
4173 
4174   // Check that none of the instructions in the bundle are already in the tree.
4175   for (Value *V : VL) {
4176     auto *I = dyn_cast<Instruction>(V);
4177     if (!I)
4178       continue;
4179     if (getTreeEntry(I)) {
4180       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
4181                         << ") is already in tree.\n");
4182       if (TryToFindDuplicates(S))
4183         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4184                      ReuseShuffleIndicies);
4185       return;
4186     }
4187   }
4188 
4189   // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
4190   for (Value *V : VL) {
4191     if (is_contained(UserIgnoreList, V)) {
4192       LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
4193       if (TryToFindDuplicates(S))
4194         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4195                      ReuseShuffleIndicies);
4196       return;
4197     }
4198   }
4199 
4200   // Check that all of the users of the scalars that we want to vectorize are
4201   // schedulable.
4202   auto *VL0 = cast<Instruction>(S.OpValue);
4203   BasicBlock *BB = VL0->getParent();
4204 
4205   if (!DT->isReachableFromEntry(BB)) {
4206     // Don't go into unreachable blocks. They may contain instructions with
4207     // dependency cycles which confuse the final scheduling.
4208     LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
4209     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4210     return;
4211   }
4212 
4213   // Check that every instruction appears once in this bundle.
4214   if (!TryToFindDuplicates(S))
4215     return;
4216 
4217   auto &BSRef = BlocksSchedules[BB];
4218   if (!BSRef)
4219     BSRef = std::make_unique<BlockScheduling>(BB);
4220 
4221   BlockScheduling &BS = *BSRef;
4222 
4223   Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S);
4224 #ifdef EXPENSIVE_CHECKS
4225   // Make sure we didn't break any internal invariants
4226   BS.verify();
4227 #endif
4228   if (!Bundle) {
4229     LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
4230     assert((!BS.getScheduleData(VL0) ||
4231             !BS.getScheduleData(VL0)->isPartOfBundle()) &&
4232            "tryScheduleBundle should cancelScheduling on failure");
4233     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4234                  ReuseShuffleIndicies);
4235     return;
4236   }
4237   LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
4238 
4239   unsigned ShuffleOrOp = S.isAltShuffle() ?
4240                 (unsigned) Instruction::ShuffleVector : S.getOpcode();
4241   switch (ShuffleOrOp) {
4242     case Instruction::PHI: {
4243       auto *PH = cast<PHINode>(VL0);
4244 
4245       // Check for terminator values (e.g. invoke).
4246       for (Value *V : VL)
4247         for (Value *Incoming : cast<PHINode>(V)->incoming_values()) {
4248           Instruction *Term = dyn_cast<Instruction>(Incoming);
4249           if (Term && Term->isTerminator()) {
4250             LLVM_DEBUG(dbgs()
4251                        << "SLP: Need to swizzle PHINodes (terminator use).\n");
4252             BS.cancelScheduling(VL, VL0);
4253             newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4254                          ReuseShuffleIndicies);
4255             return;
4256           }
4257         }
4258 
4259       TreeEntry *TE =
4260           newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies);
4261       LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
4262 
4263       // Keeps the reordered operands to avoid code duplication.
4264       SmallVector<ValueList, 2> OperandsVec;
4265       for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
4266         if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) {
4267           ValueList Operands(VL.size(), PoisonValue::get(PH->getType()));
4268           TE->setOperand(I, Operands);
4269           OperandsVec.push_back(Operands);
4270           continue;
4271         }
4272         ValueList Operands;
4273         // Prepare the operand vector.
4274         for (Value *V : VL)
4275           Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(
4276               PH->getIncomingBlock(I)));
4277         TE->setOperand(I, Operands);
4278         OperandsVec.push_back(Operands);
4279       }
4280       for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx)
4281         buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx});
4282       return;
4283     }
4284     case Instruction::ExtractValue:
4285     case Instruction::ExtractElement: {
4286       OrdersType CurrentOrder;
4287       bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
4288       if (Reuse) {
4289         LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
4290         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4291                      ReuseShuffleIndicies);
4292         // This is a special case, as it does not gather, but at the same time
4293         // we are not extending buildTree_rec() towards the operands.
4294         ValueList Op0;
4295         Op0.assign(VL.size(), VL0->getOperand(0));
4296         VectorizableTree.back()->setOperand(0, Op0);
4297         return;
4298       }
4299       if (!CurrentOrder.empty()) {
4300         LLVM_DEBUG({
4301           dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
4302                     "with order";
4303           for (unsigned Idx : CurrentOrder)
4304             dbgs() << " " << Idx;
4305           dbgs() << "\n";
4306         });
4307         fixupOrderingIndices(CurrentOrder);
4308         // Insert new order with initial value 0, if it does not exist,
4309         // otherwise return the iterator to the existing one.
4310         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4311                      ReuseShuffleIndicies, CurrentOrder);
4312         // This is a special case, as it does not gather, but at the same time
4313         // we are not extending buildTree_rec() towards the operands.
4314         ValueList Op0;
4315         Op0.assign(VL.size(), VL0->getOperand(0));
4316         VectorizableTree.back()->setOperand(0, Op0);
4317         return;
4318       }
4319       LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
4320       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4321                    ReuseShuffleIndicies);
4322       BS.cancelScheduling(VL, VL0);
4323       return;
4324     }
4325     case Instruction::InsertElement: {
4326       assert(ReuseShuffleIndicies.empty() && "All inserts should be unique");
4327 
4328       // Check that we have a buildvector and not a shuffle of 2 or more
4329       // different vectors.
4330       ValueSet SourceVectors;
4331       for (Value *V : VL) {
4332         SourceVectors.insert(cast<Instruction>(V)->getOperand(0));
4333         assert(getInsertIndex(V) != None && "Non-constant or undef index?");
4334       }
4335 
4336       if (count_if(VL, [&SourceVectors](Value *V) {
4337             return !SourceVectors.contains(V);
4338           }) >= 2) {
4339         // Found 2nd source vector - cancel.
4340         LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with "
4341                              "different source vectors.\n");
4342         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4343         BS.cancelScheduling(VL, VL0);
4344         return;
4345       }
4346 
4347       auto OrdCompare = [](const std::pair<int, int> &P1,
4348                            const std::pair<int, int> &P2) {
4349         return P1.first > P2.first;
4350       };
4351       PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>,
4352                     decltype(OrdCompare)>
4353           Indices(OrdCompare);
4354       for (int I = 0, E = VL.size(); I < E; ++I) {
4355         unsigned Idx = *getInsertIndex(VL[I]);
4356         Indices.emplace(Idx, I);
4357       }
4358       OrdersType CurrentOrder(VL.size(), VL.size());
4359       bool IsIdentity = true;
4360       for (int I = 0, E = VL.size(); I < E; ++I) {
4361         CurrentOrder[Indices.top().second] = I;
4362         IsIdentity &= Indices.top().second == I;
4363         Indices.pop();
4364       }
4365       if (IsIdentity)
4366         CurrentOrder.clear();
4367       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4368                                    None, CurrentOrder);
4369       LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n");
4370 
4371       constexpr int NumOps = 2;
4372       ValueList VectorOperands[NumOps];
4373       for (int I = 0; I < NumOps; ++I) {
4374         for (Value *V : VL)
4375           VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I));
4376 
4377         TE->setOperand(I, VectorOperands[I]);
4378       }
4379       buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1});
4380       return;
4381     }
4382     case Instruction::Load: {
4383       // Check that a vectorized load would load the same memory as a scalar
4384       // load. For example, we don't want to vectorize loads that are smaller
4385       // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
4386       // treats loading/storing it as an i8 struct. If we vectorize loads/stores
4387       // from such a struct, we read/write packed bits disagreeing with the
4388       // unvectorized version.
4389       SmallVector<Value *> PointerOps;
4390       OrdersType CurrentOrder;
4391       TreeEntry *TE = nullptr;
4392       switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, CurrentOrder,
4393                                 PointerOps)) {
4394       case LoadsState::Vectorize:
4395         if (CurrentOrder.empty()) {
4396           // Original loads are consecutive and does not require reordering.
4397           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4398                             ReuseShuffleIndicies);
4399           LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
4400         } else {
4401           fixupOrderingIndices(CurrentOrder);
4402           // Need to reorder.
4403           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4404                             ReuseShuffleIndicies, CurrentOrder);
4405           LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
4406         }
4407         TE->setOperandsInOrder();
4408         break;
4409       case LoadsState::ScatterVectorize:
4410         // Vectorizing non-consecutive loads with `llvm.masked.gather`.
4411         TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S,
4412                           UserTreeIdx, ReuseShuffleIndicies);
4413         TE->setOperandsInOrder();
4414         buildTree_rec(PointerOps, Depth + 1, {TE, 0});
4415         LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n");
4416         break;
4417       case LoadsState::Gather:
4418         BS.cancelScheduling(VL, VL0);
4419         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4420                      ReuseShuffleIndicies);
4421 #ifndef NDEBUG
4422         Type *ScalarTy = VL0->getType();
4423         if (DL->getTypeSizeInBits(ScalarTy) !=
4424             DL->getTypeAllocSizeInBits(ScalarTy))
4425           LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
4426         else if (any_of(VL, [](Value *V) {
4427                    return !cast<LoadInst>(V)->isSimple();
4428                  }))
4429           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
4430         else
4431           LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
4432 #endif // NDEBUG
4433         break;
4434       }
4435       return;
4436     }
4437     case Instruction::ZExt:
4438     case Instruction::SExt:
4439     case Instruction::FPToUI:
4440     case Instruction::FPToSI:
4441     case Instruction::FPExt:
4442     case Instruction::PtrToInt:
4443     case Instruction::IntToPtr:
4444     case Instruction::SIToFP:
4445     case Instruction::UIToFP:
4446     case Instruction::Trunc:
4447     case Instruction::FPTrunc:
4448     case Instruction::BitCast: {
4449       Type *SrcTy = VL0->getOperand(0)->getType();
4450       for (Value *V : VL) {
4451         Type *Ty = cast<Instruction>(V)->getOperand(0)->getType();
4452         if (Ty != SrcTy || !isValidElementType(Ty)) {
4453           BS.cancelScheduling(VL, VL0);
4454           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4455                        ReuseShuffleIndicies);
4456           LLVM_DEBUG(dbgs()
4457                      << "SLP: Gathering casts with different src types.\n");
4458           return;
4459         }
4460       }
4461       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4462                                    ReuseShuffleIndicies);
4463       LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
4464 
4465       TE->setOperandsInOrder();
4466       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4467         ValueList Operands;
4468         // Prepare the operand vector.
4469         for (Value *V : VL)
4470           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4471 
4472         buildTree_rec(Operands, Depth + 1, {TE, i});
4473       }
4474       return;
4475     }
4476     case Instruction::ICmp:
4477     case Instruction::FCmp: {
4478       // Check that all of the compares have the same predicate.
4479       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
4480       CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0);
4481       Type *ComparedTy = VL0->getOperand(0)->getType();
4482       for (Value *V : VL) {
4483         CmpInst *Cmp = cast<CmpInst>(V);
4484         if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) ||
4485             Cmp->getOperand(0)->getType() != ComparedTy) {
4486           BS.cancelScheduling(VL, VL0);
4487           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4488                        ReuseShuffleIndicies);
4489           LLVM_DEBUG(dbgs()
4490                      << "SLP: Gathering cmp with different predicate.\n");
4491           return;
4492         }
4493       }
4494 
4495       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4496                                    ReuseShuffleIndicies);
4497       LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
4498 
4499       ValueList Left, Right;
4500       if (cast<CmpInst>(VL0)->isCommutative()) {
4501         // Commutative predicate - collect + sort operands of the instructions
4502         // so that each side is more likely to have the same opcode.
4503         assert(P0 == SwapP0 && "Commutative Predicate mismatch");
4504         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4505       } else {
4506         // Collect operands - commute if it uses the swapped predicate.
4507         for (Value *V : VL) {
4508           auto *Cmp = cast<CmpInst>(V);
4509           Value *LHS = Cmp->getOperand(0);
4510           Value *RHS = Cmp->getOperand(1);
4511           if (Cmp->getPredicate() != P0)
4512             std::swap(LHS, RHS);
4513           Left.push_back(LHS);
4514           Right.push_back(RHS);
4515         }
4516       }
4517       TE->setOperand(0, Left);
4518       TE->setOperand(1, Right);
4519       buildTree_rec(Left, Depth + 1, {TE, 0});
4520       buildTree_rec(Right, Depth + 1, {TE, 1});
4521       return;
4522     }
4523     case Instruction::Select:
4524     case Instruction::FNeg:
4525     case Instruction::Add:
4526     case Instruction::FAdd:
4527     case Instruction::Sub:
4528     case Instruction::FSub:
4529     case Instruction::Mul:
4530     case Instruction::FMul:
4531     case Instruction::UDiv:
4532     case Instruction::SDiv:
4533     case Instruction::FDiv:
4534     case Instruction::URem:
4535     case Instruction::SRem:
4536     case Instruction::FRem:
4537     case Instruction::Shl:
4538     case Instruction::LShr:
4539     case Instruction::AShr:
4540     case Instruction::And:
4541     case Instruction::Or:
4542     case Instruction::Xor: {
4543       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4544                                    ReuseShuffleIndicies);
4545       LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n");
4546 
4547       // Sort operands of the instructions so that each side is more likely to
4548       // have the same opcode.
4549       if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
4550         ValueList Left, Right;
4551         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4552         TE->setOperand(0, Left);
4553         TE->setOperand(1, Right);
4554         buildTree_rec(Left, Depth + 1, {TE, 0});
4555         buildTree_rec(Right, Depth + 1, {TE, 1});
4556         return;
4557       }
4558 
4559       TE->setOperandsInOrder();
4560       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4561         ValueList Operands;
4562         // Prepare the operand vector.
4563         for (Value *V : VL)
4564           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4565 
4566         buildTree_rec(Operands, Depth + 1, {TE, i});
4567       }
4568       return;
4569     }
4570     case Instruction::GetElementPtr: {
4571       // We don't combine GEPs with complicated (nested) indexing.
4572       for (Value *V : VL) {
4573         if (cast<Instruction>(V)->getNumOperands() != 2) {
4574           LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
4575           BS.cancelScheduling(VL, VL0);
4576           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4577                        ReuseShuffleIndicies);
4578           return;
4579         }
4580       }
4581 
4582       // We can't combine several GEPs into one vector if they operate on
4583       // different types.
4584       Type *Ty0 = cast<GEPOperator>(VL0)->getSourceElementType();
4585       for (Value *V : VL) {
4586         Type *CurTy = cast<GEPOperator>(V)->getSourceElementType();
4587         if (Ty0 != CurTy) {
4588           LLVM_DEBUG(dbgs()
4589                      << "SLP: not-vectorizable GEP (different types).\n");
4590           BS.cancelScheduling(VL, VL0);
4591           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4592                        ReuseShuffleIndicies);
4593           return;
4594         }
4595       }
4596 
4597       // We don't combine GEPs with non-constant indexes.
4598       Type *Ty1 = VL0->getOperand(1)->getType();
4599       for (Value *V : VL) {
4600         auto Op = cast<Instruction>(V)->getOperand(1);
4601         if (!isa<ConstantInt>(Op) ||
4602             (Op->getType() != Ty1 &&
4603              Op->getType()->getScalarSizeInBits() >
4604                  DL->getIndexSizeInBits(
4605                      V->getType()->getPointerAddressSpace()))) {
4606           LLVM_DEBUG(dbgs()
4607                      << "SLP: not-vectorizable GEP (non-constant indexes).\n");
4608           BS.cancelScheduling(VL, VL0);
4609           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4610                        ReuseShuffleIndicies);
4611           return;
4612         }
4613       }
4614 
4615       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4616                                    ReuseShuffleIndicies);
4617       LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
4618       SmallVector<ValueList, 2> Operands(2);
4619       // Prepare the operand vector for pointer operands.
4620       for (Value *V : VL)
4621         Operands.front().push_back(
4622             cast<GetElementPtrInst>(V)->getPointerOperand());
4623       TE->setOperand(0, Operands.front());
4624       // Need to cast all indices to the same type before vectorization to
4625       // avoid crash.
4626       // Required to be able to find correct matches between different gather
4627       // nodes and reuse the vectorized values rather than trying to gather them
4628       // again.
4629       int IndexIdx = 1;
4630       Type *VL0Ty = VL0->getOperand(IndexIdx)->getType();
4631       Type *Ty = all_of(VL,
4632                         [VL0Ty, IndexIdx](Value *V) {
4633                           return VL0Ty == cast<GetElementPtrInst>(V)
4634                                               ->getOperand(IndexIdx)
4635                                               ->getType();
4636                         })
4637                      ? VL0Ty
4638                      : DL->getIndexType(cast<GetElementPtrInst>(VL0)
4639                                             ->getPointerOperandType()
4640                                             ->getScalarType());
4641       // Prepare the operand vector.
4642       for (Value *V : VL) {
4643         auto *Op = cast<Instruction>(V)->getOperand(IndexIdx);
4644         auto *CI = cast<ConstantInt>(Op);
4645         Operands.back().push_back(ConstantExpr::getIntegerCast(
4646             CI, Ty, CI->getValue().isSignBitSet()));
4647       }
4648       TE->setOperand(IndexIdx, Operands.back());
4649 
4650       for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I)
4651         buildTree_rec(Operands[I], Depth + 1, {TE, I});
4652       return;
4653     }
4654     case Instruction::Store: {
4655       // Check if the stores are consecutive or if we need to swizzle them.
4656       llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType();
4657       // Avoid types that are padded when being allocated as scalars, while
4658       // being packed together in a vector (such as i1).
4659       if (DL->getTypeSizeInBits(ScalarTy) !=
4660           DL->getTypeAllocSizeInBits(ScalarTy)) {
4661         BS.cancelScheduling(VL, VL0);
4662         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4663                      ReuseShuffleIndicies);
4664         LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n");
4665         return;
4666       }
4667       // Make sure all stores in the bundle are simple - we can't vectorize
4668       // atomic or volatile stores.
4669       SmallVector<Value *, 4> PointerOps(VL.size());
4670       ValueList Operands(VL.size());
4671       auto POIter = PointerOps.begin();
4672       auto OIter = Operands.begin();
4673       for (Value *V : VL) {
4674         auto *SI = cast<StoreInst>(V);
4675         if (!SI->isSimple()) {
4676           BS.cancelScheduling(VL, VL0);
4677           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4678                        ReuseShuffleIndicies);
4679           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n");
4680           return;
4681         }
4682         *POIter = SI->getPointerOperand();
4683         *OIter = SI->getValueOperand();
4684         ++POIter;
4685         ++OIter;
4686       }
4687 
4688       OrdersType CurrentOrder;
4689       // Check the order of pointer operands.
4690       if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) {
4691         Value *Ptr0;
4692         Value *PtrN;
4693         if (CurrentOrder.empty()) {
4694           Ptr0 = PointerOps.front();
4695           PtrN = PointerOps.back();
4696         } else {
4697           Ptr0 = PointerOps[CurrentOrder.front()];
4698           PtrN = PointerOps[CurrentOrder.back()];
4699         }
4700         Optional<int> Dist =
4701             getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE);
4702         // Check that the sorted pointer operands are consecutive.
4703         if (static_cast<unsigned>(*Dist) == VL.size() - 1) {
4704           if (CurrentOrder.empty()) {
4705             // Original stores are consecutive and does not require reordering.
4706             TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
4707                                          UserTreeIdx, ReuseShuffleIndicies);
4708             TE->setOperandsInOrder();
4709             buildTree_rec(Operands, Depth + 1, {TE, 0});
4710             LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
4711           } else {
4712             fixupOrderingIndices(CurrentOrder);
4713             TreeEntry *TE =
4714                 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4715                              ReuseShuffleIndicies, CurrentOrder);
4716             TE->setOperandsInOrder();
4717             buildTree_rec(Operands, Depth + 1, {TE, 0});
4718             LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n");
4719           }
4720           return;
4721         }
4722       }
4723 
4724       BS.cancelScheduling(VL, VL0);
4725       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4726                    ReuseShuffleIndicies);
4727       LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
4728       return;
4729     }
4730     case Instruction::Call: {
4731       // Check if the calls are all to the same vectorizable intrinsic or
4732       // library function.
4733       CallInst *CI = cast<CallInst>(VL0);
4734       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4735 
4736       VFShape Shape = VFShape::get(
4737           *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())),
4738           false /*HasGlobalPred*/);
4739       Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4740 
4741       if (!VecFunc && !isTriviallyVectorizable(ID)) {
4742         BS.cancelScheduling(VL, VL0);
4743         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4744                      ReuseShuffleIndicies);
4745         LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
4746         return;
4747       }
4748       Function *F = CI->getCalledFunction();
4749       unsigned NumArgs = CI->arg_size();
4750       SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr);
4751       for (unsigned j = 0; j != NumArgs; ++j)
4752         if (hasVectorInstrinsicScalarOpd(ID, j))
4753           ScalarArgs[j] = CI->getArgOperand(j);
4754       for (Value *V : VL) {
4755         CallInst *CI2 = dyn_cast<CallInst>(V);
4756         if (!CI2 || CI2->getCalledFunction() != F ||
4757             getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
4758             (VecFunc &&
4759              VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) ||
4760             !CI->hasIdenticalOperandBundleSchema(*CI2)) {
4761           BS.cancelScheduling(VL, VL0);
4762           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4763                        ReuseShuffleIndicies);
4764           LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V
4765                             << "\n");
4766           return;
4767         }
4768         // Some intrinsics have scalar arguments and should be same in order for
4769         // them to be vectorized.
4770         for (unsigned j = 0; j != NumArgs; ++j) {
4771           if (hasVectorInstrinsicScalarOpd(ID, j)) {
4772             Value *A1J = CI2->getArgOperand(j);
4773             if (ScalarArgs[j] != A1J) {
4774               BS.cancelScheduling(VL, VL0);
4775               newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4776                            ReuseShuffleIndicies);
4777               LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
4778                                 << " argument " << ScalarArgs[j] << "!=" << A1J
4779                                 << "\n");
4780               return;
4781             }
4782           }
4783         }
4784         // Verify that the bundle operands are identical between the two calls.
4785         if (CI->hasOperandBundles() &&
4786             !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
4787                         CI->op_begin() + CI->getBundleOperandsEndIndex(),
4788                         CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
4789           BS.cancelScheduling(VL, VL0);
4790           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4791                        ReuseShuffleIndicies);
4792           LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
4793                             << *CI << "!=" << *V << '\n');
4794           return;
4795         }
4796       }
4797 
4798       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4799                                    ReuseShuffleIndicies);
4800       TE->setOperandsInOrder();
4801       for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
4802         // For scalar operands no need to to create an entry since no need to
4803         // vectorize it.
4804         if (hasVectorInstrinsicScalarOpd(ID, i))
4805           continue;
4806         ValueList Operands;
4807         // Prepare the operand vector.
4808         for (Value *V : VL) {
4809           auto *CI2 = cast<CallInst>(V);
4810           Operands.push_back(CI2->getArgOperand(i));
4811         }
4812         buildTree_rec(Operands, Depth + 1, {TE, i});
4813       }
4814       return;
4815     }
4816     case Instruction::ShuffleVector: {
4817       // If this is not an alternate sequence of opcode like add-sub
4818       // then do not vectorize this instruction.
4819       if (!S.isAltShuffle()) {
4820         BS.cancelScheduling(VL, VL0);
4821         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4822                      ReuseShuffleIndicies);
4823         LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
4824         return;
4825       }
4826       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4827                                    ReuseShuffleIndicies);
4828       LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
4829 
4830       // Reorder operands if reordering would enable vectorization.
4831       auto *CI = dyn_cast<CmpInst>(VL0);
4832       if (isa<BinaryOperator>(VL0) || CI) {
4833         ValueList Left, Right;
4834         if (!CI || all_of(VL, [](Value *V) {
4835               return cast<CmpInst>(V)->isCommutative();
4836             })) {
4837           reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4838         } else {
4839           CmpInst::Predicate P0 = CI->getPredicate();
4840           CmpInst::Predicate AltP0 = cast<CmpInst>(S.AltOp)->getPredicate();
4841           assert(P0 != AltP0 &&
4842                  "Expected different main/alternate predicates.");
4843           CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
4844           Value *BaseOp0 = VL0->getOperand(0);
4845           Value *BaseOp1 = VL0->getOperand(1);
4846           // Collect operands - commute if it uses the swapped predicate or
4847           // alternate operation.
4848           for (Value *V : VL) {
4849             auto *Cmp = cast<CmpInst>(V);
4850             Value *LHS = Cmp->getOperand(0);
4851             Value *RHS = Cmp->getOperand(1);
4852             CmpInst::Predicate CurrentPred = Cmp->getPredicate();
4853             if (P0 == AltP0Swapped) {
4854               if (CI != Cmp && S.AltOp != Cmp &&
4855                   ((P0 == CurrentPred &&
4856                     !areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)) ||
4857                    (AltP0 == CurrentPred &&
4858                     areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS))))
4859                 std::swap(LHS, RHS);
4860             } else if (P0 != CurrentPred && AltP0 != CurrentPred) {
4861               std::swap(LHS, RHS);
4862             }
4863             Left.push_back(LHS);
4864             Right.push_back(RHS);
4865           }
4866         }
4867         TE->setOperand(0, Left);
4868         TE->setOperand(1, Right);
4869         buildTree_rec(Left, Depth + 1, {TE, 0});
4870         buildTree_rec(Right, Depth + 1, {TE, 1});
4871         return;
4872       }
4873 
4874       TE->setOperandsInOrder();
4875       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4876         ValueList Operands;
4877         // Prepare the operand vector.
4878         for (Value *V : VL)
4879           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4880 
4881         buildTree_rec(Operands, Depth + 1, {TE, i});
4882       }
4883       return;
4884     }
4885     default:
4886       BS.cancelScheduling(VL, VL0);
4887       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4888                    ReuseShuffleIndicies);
4889       LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
4890       return;
4891   }
4892 }
4893 
4894 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
4895   unsigned N = 1;
4896   Type *EltTy = T;
4897 
4898   while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) ||
4899          isa<VectorType>(EltTy)) {
4900     if (auto *ST = dyn_cast<StructType>(EltTy)) {
4901       // Check that struct is homogeneous.
4902       for (const auto *Ty : ST->elements())
4903         if (Ty != *ST->element_begin())
4904           return 0;
4905       N *= ST->getNumElements();
4906       EltTy = *ST->element_begin();
4907     } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) {
4908       N *= AT->getNumElements();
4909       EltTy = AT->getElementType();
4910     } else {
4911       auto *VT = cast<FixedVectorType>(EltTy);
4912       N *= VT->getNumElements();
4913       EltTy = VT->getElementType();
4914     }
4915   }
4916 
4917   if (!isValidElementType(EltTy))
4918     return 0;
4919   uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N));
4920   if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
4921     return 0;
4922   return N;
4923 }
4924 
4925 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
4926                               SmallVectorImpl<unsigned> &CurrentOrder) const {
4927   const auto *It = find_if(VL, [](Value *V) {
4928     return isa<ExtractElementInst, ExtractValueInst>(V);
4929   });
4930   assert(It != VL.end() && "Expected at least one extract instruction.");
4931   auto *E0 = cast<Instruction>(*It);
4932   assert(all_of(VL,
4933                 [](Value *V) {
4934                   return isa<UndefValue, ExtractElementInst, ExtractValueInst>(
4935                       V);
4936                 }) &&
4937          "Invalid opcode");
4938   // Check if all of the extracts come from the same vector and from the
4939   // correct offset.
4940   Value *Vec = E0->getOperand(0);
4941 
4942   CurrentOrder.clear();
4943 
4944   // We have to extract from a vector/aggregate with the same number of elements.
4945   unsigned NElts;
4946   if (E0->getOpcode() == Instruction::ExtractValue) {
4947     const DataLayout &DL = E0->getModule()->getDataLayout();
4948     NElts = canMapToVector(Vec->getType(), DL);
4949     if (!NElts)
4950       return false;
4951     // Check if load can be rewritten as load of vector.
4952     LoadInst *LI = dyn_cast<LoadInst>(Vec);
4953     if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
4954       return false;
4955   } else {
4956     NElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
4957   }
4958 
4959   if (NElts != VL.size())
4960     return false;
4961 
4962   // Check that all of the indices extract from the correct offset.
4963   bool ShouldKeepOrder = true;
4964   unsigned E = VL.size();
4965   // Assign to all items the initial value E + 1 so we can check if the extract
4966   // instruction index was used already.
4967   // Also, later we can check that all the indices are used and we have a
4968   // consecutive access in the extract instructions, by checking that no
4969   // element of CurrentOrder still has value E + 1.
4970   CurrentOrder.assign(E, E);
4971   unsigned I = 0;
4972   for (; I < E; ++I) {
4973     auto *Inst = dyn_cast<Instruction>(VL[I]);
4974     if (!Inst)
4975       continue;
4976     if (Inst->getOperand(0) != Vec)
4977       break;
4978     if (auto *EE = dyn_cast<ExtractElementInst>(Inst))
4979       if (isa<UndefValue>(EE->getIndexOperand()))
4980         continue;
4981     Optional<unsigned> Idx = getExtractIndex(Inst);
4982     if (!Idx)
4983       break;
4984     const unsigned ExtIdx = *Idx;
4985     if (ExtIdx != I) {
4986       if (ExtIdx >= E || CurrentOrder[ExtIdx] != E)
4987         break;
4988       ShouldKeepOrder = false;
4989       CurrentOrder[ExtIdx] = I;
4990     } else {
4991       if (CurrentOrder[I] != E)
4992         break;
4993       CurrentOrder[I] = I;
4994     }
4995   }
4996   if (I < E) {
4997     CurrentOrder.clear();
4998     return false;
4999   }
5000   if (ShouldKeepOrder)
5001     CurrentOrder.clear();
5002 
5003   return ShouldKeepOrder;
5004 }
5005 
5006 bool BoUpSLP::areAllUsersVectorized(Instruction *I,
5007                                     ArrayRef<Value *> VectorizedVals) const {
5008   return (I->hasOneUse() && is_contained(VectorizedVals, I)) ||
5009          all_of(I->users(), [this](User *U) {
5010            return ScalarToTreeEntry.count(U) > 0 ||
5011                   isVectorLikeInstWithConstOps(U) ||
5012                   (isa<ExtractElementInst>(U) && MustGather.contains(U));
5013          });
5014 }
5015 
5016 static std::pair<InstructionCost, InstructionCost>
5017 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy,
5018                    TargetTransformInfo *TTI, TargetLibraryInfo *TLI) {
5019   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5020 
5021   // Calculate the cost of the scalar and vector calls.
5022   SmallVector<Type *, 4> VecTys;
5023   for (Use &Arg : CI->args())
5024     VecTys.push_back(
5025         FixedVectorType::get(Arg->getType(), VecTy->getNumElements()));
5026   FastMathFlags FMF;
5027   if (auto *FPCI = dyn_cast<FPMathOperator>(CI))
5028     FMF = FPCI->getFastMathFlags();
5029   SmallVector<const Value *> Arguments(CI->args());
5030   IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF,
5031                                     dyn_cast<IntrinsicInst>(CI));
5032   auto IntrinsicCost =
5033     TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput);
5034 
5035   auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
5036                                      VecTy->getNumElements())),
5037                             false /*HasGlobalPred*/);
5038   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
5039   auto LibCost = IntrinsicCost;
5040   if (!CI->isNoBuiltin() && VecFunc) {
5041     // Calculate the cost of the vector library call.
5042     // If the corresponding vector call is cheaper, return its cost.
5043     LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys,
5044                                     TTI::TCK_RecipThroughput);
5045   }
5046   return {IntrinsicCost, LibCost};
5047 }
5048 
5049 /// Compute the cost of creating a vector of type \p VecTy containing the
5050 /// extracted values from \p VL.
5051 static InstructionCost
5052 computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy,
5053                    TargetTransformInfo::ShuffleKind ShuffleKind,
5054                    ArrayRef<int> Mask, TargetTransformInfo &TTI) {
5055   unsigned NumOfParts = TTI.getNumberOfParts(VecTy);
5056 
5057   if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts ||
5058       VecTy->getNumElements() < NumOfParts)
5059     return TTI.getShuffleCost(ShuffleKind, VecTy, Mask);
5060 
5061   bool AllConsecutive = true;
5062   unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts;
5063   unsigned Idx = -1;
5064   InstructionCost Cost = 0;
5065 
5066   // Process extracts in blocks of EltsPerVector to check if the source vector
5067   // operand can be re-used directly. If not, add the cost of creating a shuffle
5068   // to extract the values into a vector register.
5069   for (auto *V : VL) {
5070     ++Idx;
5071 
5072     // Need to exclude undefs from analysis.
5073     if (isa<UndefValue>(V) || Mask[Idx] == UndefMaskElem)
5074       continue;
5075 
5076     // Reached the start of a new vector registers.
5077     if (Idx % EltsPerVector == 0) {
5078       AllConsecutive = true;
5079       continue;
5080     }
5081 
5082     // Check all extracts for a vector register on the target directly
5083     // extract values in order.
5084     unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V));
5085     if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != UndefMaskElem) {
5086       unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1]));
5087       AllConsecutive &= PrevIdx + 1 == CurrentIdx &&
5088                         CurrentIdx % EltsPerVector == Idx % EltsPerVector;
5089     }
5090 
5091     if (AllConsecutive)
5092       continue;
5093 
5094     // Skip all indices, except for the last index per vector block.
5095     if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size())
5096       continue;
5097 
5098     // If we have a series of extracts which are not consecutive and hence
5099     // cannot re-use the source vector register directly, compute the shuffle
5100     // cost to extract the a vector with EltsPerVector elements.
5101     Cost += TTI.getShuffleCost(
5102         TargetTransformInfo::SK_PermuteSingleSrc,
5103         FixedVectorType::get(VecTy->getElementType(), EltsPerVector));
5104   }
5105   return Cost;
5106 }
5107 
5108 /// Build shuffle mask for shuffle graph entries and lists of main and alternate
5109 /// operations operands.
5110 static void
5111 buildShuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices,
5112                       ArrayRef<int> ReusesIndices,
5113                       const function_ref<bool(Instruction *)> IsAltOp,
5114                       SmallVectorImpl<int> &Mask,
5115                       SmallVectorImpl<Value *> *OpScalars = nullptr,
5116                       SmallVectorImpl<Value *> *AltScalars = nullptr) {
5117   unsigned Sz = VL.size();
5118   Mask.assign(Sz, UndefMaskElem);
5119   SmallVector<int> OrderMask;
5120   if (!ReorderIndices.empty())
5121     inversePermutation(ReorderIndices, OrderMask);
5122   for (unsigned I = 0; I < Sz; ++I) {
5123     unsigned Idx = I;
5124     if (!ReorderIndices.empty())
5125       Idx = OrderMask[I];
5126     auto *OpInst = cast<Instruction>(VL[Idx]);
5127     if (IsAltOp(OpInst)) {
5128       Mask[I] = Sz + Idx;
5129       if (AltScalars)
5130         AltScalars->push_back(OpInst);
5131     } else {
5132       Mask[I] = Idx;
5133       if (OpScalars)
5134         OpScalars->push_back(OpInst);
5135     }
5136   }
5137   if (!ReusesIndices.empty()) {
5138     SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem);
5139     transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) {
5140       return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem;
5141     });
5142     Mask.swap(NewMask);
5143   }
5144 }
5145 
5146 /// Checks if the specified instruction \p I is an alternate operation for the
5147 /// given \p MainOp and \p AltOp instructions.
5148 static bool isAlternateInstruction(const Instruction *I,
5149                                    const Instruction *MainOp,
5150                                    const Instruction *AltOp) {
5151   if (auto *CI0 = dyn_cast<CmpInst>(MainOp)) {
5152     auto *AltCI0 = cast<CmpInst>(AltOp);
5153     auto *CI = cast<CmpInst>(I);
5154     CmpInst::Predicate P0 = CI0->getPredicate();
5155     CmpInst::Predicate AltP0 = AltCI0->getPredicate();
5156     assert(P0 != AltP0 && "Expected different main/alternate predicates.");
5157     CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
5158     CmpInst::Predicate CurrentPred = CI->getPredicate();
5159     if (P0 == AltP0Swapped)
5160       return I == AltCI0 ||
5161              (I != MainOp &&
5162               !areCompatibleCmpOps(CI0->getOperand(0), CI0->getOperand(1),
5163                                    CI->getOperand(0), CI->getOperand(1)));
5164     return AltP0 == CurrentPred || AltP0Swapped == CurrentPred;
5165   }
5166   return I->getOpcode() == AltOp->getOpcode();
5167 }
5168 
5169 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E,
5170                                       ArrayRef<Value *> VectorizedVals) {
5171   ArrayRef<Value*> VL = E->Scalars;
5172 
5173   Type *ScalarTy = VL[0]->getType();
5174   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
5175     ScalarTy = SI->getValueOperand()->getType();
5176   else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
5177     ScalarTy = CI->getOperand(0)->getType();
5178   else if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
5179     ScalarTy = IE->getOperand(1)->getType();
5180   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
5181   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
5182 
5183   // If we have computed a smaller type for the expression, update VecTy so
5184   // that the costs will be accurate.
5185   if (MinBWs.count(VL[0]))
5186     VecTy = FixedVectorType::get(
5187         IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
5188   unsigned EntryVF = E->getVectorFactor();
5189   auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF);
5190 
5191   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
5192   // FIXME: it tries to fix a problem with MSVC buildbots.
5193   TargetTransformInfo &TTIRef = *TTI;
5194   auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy,
5195                                VectorizedVals, E](InstructionCost &Cost) {
5196     DenseMap<Value *, int> ExtractVectorsTys;
5197     SmallPtrSet<Value *, 4> CheckedExtracts;
5198     for (auto *V : VL) {
5199       if (isa<UndefValue>(V))
5200         continue;
5201       // If all users of instruction are going to be vectorized and this
5202       // instruction itself is not going to be vectorized, consider this
5203       // instruction as dead and remove its cost from the final cost of the
5204       // vectorized tree.
5205       // Also, avoid adjusting the cost for extractelements with multiple uses
5206       // in different graph entries.
5207       const TreeEntry *VE = getTreeEntry(V);
5208       if (!CheckedExtracts.insert(V).second ||
5209           !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) ||
5210           (VE && VE != E))
5211         continue;
5212       auto *EE = cast<ExtractElementInst>(V);
5213       Optional<unsigned> EEIdx = getExtractIndex(EE);
5214       if (!EEIdx)
5215         continue;
5216       unsigned Idx = *EEIdx;
5217       if (TTIRef.getNumberOfParts(VecTy) !=
5218           TTIRef.getNumberOfParts(EE->getVectorOperandType())) {
5219         auto It =
5220             ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first;
5221         It->getSecond() = std::min<int>(It->second, Idx);
5222       }
5223       // Take credit for instruction that will become dead.
5224       if (EE->hasOneUse()) {
5225         Instruction *Ext = EE->user_back();
5226         if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5227             all_of(Ext->users(),
5228                    [](User *U) { return isa<GetElementPtrInst>(U); })) {
5229           // Use getExtractWithExtendCost() to calculate the cost of
5230           // extractelement/ext pair.
5231           Cost -=
5232               TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(),
5233                                               EE->getVectorOperandType(), Idx);
5234           // Add back the cost of s|zext which is subtracted separately.
5235           Cost += TTIRef.getCastInstrCost(
5236               Ext->getOpcode(), Ext->getType(), EE->getType(),
5237               TTI::getCastContextHint(Ext), CostKind, Ext);
5238           continue;
5239         }
5240       }
5241       Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement,
5242                                         EE->getVectorOperandType(), Idx);
5243     }
5244     // Add a cost for subvector extracts/inserts if required.
5245     for (const auto &Data : ExtractVectorsTys) {
5246       auto *EEVTy = cast<FixedVectorType>(Data.first->getType());
5247       unsigned NumElts = VecTy->getNumElements();
5248       if (Data.second % NumElts == 0)
5249         continue;
5250       if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) {
5251         unsigned Idx = (Data.second / NumElts) * NumElts;
5252         unsigned EENumElts = EEVTy->getNumElements();
5253         if (Idx + NumElts <= EENumElts) {
5254           Cost +=
5255               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5256                                     EEVTy, None, Idx, VecTy);
5257         } else {
5258           // Need to round up the subvector type vectorization factor to avoid a
5259           // crash in cost model functions. Make SubVT so that Idx + VF of SubVT
5260           // <= EENumElts.
5261           auto *SubVT =
5262               FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx);
5263           Cost +=
5264               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5265                                     EEVTy, None, Idx, SubVT);
5266         }
5267       } else {
5268         Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector,
5269                                       VecTy, None, 0, EEVTy);
5270       }
5271     }
5272   };
5273   if (E->State == TreeEntry::NeedToGather) {
5274     if (allConstant(VL))
5275       return 0;
5276     if (isa<InsertElementInst>(VL[0]))
5277       return InstructionCost::getInvalid();
5278     SmallVector<int> Mask;
5279     SmallVector<const TreeEntry *> Entries;
5280     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
5281         isGatherShuffledEntry(E, Mask, Entries);
5282     if (Shuffle.hasValue()) {
5283       InstructionCost GatherCost = 0;
5284       if (ShuffleVectorInst::isIdentityMask(Mask)) {
5285         // Perfect match in the graph, will reuse the previously vectorized
5286         // node. Cost is 0.
5287         LLVM_DEBUG(
5288             dbgs()
5289             << "SLP: perfect diamond match for gather bundle that starts with "
5290             << *VL.front() << ".\n");
5291         if (NeedToShuffleReuses)
5292           GatherCost =
5293               TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5294                                   FinalVecTy, E->ReuseShuffleIndices);
5295       } else {
5296         LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size()
5297                           << " entries for bundle that starts with "
5298                           << *VL.front() << ".\n");
5299         // Detected that instead of gather we can emit a shuffle of single/two
5300         // previously vectorized nodes. Add the cost of the permutation rather
5301         // than gather.
5302         ::addMask(Mask, E->ReuseShuffleIndices);
5303         GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask);
5304       }
5305       return GatherCost;
5306     }
5307     if ((E->getOpcode() == Instruction::ExtractElement ||
5308          all_of(E->Scalars,
5309                 [](Value *V) {
5310                   return isa<ExtractElementInst, UndefValue>(V);
5311                 })) &&
5312         allSameType(VL)) {
5313       // Check that gather of extractelements can be represented as just a
5314       // shuffle of a single/two vectors the scalars are extracted from.
5315       SmallVector<int> Mask;
5316       Optional<TargetTransformInfo::ShuffleKind> ShuffleKind =
5317           isFixedVectorShuffle(VL, Mask);
5318       if (ShuffleKind.hasValue()) {
5319         // Found the bunch of extractelement instructions that must be gathered
5320         // into a vector and can be represented as a permutation elements in a
5321         // single input vector or of 2 input vectors.
5322         InstructionCost Cost =
5323             computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI);
5324         AdjustExtractsCost(Cost);
5325         if (NeedToShuffleReuses)
5326           Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5327                                       FinalVecTy, E->ReuseShuffleIndices);
5328         return Cost;
5329       }
5330     }
5331     if (isSplat(VL)) {
5332       // Found the broadcasting of the single scalar, calculate the cost as the
5333       // broadcast.
5334       assert(VecTy == FinalVecTy &&
5335              "No reused scalars expected for broadcast.");
5336       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy,
5337                                  /*Mask=*/None, /*Index=*/0,
5338                                  /*SubTp=*/nullptr, /*Args=*/VL);
5339     }
5340     InstructionCost ReuseShuffleCost = 0;
5341     if (NeedToShuffleReuses)
5342       ReuseShuffleCost = TTI->getShuffleCost(
5343           TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices);
5344     // Improve gather cost for gather of loads, if we can group some of the
5345     // loads into vector loads.
5346     if (VL.size() > 2 && E->getOpcode() == Instruction::Load &&
5347         !E->isAltShuffle()) {
5348       BoUpSLP::ValueSet VectorizedLoads;
5349       unsigned StartIdx = 0;
5350       unsigned VF = VL.size() / 2;
5351       unsigned VectorizedCnt = 0;
5352       unsigned ScatterVectorizeCnt = 0;
5353       const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType());
5354       for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) {
5355         for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End;
5356              Cnt += VF) {
5357           ArrayRef<Value *> Slice = VL.slice(Cnt, VF);
5358           if (!VectorizedLoads.count(Slice.front()) &&
5359               !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) {
5360             SmallVector<Value *> PointerOps;
5361             OrdersType CurrentOrder;
5362             LoadsState LS = canVectorizeLoads(Slice, Slice.front(), *TTI, *DL,
5363                                               *SE, CurrentOrder, PointerOps);
5364             switch (LS) {
5365             case LoadsState::Vectorize:
5366             case LoadsState::ScatterVectorize:
5367               // Mark the vectorized loads so that we don't vectorize them
5368               // again.
5369               if (LS == LoadsState::Vectorize)
5370                 ++VectorizedCnt;
5371               else
5372                 ++ScatterVectorizeCnt;
5373               VectorizedLoads.insert(Slice.begin(), Slice.end());
5374               // If we vectorized initial block, no need to try to vectorize it
5375               // again.
5376               if (Cnt == StartIdx)
5377                 StartIdx += VF;
5378               break;
5379             case LoadsState::Gather:
5380               break;
5381             }
5382           }
5383         }
5384         // Check if the whole array was vectorized already - exit.
5385         if (StartIdx >= VL.size())
5386           break;
5387         // Found vectorizable parts - exit.
5388         if (!VectorizedLoads.empty())
5389           break;
5390       }
5391       if (!VectorizedLoads.empty()) {
5392         InstructionCost GatherCost = 0;
5393         unsigned NumParts = TTI->getNumberOfParts(VecTy);
5394         bool NeedInsertSubvectorAnalysis =
5395             !NumParts || (VL.size() / VF) > NumParts;
5396         // Get the cost for gathered loads.
5397         for (unsigned I = 0, End = VL.size(); I < End; I += VF) {
5398           if (VectorizedLoads.contains(VL[I]))
5399             continue;
5400           GatherCost += getGatherCost(VL.slice(I, VF));
5401         }
5402         // The cost for vectorized loads.
5403         InstructionCost ScalarsCost = 0;
5404         for (Value *V : VectorizedLoads) {
5405           auto *LI = cast<LoadInst>(V);
5406           ScalarsCost += TTI->getMemoryOpCost(
5407               Instruction::Load, LI->getType(), LI->getAlign(),
5408               LI->getPointerAddressSpace(), CostKind, LI);
5409         }
5410         auto *LI = cast<LoadInst>(E->getMainOp());
5411         auto *LoadTy = FixedVectorType::get(LI->getType(), VF);
5412         Align Alignment = LI->getAlign();
5413         GatherCost +=
5414             VectorizedCnt *
5415             TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment,
5416                                  LI->getPointerAddressSpace(), CostKind, LI);
5417         GatherCost += ScatterVectorizeCnt *
5418                       TTI->getGatherScatterOpCost(
5419                           Instruction::Load, LoadTy, LI->getPointerOperand(),
5420                           /*VariableMask=*/false, Alignment, CostKind, LI);
5421         if (NeedInsertSubvectorAnalysis) {
5422           // Add the cost for the subvectors insert.
5423           for (int I = VF, E = VL.size(); I < E; I += VF)
5424             GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy,
5425                                               None, I, LoadTy);
5426         }
5427         return ReuseShuffleCost + GatherCost - ScalarsCost;
5428       }
5429     }
5430     return ReuseShuffleCost + getGatherCost(VL);
5431   }
5432   InstructionCost CommonCost = 0;
5433   SmallVector<int> Mask;
5434   if (!E->ReorderIndices.empty()) {
5435     SmallVector<int> NewMask;
5436     if (E->getOpcode() == Instruction::Store) {
5437       // For stores the order is actually a mask.
5438       NewMask.resize(E->ReorderIndices.size());
5439       copy(E->ReorderIndices, NewMask.begin());
5440     } else {
5441       inversePermutation(E->ReorderIndices, NewMask);
5442     }
5443     ::addMask(Mask, NewMask);
5444   }
5445   if (NeedToShuffleReuses)
5446     ::addMask(Mask, E->ReuseShuffleIndices);
5447   if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask))
5448     CommonCost =
5449         TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask);
5450   assert((E->State == TreeEntry::Vectorize ||
5451           E->State == TreeEntry::ScatterVectorize) &&
5452          "Unhandled state");
5453   assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
5454   Instruction *VL0 = E->getMainOp();
5455   unsigned ShuffleOrOp =
5456       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
5457   switch (ShuffleOrOp) {
5458     case Instruction::PHI:
5459       return 0;
5460 
5461     case Instruction::ExtractValue:
5462     case Instruction::ExtractElement: {
5463       // The common cost of removal ExtractElement/ExtractValue instructions +
5464       // the cost of shuffles, if required to resuffle the original vector.
5465       if (NeedToShuffleReuses) {
5466         unsigned Idx = 0;
5467         for (unsigned I : E->ReuseShuffleIndices) {
5468           if (ShuffleOrOp == Instruction::ExtractElement) {
5469             auto *EE = cast<ExtractElementInst>(VL[I]);
5470             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5471                                                   EE->getVectorOperandType(),
5472                                                   *getExtractIndex(EE));
5473           } else {
5474             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5475                                                   VecTy, Idx);
5476             ++Idx;
5477           }
5478         }
5479         Idx = EntryVF;
5480         for (Value *V : VL) {
5481           if (ShuffleOrOp == Instruction::ExtractElement) {
5482             auto *EE = cast<ExtractElementInst>(V);
5483             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5484                                                   EE->getVectorOperandType(),
5485                                                   *getExtractIndex(EE));
5486           } else {
5487             --Idx;
5488             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5489                                                   VecTy, Idx);
5490           }
5491         }
5492       }
5493       if (ShuffleOrOp == Instruction::ExtractValue) {
5494         for (unsigned I = 0, E = VL.size(); I < E; ++I) {
5495           auto *EI = cast<Instruction>(VL[I]);
5496           // Take credit for instruction that will become dead.
5497           if (EI->hasOneUse()) {
5498             Instruction *Ext = EI->user_back();
5499             if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5500                 all_of(Ext->users(),
5501                        [](User *U) { return isa<GetElementPtrInst>(U); })) {
5502               // Use getExtractWithExtendCost() to calculate the cost of
5503               // extractelement/ext pair.
5504               CommonCost -= TTI->getExtractWithExtendCost(
5505                   Ext->getOpcode(), Ext->getType(), VecTy, I);
5506               // Add back the cost of s|zext which is subtracted separately.
5507               CommonCost += TTI->getCastInstrCost(
5508                   Ext->getOpcode(), Ext->getType(), EI->getType(),
5509                   TTI::getCastContextHint(Ext), CostKind, Ext);
5510               continue;
5511             }
5512           }
5513           CommonCost -=
5514               TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I);
5515         }
5516       } else {
5517         AdjustExtractsCost(CommonCost);
5518       }
5519       return CommonCost;
5520     }
5521     case Instruction::InsertElement: {
5522       assert(E->ReuseShuffleIndices.empty() &&
5523              "Unique insertelements only are expected.");
5524       auto *SrcVecTy = cast<FixedVectorType>(VL0->getType());
5525 
5526       unsigned const NumElts = SrcVecTy->getNumElements();
5527       unsigned const NumScalars = VL.size();
5528       APInt DemandedElts = APInt::getZero(NumElts);
5529       // TODO: Add support for Instruction::InsertValue.
5530       SmallVector<int> Mask;
5531       if (!E->ReorderIndices.empty()) {
5532         inversePermutation(E->ReorderIndices, Mask);
5533         Mask.append(NumElts - NumScalars, UndefMaskElem);
5534       } else {
5535         Mask.assign(NumElts, UndefMaskElem);
5536         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
5537       }
5538       unsigned Offset = *getInsertIndex(VL0);
5539       bool IsIdentity = true;
5540       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
5541       Mask.swap(PrevMask);
5542       for (unsigned I = 0; I < NumScalars; ++I) {
5543         unsigned InsertIdx = *getInsertIndex(VL[PrevMask[I]]);
5544         DemandedElts.setBit(InsertIdx);
5545         IsIdentity &= InsertIdx - Offset == I;
5546         Mask[InsertIdx - Offset] = I;
5547       }
5548       assert(Offset < NumElts && "Failed to find vector index offset");
5549 
5550       InstructionCost Cost = 0;
5551       Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts,
5552                                             /*Insert*/ true, /*Extract*/ false);
5553 
5554       if (IsIdentity && NumElts != NumScalars && Offset % NumScalars != 0) {
5555         // FIXME: Replace with SK_InsertSubvector once it is properly supported.
5556         unsigned Sz = PowerOf2Ceil(Offset + NumScalars);
5557         Cost += TTI->getShuffleCost(
5558             TargetTransformInfo::SK_PermuteSingleSrc,
5559             FixedVectorType::get(SrcVecTy->getElementType(), Sz));
5560       } else if (!IsIdentity) {
5561         auto *FirstInsert =
5562             cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
5563               return !is_contained(E->Scalars,
5564                                    cast<Instruction>(V)->getOperand(0));
5565             }));
5566         if (isUndefVector(FirstInsert->getOperand(0))) {
5567           Cost += TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, SrcVecTy, Mask);
5568         } else {
5569           SmallVector<int> InsertMask(NumElts);
5570           std::iota(InsertMask.begin(), InsertMask.end(), 0);
5571           for (unsigned I = 0; I < NumElts; I++) {
5572             if (Mask[I] != UndefMaskElem)
5573               InsertMask[Offset + I] = NumElts + I;
5574           }
5575           Cost +=
5576               TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVecTy, InsertMask);
5577         }
5578       }
5579 
5580       return Cost;
5581     }
5582     case Instruction::ZExt:
5583     case Instruction::SExt:
5584     case Instruction::FPToUI:
5585     case Instruction::FPToSI:
5586     case Instruction::FPExt:
5587     case Instruction::PtrToInt:
5588     case Instruction::IntToPtr:
5589     case Instruction::SIToFP:
5590     case Instruction::UIToFP:
5591     case Instruction::Trunc:
5592     case Instruction::FPTrunc:
5593     case Instruction::BitCast: {
5594       Type *SrcTy = VL0->getOperand(0)->getType();
5595       InstructionCost ScalarEltCost =
5596           TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy,
5597                                 TTI::getCastContextHint(VL0), CostKind, VL0);
5598       if (NeedToShuffleReuses) {
5599         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5600       }
5601 
5602       // Calculate the cost of this instruction.
5603       InstructionCost ScalarCost = VL.size() * ScalarEltCost;
5604 
5605       auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size());
5606       InstructionCost VecCost = 0;
5607       // Check if the values are candidates to demote.
5608       if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
5609         VecCost = CommonCost + TTI->getCastInstrCost(
5610                                    E->getOpcode(), VecTy, SrcVecTy,
5611                                    TTI::getCastContextHint(VL0), CostKind, VL0);
5612       }
5613       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5614       return VecCost - ScalarCost;
5615     }
5616     case Instruction::FCmp:
5617     case Instruction::ICmp:
5618     case Instruction::Select: {
5619       // Calculate the cost of this instruction.
5620       InstructionCost ScalarEltCost =
5621           TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5622                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0);
5623       if (NeedToShuffleReuses) {
5624         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5625       }
5626       auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size());
5627       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5628 
5629       // Check if all entries in VL are either compares or selects with compares
5630       // as condition that have the same predicates.
5631       CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE;
5632       bool First = true;
5633       for (auto *V : VL) {
5634         CmpInst::Predicate CurrentPred;
5635         auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value());
5636         if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) &&
5637              !match(V, MatchCmp)) ||
5638             (!First && VecPred != CurrentPred)) {
5639           VecPred = CmpInst::BAD_ICMP_PREDICATE;
5640           break;
5641         }
5642         First = false;
5643         VecPred = CurrentPred;
5644       }
5645 
5646       InstructionCost VecCost = TTI->getCmpSelInstrCost(
5647           E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0);
5648       // Check if it is possible and profitable to use min/max for selects in
5649       // VL.
5650       //
5651       auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL);
5652       if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) {
5653         IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy,
5654                                           {VecTy, VecTy});
5655         InstructionCost IntrinsicCost =
5656             TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5657         // If the selects are the only uses of the compares, they will be dead
5658         // and we can adjust the cost by removing their cost.
5659         if (IntrinsicAndUse.second)
5660           IntrinsicCost -= TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy,
5661                                                    MaskTy, VecPred, CostKind);
5662         VecCost = std::min(VecCost, IntrinsicCost);
5663       }
5664       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5665       return CommonCost + VecCost - ScalarCost;
5666     }
5667     case Instruction::FNeg:
5668     case Instruction::Add:
5669     case Instruction::FAdd:
5670     case Instruction::Sub:
5671     case Instruction::FSub:
5672     case Instruction::Mul:
5673     case Instruction::FMul:
5674     case Instruction::UDiv:
5675     case Instruction::SDiv:
5676     case Instruction::FDiv:
5677     case Instruction::URem:
5678     case Instruction::SRem:
5679     case Instruction::FRem:
5680     case Instruction::Shl:
5681     case Instruction::LShr:
5682     case Instruction::AShr:
5683     case Instruction::And:
5684     case Instruction::Or:
5685     case Instruction::Xor: {
5686       // Certain instructions can be cheaper to vectorize if they have a
5687       // constant second vector operand.
5688       TargetTransformInfo::OperandValueKind Op1VK =
5689           TargetTransformInfo::OK_AnyValue;
5690       TargetTransformInfo::OperandValueKind Op2VK =
5691           TargetTransformInfo::OK_UniformConstantValue;
5692       TargetTransformInfo::OperandValueProperties Op1VP =
5693           TargetTransformInfo::OP_None;
5694       TargetTransformInfo::OperandValueProperties Op2VP =
5695           TargetTransformInfo::OP_PowerOf2;
5696 
5697       // If all operands are exactly the same ConstantInt then set the
5698       // operand kind to OK_UniformConstantValue.
5699       // If instead not all operands are constants, then set the operand kind
5700       // to OK_AnyValue. If all operands are constants but not the same,
5701       // then set the operand kind to OK_NonUniformConstantValue.
5702       ConstantInt *CInt0 = nullptr;
5703       for (unsigned i = 0, e = VL.size(); i < e; ++i) {
5704         const Instruction *I = cast<Instruction>(VL[i]);
5705         unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0;
5706         ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx));
5707         if (!CInt) {
5708           Op2VK = TargetTransformInfo::OK_AnyValue;
5709           Op2VP = TargetTransformInfo::OP_None;
5710           break;
5711         }
5712         if (Op2VP == TargetTransformInfo::OP_PowerOf2 &&
5713             !CInt->getValue().isPowerOf2())
5714           Op2VP = TargetTransformInfo::OP_None;
5715         if (i == 0) {
5716           CInt0 = CInt;
5717           continue;
5718         }
5719         if (CInt0 != CInt)
5720           Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5721       }
5722 
5723       SmallVector<const Value *, 4> Operands(VL0->operand_values());
5724       InstructionCost ScalarEltCost =
5725           TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK,
5726                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5727       if (NeedToShuffleReuses) {
5728         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5729       }
5730       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5731       InstructionCost VecCost =
5732           TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK,
5733                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5734       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5735       return CommonCost + VecCost - ScalarCost;
5736     }
5737     case Instruction::GetElementPtr: {
5738       TargetTransformInfo::OperandValueKind Op1VK =
5739           TargetTransformInfo::OK_AnyValue;
5740       TargetTransformInfo::OperandValueKind Op2VK =
5741           TargetTransformInfo::OK_UniformConstantValue;
5742 
5743       InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost(
5744           Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK);
5745       if (NeedToShuffleReuses) {
5746         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5747       }
5748       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5749       InstructionCost VecCost = TTI->getArithmeticInstrCost(
5750           Instruction::Add, VecTy, CostKind, Op1VK, Op2VK);
5751       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5752       return CommonCost + VecCost - ScalarCost;
5753     }
5754     case Instruction::Load: {
5755       // Cost of wide load - cost of scalar loads.
5756       Align Alignment = cast<LoadInst>(VL0)->getAlign();
5757       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5758           Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0);
5759       if (NeedToShuffleReuses) {
5760         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5761       }
5762       InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost;
5763       InstructionCost VecLdCost;
5764       if (E->State == TreeEntry::Vectorize) {
5765         VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0,
5766                                          CostKind, VL0);
5767       } else {
5768         assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState");
5769         Align CommonAlignment = Alignment;
5770         for (Value *V : VL)
5771           CommonAlignment =
5772               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
5773         VecLdCost = TTI->getGatherScatterOpCost(
5774             Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(),
5775             /*VariableMask=*/false, CommonAlignment, CostKind, VL0);
5776       }
5777       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost));
5778       return CommonCost + VecLdCost - ScalarLdCost;
5779     }
5780     case Instruction::Store: {
5781       // We know that we can merge the stores. Calculate the cost.
5782       bool IsReorder = !E->ReorderIndices.empty();
5783       auto *SI =
5784           cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0);
5785       Align Alignment = SI->getAlign();
5786       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5787           Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0);
5788       InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost;
5789       InstructionCost VecStCost = TTI->getMemoryOpCost(
5790           Instruction::Store, VecTy, Alignment, 0, CostKind, VL0);
5791       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost));
5792       return CommonCost + VecStCost - ScalarStCost;
5793     }
5794     case Instruction::Call: {
5795       CallInst *CI = cast<CallInst>(VL0);
5796       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5797 
5798       // Calculate the cost of the scalar and vector calls.
5799       IntrinsicCostAttributes CostAttrs(ID, *CI, 1);
5800       InstructionCost ScalarEltCost =
5801           TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5802       if (NeedToShuffleReuses) {
5803         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5804       }
5805       InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
5806 
5807       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
5808       InstructionCost VecCallCost =
5809           std::min(VecCallCosts.first, VecCallCosts.second);
5810 
5811       LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
5812                         << " (" << VecCallCost << "-" << ScalarCallCost << ")"
5813                         << " for " << *CI << "\n");
5814 
5815       return CommonCost + VecCallCost - ScalarCallCost;
5816     }
5817     case Instruction::ShuffleVector: {
5818       assert(E->isAltShuffle() &&
5819              ((Instruction::isBinaryOp(E->getOpcode()) &&
5820                Instruction::isBinaryOp(E->getAltOpcode())) ||
5821               (Instruction::isCast(E->getOpcode()) &&
5822                Instruction::isCast(E->getAltOpcode())) ||
5823               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
5824              "Invalid Shuffle Vector Operand");
5825       InstructionCost ScalarCost = 0;
5826       if (NeedToShuffleReuses) {
5827         for (unsigned Idx : E->ReuseShuffleIndices) {
5828           Instruction *I = cast<Instruction>(VL[Idx]);
5829           CommonCost -= TTI->getInstructionCost(I, CostKind);
5830         }
5831         for (Value *V : VL) {
5832           Instruction *I = cast<Instruction>(V);
5833           CommonCost += TTI->getInstructionCost(I, CostKind);
5834         }
5835       }
5836       for (Value *V : VL) {
5837         Instruction *I = cast<Instruction>(V);
5838         assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5839         ScalarCost += TTI->getInstructionCost(I, CostKind);
5840       }
5841       // VecCost is equal to sum of the cost of creating 2 vectors
5842       // and the cost of creating shuffle.
5843       InstructionCost VecCost = 0;
5844       // Try to find the previous shuffle node with the same operands and same
5845       // main/alternate ops.
5846       auto &&TryFindNodeWithEqualOperands = [this, E]() {
5847         for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
5848           if (TE.get() == E)
5849             break;
5850           if (TE->isAltShuffle() &&
5851               ((TE->getOpcode() == E->getOpcode() &&
5852                 TE->getAltOpcode() == E->getAltOpcode()) ||
5853                (TE->getOpcode() == E->getAltOpcode() &&
5854                 TE->getAltOpcode() == E->getOpcode())) &&
5855               TE->hasEqualOperands(*E))
5856             return true;
5857         }
5858         return false;
5859       };
5860       if (TryFindNodeWithEqualOperands()) {
5861         LLVM_DEBUG({
5862           dbgs() << "SLP: diamond match for alternate node found.\n";
5863           E->dump();
5864         });
5865         // No need to add new vector costs here since we're going to reuse
5866         // same main/alternate vector ops, just do different shuffling.
5867       } else if (Instruction::isBinaryOp(E->getOpcode())) {
5868         VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind);
5869         VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy,
5870                                                CostKind);
5871       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
5872         VecCost = TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy,
5873                                           Builder.getInt1Ty(),
5874                                           CI0->getPredicate(), CostKind, VL0);
5875         VecCost += TTI->getCmpSelInstrCost(
5876             E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5877             cast<CmpInst>(E->getAltOp())->getPredicate(), CostKind,
5878             E->getAltOp());
5879       } else {
5880         Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
5881         Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
5882         auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size());
5883         auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size());
5884         VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty,
5885                                         TTI::CastContextHint::None, CostKind);
5886         VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty,
5887                                          TTI::CastContextHint::None, CostKind);
5888       }
5889 
5890       SmallVector<int> Mask;
5891       buildShuffleEntryMask(
5892           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
5893           [E](Instruction *I) {
5894             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5895             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
5896           },
5897           Mask);
5898       CommonCost =
5899           TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy, Mask);
5900       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5901       return CommonCost + VecCost - ScalarCost;
5902     }
5903     default:
5904       llvm_unreachable("Unknown instruction");
5905   }
5906 }
5907 
5908 bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const {
5909   LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
5910                     << VectorizableTree.size() << " is fully vectorizable .\n");
5911 
5912   auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) {
5913     SmallVector<int> Mask;
5914     return TE->State == TreeEntry::NeedToGather &&
5915            !any_of(TE->Scalars,
5916                    [this](Value *V) { return EphValues.contains(V); }) &&
5917            (allConstant(TE->Scalars) || isSplat(TE->Scalars) ||
5918             TE->Scalars.size() < Limit ||
5919             ((TE->getOpcode() == Instruction::ExtractElement ||
5920               all_of(TE->Scalars,
5921                      [](Value *V) {
5922                        return isa<ExtractElementInst, UndefValue>(V);
5923                      })) &&
5924              isFixedVectorShuffle(TE->Scalars, Mask)) ||
5925             (TE->State == TreeEntry::NeedToGather &&
5926              TE->getOpcode() == Instruction::Load && !TE->isAltShuffle()));
5927   };
5928 
5929   // We only handle trees of heights 1 and 2.
5930   if (VectorizableTree.size() == 1 &&
5931       (VectorizableTree[0]->State == TreeEntry::Vectorize ||
5932        (ForReduction &&
5933         AreVectorizableGathers(VectorizableTree[0].get(),
5934                                VectorizableTree[0]->Scalars.size()) &&
5935         VectorizableTree[0]->getVectorFactor() > 2)))
5936     return true;
5937 
5938   if (VectorizableTree.size() != 2)
5939     return false;
5940 
5941   // Handle splat and all-constants stores. Also try to vectorize tiny trees
5942   // with the second gather nodes if they have less scalar operands rather than
5943   // the initial tree element (may be profitable to shuffle the second gather)
5944   // or they are extractelements, which form shuffle.
5945   SmallVector<int> Mask;
5946   if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
5947       AreVectorizableGathers(VectorizableTree[1].get(),
5948                              VectorizableTree[0]->Scalars.size()))
5949     return true;
5950 
5951   // Gathering cost would be too much for tiny trees.
5952   if (VectorizableTree[0]->State == TreeEntry::NeedToGather ||
5953       (VectorizableTree[1]->State == TreeEntry::NeedToGather &&
5954        VectorizableTree[0]->State != TreeEntry::ScatterVectorize))
5955     return false;
5956 
5957   return true;
5958 }
5959 
5960 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts,
5961                                        TargetTransformInfo *TTI,
5962                                        bool MustMatchOrInst) {
5963   // Look past the root to find a source value. Arbitrarily follow the
5964   // path through operand 0 of any 'or'. Also, peek through optional
5965   // shift-left-by-multiple-of-8-bits.
5966   Value *ZextLoad = Root;
5967   const APInt *ShAmtC;
5968   bool FoundOr = false;
5969   while (!isa<ConstantExpr>(ZextLoad) &&
5970          (match(ZextLoad, m_Or(m_Value(), m_Value())) ||
5971           (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) &&
5972            ShAmtC->urem(8) == 0))) {
5973     auto *BinOp = cast<BinaryOperator>(ZextLoad);
5974     ZextLoad = BinOp->getOperand(0);
5975     if (BinOp->getOpcode() == Instruction::Or)
5976       FoundOr = true;
5977   }
5978   // Check if the input is an extended load of the required or/shift expression.
5979   Value *Load;
5980   if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root ||
5981       !match(ZextLoad, m_ZExt(m_Value(Load))) || !isa<LoadInst>(Load))
5982     return false;
5983 
5984   // Require that the total load bit width is a legal integer type.
5985   // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
5986   // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
5987   Type *SrcTy = Load->getType();
5988   unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts;
5989   if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth)))
5990     return false;
5991 
5992   // Everything matched - assume that we can fold the whole sequence using
5993   // load combining.
5994   LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "
5995              << *(cast<Instruction>(Root)) << "\n");
5996 
5997   return true;
5998 }
5999 
6000 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const {
6001   if (RdxKind != RecurKind::Or)
6002     return false;
6003 
6004   unsigned NumElts = VectorizableTree[0]->Scalars.size();
6005   Value *FirstReduced = VectorizableTree[0]->Scalars[0];
6006   return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI,
6007                                     /* MatchOr */ false);
6008 }
6009 
6010 bool BoUpSLP::isLoadCombineCandidate() const {
6011   // Peek through a final sequence of stores and check if all operations are
6012   // likely to be load-combined.
6013   unsigned NumElts = VectorizableTree[0]->Scalars.size();
6014   for (Value *Scalar : VectorizableTree[0]->Scalars) {
6015     Value *X;
6016     if (!match(Scalar, m_Store(m_Value(X), m_Value())) ||
6017         !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true))
6018       return false;
6019   }
6020   return true;
6021 }
6022 
6023 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const {
6024   // No need to vectorize inserts of gathered values.
6025   if (VectorizableTree.size() == 2 &&
6026       isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) &&
6027       VectorizableTree[1]->State == TreeEntry::NeedToGather)
6028     return true;
6029 
6030   // We can vectorize the tree if its size is greater than or equal to the
6031   // minimum size specified by the MinTreeSize command line option.
6032   if (VectorizableTree.size() >= MinTreeSize)
6033     return false;
6034 
6035   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
6036   // can vectorize it if we can prove it fully vectorizable.
6037   if (isFullyVectorizableTinyTree(ForReduction))
6038     return false;
6039 
6040   assert(VectorizableTree.empty()
6041              ? ExternalUses.empty()
6042              : true && "We shouldn't have any external users");
6043 
6044   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
6045   // vectorizable.
6046   return true;
6047 }
6048 
6049 InstructionCost BoUpSLP::getSpillCost() const {
6050   // Walk from the bottom of the tree to the top, tracking which values are
6051   // live. When we see a call instruction that is not part of our tree,
6052   // query TTI to see if there is a cost to keeping values live over it
6053   // (for example, if spills and fills are required).
6054   unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
6055   InstructionCost Cost = 0;
6056 
6057   SmallPtrSet<Instruction*, 4> LiveValues;
6058   Instruction *PrevInst = nullptr;
6059 
6060   // The entries in VectorizableTree are not necessarily ordered by their
6061   // position in basic blocks. Collect them and order them by dominance so later
6062   // instructions are guaranteed to be visited first. For instructions in
6063   // different basic blocks, we only scan to the beginning of the block, so
6064   // their order does not matter, as long as all instructions in a basic block
6065   // are grouped together. Using dominance ensures a deterministic order.
6066   SmallVector<Instruction *, 16> OrderedScalars;
6067   for (const auto &TEPtr : VectorizableTree) {
6068     Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
6069     if (!Inst)
6070       continue;
6071     OrderedScalars.push_back(Inst);
6072   }
6073   llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) {
6074     auto *NodeA = DT->getNode(A->getParent());
6075     auto *NodeB = DT->getNode(B->getParent());
6076     assert(NodeA && "Should only process reachable instructions");
6077     assert(NodeB && "Should only process reachable instructions");
6078     assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
6079            "Different nodes should have different DFS numbers");
6080     if (NodeA != NodeB)
6081       return NodeA->getDFSNumIn() < NodeB->getDFSNumIn();
6082     return B->comesBefore(A);
6083   });
6084 
6085   for (Instruction *Inst : OrderedScalars) {
6086     if (!PrevInst) {
6087       PrevInst = Inst;
6088       continue;
6089     }
6090 
6091     // Update LiveValues.
6092     LiveValues.erase(PrevInst);
6093     for (auto &J : PrevInst->operands()) {
6094       if (isa<Instruction>(&*J) && getTreeEntry(&*J))
6095         LiveValues.insert(cast<Instruction>(&*J));
6096     }
6097 
6098     LLVM_DEBUG({
6099       dbgs() << "SLP: #LV: " << LiveValues.size();
6100       for (auto *X : LiveValues)
6101         dbgs() << " " << X->getName();
6102       dbgs() << ", Looking at ";
6103       Inst->dump();
6104     });
6105 
6106     // Now find the sequence of instructions between PrevInst and Inst.
6107     unsigned NumCalls = 0;
6108     BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
6109                                  PrevInstIt =
6110                                      PrevInst->getIterator().getReverse();
6111     while (InstIt != PrevInstIt) {
6112       if (PrevInstIt == PrevInst->getParent()->rend()) {
6113         PrevInstIt = Inst->getParent()->rbegin();
6114         continue;
6115       }
6116 
6117       // Debug information does not impact spill cost.
6118       if ((isa<CallInst>(&*PrevInstIt) &&
6119            !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
6120           &*PrevInstIt != PrevInst)
6121         NumCalls++;
6122 
6123       ++PrevInstIt;
6124     }
6125 
6126     if (NumCalls) {
6127       SmallVector<Type*, 4> V;
6128       for (auto *II : LiveValues) {
6129         auto *ScalarTy = II->getType();
6130         if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy))
6131           ScalarTy = VectorTy->getElementType();
6132         V.push_back(FixedVectorType::get(ScalarTy, BundleWidth));
6133       }
6134       Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
6135     }
6136 
6137     PrevInst = Inst;
6138   }
6139 
6140   return Cost;
6141 }
6142 
6143 /// Check if two insertelement instructions are from the same buildvector.
6144 static bool areTwoInsertFromSameBuildVector(InsertElementInst *VU,
6145                                             InsertElementInst *V) {
6146   // Instructions must be from the same basic blocks.
6147   if (VU->getParent() != V->getParent())
6148     return false;
6149   // Checks if 2 insertelements are from the same buildvector.
6150   if (VU->getType() != V->getType())
6151     return false;
6152   // Multiple used inserts are separate nodes.
6153   if (!VU->hasOneUse() && !V->hasOneUse())
6154     return false;
6155   auto *IE1 = VU;
6156   auto *IE2 = V;
6157   // Go through the vector operand of insertelement instructions trying to find
6158   // either VU as the original vector for IE2 or V as the original vector for
6159   // IE1.
6160   do {
6161     if (IE2 == VU || IE1 == V)
6162       return true;
6163     if (IE1) {
6164       if (IE1 != VU && !IE1->hasOneUse())
6165         IE1 = nullptr;
6166       else
6167         IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0));
6168     }
6169     if (IE2) {
6170       if (IE2 != V && !IE2->hasOneUse())
6171         IE2 = nullptr;
6172       else
6173         IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0));
6174     }
6175   } while (IE1 || IE2);
6176   return false;
6177 }
6178 
6179 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) {
6180   InstructionCost Cost = 0;
6181   LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
6182                     << VectorizableTree.size() << ".\n");
6183 
6184   unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
6185 
6186   for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
6187     TreeEntry &TE = *VectorizableTree[I];
6188 
6189     InstructionCost C = getEntryCost(&TE, VectorizedVals);
6190     Cost += C;
6191     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6192                       << " for bundle that starts with " << *TE.Scalars[0]
6193                       << ".\n"
6194                       << "SLP: Current total cost = " << Cost << "\n");
6195   }
6196 
6197   SmallPtrSet<Value *, 16> ExtractCostCalculated;
6198   InstructionCost ExtractCost = 0;
6199   SmallVector<unsigned> VF;
6200   SmallVector<SmallVector<int>> ShuffleMask;
6201   SmallVector<Value *> FirstUsers;
6202   SmallVector<APInt> DemandedElts;
6203   for (ExternalUser &EU : ExternalUses) {
6204     // We only add extract cost once for the same scalar.
6205     if (!isa_and_nonnull<InsertElementInst>(EU.User) &&
6206         !ExtractCostCalculated.insert(EU.Scalar).second)
6207       continue;
6208 
6209     // Uses by ephemeral values are free (because the ephemeral value will be
6210     // removed prior to code generation, and so the extraction will be
6211     // removed as well).
6212     if (EphValues.count(EU.User))
6213       continue;
6214 
6215     // No extract cost for vector "scalar"
6216     if (isa<FixedVectorType>(EU.Scalar->getType()))
6217       continue;
6218 
6219     // Already counted the cost for external uses when tried to adjust the cost
6220     // for extractelements, no need to add it again.
6221     if (isa<ExtractElementInst>(EU.Scalar))
6222       continue;
6223 
6224     // If found user is an insertelement, do not calculate extract cost but try
6225     // to detect it as a final shuffled/identity match.
6226     if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) {
6227       if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) {
6228         Optional<unsigned> InsertIdx = getInsertIndex(VU);
6229         if (InsertIdx) {
6230           auto *It = find_if(FirstUsers, [VU](Value *V) {
6231             return areTwoInsertFromSameBuildVector(VU,
6232                                                    cast<InsertElementInst>(V));
6233           });
6234           int VecId = -1;
6235           if (It == FirstUsers.end()) {
6236             VF.push_back(FTy->getNumElements());
6237             ShuffleMask.emplace_back(VF.back(), UndefMaskElem);
6238             // Find the insertvector, vectorized in tree, if any.
6239             Value *Base = VU;
6240             while (isa<InsertElementInst>(Base)) {
6241               // Build the mask for the vectorized insertelement instructions.
6242               if (const TreeEntry *E = getTreeEntry(Base)) {
6243                 VU = cast<InsertElementInst>(Base);
6244                 do {
6245                   int Idx = E->findLaneForValue(Base);
6246                   ShuffleMask.back()[Idx] = Idx;
6247                   Base = cast<InsertElementInst>(Base)->getOperand(0);
6248                 } while (E == getTreeEntry(Base));
6249                 break;
6250               }
6251               Base = cast<InsertElementInst>(Base)->getOperand(0);
6252             }
6253             FirstUsers.push_back(VU);
6254             DemandedElts.push_back(APInt::getZero(VF.back()));
6255             VecId = FirstUsers.size() - 1;
6256           } else {
6257             VecId = std::distance(FirstUsers.begin(), It);
6258           }
6259           ShuffleMask[VecId][*InsertIdx] = EU.Lane;
6260           DemandedElts[VecId].setBit(*InsertIdx);
6261           continue;
6262         }
6263       }
6264     }
6265 
6266     // If we plan to rewrite the tree in a smaller type, we will need to sign
6267     // extend the extracted value back to the original type. Here, we account
6268     // for the extract and the added cost of the sign extend if needed.
6269     auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth);
6270     auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
6271     if (MinBWs.count(ScalarRoot)) {
6272       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
6273       auto Extend =
6274           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
6275       VecTy = FixedVectorType::get(MinTy, BundleWidth);
6276       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
6277                                                    VecTy, EU.Lane);
6278     } else {
6279       ExtractCost +=
6280           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
6281     }
6282   }
6283 
6284   InstructionCost SpillCost = getSpillCost();
6285   Cost += SpillCost + ExtractCost;
6286   if (FirstUsers.size() == 1) {
6287     int Limit = ShuffleMask.front().size() * 2;
6288     if (all_of(ShuffleMask.front(), [Limit](int Idx) { return Idx < Limit; }) &&
6289         !ShuffleVectorInst::isIdentityMask(ShuffleMask.front())) {
6290       InstructionCost C = TTI->getShuffleCost(
6291           TTI::SK_PermuteSingleSrc,
6292           cast<FixedVectorType>(FirstUsers.front()->getType()),
6293           ShuffleMask.front());
6294       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6295                         << " for final shuffle of insertelement external users "
6296                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6297                         << "SLP: Current total cost = " << Cost << "\n");
6298       Cost += C;
6299     }
6300     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6301         cast<FixedVectorType>(FirstUsers.front()->getType()),
6302         DemandedElts.front(), /*Insert*/ true, /*Extract*/ false);
6303     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6304                       << " for insertelements gather.\n"
6305                       << "SLP: Current total cost = " << Cost << "\n");
6306     Cost -= InsertCost;
6307   } else if (FirstUsers.size() >= 2) {
6308     unsigned MaxVF = *std::max_element(VF.begin(), VF.end());
6309     // Combined masks of the first 2 vectors.
6310     SmallVector<int> CombinedMask(MaxVF, UndefMaskElem);
6311     copy(ShuffleMask.front(), CombinedMask.begin());
6312     APInt CombinedDemandedElts = DemandedElts.front().zextOrSelf(MaxVF);
6313     auto *VecTy = FixedVectorType::get(
6314         cast<VectorType>(FirstUsers.front()->getType())->getElementType(),
6315         MaxVF);
6316     for (int I = 0, E = ShuffleMask[1].size(); I < E; ++I) {
6317       if (ShuffleMask[1][I] != UndefMaskElem) {
6318         CombinedMask[I] = ShuffleMask[1][I] + MaxVF;
6319         CombinedDemandedElts.setBit(I);
6320       }
6321     }
6322     InstructionCost C =
6323         TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6324     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6325                       << " for final shuffle of vector node and external "
6326                          "insertelement users "
6327                       << *VectorizableTree.front()->Scalars.front() << ".\n"
6328                       << "SLP: Current total cost = " << Cost << "\n");
6329     Cost += C;
6330     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6331         VecTy, CombinedDemandedElts, /*Insert*/ true, /*Extract*/ false);
6332     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6333                       << " for insertelements gather.\n"
6334                       << "SLP: Current total cost = " << Cost << "\n");
6335     Cost -= InsertCost;
6336     for (int I = 2, E = FirstUsers.size(); I < E; ++I) {
6337       // Other elements - permutation of 2 vectors (the initial one and the
6338       // next Ith incoming vector).
6339       unsigned VF = ShuffleMask[I].size();
6340       for (unsigned Idx = 0; Idx < VF; ++Idx) {
6341         int Mask = ShuffleMask[I][Idx];
6342         if (Mask != UndefMaskElem)
6343           CombinedMask[Idx] = MaxVF + Mask;
6344         else if (CombinedMask[Idx] != UndefMaskElem)
6345           CombinedMask[Idx] = Idx;
6346       }
6347       for (unsigned Idx = VF; Idx < MaxVF; ++Idx)
6348         if (CombinedMask[Idx] != UndefMaskElem)
6349           CombinedMask[Idx] = Idx;
6350       InstructionCost C =
6351           TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6352       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6353                         << " for final shuffle of vector node and external "
6354                            "insertelement users "
6355                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6356                         << "SLP: Current total cost = " << Cost << "\n");
6357       Cost += C;
6358       InstructionCost InsertCost = TTI->getScalarizationOverhead(
6359           cast<FixedVectorType>(FirstUsers[I]->getType()), DemandedElts[I],
6360           /*Insert*/ true, /*Extract*/ false);
6361       LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6362                         << " for insertelements gather.\n"
6363                         << "SLP: Current total cost = " << Cost << "\n");
6364       Cost -= InsertCost;
6365     }
6366   }
6367 
6368 #ifndef NDEBUG
6369   SmallString<256> Str;
6370   {
6371     raw_svector_ostream OS(Str);
6372     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
6373        << "SLP: Extract Cost = " << ExtractCost << ".\n"
6374        << "SLP: Total Cost = " << Cost << ".\n";
6375   }
6376   LLVM_DEBUG(dbgs() << Str);
6377   if (ViewSLPTree)
6378     ViewGraph(this, "SLP" + F->getName(), false, Str);
6379 #endif
6380 
6381   return Cost;
6382 }
6383 
6384 Optional<TargetTransformInfo::ShuffleKind>
6385 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
6386                                SmallVectorImpl<const TreeEntry *> &Entries) {
6387   // TODO: currently checking only for Scalars in the tree entry, need to count
6388   // reused elements too for better cost estimation.
6389   Mask.assign(TE->Scalars.size(), UndefMaskElem);
6390   Entries.clear();
6391   // Build a lists of values to tree entries.
6392   DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs;
6393   for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) {
6394     if (EntryPtr.get() == TE)
6395       break;
6396     if (EntryPtr->State != TreeEntry::NeedToGather)
6397       continue;
6398     for (Value *V : EntryPtr->Scalars)
6399       ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get());
6400   }
6401   // Find all tree entries used by the gathered values. If no common entries
6402   // found - not a shuffle.
6403   // Here we build a set of tree nodes for each gathered value and trying to
6404   // find the intersection between these sets. If we have at least one common
6405   // tree node for each gathered value - we have just a permutation of the
6406   // single vector. If we have 2 different sets, we're in situation where we
6407   // have a permutation of 2 input vectors.
6408   SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs;
6409   DenseMap<Value *, int> UsedValuesEntry;
6410   for (Value *V : TE->Scalars) {
6411     if (isa<UndefValue>(V))
6412       continue;
6413     // Build a list of tree entries where V is used.
6414     SmallPtrSet<const TreeEntry *, 4> VToTEs;
6415     auto It = ValueToTEs.find(V);
6416     if (It != ValueToTEs.end())
6417       VToTEs = It->second;
6418     if (const TreeEntry *VTE = getTreeEntry(V))
6419       VToTEs.insert(VTE);
6420     if (VToTEs.empty())
6421       return None;
6422     if (UsedTEs.empty()) {
6423       // The first iteration, just insert the list of nodes to vector.
6424       UsedTEs.push_back(VToTEs);
6425     } else {
6426       // Need to check if there are any previously used tree nodes which use V.
6427       // If there are no such nodes, consider that we have another one input
6428       // vector.
6429       SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs);
6430       unsigned Idx = 0;
6431       for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) {
6432         // Do we have a non-empty intersection of previously listed tree entries
6433         // and tree entries using current V?
6434         set_intersect(VToTEs, Set);
6435         if (!VToTEs.empty()) {
6436           // Yes, write the new subset and continue analysis for the next
6437           // scalar.
6438           Set.swap(VToTEs);
6439           break;
6440         }
6441         VToTEs = SavedVToTEs;
6442         ++Idx;
6443       }
6444       // No non-empty intersection found - need to add a second set of possible
6445       // source vectors.
6446       if (Idx == UsedTEs.size()) {
6447         // If the number of input vectors is greater than 2 - not a permutation,
6448         // fallback to the regular gather.
6449         if (UsedTEs.size() == 2)
6450           return None;
6451         UsedTEs.push_back(SavedVToTEs);
6452         Idx = UsedTEs.size() - 1;
6453       }
6454       UsedValuesEntry.try_emplace(V, Idx);
6455     }
6456   }
6457 
6458   if (UsedTEs.empty()) {
6459     assert(all_of(TE->Scalars, UndefValue::classof) &&
6460            "Expected vector of undefs only.");
6461     return None;
6462   }
6463 
6464   unsigned VF = 0;
6465   if (UsedTEs.size() == 1) {
6466     // Try to find the perfect match in another gather node at first.
6467     auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) {
6468       return EntryPtr->isSame(TE->Scalars);
6469     });
6470     if (It != UsedTEs.front().end()) {
6471       Entries.push_back(*It);
6472       std::iota(Mask.begin(), Mask.end(), 0);
6473       return TargetTransformInfo::SK_PermuteSingleSrc;
6474     }
6475     // No perfect match, just shuffle, so choose the first tree node.
6476     Entries.push_back(*UsedTEs.front().begin());
6477   } else {
6478     // Try to find nodes with the same vector factor.
6479     assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries.");
6480     DenseMap<int, const TreeEntry *> VFToTE;
6481     for (const TreeEntry *TE : UsedTEs.front())
6482       VFToTE.try_emplace(TE->getVectorFactor(), TE);
6483     for (const TreeEntry *TE : UsedTEs.back()) {
6484       auto It = VFToTE.find(TE->getVectorFactor());
6485       if (It != VFToTE.end()) {
6486         VF = It->first;
6487         Entries.push_back(It->second);
6488         Entries.push_back(TE);
6489         break;
6490       }
6491     }
6492     // No 2 source vectors with the same vector factor - give up and do regular
6493     // gather.
6494     if (Entries.empty())
6495       return None;
6496   }
6497 
6498   // Build a shuffle mask for better cost estimation and vector emission.
6499   for (int I = 0, E = TE->Scalars.size(); I < E; ++I) {
6500     Value *V = TE->Scalars[I];
6501     if (isa<UndefValue>(V))
6502       continue;
6503     unsigned Idx = UsedValuesEntry.lookup(V);
6504     const TreeEntry *VTE = Entries[Idx];
6505     int FoundLane = VTE->findLaneForValue(V);
6506     Mask[I] = Idx * VF + FoundLane;
6507     // Extra check required by isSingleSourceMaskImpl function (called by
6508     // ShuffleVectorInst::isSingleSourceMask).
6509     if (Mask[I] >= 2 * E)
6510       return None;
6511   }
6512   switch (Entries.size()) {
6513   case 1:
6514     return TargetTransformInfo::SK_PermuteSingleSrc;
6515   case 2:
6516     return TargetTransformInfo::SK_PermuteTwoSrc;
6517   default:
6518     break;
6519   }
6520   return None;
6521 }
6522 
6523 InstructionCost BoUpSLP::getGatherCost(FixedVectorType *Ty,
6524                                        const APInt &ShuffledIndices,
6525                                        bool NeedToShuffle) const {
6526   InstructionCost Cost =
6527       TTI->getScalarizationOverhead(Ty, ~ShuffledIndices, /*Insert*/ true,
6528                                     /*Extract*/ false);
6529   if (NeedToShuffle)
6530     Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
6531   return Cost;
6532 }
6533 
6534 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
6535   // Find the type of the operands in VL.
6536   Type *ScalarTy = VL[0]->getType();
6537   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
6538     ScalarTy = SI->getValueOperand()->getType();
6539   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
6540   bool DuplicateNonConst = false;
6541   // Find the cost of inserting/extracting values from the vector.
6542   // Check if the same elements are inserted several times and count them as
6543   // shuffle candidates.
6544   APInt ShuffledElements = APInt::getZero(VL.size());
6545   DenseSet<Value *> UniqueElements;
6546   // Iterate in reverse order to consider insert elements with the high cost.
6547   for (unsigned I = VL.size(); I > 0; --I) {
6548     unsigned Idx = I - 1;
6549     // No need to shuffle duplicates for constants.
6550     if (isConstant(VL[Idx])) {
6551       ShuffledElements.setBit(Idx);
6552       continue;
6553     }
6554     if (!UniqueElements.insert(VL[Idx]).second) {
6555       DuplicateNonConst = true;
6556       ShuffledElements.setBit(Idx);
6557     }
6558   }
6559   return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst);
6560 }
6561 
6562 // Perform operand reordering on the instructions in VL and return the reordered
6563 // operands in Left and Right.
6564 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
6565                                              SmallVectorImpl<Value *> &Left,
6566                                              SmallVectorImpl<Value *> &Right,
6567                                              const DataLayout &DL,
6568                                              ScalarEvolution &SE,
6569                                              const BoUpSLP &R) {
6570   if (VL.empty())
6571     return;
6572   VLOperands Ops(VL, DL, SE, R);
6573   // Reorder the operands in place.
6574   Ops.reorder();
6575   Left = Ops.getVL(0);
6576   Right = Ops.getVL(1);
6577 }
6578 
6579 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) {
6580   // Get the basic block this bundle is in. All instructions in the bundle
6581   // should be in this block.
6582   auto *Front = E->getMainOp();
6583   auto *BB = Front->getParent();
6584   assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool {
6585     auto *I = cast<Instruction>(V);
6586     return !E->isOpcodeOrAlt(I) || I->getParent() == BB;
6587   }));
6588 
6589   auto &&FindLastInst = [E, Front]() {
6590     Instruction *LastInst = Front;
6591     for (Value *V : E->Scalars) {
6592       auto *I = dyn_cast<Instruction>(V);
6593       if (!I)
6594         continue;
6595       if (LastInst->comesBefore(I))
6596         LastInst = I;
6597     }
6598     return LastInst;
6599   };
6600 
6601   auto &&FindFirstInst = [E, Front]() {
6602     Instruction *FirstInst = Front;
6603     for (Value *V : E->Scalars) {
6604       auto *I = dyn_cast<Instruction>(V);
6605       if (!I)
6606         continue;
6607       if (I->comesBefore(FirstInst))
6608         FirstInst = I;
6609     }
6610     return FirstInst;
6611   };
6612 
6613   // Set the insert point to the beginning of the basic block if the entry
6614   // should not be scheduled.
6615   if (E->State != TreeEntry::NeedToGather &&
6616       doesNotNeedToSchedule(E->Scalars)) {
6617     BasicBlock::iterator InsertPt;
6618     if (all_of(E->Scalars, isUsedOutsideBlock))
6619       InsertPt = FindLastInst()->getIterator();
6620     else
6621       InsertPt = FindFirstInst()->getIterator();
6622     Builder.SetInsertPoint(BB, InsertPt);
6623     Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6624     return;
6625   }
6626 
6627   // The last instruction in the bundle in program order.
6628   Instruction *LastInst = nullptr;
6629 
6630   // Find the last instruction. The common case should be that BB has been
6631   // scheduled, and the last instruction is VL.back(). So we start with
6632   // VL.back() and iterate over schedule data until we reach the end of the
6633   // bundle. The end of the bundle is marked by null ScheduleData.
6634   if (BlocksSchedules.count(BB)) {
6635     Value *V = E->isOneOf(E->Scalars.back());
6636     if (doesNotNeedToBeScheduled(V))
6637       V = *find_if_not(E->Scalars, doesNotNeedToBeScheduled);
6638     auto *Bundle = BlocksSchedules[BB]->getScheduleData(V);
6639     if (Bundle && Bundle->isPartOfBundle())
6640       for (; Bundle; Bundle = Bundle->NextInBundle)
6641         if (Bundle->OpValue == Bundle->Inst)
6642           LastInst = Bundle->Inst;
6643   }
6644 
6645   // LastInst can still be null at this point if there's either not an entry
6646   // for BB in BlocksSchedules or there's no ScheduleData available for
6647   // VL.back(). This can be the case if buildTree_rec aborts for various
6648   // reasons (e.g., the maximum recursion depth is reached, the maximum region
6649   // size is reached, etc.). ScheduleData is initialized in the scheduling
6650   // "dry-run".
6651   //
6652   // If this happens, we can still find the last instruction by brute force. We
6653   // iterate forwards from Front (inclusive) until we either see all
6654   // instructions in the bundle or reach the end of the block. If Front is the
6655   // last instruction in program order, LastInst will be set to Front, and we
6656   // will visit all the remaining instructions in the block.
6657   //
6658   // One of the reasons we exit early from buildTree_rec is to place an upper
6659   // bound on compile-time. Thus, taking an additional compile-time hit here is
6660   // not ideal. However, this should be exceedingly rare since it requires that
6661   // we both exit early from buildTree_rec and that the bundle be out-of-order
6662   // (causing us to iterate all the way to the end of the block).
6663   if (!LastInst)
6664     LastInst = FindLastInst();
6665   assert(LastInst && "Failed to find last instruction in bundle");
6666 
6667   // Set the insertion point after the last instruction in the bundle. Set the
6668   // debug location to Front.
6669   Builder.SetInsertPoint(BB, ++LastInst->getIterator());
6670   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6671 }
6672 
6673 Value *BoUpSLP::gather(ArrayRef<Value *> VL) {
6674   // List of instructions/lanes from current block and/or the blocks which are
6675   // part of the current loop. These instructions will be inserted at the end to
6676   // make it possible to optimize loops and hoist invariant instructions out of
6677   // the loops body with better chances for success.
6678   SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts;
6679   SmallSet<int, 4> PostponedIndices;
6680   Loop *L = LI->getLoopFor(Builder.GetInsertBlock());
6681   auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) {
6682     SmallPtrSet<BasicBlock *, 4> Visited;
6683     while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second)
6684       InsertBB = InsertBB->getSinglePredecessor();
6685     return InsertBB && InsertBB == InstBB;
6686   };
6687   for (int I = 0, E = VL.size(); I < E; ++I) {
6688     if (auto *Inst = dyn_cast<Instruction>(VL[I]))
6689       if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) ||
6690            getTreeEntry(Inst) || (L && (L->contains(Inst)))) &&
6691           PostponedIndices.insert(I).second)
6692         PostponedInsts.emplace_back(Inst, I);
6693   }
6694 
6695   auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) {
6696     Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos));
6697     auto *InsElt = dyn_cast<InsertElementInst>(Vec);
6698     if (!InsElt)
6699       return Vec;
6700     GatherShuffleSeq.insert(InsElt);
6701     CSEBlocks.insert(InsElt->getParent());
6702     // Add to our 'need-to-extract' list.
6703     if (TreeEntry *Entry = getTreeEntry(V)) {
6704       // Find which lane we need to extract.
6705       unsigned FoundLane = Entry->findLaneForValue(V);
6706       ExternalUses.emplace_back(V, InsElt, FoundLane);
6707     }
6708     return Vec;
6709   };
6710   Value *Val0 =
6711       isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0];
6712   FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size());
6713   Value *Vec = PoisonValue::get(VecTy);
6714   SmallVector<int> NonConsts;
6715   // Insert constant values at first.
6716   for (int I = 0, E = VL.size(); I < E; ++I) {
6717     if (PostponedIndices.contains(I))
6718       continue;
6719     if (!isConstant(VL[I])) {
6720       NonConsts.push_back(I);
6721       continue;
6722     }
6723     Vec = CreateInsertElement(Vec, VL[I], I);
6724   }
6725   // Insert non-constant values.
6726   for (int I : NonConsts)
6727     Vec = CreateInsertElement(Vec, VL[I], I);
6728   // Append instructions, which are/may be part of the loop, in the end to make
6729   // it possible to hoist non-loop-based instructions.
6730   for (const std::pair<Value *, unsigned> &Pair : PostponedInsts)
6731     Vec = CreateInsertElement(Vec, Pair.first, Pair.second);
6732 
6733   return Vec;
6734 }
6735 
6736 namespace {
6737 /// Merges shuffle masks and emits final shuffle instruction, if required.
6738 class ShuffleInstructionBuilder {
6739   IRBuilderBase &Builder;
6740   const unsigned VF = 0;
6741   bool IsFinalized = false;
6742   SmallVector<int, 4> Mask;
6743   /// Holds all of the instructions that we gathered.
6744   SetVector<Instruction *> &GatherShuffleSeq;
6745   /// A list of blocks that we are going to CSE.
6746   SetVector<BasicBlock *> &CSEBlocks;
6747 
6748 public:
6749   ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF,
6750                             SetVector<Instruction *> &GatherShuffleSeq,
6751                             SetVector<BasicBlock *> &CSEBlocks)
6752       : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq),
6753         CSEBlocks(CSEBlocks) {}
6754 
6755   /// Adds a mask, inverting it before applying.
6756   void addInversedMask(ArrayRef<unsigned> SubMask) {
6757     if (SubMask.empty())
6758       return;
6759     SmallVector<int, 4> NewMask;
6760     inversePermutation(SubMask, NewMask);
6761     addMask(NewMask);
6762   }
6763 
6764   /// Functions adds masks, merging them into  single one.
6765   void addMask(ArrayRef<unsigned> SubMask) {
6766     SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end());
6767     addMask(NewMask);
6768   }
6769 
6770   void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); }
6771 
6772   Value *finalize(Value *V) {
6773     IsFinalized = true;
6774     unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements();
6775     if (VF == ValueVF && Mask.empty())
6776       return V;
6777     SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem);
6778     std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0);
6779     addMask(NormalizedMask);
6780 
6781     if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask))
6782       return V;
6783     Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle");
6784     if (auto *I = dyn_cast<Instruction>(Vec)) {
6785       GatherShuffleSeq.insert(I);
6786       CSEBlocks.insert(I->getParent());
6787     }
6788     return Vec;
6789   }
6790 
6791   ~ShuffleInstructionBuilder() {
6792     assert((IsFinalized || Mask.empty()) &&
6793            "Shuffle construction must be finalized.");
6794   }
6795 };
6796 } // namespace
6797 
6798 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
6799   const unsigned VF = VL.size();
6800   InstructionsState S = getSameOpcode(VL);
6801   if (S.getOpcode()) {
6802     if (TreeEntry *E = getTreeEntry(S.OpValue))
6803       if (E->isSame(VL)) {
6804         Value *V = vectorizeTree(E);
6805         if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) {
6806           if (!E->ReuseShuffleIndices.empty()) {
6807             // Reshuffle to get only unique values.
6808             // If some of the scalars are duplicated in the vectorization tree
6809             // entry, we do not vectorize them but instead generate a mask for
6810             // the reuses. But if there are several users of the same entry,
6811             // they may have different vectorization factors. This is especially
6812             // important for PHI nodes. In this case, we need to adapt the
6813             // resulting instruction for the user vectorization factor and have
6814             // to reshuffle it again to take only unique elements of the vector.
6815             // Without this code the function incorrectly returns reduced vector
6816             // instruction with the same elements, not with the unique ones.
6817 
6818             // block:
6819             // %phi = phi <2 x > { .., %entry} {%shuffle, %block}
6820             // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0>
6821             // ... (use %2)
6822             // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0}
6823             // br %block
6824             SmallVector<int> UniqueIdxs(VF, UndefMaskElem);
6825             SmallSet<int, 4> UsedIdxs;
6826             int Pos = 0;
6827             int Sz = VL.size();
6828             for (int Idx : E->ReuseShuffleIndices) {
6829               if (Idx != Sz && Idx != UndefMaskElem &&
6830                   UsedIdxs.insert(Idx).second)
6831                 UniqueIdxs[Idx] = Pos;
6832               ++Pos;
6833             }
6834             assert(VF >= UsedIdxs.size() && "Expected vectorization factor "
6835                                             "less than original vector size.");
6836             UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem);
6837             V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle");
6838           } else {
6839             assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() &&
6840                    "Expected vectorization factor less "
6841                    "than original vector size.");
6842             SmallVector<int> UniformMask(VF, 0);
6843             std::iota(UniformMask.begin(), UniformMask.end(), 0);
6844             V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle");
6845           }
6846           if (auto *I = dyn_cast<Instruction>(V)) {
6847             GatherShuffleSeq.insert(I);
6848             CSEBlocks.insert(I->getParent());
6849           }
6850         }
6851         return V;
6852       }
6853   }
6854 
6855   // Can't vectorize this, so simply build a new vector with each lane
6856   // corresponding to the requested value.
6857   return createBuildVector(VL);
6858 }
6859 Value *BoUpSLP::createBuildVector(ArrayRef<Value *> VL) {
6860   unsigned VF = VL.size();
6861   // Exploit possible reuse of values across lanes.
6862   SmallVector<int> ReuseShuffleIndicies;
6863   SmallVector<Value *> UniqueValues;
6864   if (VL.size() > 2) {
6865     DenseMap<Value *, unsigned> UniquePositions;
6866     unsigned NumValues =
6867         std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) {
6868                                     return !isa<UndefValue>(V);
6869                                   }).base());
6870     VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues));
6871     int UniqueVals = 0;
6872     for (Value *V : VL.drop_back(VL.size() - VF)) {
6873       if (isa<UndefValue>(V)) {
6874         ReuseShuffleIndicies.emplace_back(UndefMaskElem);
6875         continue;
6876       }
6877       if (isConstant(V)) {
6878         ReuseShuffleIndicies.emplace_back(UniqueValues.size());
6879         UniqueValues.emplace_back(V);
6880         continue;
6881       }
6882       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
6883       ReuseShuffleIndicies.emplace_back(Res.first->second);
6884       if (Res.second) {
6885         UniqueValues.emplace_back(V);
6886         ++UniqueVals;
6887       }
6888     }
6889     if (UniqueVals == 1 && UniqueValues.size() == 1) {
6890       // Emit pure splat vector.
6891       ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(),
6892                                   UndefMaskElem);
6893     } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) {
6894       ReuseShuffleIndicies.clear();
6895       UniqueValues.clear();
6896       UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues));
6897     }
6898     UniqueValues.append(VF - UniqueValues.size(),
6899                         PoisonValue::get(VL[0]->getType()));
6900     VL = UniqueValues;
6901   }
6902 
6903   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6904                                            CSEBlocks);
6905   Value *Vec = gather(VL);
6906   if (!ReuseShuffleIndicies.empty()) {
6907     ShuffleBuilder.addMask(ReuseShuffleIndicies);
6908     Vec = ShuffleBuilder.finalize(Vec);
6909   }
6910   return Vec;
6911 }
6912 
6913 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
6914   IRBuilder<>::InsertPointGuard Guard(Builder);
6915 
6916   if (E->VectorizedValue) {
6917     LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
6918     return E->VectorizedValue;
6919   }
6920 
6921   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
6922   unsigned VF = E->getVectorFactor();
6923   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6924                                            CSEBlocks);
6925   if (E->State == TreeEntry::NeedToGather) {
6926     if (E->getMainOp())
6927       setInsertPointAfterBundle(E);
6928     Value *Vec;
6929     SmallVector<int> Mask;
6930     SmallVector<const TreeEntry *> Entries;
6931     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
6932         isGatherShuffledEntry(E, Mask, Entries);
6933     if (Shuffle.hasValue()) {
6934       assert((Entries.size() == 1 || Entries.size() == 2) &&
6935              "Expected shuffle of 1 or 2 entries.");
6936       Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue,
6937                                         Entries.back()->VectorizedValue, Mask);
6938       if (auto *I = dyn_cast<Instruction>(Vec)) {
6939         GatherShuffleSeq.insert(I);
6940         CSEBlocks.insert(I->getParent());
6941       }
6942     } else {
6943       Vec = gather(E->Scalars);
6944     }
6945     if (NeedToShuffleReuses) {
6946       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6947       Vec = ShuffleBuilder.finalize(Vec);
6948     }
6949     E->VectorizedValue = Vec;
6950     return Vec;
6951   }
6952 
6953   assert((E->State == TreeEntry::Vectorize ||
6954           E->State == TreeEntry::ScatterVectorize) &&
6955          "Unhandled state");
6956   unsigned ShuffleOrOp =
6957       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
6958   Instruction *VL0 = E->getMainOp();
6959   Type *ScalarTy = VL0->getType();
6960   if (auto *Store = dyn_cast<StoreInst>(VL0))
6961     ScalarTy = Store->getValueOperand()->getType();
6962   else if (auto *IE = dyn_cast<InsertElementInst>(VL0))
6963     ScalarTy = IE->getOperand(1)->getType();
6964   auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
6965   switch (ShuffleOrOp) {
6966     case Instruction::PHI: {
6967       assert(
6968           (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) &&
6969           "PHI reordering is free.");
6970       auto *PH = cast<PHINode>(VL0);
6971       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
6972       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6973       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
6974       Value *V = NewPhi;
6975 
6976       // Adjust insertion point once all PHI's have been generated.
6977       Builder.SetInsertPoint(&*PH->getParent()->getFirstInsertionPt());
6978       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6979 
6980       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6981       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6982       V = ShuffleBuilder.finalize(V);
6983 
6984       E->VectorizedValue = V;
6985 
6986       // PHINodes may have multiple entries from the same block. We want to
6987       // visit every block once.
6988       SmallPtrSet<BasicBlock*, 4> VisitedBBs;
6989 
6990       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
6991         ValueList Operands;
6992         BasicBlock *IBB = PH->getIncomingBlock(i);
6993 
6994         if (!VisitedBBs.insert(IBB).second) {
6995           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
6996           continue;
6997         }
6998 
6999         Builder.SetInsertPoint(IBB->getTerminator());
7000         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
7001         Value *Vec = vectorizeTree(E->getOperand(i));
7002         NewPhi->addIncoming(Vec, IBB);
7003       }
7004 
7005       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
7006              "Invalid number of incoming values");
7007       return V;
7008     }
7009 
7010     case Instruction::ExtractElement: {
7011       Value *V = E->getSingleOperand(0);
7012       Builder.SetInsertPoint(VL0);
7013       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7014       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7015       V = ShuffleBuilder.finalize(V);
7016       E->VectorizedValue = V;
7017       return V;
7018     }
7019     case Instruction::ExtractValue: {
7020       auto *LI = cast<LoadInst>(E->getSingleOperand(0));
7021       Builder.SetInsertPoint(LI);
7022       auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
7023       Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
7024       LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
7025       Value *NewV = propagateMetadata(V, E->Scalars);
7026       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7027       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7028       NewV = ShuffleBuilder.finalize(NewV);
7029       E->VectorizedValue = NewV;
7030       return NewV;
7031     }
7032     case Instruction::InsertElement: {
7033       assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique");
7034       Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back()));
7035       Value *V = vectorizeTree(E->getOperand(1));
7036 
7037       // Create InsertVector shuffle if necessary
7038       auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
7039         return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0));
7040       }));
7041       const unsigned NumElts =
7042           cast<FixedVectorType>(FirstInsert->getType())->getNumElements();
7043       const unsigned NumScalars = E->Scalars.size();
7044 
7045       unsigned Offset = *getInsertIndex(VL0);
7046       assert(Offset < NumElts && "Failed to find vector index offset");
7047 
7048       // Create shuffle to resize vector
7049       SmallVector<int> Mask;
7050       if (!E->ReorderIndices.empty()) {
7051         inversePermutation(E->ReorderIndices, Mask);
7052         Mask.append(NumElts - NumScalars, UndefMaskElem);
7053       } else {
7054         Mask.assign(NumElts, UndefMaskElem);
7055         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
7056       }
7057       // Create InsertVector shuffle if necessary
7058       bool IsIdentity = true;
7059       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
7060       Mask.swap(PrevMask);
7061       for (unsigned I = 0; I < NumScalars; ++I) {
7062         Value *Scalar = E->Scalars[PrevMask[I]];
7063         unsigned InsertIdx = *getInsertIndex(Scalar);
7064         IsIdentity &= InsertIdx - Offset == I;
7065         Mask[InsertIdx - Offset] = I;
7066       }
7067       if (!IsIdentity || NumElts != NumScalars) {
7068         V = Builder.CreateShuffleVector(V, Mask);
7069         if (auto *I = dyn_cast<Instruction>(V)) {
7070           GatherShuffleSeq.insert(I);
7071           CSEBlocks.insert(I->getParent());
7072         }
7073       }
7074 
7075       if ((!IsIdentity || Offset != 0 ||
7076            !isUndefVector(FirstInsert->getOperand(0))) &&
7077           NumElts != NumScalars) {
7078         SmallVector<int> InsertMask(NumElts);
7079         std::iota(InsertMask.begin(), InsertMask.end(), 0);
7080         for (unsigned I = 0; I < NumElts; I++) {
7081           if (Mask[I] != UndefMaskElem)
7082             InsertMask[Offset + I] = NumElts + I;
7083         }
7084 
7085         V = Builder.CreateShuffleVector(
7086             FirstInsert->getOperand(0), V, InsertMask,
7087             cast<Instruction>(E->Scalars.back())->getName());
7088         if (auto *I = dyn_cast<Instruction>(V)) {
7089           GatherShuffleSeq.insert(I);
7090           CSEBlocks.insert(I->getParent());
7091         }
7092       }
7093 
7094       ++NumVectorInstructions;
7095       E->VectorizedValue = V;
7096       return V;
7097     }
7098     case Instruction::ZExt:
7099     case Instruction::SExt:
7100     case Instruction::FPToUI:
7101     case Instruction::FPToSI:
7102     case Instruction::FPExt:
7103     case Instruction::PtrToInt:
7104     case Instruction::IntToPtr:
7105     case Instruction::SIToFP:
7106     case Instruction::UIToFP:
7107     case Instruction::Trunc:
7108     case Instruction::FPTrunc:
7109     case Instruction::BitCast: {
7110       setInsertPointAfterBundle(E);
7111 
7112       Value *InVec = vectorizeTree(E->getOperand(0));
7113 
7114       if (E->VectorizedValue) {
7115         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7116         return E->VectorizedValue;
7117       }
7118 
7119       auto *CI = cast<CastInst>(VL0);
7120       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
7121       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7122       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7123       V = ShuffleBuilder.finalize(V);
7124 
7125       E->VectorizedValue = V;
7126       ++NumVectorInstructions;
7127       return V;
7128     }
7129     case Instruction::FCmp:
7130     case Instruction::ICmp: {
7131       setInsertPointAfterBundle(E);
7132 
7133       Value *L = vectorizeTree(E->getOperand(0));
7134       Value *R = vectorizeTree(E->getOperand(1));
7135 
7136       if (E->VectorizedValue) {
7137         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7138         return E->VectorizedValue;
7139       }
7140 
7141       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
7142       Value *V = Builder.CreateCmp(P0, L, R);
7143       propagateIRFlags(V, E->Scalars, VL0);
7144       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7145       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7146       V = ShuffleBuilder.finalize(V);
7147 
7148       E->VectorizedValue = V;
7149       ++NumVectorInstructions;
7150       return V;
7151     }
7152     case Instruction::Select: {
7153       setInsertPointAfterBundle(E);
7154 
7155       Value *Cond = vectorizeTree(E->getOperand(0));
7156       Value *True = vectorizeTree(E->getOperand(1));
7157       Value *False = vectorizeTree(E->getOperand(2));
7158 
7159       if (E->VectorizedValue) {
7160         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7161         return E->VectorizedValue;
7162       }
7163 
7164       Value *V = Builder.CreateSelect(Cond, True, False);
7165       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7166       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7167       V = ShuffleBuilder.finalize(V);
7168 
7169       E->VectorizedValue = V;
7170       ++NumVectorInstructions;
7171       return V;
7172     }
7173     case Instruction::FNeg: {
7174       setInsertPointAfterBundle(E);
7175 
7176       Value *Op = vectorizeTree(E->getOperand(0));
7177 
7178       if (E->VectorizedValue) {
7179         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7180         return E->VectorizedValue;
7181       }
7182 
7183       Value *V = Builder.CreateUnOp(
7184           static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
7185       propagateIRFlags(V, E->Scalars, VL0);
7186       if (auto *I = dyn_cast<Instruction>(V))
7187         V = propagateMetadata(I, E->Scalars);
7188 
7189       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7190       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7191       V = ShuffleBuilder.finalize(V);
7192 
7193       E->VectorizedValue = V;
7194       ++NumVectorInstructions;
7195 
7196       return V;
7197     }
7198     case Instruction::Add:
7199     case Instruction::FAdd:
7200     case Instruction::Sub:
7201     case Instruction::FSub:
7202     case Instruction::Mul:
7203     case Instruction::FMul:
7204     case Instruction::UDiv:
7205     case Instruction::SDiv:
7206     case Instruction::FDiv:
7207     case Instruction::URem:
7208     case Instruction::SRem:
7209     case Instruction::FRem:
7210     case Instruction::Shl:
7211     case Instruction::LShr:
7212     case Instruction::AShr:
7213     case Instruction::And:
7214     case Instruction::Or:
7215     case Instruction::Xor: {
7216       setInsertPointAfterBundle(E);
7217 
7218       Value *LHS = vectorizeTree(E->getOperand(0));
7219       Value *RHS = vectorizeTree(E->getOperand(1));
7220 
7221       if (E->VectorizedValue) {
7222         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7223         return E->VectorizedValue;
7224       }
7225 
7226       Value *V = Builder.CreateBinOp(
7227           static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
7228           RHS);
7229       propagateIRFlags(V, E->Scalars, VL0);
7230       if (auto *I = dyn_cast<Instruction>(V))
7231         V = propagateMetadata(I, E->Scalars);
7232 
7233       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7234       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7235       V = ShuffleBuilder.finalize(V);
7236 
7237       E->VectorizedValue = V;
7238       ++NumVectorInstructions;
7239 
7240       return V;
7241     }
7242     case Instruction::Load: {
7243       // Loads are inserted at the head of the tree because we don't want to
7244       // sink them all the way down past store instructions.
7245       setInsertPointAfterBundle(E);
7246 
7247       LoadInst *LI = cast<LoadInst>(VL0);
7248       Instruction *NewLI;
7249       unsigned AS = LI->getPointerAddressSpace();
7250       Value *PO = LI->getPointerOperand();
7251       if (E->State == TreeEntry::Vectorize) {
7252         Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS));
7253         NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
7254 
7255         // The pointer operand uses an in-tree scalar so we add the new BitCast
7256         // or LoadInst to ExternalUses list to make sure that an extract will
7257         // be generated in the future.
7258         if (TreeEntry *Entry = getTreeEntry(PO)) {
7259           // Find which lane we need to extract.
7260           unsigned FoundLane = Entry->findLaneForValue(PO);
7261           ExternalUses.emplace_back(
7262               PO, PO != VecPtr ? cast<User>(VecPtr) : NewLI, FoundLane);
7263         }
7264       } else {
7265         assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state");
7266         Value *VecPtr = vectorizeTree(E->getOperand(0));
7267         // Use the minimum alignment of the gathered loads.
7268         Align CommonAlignment = LI->getAlign();
7269         for (Value *V : E->Scalars)
7270           CommonAlignment =
7271               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
7272         NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment);
7273       }
7274       Value *V = propagateMetadata(NewLI, E->Scalars);
7275 
7276       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7277       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7278       V = ShuffleBuilder.finalize(V);
7279       E->VectorizedValue = V;
7280       ++NumVectorInstructions;
7281       return V;
7282     }
7283     case Instruction::Store: {
7284       auto *SI = cast<StoreInst>(VL0);
7285       unsigned AS = SI->getPointerAddressSpace();
7286 
7287       setInsertPointAfterBundle(E);
7288 
7289       Value *VecValue = vectorizeTree(E->getOperand(0));
7290       ShuffleBuilder.addMask(E->ReorderIndices);
7291       VecValue = ShuffleBuilder.finalize(VecValue);
7292 
7293       Value *ScalarPtr = SI->getPointerOperand();
7294       Value *VecPtr = Builder.CreateBitCast(
7295           ScalarPtr, VecValue->getType()->getPointerTo(AS));
7296       StoreInst *ST =
7297           Builder.CreateAlignedStore(VecValue, VecPtr, SI->getAlign());
7298 
7299       // The pointer operand uses an in-tree scalar, so add the new BitCast or
7300       // StoreInst to ExternalUses to make sure that an extract will be
7301       // generated in the future.
7302       if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) {
7303         // Find which lane we need to extract.
7304         unsigned FoundLane = Entry->findLaneForValue(ScalarPtr);
7305         ExternalUses.push_back(ExternalUser(
7306             ScalarPtr, ScalarPtr != VecPtr ? cast<User>(VecPtr) : ST,
7307             FoundLane));
7308       }
7309 
7310       Value *V = propagateMetadata(ST, E->Scalars);
7311 
7312       E->VectorizedValue = V;
7313       ++NumVectorInstructions;
7314       return V;
7315     }
7316     case Instruction::GetElementPtr: {
7317       auto *GEP0 = cast<GetElementPtrInst>(VL0);
7318       setInsertPointAfterBundle(E);
7319 
7320       Value *Op0 = vectorizeTree(E->getOperand(0));
7321 
7322       SmallVector<Value *> OpVecs;
7323       for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) {
7324         Value *OpVec = vectorizeTree(E->getOperand(J));
7325         OpVecs.push_back(OpVec);
7326       }
7327 
7328       Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs);
7329       if (Instruction *I = dyn_cast<Instruction>(V))
7330         V = propagateMetadata(I, E->Scalars);
7331 
7332       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7333       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7334       V = ShuffleBuilder.finalize(V);
7335 
7336       E->VectorizedValue = V;
7337       ++NumVectorInstructions;
7338 
7339       return V;
7340     }
7341     case Instruction::Call: {
7342       CallInst *CI = cast<CallInst>(VL0);
7343       setInsertPointAfterBundle(E);
7344 
7345       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
7346       if (Function *FI = CI->getCalledFunction())
7347         IID = FI->getIntrinsicID();
7348 
7349       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
7350 
7351       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
7352       bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
7353                           VecCallCosts.first <= VecCallCosts.second;
7354 
7355       Value *ScalarArg = nullptr;
7356       std::vector<Value *> OpVecs;
7357       SmallVector<Type *, 2> TysForDecl =
7358           {FixedVectorType::get(CI->getType(), E->Scalars.size())};
7359       for (int j = 0, e = CI->arg_size(); j < e; ++j) {
7360         ValueList OpVL;
7361         // Some intrinsics have scalar arguments. This argument should not be
7362         // vectorized.
7363         if (UseIntrinsic && hasVectorInstrinsicScalarOpd(IID, j)) {
7364           CallInst *CEI = cast<CallInst>(VL0);
7365           ScalarArg = CEI->getArgOperand(j);
7366           OpVecs.push_back(CEI->getArgOperand(j));
7367           if (hasVectorInstrinsicOverloadedScalarOpd(IID, j))
7368             TysForDecl.push_back(ScalarArg->getType());
7369           continue;
7370         }
7371 
7372         Value *OpVec = vectorizeTree(E->getOperand(j));
7373         LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
7374         OpVecs.push_back(OpVec);
7375       }
7376 
7377       Function *CF;
7378       if (!UseIntrinsic) {
7379         VFShape Shape =
7380             VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
7381                                   VecTy->getNumElements())),
7382                          false /*HasGlobalPred*/);
7383         CF = VFDatabase(*CI).getVectorizedFunction(Shape);
7384       } else {
7385         CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl);
7386       }
7387 
7388       SmallVector<OperandBundleDef, 1> OpBundles;
7389       CI->getOperandBundlesAsDefs(OpBundles);
7390       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
7391 
7392       // The scalar argument uses an in-tree scalar so we add the new vectorized
7393       // call to ExternalUses list to make sure that an extract will be
7394       // generated in the future.
7395       if (ScalarArg) {
7396         if (TreeEntry *Entry = getTreeEntry(ScalarArg)) {
7397           // Find which lane we need to extract.
7398           unsigned FoundLane = Entry->findLaneForValue(ScalarArg);
7399           ExternalUses.push_back(
7400               ExternalUser(ScalarArg, cast<User>(V), FoundLane));
7401         }
7402       }
7403 
7404       propagateIRFlags(V, E->Scalars, VL0);
7405       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7406       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7407       V = ShuffleBuilder.finalize(V);
7408 
7409       E->VectorizedValue = V;
7410       ++NumVectorInstructions;
7411       return V;
7412     }
7413     case Instruction::ShuffleVector: {
7414       assert(E->isAltShuffle() &&
7415              ((Instruction::isBinaryOp(E->getOpcode()) &&
7416                Instruction::isBinaryOp(E->getAltOpcode())) ||
7417               (Instruction::isCast(E->getOpcode()) &&
7418                Instruction::isCast(E->getAltOpcode())) ||
7419               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
7420              "Invalid Shuffle Vector Operand");
7421 
7422       Value *LHS = nullptr, *RHS = nullptr;
7423       if (Instruction::isBinaryOp(E->getOpcode()) || isa<CmpInst>(VL0)) {
7424         setInsertPointAfterBundle(E);
7425         LHS = vectorizeTree(E->getOperand(0));
7426         RHS = vectorizeTree(E->getOperand(1));
7427       } else {
7428         setInsertPointAfterBundle(E);
7429         LHS = vectorizeTree(E->getOperand(0));
7430       }
7431 
7432       if (E->VectorizedValue) {
7433         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7434         return E->VectorizedValue;
7435       }
7436 
7437       Value *V0, *V1;
7438       if (Instruction::isBinaryOp(E->getOpcode())) {
7439         V0 = Builder.CreateBinOp(
7440             static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
7441         V1 = Builder.CreateBinOp(
7442             static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
7443       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
7444         V0 = Builder.CreateCmp(CI0->getPredicate(), LHS, RHS);
7445         auto *AltCI = cast<CmpInst>(E->getAltOp());
7446         CmpInst::Predicate AltPred = AltCI->getPredicate();
7447         V1 = Builder.CreateCmp(AltPred, LHS, RHS);
7448       } else {
7449         V0 = Builder.CreateCast(
7450             static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
7451         V1 = Builder.CreateCast(
7452             static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
7453       }
7454       // Add V0 and V1 to later analysis to try to find and remove matching
7455       // instruction, if any.
7456       for (Value *V : {V0, V1}) {
7457         if (auto *I = dyn_cast<Instruction>(V)) {
7458           GatherShuffleSeq.insert(I);
7459           CSEBlocks.insert(I->getParent());
7460         }
7461       }
7462 
7463       // Create shuffle to take alternate operations from the vector.
7464       // Also, gather up main and alt scalar ops to propagate IR flags to
7465       // each vector operation.
7466       ValueList OpScalars, AltScalars;
7467       SmallVector<int> Mask;
7468       buildShuffleEntryMask(
7469           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
7470           [E](Instruction *I) {
7471             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
7472             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
7473           },
7474           Mask, &OpScalars, &AltScalars);
7475 
7476       propagateIRFlags(V0, OpScalars);
7477       propagateIRFlags(V1, AltScalars);
7478 
7479       Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
7480       if (auto *I = dyn_cast<Instruction>(V)) {
7481         V = propagateMetadata(I, E->Scalars);
7482         GatherShuffleSeq.insert(I);
7483         CSEBlocks.insert(I->getParent());
7484       }
7485       V = ShuffleBuilder.finalize(V);
7486 
7487       E->VectorizedValue = V;
7488       ++NumVectorInstructions;
7489 
7490       return V;
7491     }
7492     default:
7493     llvm_unreachable("unknown inst");
7494   }
7495   return nullptr;
7496 }
7497 
7498 Value *BoUpSLP::vectorizeTree() {
7499   ExtraValueToDebugLocsMap ExternallyUsedValues;
7500   return vectorizeTree(ExternallyUsedValues);
7501 }
7502 
7503 Value *
7504 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
7505   // All blocks must be scheduled before any instructions are inserted.
7506   for (auto &BSIter : BlocksSchedules) {
7507     scheduleBlock(BSIter.second.get());
7508   }
7509 
7510   Builder.SetInsertPoint(&F->getEntryBlock().front());
7511   auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
7512 
7513   // If the vectorized tree can be rewritten in a smaller type, we truncate the
7514   // vectorized root. InstCombine will then rewrite the entire expression. We
7515   // sign extend the extracted values below.
7516   auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
7517   if (MinBWs.count(ScalarRoot)) {
7518     if (auto *I = dyn_cast<Instruction>(VectorRoot)) {
7519       // If current instr is a phi and not the last phi, insert it after the
7520       // last phi node.
7521       if (isa<PHINode>(I))
7522         Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt());
7523       else
7524         Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
7525     }
7526     auto BundleWidth = VectorizableTree[0]->Scalars.size();
7527     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
7528     auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
7529     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
7530     VectorizableTree[0]->VectorizedValue = Trunc;
7531   }
7532 
7533   LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
7534                     << " values .\n");
7535 
7536   // Extract all of the elements with the external uses.
7537   for (const auto &ExternalUse : ExternalUses) {
7538     Value *Scalar = ExternalUse.Scalar;
7539     llvm::User *User = ExternalUse.User;
7540 
7541     // Skip users that we already RAUW. This happens when one instruction
7542     // has multiple uses of the same value.
7543     if (User && !is_contained(Scalar->users(), User))
7544       continue;
7545     TreeEntry *E = getTreeEntry(Scalar);
7546     assert(E && "Invalid scalar");
7547     assert(E->State != TreeEntry::NeedToGather &&
7548            "Extracting from a gather list");
7549 
7550     Value *Vec = E->VectorizedValue;
7551     assert(Vec && "Can't find vectorizable value");
7552 
7553     Value *Lane = Builder.getInt32(ExternalUse.Lane);
7554     auto ExtractAndExtendIfNeeded = [&](Value *Vec) {
7555       if (Scalar->getType() != Vec->getType()) {
7556         Value *Ex;
7557         // "Reuse" the existing extract to improve final codegen.
7558         if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) {
7559           Ex = Builder.CreateExtractElement(ES->getOperand(0),
7560                                             ES->getOperand(1));
7561         } else {
7562           Ex = Builder.CreateExtractElement(Vec, Lane);
7563         }
7564         // If necessary, sign-extend or zero-extend ScalarRoot
7565         // to the larger type.
7566         if (!MinBWs.count(ScalarRoot))
7567           return Ex;
7568         if (MinBWs[ScalarRoot].second)
7569           return Builder.CreateSExt(Ex, Scalar->getType());
7570         return Builder.CreateZExt(Ex, Scalar->getType());
7571       }
7572       assert(isa<FixedVectorType>(Scalar->getType()) &&
7573              isa<InsertElementInst>(Scalar) &&
7574              "In-tree scalar of vector type is not insertelement?");
7575       return Vec;
7576     };
7577     // If User == nullptr, the Scalar is used as extra arg. Generate
7578     // ExtractElement instruction and update the record for this scalar in
7579     // ExternallyUsedValues.
7580     if (!User) {
7581       assert(ExternallyUsedValues.count(Scalar) &&
7582              "Scalar with nullptr as an external user must be registered in "
7583              "ExternallyUsedValues map");
7584       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7585         Builder.SetInsertPoint(VecI->getParent(),
7586                                std::next(VecI->getIterator()));
7587       } else {
7588         Builder.SetInsertPoint(&F->getEntryBlock().front());
7589       }
7590       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7591       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
7592       auto &NewInstLocs = ExternallyUsedValues[NewInst];
7593       auto It = ExternallyUsedValues.find(Scalar);
7594       assert(It != ExternallyUsedValues.end() &&
7595              "Externally used scalar is not found in ExternallyUsedValues");
7596       NewInstLocs.append(It->second);
7597       ExternallyUsedValues.erase(Scalar);
7598       // Required to update internally referenced instructions.
7599       Scalar->replaceAllUsesWith(NewInst);
7600       continue;
7601     }
7602 
7603     // Generate extracts for out-of-tree users.
7604     // Find the insertion point for the extractelement lane.
7605     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7606       if (PHINode *PH = dyn_cast<PHINode>(User)) {
7607         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
7608           if (PH->getIncomingValue(i) == Scalar) {
7609             Instruction *IncomingTerminator =
7610                 PH->getIncomingBlock(i)->getTerminator();
7611             if (isa<CatchSwitchInst>(IncomingTerminator)) {
7612               Builder.SetInsertPoint(VecI->getParent(),
7613                                      std::next(VecI->getIterator()));
7614             } else {
7615               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
7616             }
7617             Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7618             CSEBlocks.insert(PH->getIncomingBlock(i));
7619             PH->setOperand(i, NewInst);
7620           }
7621         }
7622       } else {
7623         Builder.SetInsertPoint(cast<Instruction>(User));
7624         Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7625         CSEBlocks.insert(cast<Instruction>(User)->getParent());
7626         User->replaceUsesOfWith(Scalar, NewInst);
7627       }
7628     } else {
7629       Builder.SetInsertPoint(&F->getEntryBlock().front());
7630       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7631       CSEBlocks.insert(&F->getEntryBlock());
7632       User->replaceUsesOfWith(Scalar, NewInst);
7633     }
7634 
7635     LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
7636   }
7637 
7638   // For each vectorized value:
7639   for (auto &TEPtr : VectorizableTree) {
7640     TreeEntry *Entry = TEPtr.get();
7641 
7642     // No need to handle users of gathered values.
7643     if (Entry->State == TreeEntry::NeedToGather)
7644       continue;
7645 
7646     assert(Entry->VectorizedValue && "Can't find vectorizable value");
7647 
7648     // For each lane:
7649     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
7650       Value *Scalar = Entry->Scalars[Lane];
7651 
7652 #ifndef NDEBUG
7653       Type *Ty = Scalar->getType();
7654       if (!Ty->isVoidTy()) {
7655         for (User *U : Scalar->users()) {
7656           LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
7657 
7658           // It is legal to delete users in the ignorelist.
7659           assert((getTreeEntry(U) || is_contained(UserIgnoreList, U) ||
7660                   (isa_and_nonnull<Instruction>(U) &&
7661                    isDeleted(cast<Instruction>(U)))) &&
7662                  "Deleting out-of-tree value");
7663         }
7664       }
7665 #endif
7666       LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
7667       eraseInstruction(cast<Instruction>(Scalar));
7668     }
7669   }
7670 
7671   Builder.ClearInsertionPoint();
7672   InstrElementSize.clear();
7673 
7674   return VectorizableTree[0]->VectorizedValue;
7675 }
7676 
7677 void BoUpSLP::optimizeGatherSequence() {
7678   LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleSeq.size()
7679                     << " gather sequences instructions.\n");
7680   // LICM InsertElementInst sequences.
7681   for (Instruction *I : GatherShuffleSeq) {
7682     if (isDeleted(I))
7683       continue;
7684 
7685     // Check if this block is inside a loop.
7686     Loop *L = LI->getLoopFor(I->getParent());
7687     if (!L)
7688       continue;
7689 
7690     // Check if it has a preheader.
7691     BasicBlock *PreHeader = L->getLoopPreheader();
7692     if (!PreHeader)
7693       continue;
7694 
7695     // If the vector or the element that we insert into it are
7696     // instructions that are defined in this basic block then we can't
7697     // hoist this instruction.
7698     if (any_of(I->operands(), [L](Value *V) {
7699           auto *OpI = dyn_cast<Instruction>(V);
7700           return OpI && L->contains(OpI);
7701         }))
7702       continue;
7703 
7704     // We can hoist this instruction. Move it to the pre-header.
7705     I->moveBefore(PreHeader->getTerminator());
7706   }
7707 
7708   // Make a list of all reachable blocks in our CSE queue.
7709   SmallVector<const DomTreeNode *, 8> CSEWorkList;
7710   CSEWorkList.reserve(CSEBlocks.size());
7711   for (BasicBlock *BB : CSEBlocks)
7712     if (DomTreeNode *N = DT->getNode(BB)) {
7713       assert(DT->isReachableFromEntry(N));
7714       CSEWorkList.push_back(N);
7715     }
7716 
7717   // Sort blocks by domination. This ensures we visit a block after all blocks
7718   // dominating it are visited.
7719   llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) {
7720     assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) &&
7721            "Different nodes should have different DFS numbers");
7722     return A->getDFSNumIn() < B->getDFSNumIn();
7723   });
7724 
7725   // Less defined shuffles can be replaced by the more defined copies.
7726   // Between two shuffles one is less defined if it has the same vector operands
7727   // and its mask indeces are the same as in the first one or undefs. E.g.
7728   // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0,
7729   // poison, <0, 0, 0, 0>.
7730   auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2,
7731                                            SmallVectorImpl<int> &NewMask) {
7732     if (I1->getType() != I2->getType())
7733       return false;
7734     auto *SI1 = dyn_cast<ShuffleVectorInst>(I1);
7735     auto *SI2 = dyn_cast<ShuffleVectorInst>(I2);
7736     if (!SI1 || !SI2)
7737       return I1->isIdenticalTo(I2);
7738     if (SI1->isIdenticalTo(SI2))
7739       return true;
7740     for (int I = 0, E = SI1->getNumOperands(); I < E; ++I)
7741       if (SI1->getOperand(I) != SI2->getOperand(I))
7742         return false;
7743     // Check if the second instruction is more defined than the first one.
7744     NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end());
7745     ArrayRef<int> SM1 = SI1->getShuffleMask();
7746     // Count trailing undefs in the mask to check the final number of used
7747     // registers.
7748     unsigned LastUndefsCnt = 0;
7749     for (int I = 0, E = NewMask.size(); I < E; ++I) {
7750       if (SM1[I] == UndefMaskElem)
7751         ++LastUndefsCnt;
7752       else
7753         LastUndefsCnt = 0;
7754       if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem &&
7755           NewMask[I] != SM1[I])
7756         return false;
7757       if (NewMask[I] == UndefMaskElem)
7758         NewMask[I] = SM1[I];
7759     }
7760     // Check if the last undefs actually change the final number of used vector
7761     // registers.
7762     return SM1.size() - LastUndefsCnt > 1 &&
7763            TTI->getNumberOfParts(SI1->getType()) ==
7764                TTI->getNumberOfParts(
7765                    FixedVectorType::get(SI1->getType()->getElementType(),
7766                                         SM1.size() - LastUndefsCnt));
7767   };
7768   // Perform O(N^2) search over the gather/shuffle sequences and merge identical
7769   // instructions. TODO: We can further optimize this scan if we split the
7770   // instructions into different buckets based on the insert lane.
7771   SmallVector<Instruction *, 16> Visited;
7772   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
7773     assert(*I &&
7774            (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
7775            "Worklist not sorted properly!");
7776     BasicBlock *BB = (*I)->getBlock();
7777     // For all instructions in blocks containing gather sequences:
7778     for (Instruction &In : llvm::make_early_inc_range(*BB)) {
7779       if (isDeleted(&In))
7780         continue;
7781       if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) &&
7782           !isa<ShuffleVectorInst>(&In) && !GatherShuffleSeq.contains(&In))
7783         continue;
7784 
7785       // Check if we can replace this instruction with any of the
7786       // visited instructions.
7787       bool Replaced = false;
7788       for (Instruction *&V : Visited) {
7789         SmallVector<int> NewMask;
7790         if (IsIdenticalOrLessDefined(&In, V, NewMask) &&
7791             DT->dominates(V->getParent(), In.getParent())) {
7792           In.replaceAllUsesWith(V);
7793           eraseInstruction(&In);
7794           if (auto *SI = dyn_cast<ShuffleVectorInst>(V))
7795             if (!NewMask.empty())
7796               SI->setShuffleMask(NewMask);
7797           Replaced = true;
7798           break;
7799         }
7800         if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) &&
7801             GatherShuffleSeq.contains(V) &&
7802             IsIdenticalOrLessDefined(V, &In, NewMask) &&
7803             DT->dominates(In.getParent(), V->getParent())) {
7804           In.moveAfter(V);
7805           V->replaceAllUsesWith(&In);
7806           eraseInstruction(V);
7807           if (auto *SI = dyn_cast<ShuffleVectorInst>(&In))
7808             if (!NewMask.empty())
7809               SI->setShuffleMask(NewMask);
7810           V = &In;
7811           Replaced = true;
7812           break;
7813         }
7814       }
7815       if (!Replaced) {
7816         assert(!is_contained(Visited, &In));
7817         Visited.push_back(&In);
7818       }
7819     }
7820   }
7821   CSEBlocks.clear();
7822   GatherShuffleSeq.clear();
7823 }
7824 
7825 BoUpSLP::ScheduleData *
7826 BoUpSLP::BlockScheduling::buildBundle(ArrayRef<Value *> VL) {
7827   ScheduleData *Bundle = nullptr;
7828   ScheduleData *PrevInBundle = nullptr;
7829   for (Value *V : VL) {
7830     if (doesNotNeedToBeScheduled(V))
7831       continue;
7832     ScheduleData *BundleMember = getScheduleData(V);
7833     assert(BundleMember &&
7834            "no ScheduleData for bundle member "
7835            "(maybe not in same basic block)");
7836     assert(BundleMember->isSchedulingEntity() &&
7837            "bundle member already part of other bundle");
7838     if (PrevInBundle) {
7839       PrevInBundle->NextInBundle = BundleMember;
7840     } else {
7841       Bundle = BundleMember;
7842     }
7843 
7844     // Group the instructions to a bundle.
7845     BundleMember->FirstInBundle = Bundle;
7846     PrevInBundle = BundleMember;
7847   }
7848   assert(Bundle && "Failed to find schedule bundle");
7849   return Bundle;
7850 }
7851 
7852 // Groups the instructions to a bundle (which is then a single scheduling entity)
7853 // and schedules instructions until the bundle gets ready.
7854 Optional<BoUpSLP::ScheduleData *>
7855 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
7856                                             const InstructionsState &S) {
7857   // No need to schedule PHIs, insertelement, extractelement and extractvalue
7858   // instructions.
7859   if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue) ||
7860       doesNotNeedToSchedule(VL))
7861     return nullptr;
7862 
7863   // Initialize the instruction bundle.
7864   Instruction *OldScheduleEnd = ScheduleEnd;
7865   LLVM_DEBUG(dbgs() << "SLP:  bundle: " << *S.OpValue << "\n");
7866 
7867   auto TryScheduleBundleImpl = [this, OldScheduleEnd, SLP](bool ReSchedule,
7868                                                          ScheduleData *Bundle) {
7869     // The scheduling region got new instructions at the lower end (or it is a
7870     // new region for the first bundle). This makes it necessary to
7871     // recalculate all dependencies.
7872     // It is seldom that this needs to be done a second time after adding the
7873     // initial bundle to the region.
7874     if (ScheduleEnd != OldScheduleEnd) {
7875       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode())
7876         doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); });
7877       ReSchedule = true;
7878     }
7879     if (Bundle) {
7880       LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle
7881                         << " in block " << BB->getName() << "\n");
7882       calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP);
7883     }
7884 
7885     if (ReSchedule) {
7886       resetSchedule();
7887       initialFillReadyList(ReadyInsts);
7888     }
7889 
7890     // Now try to schedule the new bundle or (if no bundle) just calculate
7891     // dependencies. As soon as the bundle is "ready" it means that there are no
7892     // cyclic dependencies and we can schedule it. Note that's important that we
7893     // don't "schedule" the bundle yet (see cancelScheduling).
7894     while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) &&
7895            !ReadyInsts.empty()) {
7896       ScheduleData *Picked = ReadyInsts.pop_back_val();
7897       assert(Picked->isSchedulingEntity() && Picked->isReady() &&
7898              "must be ready to schedule");
7899       schedule(Picked, ReadyInsts);
7900     }
7901   };
7902 
7903   // Make sure that the scheduling region contains all
7904   // instructions of the bundle.
7905   for (Value *V : VL) {
7906     if (doesNotNeedToBeScheduled(V))
7907       continue;
7908     if (!extendSchedulingRegion(V, S)) {
7909       // If the scheduling region got new instructions at the lower end (or it
7910       // is a new region for the first bundle). This makes it necessary to
7911       // recalculate all dependencies.
7912       // Otherwise the compiler may crash trying to incorrectly calculate
7913       // dependencies and emit instruction in the wrong order at the actual
7914       // scheduling.
7915       TryScheduleBundleImpl(/*ReSchedule=*/false, nullptr);
7916       return None;
7917     }
7918   }
7919 
7920   bool ReSchedule = false;
7921   for (Value *V : VL) {
7922     if (doesNotNeedToBeScheduled(V))
7923       continue;
7924     ScheduleData *BundleMember = getScheduleData(V);
7925     assert(BundleMember &&
7926            "no ScheduleData for bundle member (maybe not in same basic block)");
7927 
7928     // Make sure we don't leave the pieces of the bundle in the ready list when
7929     // whole bundle might not be ready.
7930     ReadyInsts.remove(BundleMember);
7931 
7932     if (!BundleMember->IsScheduled)
7933       continue;
7934     // A bundle member was scheduled as single instruction before and now
7935     // needs to be scheduled as part of the bundle. We just get rid of the
7936     // existing schedule.
7937     LLVM_DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
7938                       << " was already scheduled\n");
7939     ReSchedule = true;
7940   }
7941 
7942   auto *Bundle = buildBundle(VL);
7943   TryScheduleBundleImpl(ReSchedule, Bundle);
7944   if (!Bundle->isReady()) {
7945     cancelScheduling(VL, S.OpValue);
7946     return None;
7947   }
7948   return Bundle;
7949 }
7950 
7951 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
7952                                                 Value *OpValue) {
7953   if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue) ||
7954       doesNotNeedToSchedule(VL))
7955     return;
7956 
7957   if (doesNotNeedToBeScheduled(OpValue))
7958     OpValue = *find_if_not(VL, doesNotNeedToBeScheduled);
7959   ScheduleData *Bundle = getScheduleData(OpValue);
7960   LLVM_DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
7961   assert(!Bundle->IsScheduled &&
7962          "Can't cancel bundle which is already scheduled");
7963   assert(Bundle->isSchedulingEntity() &&
7964          (Bundle->isPartOfBundle() || needToScheduleSingleInstruction(VL)) &&
7965          "tried to unbundle something which is not a bundle");
7966 
7967   // Remove the bundle from the ready list.
7968   if (Bundle->isReady())
7969     ReadyInsts.remove(Bundle);
7970 
7971   // Un-bundle: make single instructions out of the bundle.
7972   ScheduleData *BundleMember = Bundle;
7973   while (BundleMember) {
7974     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
7975     BundleMember->FirstInBundle = BundleMember;
7976     ScheduleData *Next = BundleMember->NextInBundle;
7977     BundleMember->NextInBundle = nullptr;
7978     BundleMember->TE = nullptr;
7979     if (BundleMember->unscheduledDepsInBundle() == 0) {
7980       ReadyInsts.insert(BundleMember);
7981     }
7982     BundleMember = Next;
7983   }
7984 }
7985 
7986 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
7987   // Allocate a new ScheduleData for the instruction.
7988   if (ChunkPos >= ChunkSize) {
7989     ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
7990     ChunkPos = 0;
7991   }
7992   return &(ScheduleDataChunks.back()[ChunkPos++]);
7993 }
7994 
7995 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
7996                                                       const InstructionsState &S) {
7997   if (getScheduleData(V, isOneOf(S, V)))
7998     return true;
7999   Instruction *I = dyn_cast<Instruction>(V);
8000   assert(I && "bundle member must be an instruction");
8001   assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) &&
8002          !doesNotNeedToBeScheduled(I) &&
8003          "phi nodes/insertelements/extractelements/extractvalues don't need to "
8004          "be scheduled");
8005   auto &&CheckScheduleForI = [this, &S](Instruction *I) -> bool {
8006     ScheduleData *ISD = getScheduleData(I);
8007     if (!ISD)
8008       return false;
8009     assert(isInSchedulingRegion(ISD) &&
8010            "ScheduleData not in scheduling region");
8011     ScheduleData *SD = allocateScheduleDataChunks();
8012     SD->Inst = I;
8013     SD->init(SchedulingRegionID, S.OpValue);
8014     ExtraScheduleDataMap[I][S.OpValue] = SD;
8015     return true;
8016   };
8017   if (CheckScheduleForI(I))
8018     return true;
8019   if (!ScheduleStart) {
8020     // It's the first instruction in the new region.
8021     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
8022     ScheduleStart = I;
8023     ScheduleEnd = I->getNextNode();
8024     if (isOneOf(S, I) != I)
8025       CheckScheduleForI(I);
8026     assert(ScheduleEnd && "tried to vectorize a terminator?");
8027     LLVM_DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
8028     return true;
8029   }
8030   // Search up and down at the same time, because we don't know if the new
8031   // instruction is above or below the existing scheduling region.
8032   BasicBlock::reverse_iterator UpIter =
8033       ++ScheduleStart->getIterator().getReverse();
8034   BasicBlock::reverse_iterator UpperEnd = BB->rend();
8035   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
8036   BasicBlock::iterator LowerEnd = BB->end();
8037   while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I &&
8038          &*DownIter != I) {
8039     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
8040       LLVM_DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
8041       return false;
8042     }
8043 
8044     ++UpIter;
8045     ++DownIter;
8046   }
8047   if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) {
8048     assert(I->getParent() == ScheduleStart->getParent() &&
8049            "Instruction is in wrong basic block.");
8050     initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
8051     ScheduleStart = I;
8052     if (isOneOf(S, I) != I)
8053       CheckScheduleForI(I);
8054     LLVM_DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I
8055                       << "\n");
8056     return true;
8057   }
8058   assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) &&
8059          "Expected to reach top of the basic block or instruction down the "
8060          "lower end.");
8061   assert(I->getParent() == ScheduleEnd->getParent() &&
8062          "Instruction is in wrong basic block.");
8063   initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
8064                    nullptr);
8065   ScheduleEnd = I->getNextNode();
8066   if (isOneOf(S, I) != I)
8067     CheckScheduleForI(I);
8068   assert(ScheduleEnd && "tried to vectorize a terminator?");
8069   LLVM_DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
8070   return true;
8071 }
8072 
8073 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
8074                                                 Instruction *ToI,
8075                                                 ScheduleData *PrevLoadStore,
8076                                                 ScheduleData *NextLoadStore) {
8077   ScheduleData *CurrentLoadStore = PrevLoadStore;
8078   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
8079     // No need to allocate data for non-schedulable instructions.
8080     if (doesNotNeedToBeScheduled(I))
8081       continue;
8082     ScheduleData *SD = ScheduleDataMap.lookup(I);
8083     if (!SD) {
8084       SD = allocateScheduleDataChunks();
8085       ScheduleDataMap[I] = SD;
8086       SD->Inst = I;
8087     }
8088     assert(!isInSchedulingRegion(SD) &&
8089            "new ScheduleData already in scheduling region");
8090     SD->init(SchedulingRegionID, I);
8091 
8092     if (I->mayReadOrWriteMemory() &&
8093         (!isa<IntrinsicInst>(I) ||
8094          (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect &&
8095           cast<IntrinsicInst>(I)->getIntrinsicID() !=
8096               Intrinsic::pseudoprobe))) {
8097       // Update the linked list of memory accessing instructions.
8098       if (CurrentLoadStore) {
8099         CurrentLoadStore->NextLoadStore = SD;
8100       } else {
8101         FirstLoadStoreInRegion = SD;
8102       }
8103       CurrentLoadStore = SD;
8104     }
8105 
8106     if (match(I, m_Intrinsic<Intrinsic::stacksave>()) ||
8107         match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8108       RegionHasStackSave = true;
8109   }
8110   if (NextLoadStore) {
8111     if (CurrentLoadStore)
8112       CurrentLoadStore->NextLoadStore = NextLoadStore;
8113   } else {
8114     LastLoadStoreInRegion = CurrentLoadStore;
8115   }
8116 }
8117 
8118 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
8119                                                      bool InsertInReadyList,
8120                                                      BoUpSLP *SLP) {
8121   assert(SD->isSchedulingEntity());
8122 
8123   SmallVector<ScheduleData *, 10> WorkList;
8124   WorkList.push_back(SD);
8125 
8126   while (!WorkList.empty()) {
8127     ScheduleData *SD = WorkList.pop_back_val();
8128     for (ScheduleData *BundleMember = SD; BundleMember;
8129          BundleMember = BundleMember->NextInBundle) {
8130       assert(isInSchedulingRegion(BundleMember));
8131       if (BundleMember->hasValidDependencies())
8132         continue;
8133 
8134       LLVM_DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember
8135                  << "\n");
8136       BundleMember->Dependencies = 0;
8137       BundleMember->resetUnscheduledDeps();
8138 
8139       // Handle def-use chain dependencies.
8140       if (BundleMember->OpValue != BundleMember->Inst) {
8141         if (ScheduleData *UseSD = getScheduleData(BundleMember->Inst)) {
8142           BundleMember->Dependencies++;
8143           ScheduleData *DestBundle = UseSD->FirstInBundle;
8144           if (!DestBundle->IsScheduled)
8145             BundleMember->incrementUnscheduledDeps(1);
8146           if (!DestBundle->hasValidDependencies())
8147             WorkList.push_back(DestBundle);
8148         }
8149       } else {
8150         for (User *U : BundleMember->Inst->users()) {
8151           if (ScheduleData *UseSD = getScheduleData(cast<Instruction>(U))) {
8152             BundleMember->Dependencies++;
8153             ScheduleData *DestBundle = UseSD->FirstInBundle;
8154             if (!DestBundle->IsScheduled)
8155               BundleMember->incrementUnscheduledDeps(1);
8156             if (!DestBundle->hasValidDependencies())
8157               WorkList.push_back(DestBundle);
8158           }
8159         }
8160       }
8161 
8162       auto makeControlDependent = [&](Instruction *I) {
8163         auto *DepDest = getScheduleData(I);
8164         assert(DepDest && "must be in schedule window");
8165         DepDest->ControlDependencies.push_back(BundleMember);
8166         BundleMember->Dependencies++;
8167         ScheduleData *DestBundle = DepDest->FirstInBundle;
8168         if (!DestBundle->IsScheduled)
8169           BundleMember->incrementUnscheduledDeps(1);
8170         if (!DestBundle->hasValidDependencies())
8171           WorkList.push_back(DestBundle);
8172       };
8173 
8174       // Any instruction which isn't safe to speculate at the begining of the
8175       // block is control dependend on any early exit or non-willreturn call
8176       // which proceeds it.
8177       if (!isGuaranteedToTransferExecutionToSuccessor(BundleMember->Inst)) {
8178         for (Instruction *I = BundleMember->Inst->getNextNode();
8179              I != ScheduleEnd; I = I->getNextNode()) {
8180           if (isSafeToSpeculativelyExecute(I, &*BB->begin()))
8181             continue;
8182 
8183           // Add the dependency
8184           makeControlDependent(I);
8185 
8186           if (!isGuaranteedToTransferExecutionToSuccessor(I))
8187             // Everything past here must be control dependent on I.
8188             break;
8189         }
8190       }
8191 
8192       if (RegionHasStackSave) {
8193         // If we have an inalloc alloca instruction, it needs to be scheduled
8194         // after any preceeding stacksave.  We also need to prevent any alloca
8195         // from reordering above a preceeding stackrestore.
8196         if (match(BundleMember->Inst, m_Intrinsic<Intrinsic::stacksave>()) ||
8197             match(BundleMember->Inst, m_Intrinsic<Intrinsic::stackrestore>())) {
8198           for (Instruction *I = BundleMember->Inst->getNextNode();
8199                I != ScheduleEnd; I = I->getNextNode()) {
8200             if (match(I, m_Intrinsic<Intrinsic::stacksave>()) ||
8201                 match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8202               // Any allocas past here must be control dependent on I, and I
8203               // must be memory dependend on BundleMember->Inst.
8204               break;
8205 
8206             if (!isa<AllocaInst>(I))
8207               continue;
8208 
8209             // Add the dependency
8210             makeControlDependent(I);
8211           }
8212         }
8213 
8214         // In addition to the cases handle just above, we need to prevent
8215         // allocas from moving below a stacksave.  The stackrestore case
8216         // is currently thought to be conservatism.
8217         if (isa<AllocaInst>(BundleMember->Inst)) {
8218           for (Instruction *I = BundleMember->Inst->getNextNode();
8219                I != ScheduleEnd; I = I->getNextNode()) {
8220             if (!match(I, m_Intrinsic<Intrinsic::stacksave>()) &&
8221                 !match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8222               continue;
8223 
8224             // Add the dependency
8225             makeControlDependent(I);
8226             break;
8227           }
8228         }
8229       }
8230 
8231       // Handle the memory dependencies (if any).
8232       ScheduleData *DepDest = BundleMember->NextLoadStore;
8233       if (!DepDest)
8234         continue;
8235       Instruction *SrcInst = BundleMember->Inst;
8236       assert(SrcInst->mayReadOrWriteMemory() &&
8237              "NextLoadStore list for non memory effecting bundle?");
8238       MemoryLocation SrcLoc = getLocation(SrcInst);
8239       bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
8240       unsigned numAliased = 0;
8241       unsigned DistToSrc = 1;
8242 
8243       for ( ; DepDest; DepDest = DepDest->NextLoadStore) {
8244         assert(isInSchedulingRegion(DepDest));
8245 
8246         // We have two limits to reduce the complexity:
8247         // 1) AliasedCheckLimit: It's a small limit to reduce calls to
8248         //    SLP->isAliased (which is the expensive part in this loop).
8249         // 2) MaxMemDepDistance: It's for very large blocks and it aborts
8250         //    the whole loop (even if the loop is fast, it's quadratic).
8251         //    It's important for the loop break condition (see below) to
8252         //    check this limit even between two read-only instructions.
8253         if (DistToSrc >= MaxMemDepDistance ||
8254             ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
8255              (numAliased >= AliasedCheckLimit ||
8256               SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
8257 
8258           // We increment the counter only if the locations are aliased
8259           // (instead of counting all alias checks). This gives a better
8260           // balance between reduced runtime and accurate dependencies.
8261           numAliased++;
8262 
8263           DepDest->MemoryDependencies.push_back(BundleMember);
8264           BundleMember->Dependencies++;
8265           ScheduleData *DestBundle = DepDest->FirstInBundle;
8266           if (!DestBundle->IsScheduled) {
8267             BundleMember->incrementUnscheduledDeps(1);
8268           }
8269           if (!DestBundle->hasValidDependencies()) {
8270             WorkList.push_back(DestBundle);
8271           }
8272         }
8273 
8274         // Example, explaining the loop break condition: Let's assume our
8275         // starting instruction is i0 and MaxMemDepDistance = 3.
8276         //
8277         //                      +--------v--v--v
8278         //             i0,i1,i2,i3,i4,i5,i6,i7,i8
8279         //             +--------^--^--^
8280         //
8281         // MaxMemDepDistance let us stop alias-checking at i3 and we add
8282         // dependencies from i0 to i3,i4,.. (even if they are not aliased).
8283         // Previously we already added dependencies from i3 to i6,i7,i8
8284         // (because of MaxMemDepDistance). As we added a dependency from
8285         // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
8286         // and we can abort this loop at i6.
8287         if (DistToSrc >= 2 * MaxMemDepDistance)
8288           break;
8289         DistToSrc++;
8290       }
8291     }
8292     if (InsertInReadyList && SD->isReady()) {
8293       ReadyInsts.insert(SD);
8294       LLVM_DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst
8295                         << "\n");
8296     }
8297   }
8298 }
8299 
8300 void BoUpSLP::BlockScheduling::resetSchedule() {
8301   assert(ScheduleStart &&
8302          "tried to reset schedule on block which has not been scheduled");
8303   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
8304     doForAllOpcodes(I, [&](ScheduleData *SD) {
8305       assert(isInSchedulingRegion(SD) &&
8306              "ScheduleData not in scheduling region");
8307       SD->IsScheduled = false;
8308       SD->resetUnscheduledDeps();
8309     });
8310   }
8311   ReadyInsts.clear();
8312 }
8313 
8314 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
8315   if (!BS->ScheduleStart)
8316     return;
8317 
8318   LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
8319 
8320   // A key point - if we got here, pre-scheduling was able to find a valid
8321   // scheduling of the sub-graph of the scheduling window which consists
8322   // of all vector bundles and their transitive users.  As such, we do not
8323   // need to reschedule anything *outside of* that subgraph.
8324 
8325   BS->resetSchedule();
8326 
8327   // For the real scheduling we use a more sophisticated ready-list: it is
8328   // sorted by the original instruction location. This lets the final schedule
8329   // be as  close as possible to the original instruction order.
8330   // WARNING: If changing this order causes a correctness issue, that means
8331   // there is some missing dependence edge in the schedule data graph.
8332   struct ScheduleDataCompare {
8333     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
8334       return SD2->SchedulingPriority < SD1->SchedulingPriority;
8335     }
8336   };
8337   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
8338 
8339   // Ensure that all dependency data is updated (for nodes in the sub-graph)
8340   // and fill the ready-list with initial instructions.
8341   int Idx = 0;
8342   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
8343        I = I->getNextNode()) {
8344     BS->doForAllOpcodes(I, [this, &Idx, BS](ScheduleData *SD) {
8345       TreeEntry *SDTE = getTreeEntry(SD->Inst);
8346       (void)SDTE;
8347       assert((isVectorLikeInstWithConstOps(SD->Inst) ||
8348               SD->isPartOfBundle() ==
8349                   (SDTE && !doesNotNeedToSchedule(SDTE->Scalars))) &&
8350              "scheduler and vectorizer bundle mismatch");
8351       SD->FirstInBundle->SchedulingPriority = Idx++;
8352 
8353       if (SD->isSchedulingEntity() && SD->isPartOfBundle())
8354         BS->calculateDependencies(SD, false, this);
8355     });
8356   }
8357   BS->initialFillReadyList(ReadyInsts);
8358 
8359   Instruction *LastScheduledInst = BS->ScheduleEnd;
8360 
8361   // Do the "real" scheduling.
8362   while (!ReadyInsts.empty()) {
8363     ScheduleData *picked = *ReadyInsts.begin();
8364     ReadyInsts.erase(ReadyInsts.begin());
8365 
8366     // Move the scheduled instruction(s) to their dedicated places, if not
8367     // there yet.
8368     for (ScheduleData *BundleMember = picked; BundleMember;
8369          BundleMember = BundleMember->NextInBundle) {
8370       Instruction *pickedInst = BundleMember->Inst;
8371       if (pickedInst->getNextNode() != LastScheduledInst)
8372         pickedInst->moveBefore(LastScheduledInst);
8373       LastScheduledInst = pickedInst;
8374     }
8375 
8376     BS->schedule(picked, ReadyInsts);
8377   }
8378 
8379   // Check that we didn't break any of our invariants.
8380 #ifdef EXPENSIVE_CHECKS
8381   BS->verify();
8382 #endif
8383 
8384 #if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS)
8385   // Check that all schedulable entities got scheduled
8386   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; I = I->getNextNode()) {
8387     BS->doForAllOpcodes(I, [&](ScheduleData *SD) {
8388       if (SD->isSchedulingEntity() && SD->hasValidDependencies()) {
8389         assert(SD->IsScheduled && "must be scheduled at this point");
8390       }
8391     });
8392   }
8393 #endif
8394 
8395   // Avoid duplicate scheduling of the block.
8396   BS->ScheduleStart = nullptr;
8397 }
8398 
8399 unsigned BoUpSLP::getVectorElementSize(Value *V) {
8400   // If V is a store, just return the width of the stored value (or value
8401   // truncated just before storing) without traversing the expression tree.
8402   // This is the common case.
8403   if (auto *Store = dyn_cast<StoreInst>(V)) {
8404     if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand()))
8405       return DL->getTypeSizeInBits(Trunc->getSrcTy());
8406     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
8407   }
8408 
8409   if (auto *IEI = dyn_cast<InsertElementInst>(V))
8410     return getVectorElementSize(IEI->getOperand(1));
8411 
8412   auto E = InstrElementSize.find(V);
8413   if (E != InstrElementSize.end())
8414     return E->second;
8415 
8416   // If V is not a store, we can traverse the expression tree to find loads
8417   // that feed it. The type of the loaded value may indicate a more suitable
8418   // width than V's type. We want to base the vector element size on the width
8419   // of memory operations where possible.
8420   SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist;
8421   SmallPtrSet<Instruction *, 16> Visited;
8422   if (auto *I = dyn_cast<Instruction>(V)) {
8423     Worklist.emplace_back(I, I->getParent());
8424     Visited.insert(I);
8425   }
8426 
8427   // Traverse the expression tree in bottom-up order looking for loads. If we
8428   // encounter an instruction we don't yet handle, we give up.
8429   auto Width = 0u;
8430   while (!Worklist.empty()) {
8431     Instruction *I;
8432     BasicBlock *Parent;
8433     std::tie(I, Parent) = Worklist.pop_back_val();
8434 
8435     // We should only be looking at scalar instructions here. If the current
8436     // instruction has a vector type, skip.
8437     auto *Ty = I->getType();
8438     if (isa<VectorType>(Ty))
8439       continue;
8440 
8441     // If the current instruction is a load, update MaxWidth to reflect the
8442     // width of the loaded value.
8443     if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) ||
8444         isa<ExtractValueInst>(I))
8445       Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty));
8446 
8447     // Otherwise, we need to visit the operands of the instruction. We only
8448     // handle the interesting cases from buildTree here. If an operand is an
8449     // instruction we haven't yet visited and from the same basic block as the
8450     // user or the use is a PHI node, we add it to the worklist.
8451     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
8452              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) ||
8453              isa<UnaryOperator>(I)) {
8454       for (Use &U : I->operands())
8455         if (auto *J = dyn_cast<Instruction>(U.get()))
8456           if (Visited.insert(J).second &&
8457               (isa<PHINode>(I) || J->getParent() == Parent))
8458             Worklist.emplace_back(J, J->getParent());
8459     } else {
8460       break;
8461     }
8462   }
8463 
8464   // If we didn't encounter a memory access in the expression tree, or if we
8465   // gave up for some reason, just return the width of V. Otherwise, return the
8466   // maximum width we found.
8467   if (!Width) {
8468     if (auto *CI = dyn_cast<CmpInst>(V))
8469       V = CI->getOperand(0);
8470     Width = DL->getTypeSizeInBits(V->getType());
8471   }
8472 
8473   for (Instruction *I : Visited)
8474     InstrElementSize[I] = Width;
8475 
8476   return Width;
8477 }
8478 
8479 // Determine if a value V in a vectorizable expression Expr can be demoted to a
8480 // smaller type with a truncation. We collect the values that will be demoted
8481 // in ToDemote and additional roots that require investigating in Roots.
8482 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
8483                                   SmallVectorImpl<Value *> &ToDemote,
8484                                   SmallVectorImpl<Value *> &Roots) {
8485   // We can always demote constants.
8486   if (isa<Constant>(V)) {
8487     ToDemote.push_back(V);
8488     return true;
8489   }
8490 
8491   // If the value is not an instruction in the expression with only one use, it
8492   // cannot be demoted.
8493   auto *I = dyn_cast<Instruction>(V);
8494   if (!I || !I->hasOneUse() || !Expr.count(I))
8495     return false;
8496 
8497   switch (I->getOpcode()) {
8498 
8499   // We can always demote truncations and extensions. Since truncations can
8500   // seed additional demotion, we save the truncated value.
8501   case Instruction::Trunc:
8502     Roots.push_back(I->getOperand(0));
8503     break;
8504   case Instruction::ZExt:
8505   case Instruction::SExt:
8506     if (isa<ExtractElementInst>(I->getOperand(0)) ||
8507         isa<InsertElementInst>(I->getOperand(0)))
8508       return false;
8509     break;
8510 
8511   // We can demote certain binary operations if we can demote both of their
8512   // operands.
8513   case Instruction::Add:
8514   case Instruction::Sub:
8515   case Instruction::Mul:
8516   case Instruction::And:
8517   case Instruction::Or:
8518   case Instruction::Xor:
8519     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
8520         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
8521       return false;
8522     break;
8523 
8524   // We can demote selects if we can demote their true and false values.
8525   case Instruction::Select: {
8526     SelectInst *SI = cast<SelectInst>(I);
8527     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
8528         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
8529       return false;
8530     break;
8531   }
8532 
8533   // We can demote phis if we can demote all their incoming operands. Note that
8534   // we don't need to worry about cycles since we ensure single use above.
8535   case Instruction::PHI: {
8536     PHINode *PN = cast<PHINode>(I);
8537     for (Value *IncValue : PN->incoming_values())
8538       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
8539         return false;
8540     break;
8541   }
8542 
8543   // Otherwise, conservatively give up.
8544   default:
8545     return false;
8546   }
8547 
8548   // Record the value that we can demote.
8549   ToDemote.push_back(V);
8550   return true;
8551 }
8552 
8553 void BoUpSLP::computeMinimumValueSizes() {
8554   // If there are no external uses, the expression tree must be rooted by a
8555   // store. We can't demote in-memory values, so there is nothing to do here.
8556   if (ExternalUses.empty())
8557     return;
8558 
8559   // We only attempt to truncate integer expressions.
8560   auto &TreeRoot = VectorizableTree[0]->Scalars;
8561   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
8562   if (!TreeRootIT)
8563     return;
8564 
8565   // If the expression is not rooted by a store, these roots should have
8566   // external uses. We will rely on InstCombine to rewrite the expression in
8567   // the narrower type. However, InstCombine only rewrites single-use values.
8568   // This means that if a tree entry other than a root is used externally, it
8569   // must have multiple uses and InstCombine will not rewrite it. The code
8570   // below ensures that only the roots are used externally.
8571   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
8572   for (auto &EU : ExternalUses)
8573     if (!Expr.erase(EU.Scalar))
8574       return;
8575   if (!Expr.empty())
8576     return;
8577 
8578   // Collect the scalar values of the vectorizable expression. We will use this
8579   // context to determine which values can be demoted. If we see a truncation,
8580   // we mark it as seeding another demotion.
8581   for (auto &EntryPtr : VectorizableTree)
8582     Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
8583 
8584   // Ensure the roots of the vectorizable tree don't form a cycle. They must
8585   // have a single external user that is not in the vectorizable tree.
8586   for (auto *Root : TreeRoot)
8587     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
8588       return;
8589 
8590   // Conservatively determine if we can actually truncate the roots of the
8591   // expression. Collect the values that can be demoted in ToDemote and
8592   // additional roots that require investigating in Roots.
8593   SmallVector<Value *, 32> ToDemote;
8594   SmallVector<Value *, 4> Roots;
8595   for (auto *Root : TreeRoot)
8596     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
8597       return;
8598 
8599   // The maximum bit width required to represent all the values that can be
8600   // demoted without loss of precision. It would be safe to truncate the roots
8601   // of the expression to this width.
8602   auto MaxBitWidth = 8u;
8603 
8604   // We first check if all the bits of the roots are demanded. If they're not,
8605   // we can truncate the roots to this narrower type.
8606   for (auto *Root : TreeRoot) {
8607     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
8608     MaxBitWidth = std::max<unsigned>(
8609         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
8610   }
8611 
8612   // True if the roots can be zero-extended back to their original type, rather
8613   // than sign-extended. We know that if the leading bits are not demanded, we
8614   // can safely zero-extend. So we initialize IsKnownPositive to True.
8615   bool IsKnownPositive = true;
8616 
8617   // If all the bits of the roots are demanded, we can try a little harder to
8618   // compute a narrower type. This can happen, for example, if the roots are
8619   // getelementptr indices. InstCombine promotes these indices to the pointer
8620   // width. Thus, all their bits are technically demanded even though the
8621   // address computation might be vectorized in a smaller type.
8622   //
8623   // We start by looking at each entry that can be demoted. We compute the
8624   // maximum bit width required to store the scalar by using ValueTracking to
8625   // compute the number of high-order bits we can truncate.
8626   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
8627       llvm::all_of(TreeRoot, [](Value *R) {
8628         assert(R->hasOneUse() && "Root should have only one use!");
8629         return isa<GetElementPtrInst>(R->user_back());
8630       })) {
8631     MaxBitWidth = 8u;
8632 
8633     // Determine if the sign bit of all the roots is known to be zero. If not,
8634     // IsKnownPositive is set to False.
8635     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
8636       KnownBits Known = computeKnownBits(R, *DL);
8637       return Known.isNonNegative();
8638     });
8639 
8640     // Determine the maximum number of bits required to store the scalar
8641     // values.
8642     for (auto *Scalar : ToDemote) {
8643       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
8644       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
8645       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
8646     }
8647 
8648     // If we can't prove that the sign bit is zero, we must add one to the
8649     // maximum bit width to account for the unknown sign bit. This preserves
8650     // the existing sign bit so we can safely sign-extend the root back to the
8651     // original type. Otherwise, if we know the sign bit is zero, we will
8652     // zero-extend the root instead.
8653     //
8654     // FIXME: This is somewhat suboptimal, as there will be cases where adding
8655     //        one to the maximum bit width will yield a larger-than-necessary
8656     //        type. In general, we need to add an extra bit only if we can't
8657     //        prove that the upper bit of the original type is equal to the
8658     //        upper bit of the proposed smaller type. If these two bits are the
8659     //        same (either zero or one) we know that sign-extending from the
8660     //        smaller type will result in the same value. Here, since we can't
8661     //        yet prove this, we are just making the proposed smaller type
8662     //        larger to ensure correctness.
8663     if (!IsKnownPositive)
8664       ++MaxBitWidth;
8665   }
8666 
8667   // Round MaxBitWidth up to the next power-of-two.
8668   if (!isPowerOf2_64(MaxBitWidth))
8669     MaxBitWidth = NextPowerOf2(MaxBitWidth);
8670 
8671   // If the maximum bit width we compute is less than the with of the roots'
8672   // type, we can proceed with the narrowing. Otherwise, do nothing.
8673   if (MaxBitWidth >= TreeRootIT->getBitWidth())
8674     return;
8675 
8676   // If we can truncate the root, we must collect additional values that might
8677   // be demoted as a result. That is, those seeded by truncations we will
8678   // modify.
8679   while (!Roots.empty())
8680     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
8681 
8682   // Finally, map the values we can demote to the maximum bit with we computed.
8683   for (auto *Scalar : ToDemote)
8684     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
8685 }
8686 
8687 namespace {
8688 
8689 /// The SLPVectorizer Pass.
8690 struct SLPVectorizer : public FunctionPass {
8691   SLPVectorizerPass Impl;
8692 
8693   /// Pass identification, replacement for typeid
8694   static char ID;
8695 
8696   explicit SLPVectorizer() : FunctionPass(ID) {
8697     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
8698   }
8699 
8700   bool doInitialization(Module &M) override { return false; }
8701 
8702   bool runOnFunction(Function &F) override {
8703     if (skipFunction(F))
8704       return false;
8705 
8706     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
8707     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
8708     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
8709     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
8710     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
8711     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
8712     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
8713     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
8714     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
8715     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
8716 
8717     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8718   }
8719 
8720   void getAnalysisUsage(AnalysisUsage &AU) const override {
8721     FunctionPass::getAnalysisUsage(AU);
8722     AU.addRequired<AssumptionCacheTracker>();
8723     AU.addRequired<ScalarEvolutionWrapperPass>();
8724     AU.addRequired<AAResultsWrapperPass>();
8725     AU.addRequired<TargetTransformInfoWrapperPass>();
8726     AU.addRequired<LoopInfoWrapperPass>();
8727     AU.addRequired<DominatorTreeWrapperPass>();
8728     AU.addRequired<DemandedBitsWrapperPass>();
8729     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
8730     AU.addRequired<InjectTLIMappingsLegacy>();
8731     AU.addPreserved<LoopInfoWrapperPass>();
8732     AU.addPreserved<DominatorTreeWrapperPass>();
8733     AU.addPreserved<AAResultsWrapperPass>();
8734     AU.addPreserved<GlobalsAAWrapperPass>();
8735     AU.setPreservesCFG();
8736   }
8737 };
8738 
8739 } // end anonymous namespace
8740 
8741 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
8742   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
8743   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
8744   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
8745   auto *AA = &AM.getResult<AAManager>(F);
8746   auto *LI = &AM.getResult<LoopAnalysis>(F);
8747   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
8748   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
8749   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
8750   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
8751 
8752   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8753   if (!Changed)
8754     return PreservedAnalyses::all();
8755 
8756   PreservedAnalyses PA;
8757   PA.preserveSet<CFGAnalyses>();
8758   return PA;
8759 }
8760 
8761 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
8762                                 TargetTransformInfo *TTI_,
8763                                 TargetLibraryInfo *TLI_, AAResults *AA_,
8764                                 LoopInfo *LI_, DominatorTree *DT_,
8765                                 AssumptionCache *AC_, DemandedBits *DB_,
8766                                 OptimizationRemarkEmitter *ORE_) {
8767   if (!RunSLPVectorization)
8768     return false;
8769   SE = SE_;
8770   TTI = TTI_;
8771   TLI = TLI_;
8772   AA = AA_;
8773   LI = LI_;
8774   DT = DT_;
8775   AC = AC_;
8776   DB = DB_;
8777   DL = &F.getParent()->getDataLayout();
8778 
8779   Stores.clear();
8780   GEPs.clear();
8781   bool Changed = false;
8782 
8783   // If the target claims to have no vector registers don't attempt
8784   // vectorization.
8785   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true))) {
8786     LLVM_DEBUG(
8787         dbgs() << "SLP: Didn't find any vector registers for target, abort.\n");
8788     return false;
8789   }
8790 
8791   // Don't vectorize when the attribute NoImplicitFloat is used.
8792   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
8793     return false;
8794 
8795   LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
8796 
8797   // Use the bottom up slp vectorizer to construct chains that start with
8798   // store instructions.
8799   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
8800 
8801   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
8802   // delete instructions.
8803 
8804   // Update DFS numbers now so that we can use them for ordering.
8805   DT->updateDFSNumbers();
8806 
8807   // Scan the blocks in the function in post order.
8808   for (auto BB : post_order(&F.getEntryBlock())) {
8809     collectSeedInstructions(BB);
8810 
8811     // Vectorize trees that end at stores.
8812     if (!Stores.empty()) {
8813       LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
8814                         << " underlying objects.\n");
8815       Changed |= vectorizeStoreChains(R);
8816     }
8817 
8818     // Vectorize trees that end at reductions.
8819     Changed |= vectorizeChainsInBlock(BB, R);
8820 
8821     // Vectorize the index computations of getelementptr instructions. This
8822     // is primarily intended to catch gather-like idioms ending at
8823     // non-consecutive loads.
8824     if (!GEPs.empty()) {
8825       LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
8826                         << " underlying objects.\n");
8827       Changed |= vectorizeGEPIndices(BB, R);
8828     }
8829   }
8830 
8831   if (Changed) {
8832     R.optimizeGatherSequence();
8833     LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
8834   }
8835   return Changed;
8836 }
8837 
8838 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
8839                                             unsigned Idx) {
8840   LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()
8841                     << "\n");
8842   const unsigned Sz = R.getVectorElementSize(Chain[0]);
8843   const unsigned MinVF = R.getMinVecRegSize() / Sz;
8844   unsigned VF = Chain.size();
8845 
8846   if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
8847     return false;
8848 
8849   LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx
8850                     << "\n");
8851 
8852   R.buildTree(Chain);
8853   if (R.isTreeTinyAndNotFullyVectorizable())
8854     return false;
8855   if (R.isLoadCombineCandidate())
8856     return false;
8857   R.reorderTopToBottom();
8858   R.reorderBottomToTop();
8859   R.buildExternalUses();
8860 
8861   R.computeMinimumValueSizes();
8862 
8863   InstructionCost Cost = R.getTreeCost();
8864 
8865   LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n");
8866   if (Cost < -SLPCostThreshold) {
8867     LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n");
8868 
8869     using namespace ore;
8870 
8871     R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
8872                                         cast<StoreInst>(Chain[0]))
8873                      << "Stores SLP vectorized with cost " << NV("Cost", Cost)
8874                      << " and with tree size "
8875                      << NV("TreeSize", R.getTreeSize()));
8876 
8877     R.vectorizeTree();
8878     return true;
8879   }
8880 
8881   return false;
8882 }
8883 
8884 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
8885                                         BoUpSLP &R) {
8886   // We may run into multiple chains that merge into a single chain. We mark the
8887   // stores that we vectorized so that we don't visit the same store twice.
8888   BoUpSLP::ValueSet VectorizedStores;
8889   bool Changed = false;
8890 
8891   int E = Stores.size();
8892   SmallBitVector Tails(E, false);
8893   int MaxIter = MaxStoreLookup.getValue();
8894   SmallVector<std::pair<int, int>, 16> ConsecutiveChain(
8895       E, std::make_pair(E, INT_MAX));
8896   SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false));
8897   int IterCnt;
8898   auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
8899                                   &CheckedPairs,
8900                                   &ConsecutiveChain](int K, int Idx) {
8901     if (IterCnt >= MaxIter)
8902       return true;
8903     if (CheckedPairs[Idx].test(K))
8904       return ConsecutiveChain[K].second == 1 &&
8905              ConsecutiveChain[K].first == Idx;
8906     ++IterCnt;
8907     CheckedPairs[Idx].set(K);
8908     CheckedPairs[K].set(Idx);
8909     Optional<int> Diff = getPointersDiff(
8910         Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(),
8911         Stores[Idx]->getValueOperand()->getType(),
8912         Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true);
8913     if (!Diff || *Diff == 0)
8914       return false;
8915     int Val = *Diff;
8916     if (Val < 0) {
8917       if (ConsecutiveChain[Idx].second > -Val) {
8918         Tails.set(K);
8919         ConsecutiveChain[Idx] = std::make_pair(K, -Val);
8920       }
8921       return false;
8922     }
8923     if (ConsecutiveChain[K].second <= Val)
8924       return false;
8925 
8926     Tails.set(Idx);
8927     ConsecutiveChain[K] = std::make_pair(Idx, Val);
8928     return Val == 1;
8929   };
8930   // Do a quadratic search on all of the given stores in reverse order and find
8931   // all of the pairs of stores that follow each other.
8932   for (int Idx = E - 1; Idx >= 0; --Idx) {
8933     // If a store has multiple consecutive store candidates, search according
8934     // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
8935     // This is because usually pairing with immediate succeeding or preceding
8936     // candidate create the best chance to find slp vectorization opportunity.
8937     const int MaxLookDepth = std::max(E - Idx, Idx + 1);
8938     IterCnt = 0;
8939     for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
8940       if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
8941           (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
8942         break;
8943   }
8944 
8945   // Tracks if we tried to vectorize stores starting from the given tail
8946   // already.
8947   SmallBitVector TriedTails(E, false);
8948   // For stores that start but don't end a link in the chain:
8949   for (int Cnt = E; Cnt > 0; --Cnt) {
8950     int I = Cnt - 1;
8951     if (ConsecutiveChain[I].first == E || Tails.test(I))
8952       continue;
8953     // We found a store instr that starts a chain. Now follow the chain and try
8954     // to vectorize it.
8955     BoUpSLP::ValueList Operands;
8956     // Collect the chain into a list.
8957     while (I != E && !VectorizedStores.count(Stores[I])) {
8958       Operands.push_back(Stores[I]);
8959       Tails.set(I);
8960       if (ConsecutiveChain[I].second != 1) {
8961         // Mark the new end in the chain and go back, if required. It might be
8962         // required if the original stores come in reversed order, for example.
8963         if (ConsecutiveChain[I].first != E &&
8964             Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) &&
8965             !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) {
8966           TriedTails.set(I);
8967           Tails.reset(ConsecutiveChain[I].first);
8968           if (Cnt < ConsecutiveChain[I].first + 2)
8969             Cnt = ConsecutiveChain[I].first + 2;
8970         }
8971         break;
8972       }
8973       // Move to the next value in the chain.
8974       I = ConsecutiveChain[I].first;
8975     }
8976     assert(!Operands.empty() && "Expected non-empty list of stores.");
8977 
8978     unsigned MaxVecRegSize = R.getMaxVecRegSize();
8979     unsigned EltSize = R.getVectorElementSize(Operands[0]);
8980     unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize);
8981 
8982     unsigned MinVF = R.getMinVF(EltSize);
8983     unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store),
8984                               MaxElts);
8985 
8986     // FIXME: Is division-by-2 the correct step? Should we assert that the
8987     // register size is a power-of-2?
8988     unsigned StartIdx = 0;
8989     for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) {
8990       for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
8991         ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size);
8992         if (!VectorizedStores.count(Slice.front()) &&
8993             !VectorizedStores.count(Slice.back()) &&
8994             vectorizeStoreChain(Slice, R, Cnt)) {
8995           // Mark the vectorized stores so that we don't vectorize them again.
8996           VectorizedStores.insert(Slice.begin(), Slice.end());
8997           Changed = true;
8998           // If we vectorized initial block, no need to try to vectorize it
8999           // again.
9000           if (Cnt == StartIdx)
9001             StartIdx += Size;
9002           Cnt += Size;
9003           continue;
9004         }
9005         ++Cnt;
9006       }
9007       // Check if the whole array was vectorized already - exit.
9008       if (StartIdx >= Operands.size())
9009         break;
9010     }
9011   }
9012 
9013   return Changed;
9014 }
9015 
9016 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
9017   // Initialize the collections. We will make a single pass over the block.
9018   Stores.clear();
9019   GEPs.clear();
9020 
9021   // Visit the store and getelementptr instructions in BB and organize them in
9022   // Stores and GEPs according to the underlying objects of their pointer
9023   // operands.
9024   for (Instruction &I : *BB) {
9025     // Ignore store instructions that are volatile or have a pointer operand
9026     // that doesn't point to a scalar type.
9027     if (auto *SI = dyn_cast<StoreInst>(&I)) {
9028       if (!SI->isSimple())
9029         continue;
9030       if (!isValidElementType(SI->getValueOperand()->getType()))
9031         continue;
9032       Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI);
9033     }
9034 
9035     // Ignore getelementptr instructions that have more than one index, a
9036     // constant index, or a pointer operand that doesn't point to a scalar
9037     // type.
9038     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
9039       auto Idx = GEP->idx_begin()->get();
9040       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
9041         continue;
9042       if (!isValidElementType(Idx->getType()))
9043         continue;
9044       if (GEP->getType()->isVectorTy())
9045         continue;
9046       GEPs[GEP->getPointerOperand()].push_back(GEP);
9047     }
9048   }
9049 }
9050 
9051 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
9052   if (!A || !B)
9053     return false;
9054   if (isa<InsertElementInst>(A) || isa<InsertElementInst>(B))
9055     return false;
9056   Value *VL[] = {A, B};
9057   return tryToVectorizeList(VL, R);
9058 }
9059 
9060 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
9061                                            bool LimitForRegisterSize) {
9062   if (VL.size() < 2)
9063     return false;
9064 
9065   LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
9066                     << VL.size() << ".\n");
9067 
9068   // Check that all of the parts are instructions of the same type,
9069   // we permit an alternate opcode via InstructionsState.
9070   InstructionsState S = getSameOpcode(VL);
9071   if (!S.getOpcode())
9072     return false;
9073 
9074   Instruction *I0 = cast<Instruction>(S.OpValue);
9075   // Make sure invalid types (including vector type) are rejected before
9076   // determining vectorization factor for scalar instructions.
9077   for (Value *V : VL) {
9078     Type *Ty = V->getType();
9079     if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) {
9080       // NOTE: the following will give user internal llvm type name, which may
9081       // not be useful.
9082       R.getORE()->emit([&]() {
9083         std::string type_str;
9084         llvm::raw_string_ostream rso(type_str);
9085         Ty->print(rso);
9086         return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
9087                << "Cannot SLP vectorize list: type "
9088                << rso.str() + " is unsupported by vectorizer";
9089       });
9090       return false;
9091     }
9092   }
9093 
9094   unsigned Sz = R.getVectorElementSize(I0);
9095   unsigned MinVF = R.getMinVF(Sz);
9096   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
9097   MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF);
9098   if (MaxVF < 2) {
9099     R.getORE()->emit([&]() {
9100       return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
9101              << "Cannot SLP vectorize list: vectorization factor "
9102              << "less than 2 is not supported";
9103     });
9104     return false;
9105   }
9106 
9107   bool Changed = false;
9108   bool CandidateFound = false;
9109   InstructionCost MinCost = SLPCostThreshold.getValue();
9110   Type *ScalarTy = VL[0]->getType();
9111   if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
9112     ScalarTy = IE->getOperand(1)->getType();
9113 
9114   unsigned NextInst = 0, MaxInst = VL.size();
9115   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
9116     // No actual vectorization should happen, if number of parts is the same as
9117     // provided vectorization factor (i.e. the scalar type is used for vector
9118     // code during codegen).
9119     auto *VecTy = FixedVectorType::get(ScalarTy, VF);
9120     if (TTI->getNumberOfParts(VecTy) == VF)
9121       continue;
9122     for (unsigned I = NextInst; I < MaxInst; ++I) {
9123       unsigned OpsWidth = 0;
9124 
9125       if (I + VF > MaxInst)
9126         OpsWidth = MaxInst - I;
9127       else
9128         OpsWidth = VF;
9129 
9130       if (!isPowerOf2_32(OpsWidth))
9131         continue;
9132 
9133       if ((LimitForRegisterSize && OpsWidth < MaxVF) ||
9134           (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2))
9135         break;
9136 
9137       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
9138       // Check that a previous iteration of this loop did not delete the Value.
9139       if (llvm::any_of(Ops, [&R](Value *V) {
9140             auto *I = dyn_cast<Instruction>(V);
9141             return I && R.isDeleted(I);
9142           }))
9143         continue;
9144 
9145       LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
9146                         << "\n");
9147 
9148       R.buildTree(Ops);
9149       if (R.isTreeTinyAndNotFullyVectorizable())
9150         continue;
9151       R.reorderTopToBottom();
9152       R.reorderBottomToTop(!isa<InsertElementInst>(Ops.front()));
9153       R.buildExternalUses();
9154 
9155       R.computeMinimumValueSizes();
9156       InstructionCost Cost = R.getTreeCost();
9157       CandidateFound = true;
9158       MinCost = std::min(MinCost, Cost);
9159 
9160       if (Cost < -SLPCostThreshold) {
9161         LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
9162         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
9163                                                     cast<Instruction>(Ops[0]))
9164                                  << "SLP vectorized with cost " << ore::NV("Cost", Cost)
9165                                  << " and with tree size "
9166                                  << ore::NV("TreeSize", R.getTreeSize()));
9167 
9168         R.vectorizeTree();
9169         // Move to the next bundle.
9170         I += VF - 1;
9171         NextInst = I + 1;
9172         Changed = true;
9173       }
9174     }
9175   }
9176 
9177   if (!Changed && CandidateFound) {
9178     R.getORE()->emit([&]() {
9179       return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
9180              << "List vectorization was possible but not beneficial with cost "
9181              << ore::NV("Cost", MinCost) << " >= "
9182              << ore::NV("Treshold", -SLPCostThreshold);
9183     });
9184   } else if (!Changed) {
9185     R.getORE()->emit([&]() {
9186       return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
9187              << "Cannot SLP vectorize list: vectorization was impossible"
9188              << " with available vectorization factors";
9189     });
9190   }
9191   return Changed;
9192 }
9193 
9194 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
9195   if (!I)
9196     return false;
9197 
9198   if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I))
9199     return false;
9200 
9201   Value *P = I->getParent();
9202 
9203   // Vectorize in current basic block only.
9204   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
9205   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
9206   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
9207     return false;
9208 
9209   // Try to vectorize V.
9210   if (tryToVectorizePair(Op0, Op1, R))
9211     return true;
9212 
9213   auto *A = dyn_cast<BinaryOperator>(Op0);
9214   auto *B = dyn_cast<BinaryOperator>(Op1);
9215   // Try to skip B.
9216   if (B && B->hasOneUse()) {
9217     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
9218     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
9219     if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
9220       return true;
9221     if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
9222       return true;
9223   }
9224 
9225   // Try to skip A.
9226   if (A && A->hasOneUse()) {
9227     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
9228     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
9229     if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
9230       return true;
9231     if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
9232       return true;
9233   }
9234   return false;
9235 }
9236 
9237 namespace {
9238 
9239 /// Model horizontal reductions.
9240 ///
9241 /// A horizontal reduction is a tree of reduction instructions that has values
9242 /// that can be put into a vector as its leaves. For example:
9243 ///
9244 /// mul mul mul mul
9245 ///  \  /    \  /
9246 ///   +       +
9247 ///    \     /
9248 ///       +
9249 /// This tree has "mul" as its leaf values and "+" as its reduction
9250 /// instructions. A reduction can feed into a store or a binary operation
9251 /// feeding a phi.
9252 ///    ...
9253 ///    \  /
9254 ///     +
9255 ///     |
9256 ///  phi +=
9257 ///
9258 ///  Or:
9259 ///    ...
9260 ///    \  /
9261 ///     +
9262 ///     |
9263 ///   *p =
9264 ///
9265 class HorizontalReduction {
9266   using ReductionOpsType = SmallVector<Value *, 16>;
9267   using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
9268   ReductionOpsListType ReductionOps;
9269   /// List of possibly reduced values.
9270   SmallVector<SmallVector<Value *>> ReducedVals;
9271   /// Maps reduced value to the corresponding reduction operation.
9272   DenseMap<Value *, Instruction *> ReducedValsToOps;
9273   // Use map vector to make stable output.
9274   MapVector<Instruction *, Value *> ExtraArgs;
9275   WeakTrackingVH ReductionRoot;
9276   /// The type of reduction operation.
9277   RecurKind RdxKind;
9278 
9279   static bool isCmpSelMinMax(Instruction *I) {
9280     return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) &&
9281            RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I));
9282   }
9283 
9284   // And/or are potentially poison-safe logical patterns like:
9285   // select x, y, false
9286   // select x, true, y
9287   static bool isBoolLogicOp(Instruction *I) {
9288     return match(I, m_LogicalAnd(m_Value(), m_Value())) ||
9289            match(I, m_LogicalOr(m_Value(), m_Value()));
9290   }
9291 
9292   /// Checks if instruction is associative and can be vectorized.
9293   static bool isVectorizable(RecurKind Kind, Instruction *I) {
9294     if (Kind == RecurKind::None)
9295       return false;
9296 
9297     // Integer ops that map to select instructions or intrinsics are fine.
9298     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) ||
9299         isBoolLogicOp(I))
9300       return true;
9301 
9302     if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) {
9303       // FP min/max are associative except for NaN and -0.0. We do not
9304       // have to rule out -0.0 here because the intrinsic semantics do not
9305       // specify a fixed result for it.
9306       return I->getFastMathFlags().noNaNs();
9307     }
9308 
9309     return I->isAssociative();
9310   }
9311 
9312   static Value *getRdxOperand(Instruction *I, unsigned Index) {
9313     // Poison-safe 'or' takes the form: select X, true, Y
9314     // To make that work with the normal operand processing, we skip the
9315     // true value operand.
9316     // TODO: Change the code and data structures to handle this without a hack.
9317     if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1)
9318       return I->getOperand(2);
9319     return I->getOperand(Index);
9320   }
9321 
9322   /// Creates reduction operation with the current opcode.
9323   static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS,
9324                          Value *RHS, const Twine &Name, bool UseSelect) {
9325     unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind);
9326     switch (Kind) {
9327     case RecurKind::Or:
9328       if (UseSelect &&
9329           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9330         return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name);
9331       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9332                                  Name);
9333     case RecurKind::And:
9334       if (UseSelect &&
9335           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9336         return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name);
9337       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9338                                  Name);
9339     case RecurKind::Add:
9340     case RecurKind::Mul:
9341     case RecurKind::Xor:
9342     case RecurKind::FAdd:
9343     case RecurKind::FMul:
9344       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9345                                  Name);
9346     case RecurKind::FMax:
9347       return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS);
9348     case RecurKind::FMin:
9349       return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS);
9350     case RecurKind::SMax:
9351       if (UseSelect) {
9352         Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name);
9353         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9354       }
9355       return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS);
9356     case RecurKind::SMin:
9357       if (UseSelect) {
9358         Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name);
9359         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9360       }
9361       return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS);
9362     case RecurKind::UMax:
9363       if (UseSelect) {
9364         Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name);
9365         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9366       }
9367       return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS);
9368     case RecurKind::UMin:
9369       if (UseSelect) {
9370         Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name);
9371         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9372       }
9373       return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS);
9374     default:
9375       llvm_unreachable("Unknown reduction operation.");
9376     }
9377   }
9378 
9379   /// Creates reduction operation with the current opcode with the IR flags
9380   /// from \p ReductionOps.
9381   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9382                          Value *RHS, const Twine &Name,
9383                          const ReductionOpsListType &ReductionOps) {
9384     bool UseSelect = ReductionOps.size() == 2 ||
9385                      // Logical or/and.
9386                      (ReductionOps.size() == 1 &&
9387                       isa<SelectInst>(ReductionOps.front().front()));
9388     assert((!UseSelect || ReductionOps.size() != 2 ||
9389             isa<SelectInst>(ReductionOps[1][0])) &&
9390            "Expected cmp + select pairs for reduction");
9391     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect);
9392     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9393       if (auto *Sel = dyn_cast<SelectInst>(Op)) {
9394         propagateIRFlags(Sel->getCondition(), ReductionOps[0]);
9395         propagateIRFlags(Op, ReductionOps[1]);
9396         return Op;
9397       }
9398     }
9399     propagateIRFlags(Op, ReductionOps[0]);
9400     return Op;
9401   }
9402 
9403   /// Creates reduction operation with the current opcode with the IR flags
9404   /// from \p I.
9405   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9406                          Value *RHS, const Twine &Name, Value *I) {
9407     auto *SelI = dyn_cast<SelectInst>(I);
9408     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, SelI != nullptr);
9409     if (SelI && RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9410       if (auto *Sel = dyn_cast<SelectInst>(Op))
9411         propagateIRFlags(Sel->getCondition(), SelI->getCondition());
9412     }
9413     propagateIRFlags(Op, I);
9414     return Op;
9415   }
9416 
9417   static RecurKind getRdxKind(Value *V) {
9418     auto *I = dyn_cast<Instruction>(V);
9419     if (!I)
9420       return RecurKind::None;
9421     if (match(I, m_Add(m_Value(), m_Value())))
9422       return RecurKind::Add;
9423     if (match(I, m_Mul(m_Value(), m_Value())))
9424       return RecurKind::Mul;
9425     if (match(I, m_And(m_Value(), m_Value())) ||
9426         match(I, m_LogicalAnd(m_Value(), m_Value())))
9427       return RecurKind::And;
9428     if (match(I, m_Or(m_Value(), m_Value())) ||
9429         match(I, m_LogicalOr(m_Value(), m_Value())))
9430       return RecurKind::Or;
9431     if (match(I, m_Xor(m_Value(), m_Value())))
9432       return RecurKind::Xor;
9433     if (match(I, m_FAdd(m_Value(), m_Value())))
9434       return RecurKind::FAdd;
9435     if (match(I, m_FMul(m_Value(), m_Value())))
9436       return RecurKind::FMul;
9437 
9438     if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value())))
9439       return RecurKind::FMax;
9440     if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value())))
9441       return RecurKind::FMin;
9442 
9443     // This matches either cmp+select or intrinsics. SLP is expected to handle
9444     // either form.
9445     // TODO: If we are canonicalizing to intrinsics, we can remove several
9446     //       special-case paths that deal with selects.
9447     if (match(I, m_SMax(m_Value(), m_Value())))
9448       return RecurKind::SMax;
9449     if (match(I, m_SMin(m_Value(), m_Value())))
9450       return RecurKind::SMin;
9451     if (match(I, m_UMax(m_Value(), m_Value())))
9452       return RecurKind::UMax;
9453     if (match(I, m_UMin(m_Value(), m_Value())))
9454       return RecurKind::UMin;
9455 
9456     if (auto *Select = dyn_cast<SelectInst>(I)) {
9457       // Try harder: look for min/max pattern based on instructions producing
9458       // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
9459       // During the intermediate stages of SLP, it's very common to have
9460       // pattern like this (since optimizeGatherSequence is run only once
9461       // at the end):
9462       // %1 = extractelement <2 x i32> %a, i32 0
9463       // %2 = extractelement <2 x i32> %a, i32 1
9464       // %cond = icmp sgt i32 %1, %2
9465       // %3 = extractelement <2 x i32> %a, i32 0
9466       // %4 = extractelement <2 x i32> %a, i32 1
9467       // %select = select i1 %cond, i32 %3, i32 %4
9468       CmpInst::Predicate Pred;
9469       Instruction *L1;
9470       Instruction *L2;
9471 
9472       Value *LHS = Select->getTrueValue();
9473       Value *RHS = Select->getFalseValue();
9474       Value *Cond = Select->getCondition();
9475 
9476       // TODO: Support inverse predicates.
9477       if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
9478         if (!isa<ExtractElementInst>(RHS) ||
9479             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9480           return RecurKind::None;
9481       } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
9482         if (!isa<ExtractElementInst>(LHS) ||
9483             !L1->isIdenticalTo(cast<Instruction>(LHS)))
9484           return RecurKind::None;
9485       } else {
9486         if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
9487           return RecurKind::None;
9488         if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
9489             !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
9490             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9491           return RecurKind::None;
9492       }
9493 
9494       switch (Pred) {
9495       default:
9496         return RecurKind::None;
9497       case CmpInst::ICMP_SGT:
9498       case CmpInst::ICMP_SGE:
9499         return RecurKind::SMax;
9500       case CmpInst::ICMP_SLT:
9501       case CmpInst::ICMP_SLE:
9502         return RecurKind::SMin;
9503       case CmpInst::ICMP_UGT:
9504       case CmpInst::ICMP_UGE:
9505         return RecurKind::UMax;
9506       case CmpInst::ICMP_ULT:
9507       case CmpInst::ICMP_ULE:
9508         return RecurKind::UMin;
9509       }
9510     }
9511     return RecurKind::None;
9512   }
9513 
9514   /// Get the index of the first operand.
9515   static unsigned getFirstOperandIndex(Instruction *I) {
9516     return isCmpSelMinMax(I) ? 1 : 0;
9517   }
9518 
9519   /// Total number of operands in the reduction operation.
9520   static unsigned getNumberOfOperands(Instruction *I) {
9521     return isCmpSelMinMax(I) ? 3 : 2;
9522   }
9523 
9524   /// Checks if the instruction is in basic block \p BB.
9525   /// For a cmp+sel min/max reduction check that both ops are in \p BB.
9526   static bool hasSameParent(Instruction *I, BasicBlock *BB) {
9527     if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) {
9528       auto *Sel = cast<SelectInst>(I);
9529       auto *Cmp = dyn_cast<Instruction>(Sel->getCondition());
9530       return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB;
9531     }
9532     return I->getParent() == BB;
9533   }
9534 
9535   /// Expected number of uses for reduction operations/reduced values.
9536   static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) {
9537     if (IsCmpSelMinMax) {
9538       // SelectInst must be used twice while the condition op must have single
9539       // use only.
9540       if (auto *Sel = dyn_cast<SelectInst>(I))
9541         return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse();
9542       return I->hasNUses(2);
9543     }
9544 
9545     // Arithmetic reduction operation must be used once only.
9546     return I->hasOneUse();
9547   }
9548 
9549   /// Initializes the list of reduction operations.
9550   void initReductionOps(Instruction *I) {
9551     if (isCmpSelMinMax(I))
9552       ReductionOps.assign(2, ReductionOpsType());
9553     else
9554       ReductionOps.assign(1, ReductionOpsType());
9555   }
9556 
9557   /// Add all reduction operations for the reduction instruction \p I.
9558   void addReductionOps(Instruction *I) {
9559     if (isCmpSelMinMax(I)) {
9560       ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
9561       ReductionOps[1].emplace_back(I);
9562     } else {
9563       ReductionOps[0].emplace_back(I);
9564     }
9565   }
9566 
9567   static Value *getLHS(RecurKind Kind, Instruction *I) {
9568     if (Kind == RecurKind::None)
9569       return nullptr;
9570     return I->getOperand(getFirstOperandIndex(I));
9571   }
9572   static Value *getRHS(RecurKind Kind, Instruction *I) {
9573     if (Kind == RecurKind::None)
9574       return nullptr;
9575     return I->getOperand(getFirstOperandIndex(I) + 1);
9576   }
9577 
9578 public:
9579   HorizontalReduction() = default;
9580 
9581   /// Try to find a reduction tree.
9582   bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst,
9583                                  ScalarEvolution &SE, const DataLayout &DL,
9584                                  const TargetLibraryInfo &TLI) {
9585     assert((!Phi || is_contained(Phi->operands(), Inst)) &&
9586            "Phi needs to use the binary operator");
9587     assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) ||
9588             isa<IntrinsicInst>(Inst)) &&
9589            "Expected binop, select, or intrinsic for reduction matching");
9590     RdxKind = getRdxKind(Inst);
9591 
9592     // We could have a initial reductions that is not an add.
9593     //  r *= v1 + v2 + v3 + v4
9594     // In such a case start looking for a tree rooted in the first '+'.
9595     if (Phi) {
9596       if (getLHS(RdxKind, Inst) == Phi) {
9597         Phi = nullptr;
9598         Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst));
9599         if (!Inst)
9600           return false;
9601         RdxKind = getRdxKind(Inst);
9602       } else if (getRHS(RdxKind, Inst) == Phi) {
9603         Phi = nullptr;
9604         Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst));
9605         if (!Inst)
9606           return false;
9607         RdxKind = getRdxKind(Inst);
9608       }
9609     }
9610 
9611     if (!isVectorizable(RdxKind, Inst))
9612       return false;
9613 
9614     // Analyze "regular" integer/FP types for reductions - no target-specific
9615     // types or pointers.
9616     Type *Ty = Inst->getType();
9617     if (!isValidElementType(Ty) || Ty->isPointerTy())
9618       return false;
9619 
9620     // Though the ultimate reduction may have multiple uses, its condition must
9621     // have only single use.
9622     if (auto *Sel = dyn_cast<SelectInst>(Inst))
9623       if (!Sel->getCondition()->hasOneUse())
9624         return false;
9625 
9626     ReductionRoot = Inst;
9627 
9628     // Iterate through all the operands of the possible reduction tree and
9629     // gather all the reduced values, sorting them by their value id.
9630     BasicBlock *BB = Inst->getParent();
9631     bool IsCmpSelMinMax = isCmpSelMinMax(Inst);
9632     SmallVector<Instruction *> Worklist(1, Inst);
9633     // Checks if the operands of the \p TreeN instruction are also reduction
9634     // operations or should be treated as reduced values or an extra argument,
9635     // which is not part of the reduction.
9636     auto &&CheckOperands = [this, IsCmpSelMinMax,
9637                             BB](Instruction *TreeN,
9638                                 SmallVectorImpl<Value *> &ExtraArgs,
9639                                 SmallVectorImpl<Value *> &PossibleReducedVals,
9640                                 SmallVectorImpl<Instruction *> &ReductionOps) {
9641       for (int I = getFirstOperandIndex(TreeN),
9642                End = getNumberOfOperands(TreeN);
9643            I < End; ++I) {
9644         Value *EdgeVal = getRdxOperand(TreeN, I);
9645         ReducedValsToOps.try_emplace(EdgeVal, TreeN);
9646         auto *EdgeInst = dyn_cast<Instruction>(EdgeVal);
9647         // Edge has wrong parent - mark as an extra argument.
9648         if (EdgeInst && !isVectorLikeInstWithConstOps(EdgeInst) &&
9649             !hasSameParent(EdgeInst, BB)) {
9650           ExtraArgs.push_back(EdgeVal);
9651           continue;
9652         }
9653         // If the edge is not an instruction, or it is different from the main
9654         // reduction opcode or has too many uses - possible reduced value.
9655         if (!EdgeInst || getRdxKind(EdgeInst) != RdxKind ||
9656             !hasRequiredNumberOfUses(IsCmpSelMinMax, EdgeInst) ||
9657             !isVectorizable(getRdxKind(EdgeInst), EdgeInst)) {
9658           PossibleReducedVals.push_back(EdgeVal);
9659           continue;
9660         }
9661         ReductionOps.push_back(EdgeInst);
9662       }
9663     };
9664     // Try to regroup reduced values so that it gets more profitable to try to
9665     // reduce them. Values are grouped by their value ids, instructions - by
9666     // instruction op id and/or alternate op id, plus do extra analysis for
9667     // loads (grouping them by the distabce between pointers) and cmp
9668     // instructions (grouping them by the predicate).
9669     MapVector<size_t, MapVector<size_t, SmallVector<Value *>>>
9670         PossibleReducedVals;
9671     initReductionOps(Inst);
9672     while (!Worklist.empty()) {
9673       Instruction *TreeN = Worklist.pop_back_val();
9674       SmallVector<Value *> Args;
9675       SmallVector<Value *> PossibleRedVals;
9676       SmallVector<Instruction *> PossibleReductionOps;
9677       CheckOperands(TreeN, Args, PossibleRedVals, PossibleReductionOps);
9678       // If too many extra args - mark the instruction itself as a reduction
9679       // value, not a reduction operation.
9680       if (Args.size() < 2) {
9681         addReductionOps(TreeN);
9682         // Add extra args.
9683         if (!Args.empty()) {
9684           assert(Args.size() == 1 && "Expected only single argument.");
9685           ExtraArgs[TreeN] = Args.front();
9686         }
9687         // Add reduction values. The values are sorted for better vectorization
9688         // results.
9689         for (Value *V : PossibleRedVals) {
9690           size_t Key, Idx;
9691           std::tie(Key, Idx) = generateKeySubkey(
9692               V, &TLI,
9693               [&PossibleReducedVals, &DL, &SE](size_t Key, LoadInst *LI) {
9694                 for (const auto &LoadData : PossibleReducedVals[Key]) {
9695                   auto *RLI = cast<LoadInst>(LoadData.second.front());
9696                   if (getPointersDiff(RLI->getType(), RLI->getPointerOperand(),
9697                                       LI->getType(), LI->getPointerOperand(),
9698                                       DL, SE, /*StrictCheck=*/true))
9699                     return hash_value(RLI->getPointerOperand());
9700                 }
9701                 return hash_value(LI->getPointerOperand());
9702               },
9703               /*AllowAlternate=*/false);
9704           PossibleReducedVals[Key][Idx].push_back(V);
9705         }
9706         Worklist.append(PossibleReductionOps.begin(),
9707                         PossibleReductionOps.end());
9708       } else {
9709         size_t Key, Idx;
9710         std::tie(Key, Idx) = generateKeySubkey(
9711             TreeN, &TLI,
9712             [&PossibleReducedVals, &DL, &SE](size_t Key, LoadInst *LI) {
9713               for (const auto &LoadData : PossibleReducedVals[Key]) {
9714                 auto *RLI = cast<LoadInst>(LoadData.second.front());
9715                 if (getPointersDiff(RLI->getType(), RLI->getPointerOperand(),
9716                                     LI->getType(), LI->getPointerOperand(), DL,
9717                                     SE, /*StrictCheck=*/true))
9718                   return hash_value(RLI->getPointerOperand());
9719               }
9720               return hash_value(LI->getPointerOperand());
9721             },
9722             /*AllowAlternate=*/false);
9723         PossibleReducedVals[Key][Idx].push_back(TreeN);
9724       }
9725     }
9726     auto PossibleReducedValsVect = PossibleReducedVals.takeVector();
9727     // Sort values by the total number of values kinds to start the reduction
9728     // from the longest possible reduced values sequences.
9729     for (auto &PossibleReducedVals : PossibleReducedValsVect) {
9730       auto PossibleRedVals = PossibleReducedVals.second.takeVector();
9731       stable_sort(PossibleRedVals, [](const auto &P1, const auto &P2) {
9732         return P1.second.size() > P2.second.size();
9733       });
9734       ReducedVals.emplace_back();
9735       for (auto &Data : PossibleRedVals)
9736         ReducedVals.back().append(Data.second.rbegin(), Data.second.rend());
9737     }
9738     // Sort the reduced values by number of same/alternate opcode and/or pointer
9739     // operand.
9740     stable_sort(ReducedVals, [](ArrayRef<Value *> P1, ArrayRef<Value *> P2) {
9741       return P1.size() > P2.size();
9742     });
9743     return true;
9744   }
9745 
9746   /// Attempt to vectorize the tree found by matchAssociativeReduction.
9747   Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
9748     // If there are a sufficient number of reduction values, reduce
9749     // to a nearby power-of-2. We can safely generate oversized
9750     // vectors and rely on the backend to split them to legal sizes.
9751     unsigned NumReducedVals = std::accumulate(
9752         ReducedVals.begin(), ReducedVals.end(), 0,
9753         [](int Num, ArrayRef<Value *> Vals) { return Num + Vals.size(); });
9754     if (NumReducedVals < 4)
9755       return nullptr;
9756 
9757     IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
9758 
9759     // Track the reduced values in case if they are replaced by extractelement
9760     // because of the vectorization.
9761     DenseMap<Value *, WeakTrackingVH> TrackedVals;
9762     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
9763     // The same extra argument may be used several times, so log each attempt
9764     // to use it.
9765     for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) {
9766       assert(Pair.first && "DebugLoc must be set.");
9767       ExternallyUsedValues[Pair.second].push_back(Pair.first);
9768       TrackedVals.try_emplace(Pair.second, Pair.second);
9769     }
9770 
9771     // The compare instruction of a min/max is the insertion point for new
9772     // instructions and may be replaced with a new compare instruction.
9773     auto &&GetCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
9774       assert(isa<SelectInst>(RdxRootInst) &&
9775              "Expected min/max reduction to have select root instruction");
9776       Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
9777       assert(isa<Instruction>(ScalarCond) &&
9778              "Expected min/max reduction to have compare condition");
9779       return cast<Instruction>(ScalarCond);
9780     };
9781 
9782     // The reduction root is used as the insertion point for new instructions,
9783     // so set it as externally used to prevent it from being deleted.
9784     ExternallyUsedValues[ReductionRoot];
9785     SmallVector<Value *> IgnoreList;
9786     for (ReductionOpsType &RdxOps : ReductionOps)
9787       for (Value *RdxOp : RdxOps) {
9788         if (!RdxOp)
9789           continue;
9790         IgnoreList.push_back(RdxOp);
9791       }
9792 
9793     // Need to track reduced vals, they may be changed during vectorization of
9794     // subvectors.
9795     for (ArrayRef<Value *> Candidates : ReducedVals)
9796       for (Value *V : Candidates)
9797         TrackedVals.try_emplace(V, V);
9798 
9799     DenseMap<Value *, unsigned> VectorizedVals;
9800     Value *VectorizedTree = nullptr;
9801     // Try to vectorize elements based on their type.
9802     for (unsigned I = 0, E = ReducedVals.size(); I < E; ++I) {
9803       ArrayRef<Value *> OrigReducedVals = ReducedVals[I];
9804       InstructionsState S = getSameOpcode(OrigReducedVals);
9805       SmallVector<Value *> Candidates;
9806       DenseMap<Value *, Value *> TrackedToOrig;
9807       for (unsigned Cnt = 0, Sz = OrigReducedVals.size(); Cnt < Sz; ++Cnt) {
9808         Value *RdxVal = TrackedVals.find(OrigReducedVals[Cnt])->second;
9809         // Check if the reduction value was not overriden by the extractelement
9810         // instruction because of the vectorization and exclude it, if it is not
9811         // compatible with other values.
9812         if (auto *Inst = dyn_cast<Instruction>(RdxVal))
9813           if (isVectorLikeInstWithConstOps(Inst) &&
9814               (!S.getOpcode() || !S.isOpcodeOrAlt(Inst)))
9815             continue;
9816         Candidates.push_back(RdxVal);
9817         TrackedToOrig.try_emplace(RdxVal, OrigReducedVals[Cnt]);
9818       }
9819       bool ShuffledExtracts = false;
9820       // Try to handle shuffled extractelements.
9821       if (S.getOpcode() == Instruction::ExtractElement && !S.isAltShuffle() &&
9822           I + 1 < E) {
9823         InstructionsState NextS = getSameOpcode(ReducedVals[I + 1]);
9824         if (NextS.getOpcode() == Instruction::ExtractElement &&
9825             !NextS.isAltShuffle()) {
9826           SmallVector<Value *> CommonCandidates(Candidates);
9827           for (Value *RV : ReducedVals[I + 1]) {
9828             Value *RdxVal = TrackedVals.find(RV)->second;
9829             // Check if the reduction value was not overriden by the
9830             // extractelement instruction because of the vectorization and
9831             // exclude it, if it is not compatible with other values.
9832             if (auto *Inst = dyn_cast<Instruction>(RdxVal))
9833               if (!NextS.getOpcode() || !NextS.isOpcodeOrAlt(Inst))
9834                 continue;
9835             CommonCandidates.push_back(RdxVal);
9836             TrackedToOrig.try_emplace(RdxVal, RV);
9837           }
9838           SmallVector<int> Mask;
9839           if (isFixedVectorShuffle(CommonCandidates, Mask)) {
9840             ++I;
9841             Candidates.swap(CommonCandidates);
9842             ShuffledExtracts = true;
9843           }
9844         }
9845       }
9846       unsigned NumReducedVals = Candidates.size();
9847       if (NumReducedVals < 4)
9848         continue;
9849 
9850       unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
9851       unsigned Start = 0;
9852       unsigned Pos = Start;
9853       // Restarts vectorization attempt with lower vector factor.
9854       auto &&AdjustReducedVals = [&Pos, &Start, &ReduxWidth, NumReducedVals]() {
9855         if (ReduxWidth == 4 || Pos >= NumReducedVals - ReduxWidth + 1) {
9856           ++Start;
9857           ReduxWidth = PowerOf2Floor(NumReducedVals - Start) * 2;
9858         }
9859         Pos = Start;
9860         ReduxWidth /= 2;
9861       };
9862       while (Pos < NumReducedVals - ReduxWidth + 1 && ReduxWidth >= 4) {
9863         ArrayRef<Value *> VL(std::next(Candidates.begin(), Pos), ReduxWidth);
9864         V.buildTree(VL, IgnoreList);
9865         if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true)) {
9866           AdjustReducedVals();
9867           continue;
9868         }
9869         if (V.isLoadCombineReductionCandidate(RdxKind)) {
9870           AdjustReducedVals();
9871           continue;
9872         }
9873         V.reorderTopToBottom();
9874         // No need to reorder the root node at all.
9875         V.reorderBottomToTop(/*IgnoreReorder=*/true);
9876         // Keep extracted other reduction values, if they are used in the
9877         // vectorization trees.
9878         BoUpSLP::ExtraValueToDebugLocsMap LocalExternallyUsedValues(
9879             ExternallyUsedValues);
9880         for (unsigned Cnt = 0, Sz = ReducedVals.size(); Cnt < Sz; ++Cnt) {
9881           if (Cnt == I || (ShuffledExtracts && Cnt == I - 1))
9882             continue;
9883           for_each(ReducedVals[Cnt],
9884                    [&LocalExternallyUsedValues, &TrackedVals](Value *V) {
9885                      if (isa<Instruction>(V))
9886                        LocalExternallyUsedValues[TrackedVals[V]];
9887                    });
9888         }
9889         for (unsigned Cnt = 0; Cnt < NumReducedVals; ++Cnt) {
9890           if (Cnt >= Pos && Cnt < Pos + ReduxWidth)
9891             continue;
9892           if (VectorizedVals.count(Candidates[Cnt]))
9893             continue;
9894           LocalExternallyUsedValues[Candidates[Cnt]];
9895         }
9896         V.buildExternalUses(LocalExternallyUsedValues);
9897 
9898         V.computeMinimumValueSizes();
9899 
9900         // Intersect the fast-math-flags from all reduction operations.
9901         FastMathFlags RdxFMF;
9902         RdxFMF.set();
9903         for (Value *RdxVal : VL) {
9904           if (auto *FPMO = dyn_cast<FPMathOperator>(
9905                   ReducedValsToOps.find(RdxVal)->second))
9906             RdxFMF &= FPMO->getFastMathFlags();
9907         }
9908         // Estimate cost.
9909         InstructionCost TreeCost = V.getTreeCost(VL);
9910         InstructionCost ReductionCost =
9911             getReductionCost(TTI, VL[0], ReduxWidth, RdxFMF);
9912         InstructionCost Cost = TreeCost + ReductionCost;
9913         if (!Cost.isValid()) {
9914           LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n");
9915           return nullptr;
9916         }
9917         if (Cost >= -SLPCostThreshold) {
9918           V.getORE()->emit([&]() {
9919             return OptimizationRemarkMissed(
9920                        SV_NAME, "HorSLPNotBeneficial",
9921                        ReducedValsToOps.find(VL[0])->second)
9922                    << "Vectorizing horizontal reduction is possible"
9923                    << "but not beneficial with cost " << ore::NV("Cost", Cost)
9924                    << " and threshold "
9925                    << ore::NV("Threshold", -SLPCostThreshold);
9926           });
9927           AdjustReducedVals();
9928           continue;
9929         }
9930 
9931         LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
9932                           << Cost << ". (HorRdx)\n");
9933         V.getORE()->emit([&]() {
9934           return OptimizationRemark(SV_NAME, "VectorizedHorizontalReduction",
9935                                     ReducedValsToOps.find(VL[0])->second)
9936                  << "Vectorized horizontal reduction with cost "
9937                  << ore::NV("Cost", Cost) << " and with tree size "
9938                  << ore::NV("TreeSize", V.getTreeSize());
9939         });
9940 
9941         Builder.setFastMathFlags(RdxFMF);
9942 
9943         // Vectorize a tree.
9944         Value *VectorizedRoot = V.vectorizeTree(LocalExternallyUsedValues);
9945 
9946         // Emit a reduction. If the root is a select (min/max idiom), the insert
9947         // point is the compare condition of that select.
9948         Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
9949         if (isCmpSelMinMax(RdxRootInst))
9950           Builder.SetInsertPoint(GetCmpForMinMaxReduction(RdxRootInst));
9951         else
9952           Builder.SetInsertPoint(RdxRootInst);
9953 
9954         // To prevent poison from leaking across what used to be sequential,
9955         // safe, scalar boolean logic operations, the reduction operand must be
9956         // frozen.
9957         if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst))
9958           VectorizedRoot = Builder.CreateFreeze(VectorizedRoot);
9959 
9960         Value *ReducedSubTree =
9961             emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
9962 
9963         if (!VectorizedTree) {
9964           // Initialize the final value in the reduction.
9965           VectorizedTree = ReducedSubTree;
9966         } else {
9967           // Update the final value in the reduction.
9968           Builder.SetCurrentDebugLocation(
9969               cast<Instruction>(ReductionOps.front().front())->getDebugLoc());
9970           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9971                                     ReducedSubTree, "op.rdx", ReductionOps);
9972         }
9973         // Count vectorized reduced values to exclude them from final reduction.
9974         for (Value *V : VL)
9975           ++VectorizedVals.try_emplace(TrackedToOrig.find(V)->second, 0)
9976                 .first->getSecond();
9977         Pos += ReduxWidth;
9978         Start = Pos;
9979         ReduxWidth = PowerOf2Floor(NumReducedVals - Pos);
9980       }
9981     }
9982     if (VectorizedTree) {
9983       // Finish the reduction.
9984       // Need to add extra arguments and not vectorized possible reduction
9985       // values.
9986       for (unsigned I = 0, E = ReducedVals.size(); I < E; ++I) {
9987         ArrayRef<Value *> Candidates = ReducedVals[I];
9988         for (Value *RdxVal : Candidates) {
9989           auto It = VectorizedVals.find(RdxVal);
9990           if (It != VectorizedVals.end()) {
9991             --It->getSecond();
9992             if (It->second == 0)
9993               VectorizedVals.erase(It);
9994             continue;
9995           }
9996           Instruction *RedOp = ReducedValsToOps.find(RdxVal)->second;
9997           Builder.SetCurrentDebugLocation(RedOp->getDebugLoc());
9998           ReductionOpsListType Ops;
9999           if (auto *Sel = dyn_cast<SelectInst>(RedOp))
10000             Ops.emplace_back().push_back(Sel->getCondition());
10001           Ops.emplace_back().push_back(RedOp);
10002           Value *StableRdxVal = RdxVal;
10003           auto TVIt = TrackedVals.find(RdxVal);
10004           if (TVIt != TrackedVals.end())
10005             StableRdxVal = TVIt->second;
10006 
10007           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
10008                                     StableRdxVal, "op.rdx", RedOp);
10009         }
10010       }
10011       for (auto &Pair : ExternallyUsedValues) {
10012         // Add each externally used value to the final reduction.
10013         for (auto *I : Pair.second) {
10014           Builder.SetCurrentDebugLocation(I->getDebugLoc());
10015           ReductionOpsListType Ops;
10016           if (auto *Sel = dyn_cast<SelectInst>(I))
10017             Ops.emplace_back().push_back(Sel->getCondition());
10018           Ops.emplace_back().push_back(I);
10019           Value *StableRdxVal = Pair.first;
10020           auto TVIt = TrackedVals.find(Pair.first);
10021           if (TVIt != TrackedVals.end())
10022             StableRdxVal = TVIt->second;
10023           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
10024                                     StableRdxVal, "op.rdx", Ops);
10025         }
10026       }
10027 
10028       ReductionRoot->replaceAllUsesWith(VectorizedTree);
10029 
10030       // The original scalar reduction is expected to have no remaining
10031       // uses outside the reduction tree itself.  Assert that we got this
10032       // correct, replace internal uses with undef, and mark for eventual
10033       // deletion.
10034 #ifndef NDEBUG
10035       SmallSet<Value *, 4> IgnoreSet;
10036       IgnoreSet.insert(IgnoreList.begin(), IgnoreList.end());
10037 #endif
10038       for (auto *Ignore : IgnoreList) {
10039 #ifndef NDEBUG
10040         for (auto *U : Ignore->users()) {
10041           assert(IgnoreSet.count(U));
10042         }
10043 #endif
10044         if (!Ignore->use_empty()) {
10045           Value *Undef = UndefValue::get(Ignore->getType());
10046           Ignore->replaceAllUsesWith(Undef);
10047         }
10048         V.eraseInstruction(cast<Instruction>(Ignore));
10049       }
10050     }
10051     return VectorizedTree;
10052   }
10053 
10054   unsigned numReductionValues() const { return ReducedVals.size(); }
10055 
10056 private:
10057   /// Calculate the cost of a reduction.
10058   InstructionCost getReductionCost(TargetTransformInfo *TTI,
10059                                    Value *FirstReducedVal, unsigned ReduxWidth,
10060                                    FastMathFlags FMF) {
10061     TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
10062     Type *ScalarTy = FirstReducedVal->getType();
10063     FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth);
10064     InstructionCost VectorCost, ScalarCost;
10065     switch (RdxKind) {
10066     case RecurKind::Add:
10067     case RecurKind::Mul:
10068     case RecurKind::Or:
10069     case RecurKind::And:
10070     case RecurKind::Xor:
10071     case RecurKind::FAdd:
10072     case RecurKind::FMul: {
10073       unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind);
10074       VectorCost =
10075           TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind);
10076       ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind);
10077       break;
10078     }
10079     case RecurKind::FMax:
10080     case RecurKind::FMin: {
10081       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
10082       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
10083       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
10084                                                /*IsUnsigned=*/false, CostKind);
10085       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
10086       ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy,
10087                                            SclCondTy, RdxPred, CostKind) +
10088                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
10089                                            SclCondTy, RdxPred, CostKind);
10090       break;
10091     }
10092     case RecurKind::SMax:
10093     case RecurKind::SMin:
10094     case RecurKind::UMax:
10095     case RecurKind::UMin: {
10096       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
10097       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
10098       bool IsUnsigned =
10099           RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin;
10100       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, IsUnsigned,
10101                                                CostKind);
10102       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
10103       ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
10104                                            SclCondTy, RdxPred, CostKind) +
10105                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
10106                                            SclCondTy, RdxPred, CostKind);
10107       break;
10108     }
10109     default:
10110       llvm_unreachable("Expected arithmetic or min/max reduction operation");
10111     }
10112 
10113     // Scalar cost is repeated for N-1 elements.
10114     ScalarCost *= (ReduxWidth - 1);
10115     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost
10116                       << " for reduction that starts with " << *FirstReducedVal
10117                       << " (It is a splitting reduction)\n");
10118     return VectorCost - ScalarCost;
10119   }
10120 
10121   /// Emit a horizontal reduction of the vectorized value.
10122   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
10123                        unsigned ReduxWidth, const TargetTransformInfo *TTI) {
10124     assert(VectorizedValue && "Need to have a vectorized tree node");
10125     assert(isPowerOf2_32(ReduxWidth) &&
10126            "We only handle power-of-two reductions for now");
10127     assert(RdxKind != RecurKind::FMulAdd &&
10128            "A call to the llvm.fmuladd intrinsic is not handled yet");
10129 
10130     ++NumVectorInstructions;
10131     return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind);
10132   }
10133 };
10134 
10135 } // end anonymous namespace
10136 
10137 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) {
10138   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
10139     return cast<FixedVectorType>(IE->getType())->getNumElements();
10140 
10141   unsigned AggregateSize = 1;
10142   auto *IV = cast<InsertValueInst>(InsertInst);
10143   Type *CurrentType = IV->getType();
10144   do {
10145     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
10146       for (auto *Elt : ST->elements())
10147         if (Elt != ST->getElementType(0)) // check homogeneity
10148           return None;
10149       AggregateSize *= ST->getNumElements();
10150       CurrentType = ST->getElementType(0);
10151     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
10152       AggregateSize *= AT->getNumElements();
10153       CurrentType = AT->getElementType();
10154     } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
10155       AggregateSize *= VT->getNumElements();
10156       return AggregateSize;
10157     } else if (CurrentType->isSingleValueType()) {
10158       return AggregateSize;
10159     } else {
10160       return None;
10161     }
10162   } while (true);
10163 }
10164 
10165 static void findBuildAggregate_rec(Instruction *LastInsertInst,
10166                                    TargetTransformInfo *TTI,
10167                                    SmallVectorImpl<Value *> &BuildVectorOpds,
10168                                    SmallVectorImpl<Value *> &InsertElts,
10169                                    unsigned OperandOffset) {
10170   do {
10171     Value *InsertedOperand = LastInsertInst->getOperand(1);
10172     Optional<unsigned> OperandIndex =
10173         getInsertIndex(LastInsertInst, OperandOffset);
10174     if (!OperandIndex)
10175       return;
10176     if (isa<InsertElementInst>(InsertedOperand) ||
10177         isa<InsertValueInst>(InsertedOperand)) {
10178       findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI,
10179                              BuildVectorOpds, InsertElts, *OperandIndex);
10180 
10181     } else {
10182       BuildVectorOpds[*OperandIndex] = InsertedOperand;
10183       InsertElts[*OperandIndex] = LastInsertInst;
10184     }
10185     LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0));
10186   } while (LastInsertInst != nullptr &&
10187            (isa<InsertValueInst>(LastInsertInst) ||
10188             isa<InsertElementInst>(LastInsertInst)) &&
10189            LastInsertInst->hasOneUse());
10190 }
10191 
10192 /// Recognize construction of vectors like
10193 ///  %ra = insertelement <4 x float> poison, float %s0, i32 0
10194 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
10195 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
10196 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
10197 ///  starting from the last insertelement or insertvalue instruction.
10198 ///
10199 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>},
10200 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
10201 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
10202 ///
10203 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
10204 ///
10205 /// \return true if it matches.
10206 static bool findBuildAggregate(Instruction *LastInsertInst,
10207                                TargetTransformInfo *TTI,
10208                                SmallVectorImpl<Value *> &BuildVectorOpds,
10209                                SmallVectorImpl<Value *> &InsertElts) {
10210 
10211   assert((isa<InsertElementInst>(LastInsertInst) ||
10212           isa<InsertValueInst>(LastInsertInst)) &&
10213          "Expected insertelement or insertvalue instruction!");
10214 
10215   assert((BuildVectorOpds.empty() && InsertElts.empty()) &&
10216          "Expected empty result vectors!");
10217 
10218   Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst);
10219   if (!AggregateSize)
10220     return false;
10221   BuildVectorOpds.resize(*AggregateSize);
10222   InsertElts.resize(*AggregateSize);
10223 
10224   findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts, 0);
10225   llvm::erase_value(BuildVectorOpds, nullptr);
10226   llvm::erase_value(InsertElts, nullptr);
10227   if (BuildVectorOpds.size() >= 2)
10228     return true;
10229 
10230   return false;
10231 }
10232 
10233 /// Try and get a reduction value from a phi node.
10234 ///
10235 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
10236 /// if they come from either \p ParentBB or a containing loop latch.
10237 ///
10238 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
10239 /// if not possible.
10240 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
10241                                 BasicBlock *ParentBB, LoopInfo *LI) {
10242   // There are situations where the reduction value is not dominated by the
10243   // reduction phi. Vectorizing such cases has been reported to cause
10244   // miscompiles. See PR25787.
10245   auto DominatedReduxValue = [&](Value *R) {
10246     return isa<Instruction>(R) &&
10247            DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
10248   };
10249 
10250   Value *Rdx = nullptr;
10251 
10252   // Return the incoming value if it comes from the same BB as the phi node.
10253   if (P->getIncomingBlock(0) == ParentBB) {
10254     Rdx = P->getIncomingValue(0);
10255   } else if (P->getIncomingBlock(1) == ParentBB) {
10256     Rdx = P->getIncomingValue(1);
10257   }
10258 
10259   if (Rdx && DominatedReduxValue(Rdx))
10260     return Rdx;
10261 
10262   // Otherwise, check whether we have a loop latch to look at.
10263   Loop *BBL = LI->getLoopFor(ParentBB);
10264   if (!BBL)
10265     return nullptr;
10266   BasicBlock *BBLatch = BBL->getLoopLatch();
10267   if (!BBLatch)
10268     return nullptr;
10269 
10270   // There is a loop latch, return the incoming value if it comes from
10271   // that. This reduction pattern occasionally turns up.
10272   if (P->getIncomingBlock(0) == BBLatch) {
10273     Rdx = P->getIncomingValue(0);
10274   } else if (P->getIncomingBlock(1) == BBLatch) {
10275     Rdx = P->getIncomingValue(1);
10276   }
10277 
10278   if (Rdx && DominatedReduxValue(Rdx))
10279     return Rdx;
10280 
10281   return nullptr;
10282 }
10283 
10284 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) {
10285   if (match(I, m_BinOp(m_Value(V0), m_Value(V1))))
10286     return true;
10287   if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1))))
10288     return true;
10289   if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1))))
10290     return true;
10291   if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1))))
10292     return true;
10293   if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1))))
10294     return true;
10295   if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1))))
10296     return true;
10297   if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1))))
10298     return true;
10299   return false;
10300 }
10301 
10302 /// Attempt to reduce a horizontal reduction.
10303 /// If it is legal to match a horizontal reduction feeding the phi node \a P
10304 /// with reduction operators \a Root (or one of its operands) in a basic block
10305 /// \a BB, then check if it can be done. If horizontal reduction is not found
10306 /// and root instruction is a binary operation, vectorization of the operands is
10307 /// attempted.
10308 /// \returns true if a horizontal reduction was matched and reduced or operands
10309 /// of one of the binary instruction were vectorized.
10310 /// \returns false if a horizontal reduction was not matched (or not possible)
10311 /// or no vectorization of any binary operation feeding \a Root instruction was
10312 /// performed.
10313 static bool tryToVectorizeHorReductionOrInstOperands(
10314     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
10315     TargetTransformInfo *TTI, ScalarEvolution &SE, const DataLayout &DL,
10316     const TargetLibraryInfo &TLI,
10317     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
10318   if (!ShouldVectorizeHor)
10319     return false;
10320 
10321   if (!Root)
10322     return false;
10323 
10324   if (Root->getParent() != BB || isa<PHINode>(Root))
10325     return false;
10326   // Start analysis starting from Root instruction. If horizontal reduction is
10327   // found, try to vectorize it. If it is not a horizontal reduction or
10328   // vectorization is not possible or not effective, and currently analyzed
10329   // instruction is a binary operation, try to vectorize the operands, using
10330   // pre-order DFS traversal order. If the operands were not vectorized, repeat
10331   // the same procedure considering each operand as a possible root of the
10332   // horizontal reduction.
10333   // Interrupt the process if the Root instruction itself was vectorized or all
10334   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
10335   // Skip the analysis of CmpInsts.Compiler implements postanalysis of the
10336   // CmpInsts so we can skip extra attempts in
10337   // tryToVectorizeHorReductionOrInstOperands and save compile time.
10338   std::queue<std::pair<Instruction *, unsigned>> Stack;
10339   Stack.emplace(Root, 0);
10340   SmallPtrSet<Value *, 8> VisitedInstrs;
10341   SmallVector<WeakTrackingVH> PostponedInsts;
10342   bool Res = false;
10343   auto &&TryToReduce = [TTI, &SE, &DL, &P, &R, &TLI](Instruction *Inst,
10344                                                      Value *&B0,
10345                                                      Value *&B1) -> Value * {
10346     bool IsBinop = matchRdxBop(Inst, B0, B1);
10347     bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value()));
10348     if (IsBinop || IsSelect) {
10349       HorizontalReduction HorRdx;
10350       if (HorRdx.matchAssociativeReduction(P, Inst, SE, DL, TLI))
10351         return HorRdx.tryToReduce(R, TTI);
10352     }
10353     return nullptr;
10354   };
10355   while (!Stack.empty()) {
10356     Instruction *Inst;
10357     unsigned Level;
10358     std::tie(Inst, Level) = Stack.front();
10359     Stack.pop();
10360     // Do not try to analyze instruction that has already been vectorized.
10361     // This may happen when we vectorize instruction operands on a previous
10362     // iteration while stack was populated before that happened.
10363     if (R.isDeleted(Inst))
10364       continue;
10365     Value *B0 = nullptr, *B1 = nullptr;
10366     if (Value *V = TryToReduce(Inst, B0, B1)) {
10367       Res = true;
10368       // Set P to nullptr to avoid re-analysis of phi node in
10369       // matchAssociativeReduction function unless this is the root node.
10370       P = nullptr;
10371       if (auto *I = dyn_cast<Instruction>(V)) {
10372         // Try to find another reduction.
10373         Stack.emplace(I, Level);
10374         continue;
10375       }
10376     } else {
10377       bool IsBinop = B0 && B1;
10378       if (P && IsBinop) {
10379         Inst = dyn_cast<Instruction>(B0);
10380         if (Inst == P)
10381           Inst = dyn_cast<Instruction>(B1);
10382         if (!Inst) {
10383           // Set P to nullptr to avoid re-analysis of phi node in
10384           // matchAssociativeReduction function unless this is the root node.
10385           P = nullptr;
10386           continue;
10387         }
10388       }
10389       // Set P to nullptr to avoid re-analysis of phi node in
10390       // matchAssociativeReduction function unless this is the root node.
10391       P = nullptr;
10392       // Do not try to vectorize CmpInst operands, this is done separately.
10393       // Final attempt for binop args vectorization should happen after the loop
10394       // to try to find reductions.
10395       if (!isa<CmpInst>(Inst))
10396         PostponedInsts.push_back(Inst);
10397     }
10398 
10399     // Try to vectorize operands.
10400     // Continue analysis for the instruction from the same basic block only to
10401     // save compile time.
10402     if (++Level < RecursionMaxDepth)
10403       for (auto *Op : Inst->operand_values())
10404         if (VisitedInstrs.insert(Op).second)
10405           if (auto *I = dyn_cast<Instruction>(Op))
10406             // Do not try to vectorize CmpInst operands,  this is done
10407             // separately.
10408             if (!isa<PHINode>(I) && !isa<CmpInst>(I) && !R.isDeleted(I) &&
10409                 I->getParent() == BB)
10410               Stack.emplace(I, Level);
10411   }
10412   // Try to vectorized binops where reductions were not found.
10413   for (Value *V : PostponedInsts)
10414     if (auto *Inst = dyn_cast<Instruction>(V))
10415       if (!R.isDeleted(Inst))
10416         Res |= Vectorize(Inst, R);
10417   return Res;
10418 }
10419 
10420 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
10421                                                  BasicBlock *BB, BoUpSLP &R,
10422                                                  TargetTransformInfo *TTI) {
10423   auto *I = dyn_cast_or_null<Instruction>(V);
10424   if (!I)
10425     return false;
10426 
10427   if (!isa<BinaryOperator>(I))
10428     P = nullptr;
10429   // Try to match and vectorize a horizontal reduction.
10430   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
10431     return tryToVectorize(I, R);
10432   };
10433   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI, *SE, *DL,
10434                                                   *TLI, ExtraVectorization);
10435 }
10436 
10437 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
10438                                                  BasicBlock *BB, BoUpSLP &R) {
10439   const DataLayout &DL = BB->getModule()->getDataLayout();
10440   if (!R.canMapToVector(IVI->getType(), DL))
10441     return false;
10442 
10443   SmallVector<Value *, 16> BuildVectorOpds;
10444   SmallVector<Value *, 16> BuildVectorInsts;
10445   if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts))
10446     return false;
10447 
10448   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
10449   // Aggregate value is unlikely to be processed in vector register.
10450   return tryToVectorizeList(BuildVectorOpds, R);
10451 }
10452 
10453 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
10454                                                    BasicBlock *BB, BoUpSLP &R) {
10455   SmallVector<Value *, 16> BuildVectorInsts;
10456   SmallVector<Value *, 16> BuildVectorOpds;
10457   SmallVector<int> Mask;
10458   if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
10459       (llvm::all_of(
10460            BuildVectorOpds,
10461            [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) &&
10462        isFixedVectorShuffle(BuildVectorOpds, Mask)))
10463     return false;
10464 
10465   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n");
10466   return tryToVectorizeList(BuildVectorInsts, R);
10467 }
10468 
10469 template <typename T>
10470 static bool
10471 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming,
10472                        function_ref<unsigned(T *)> Limit,
10473                        function_ref<bool(T *, T *)> Comparator,
10474                        function_ref<bool(T *, T *)> AreCompatible,
10475                        function_ref<bool(ArrayRef<T *>, bool)> TryToVectorizeHelper,
10476                        bool LimitForRegisterSize) {
10477   bool Changed = false;
10478   // Sort by type, parent, operands.
10479   stable_sort(Incoming, Comparator);
10480 
10481   // Try to vectorize elements base on their type.
10482   SmallVector<T *> Candidates;
10483   for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) {
10484     // Look for the next elements with the same type, parent and operand
10485     // kinds.
10486     auto *SameTypeIt = IncIt;
10487     while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt))
10488       ++SameTypeIt;
10489 
10490     // Try to vectorize them.
10491     unsigned NumElts = (SameTypeIt - IncIt);
10492     LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes ("
10493                       << NumElts << ")\n");
10494     // The vectorization is a 3-state attempt:
10495     // 1. Try to vectorize instructions with the same/alternate opcodes with the
10496     // size of maximal register at first.
10497     // 2. Try to vectorize remaining instructions with the same type, if
10498     // possible. This may result in the better vectorization results rather than
10499     // if we try just to vectorize instructions with the same/alternate opcodes.
10500     // 3. Final attempt to try to vectorize all instructions with the
10501     // same/alternate ops only, this may result in some extra final
10502     // vectorization.
10503     if (NumElts > 1 &&
10504         TryToVectorizeHelper(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) {
10505       // Success start over because instructions might have been changed.
10506       Changed = true;
10507     } else if (NumElts < Limit(*IncIt) &&
10508                (Candidates.empty() ||
10509                 Candidates.front()->getType() == (*IncIt)->getType())) {
10510       Candidates.append(IncIt, std::next(IncIt, NumElts));
10511     }
10512     // Final attempt to vectorize instructions with the same types.
10513     if (Candidates.size() > 1 &&
10514         (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) {
10515       if (TryToVectorizeHelper(Candidates, /*LimitForRegisterSize=*/false)) {
10516         // Success start over because instructions might have been changed.
10517         Changed = true;
10518       } else if (LimitForRegisterSize) {
10519         // Try to vectorize using small vectors.
10520         for (auto *It = Candidates.begin(), *End = Candidates.end();
10521              It != End;) {
10522           auto *SameTypeIt = It;
10523           while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It))
10524             ++SameTypeIt;
10525           unsigned NumElts = (SameTypeIt - It);
10526           if (NumElts > 1 && TryToVectorizeHelper(makeArrayRef(It, NumElts),
10527                                             /*LimitForRegisterSize=*/false))
10528             Changed = true;
10529           It = SameTypeIt;
10530         }
10531       }
10532       Candidates.clear();
10533     }
10534 
10535     // Start over at the next instruction of a different type (or the end).
10536     IncIt = SameTypeIt;
10537   }
10538   return Changed;
10539 }
10540 
10541 /// Compare two cmp instructions. If IsCompatibility is true, function returns
10542 /// true if 2 cmps have same/swapped predicates and mos compatible corresponding
10543 /// operands. If IsCompatibility is false, function implements strict weak
10544 /// ordering relation between two cmp instructions, returning true if the first
10545 /// instruction is "less" than the second, i.e. its predicate is less than the
10546 /// predicate of the second or the operands IDs are less than the operands IDs
10547 /// of the second cmp instruction.
10548 template <bool IsCompatibility>
10549 static bool compareCmp(Value *V, Value *V2,
10550                        function_ref<bool(Instruction *)> IsDeleted) {
10551   auto *CI1 = cast<CmpInst>(V);
10552   auto *CI2 = cast<CmpInst>(V2);
10553   if (IsDeleted(CI2) || !isValidElementType(CI2->getType()))
10554     return false;
10555   if (CI1->getOperand(0)->getType()->getTypeID() <
10556       CI2->getOperand(0)->getType()->getTypeID())
10557     return !IsCompatibility;
10558   if (CI1->getOperand(0)->getType()->getTypeID() >
10559       CI2->getOperand(0)->getType()->getTypeID())
10560     return false;
10561   CmpInst::Predicate Pred1 = CI1->getPredicate();
10562   CmpInst::Predicate Pred2 = CI2->getPredicate();
10563   CmpInst::Predicate SwapPred1 = CmpInst::getSwappedPredicate(Pred1);
10564   CmpInst::Predicate SwapPred2 = CmpInst::getSwappedPredicate(Pred2);
10565   CmpInst::Predicate BasePred1 = std::min(Pred1, SwapPred1);
10566   CmpInst::Predicate BasePred2 = std::min(Pred2, SwapPred2);
10567   if (BasePred1 < BasePred2)
10568     return !IsCompatibility;
10569   if (BasePred1 > BasePred2)
10570     return false;
10571   // Compare operands.
10572   bool LEPreds = Pred1 <= Pred2;
10573   bool GEPreds = Pred1 >= Pred2;
10574   for (int I = 0, E = CI1->getNumOperands(); I < E; ++I) {
10575     auto *Op1 = CI1->getOperand(LEPreds ? I : E - I - 1);
10576     auto *Op2 = CI2->getOperand(GEPreds ? I : E - I - 1);
10577     if (Op1->getValueID() < Op2->getValueID())
10578       return !IsCompatibility;
10579     if (Op1->getValueID() > Op2->getValueID())
10580       return false;
10581     if (auto *I1 = dyn_cast<Instruction>(Op1))
10582       if (auto *I2 = dyn_cast<Instruction>(Op2)) {
10583         if (I1->getParent() != I2->getParent())
10584           return false;
10585         InstructionsState S = getSameOpcode({I1, I2});
10586         if (S.getOpcode())
10587           continue;
10588         return false;
10589       }
10590   }
10591   return IsCompatibility;
10592 }
10593 
10594 bool SLPVectorizerPass::vectorizeSimpleInstructions(
10595     SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R,
10596     bool AtTerminator) {
10597   bool OpsChanged = false;
10598   SmallVector<Instruction *, 4> PostponedCmps;
10599   for (auto *I : reverse(Instructions)) {
10600     if (R.isDeleted(I))
10601       continue;
10602     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I))
10603       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
10604     else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I))
10605       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
10606     else if (isa<CmpInst>(I))
10607       PostponedCmps.push_back(I);
10608   }
10609   if (AtTerminator) {
10610     // Try to find reductions first.
10611     for (Instruction *I : PostponedCmps) {
10612       if (R.isDeleted(I))
10613         continue;
10614       for (Value *Op : I->operands())
10615         OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI);
10616     }
10617     // Try to vectorize operands as vector bundles.
10618     for (Instruction *I : PostponedCmps) {
10619       if (R.isDeleted(I))
10620         continue;
10621       OpsChanged |= tryToVectorize(I, R);
10622     }
10623     // Try to vectorize list of compares.
10624     // Sort by type, compare predicate, etc.
10625     auto &&CompareSorter = [&R](Value *V, Value *V2) {
10626       return compareCmp<false>(V, V2,
10627                                [&R](Instruction *I) { return R.isDeleted(I); });
10628     };
10629 
10630     auto &&AreCompatibleCompares = [&R](Value *V1, Value *V2) {
10631       if (V1 == V2)
10632         return true;
10633       return compareCmp<true>(V1, V2,
10634                               [&R](Instruction *I) { return R.isDeleted(I); });
10635     };
10636     auto Limit = [&R](Value *V) {
10637       unsigned EltSize = R.getVectorElementSize(V);
10638       return std::max(2U, R.getMaxVecRegSize() / EltSize);
10639     };
10640 
10641     SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end());
10642     OpsChanged |= tryToVectorizeSequence<Value>(
10643         Vals, Limit, CompareSorter, AreCompatibleCompares,
10644         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10645           // Exclude possible reductions from other blocks.
10646           bool ArePossiblyReducedInOtherBlock =
10647               any_of(Candidates, [](Value *V) {
10648                 return any_of(V->users(), [V](User *U) {
10649                   return isa<SelectInst>(U) &&
10650                          cast<SelectInst>(U)->getParent() !=
10651                              cast<Instruction>(V)->getParent();
10652                 });
10653               });
10654           if (ArePossiblyReducedInOtherBlock)
10655             return false;
10656           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10657         },
10658         /*LimitForRegisterSize=*/true);
10659     Instructions.clear();
10660   } else {
10661     // Insert in reverse order since the PostponedCmps vector was filled in
10662     // reverse order.
10663     Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend());
10664   }
10665   return OpsChanged;
10666 }
10667 
10668 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
10669   bool Changed = false;
10670   SmallVector<Value *, 4> Incoming;
10671   SmallPtrSet<Value *, 16> VisitedInstrs;
10672   // Maps phi nodes to the non-phi nodes found in the use tree for each phi
10673   // node. Allows better to identify the chains that can be vectorized in the
10674   // better way.
10675   DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes;
10676   auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) {
10677     assert(isValidElementType(V1->getType()) &&
10678            isValidElementType(V2->getType()) &&
10679            "Expected vectorizable types only.");
10680     // It is fine to compare type IDs here, since we expect only vectorizable
10681     // types, like ints, floats and pointers, we don't care about other type.
10682     if (V1->getType()->getTypeID() < V2->getType()->getTypeID())
10683       return true;
10684     if (V1->getType()->getTypeID() > V2->getType()->getTypeID())
10685       return false;
10686     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10687     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10688     if (Opcodes1.size() < Opcodes2.size())
10689       return true;
10690     if (Opcodes1.size() > Opcodes2.size())
10691       return false;
10692     Optional<bool> ConstOrder;
10693     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10694       // Undefs are compatible with any other value.
10695       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) {
10696         if (!ConstOrder)
10697           ConstOrder =
10698               !isa<UndefValue>(Opcodes1[I]) && isa<UndefValue>(Opcodes2[I]);
10699         continue;
10700       }
10701       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10702         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10703           DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent());
10704           DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent());
10705           if (!NodeI1)
10706             return NodeI2 != nullptr;
10707           if (!NodeI2)
10708             return false;
10709           assert((NodeI1 == NodeI2) ==
10710                      (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10711                  "Different nodes should have different DFS numbers");
10712           if (NodeI1 != NodeI2)
10713             return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10714           InstructionsState S = getSameOpcode({I1, I2});
10715           if (S.getOpcode())
10716             continue;
10717           return I1->getOpcode() < I2->getOpcode();
10718         }
10719       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) {
10720         if (!ConstOrder)
10721           ConstOrder = Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID();
10722         continue;
10723       }
10724       if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID())
10725         return true;
10726       if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID())
10727         return false;
10728     }
10729     return ConstOrder && *ConstOrder;
10730   };
10731   auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) {
10732     if (V1 == V2)
10733       return true;
10734     if (V1->getType() != V2->getType())
10735       return false;
10736     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10737     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10738     if (Opcodes1.size() != Opcodes2.size())
10739       return false;
10740     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10741       // Undefs are compatible with any other value.
10742       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
10743         continue;
10744       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10745         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10746           if (I1->getParent() != I2->getParent())
10747             return false;
10748           InstructionsState S = getSameOpcode({I1, I2});
10749           if (S.getOpcode())
10750             continue;
10751           return false;
10752         }
10753       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
10754         continue;
10755       if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID())
10756         return false;
10757     }
10758     return true;
10759   };
10760   auto Limit = [&R](Value *V) {
10761     unsigned EltSize = R.getVectorElementSize(V);
10762     return std::max(2U, R.getMaxVecRegSize() / EltSize);
10763   };
10764 
10765   bool HaveVectorizedPhiNodes = false;
10766   do {
10767     // Collect the incoming values from the PHIs.
10768     Incoming.clear();
10769     for (Instruction &I : *BB) {
10770       PHINode *P = dyn_cast<PHINode>(&I);
10771       if (!P)
10772         break;
10773 
10774       // No need to analyze deleted, vectorized and non-vectorizable
10775       // instructions.
10776       if (!VisitedInstrs.count(P) && !R.isDeleted(P) &&
10777           isValidElementType(P->getType()))
10778         Incoming.push_back(P);
10779     }
10780 
10781     // Find the corresponding non-phi nodes for better matching when trying to
10782     // build the tree.
10783     for (Value *V : Incoming) {
10784       SmallVectorImpl<Value *> &Opcodes =
10785           PHIToOpcodes.try_emplace(V).first->getSecond();
10786       if (!Opcodes.empty())
10787         continue;
10788       SmallVector<Value *, 4> Nodes(1, V);
10789       SmallPtrSet<Value *, 4> Visited;
10790       while (!Nodes.empty()) {
10791         auto *PHI = cast<PHINode>(Nodes.pop_back_val());
10792         if (!Visited.insert(PHI).second)
10793           continue;
10794         for (Value *V : PHI->incoming_values()) {
10795           if (auto *PHI1 = dyn_cast<PHINode>((V))) {
10796             Nodes.push_back(PHI1);
10797             continue;
10798           }
10799           Opcodes.emplace_back(V);
10800         }
10801       }
10802     }
10803 
10804     HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>(
10805         Incoming, Limit, PHICompare, AreCompatiblePHIs,
10806         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10807           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10808         },
10809         /*LimitForRegisterSize=*/true);
10810     Changed |= HaveVectorizedPhiNodes;
10811     VisitedInstrs.insert(Incoming.begin(), Incoming.end());
10812   } while (HaveVectorizedPhiNodes);
10813 
10814   VisitedInstrs.clear();
10815 
10816   SmallVector<Instruction *, 8> PostProcessInstructions;
10817   SmallDenseSet<Instruction *, 4> KeyNodes;
10818   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
10819     // Skip instructions with scalable type. The num of elements is unknown at
10820     // compile-time for scalable type.
10821     if (isa<ScalableVectorType>(it->getType()))
10822       continue;
10823 
10824     // Skip instructions marked for the deletion.
10825     if (R.isDeleted(&*it))
10826       continue;
10827     // We may go through BB multiple times so skip the one we have checked.
10828     if (!VisitedInstrs.insert(&*it).second) {
10829       if (it->use_empty() && KeyNodes.contains(&*it) &&
10830           vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10831                                       it->isTerminator())) {
10832         // We would like to start over since some instructions are deleted
10833         // and the iterator may become invalid value.
10834         Changed = true;
10835         it = BB->begin();
10836         e = BB->end();
10837       }
10838       continue;
10839     }
10840 
10841     if (isa<DbgInfoIntrinsic>(it))
10842       continue;
10843 
10844     // Try to vectorize reductions that use PHINodes.
10845     if (PHINode *P = dyn_cast<PHINode>(it)) {
10846       // Check that the PHI is a reduction PHI.
10847       if (P->getNumIncomingValues() == 2) {
10848         // Try to match and vectorize a horizontal reduction.
10849         if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
10850                                      TTI)) {
10851           Changed = true;
10852           it = BB->begin();
10853           e = BB->end();
10854           continue;
10855         }
10856       }
10857       // Try to vectorize the incoming values of the PHI, to catch reductions
10858       // that feed into PHIs.
10859       for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) {
10860         // Skip if the incoming block is the current BB for now. Also, bypass
10861         // unreachable IR for efficiency and to avoid crashing.
10862         // TODO: Collect the skipped incoming values and try to vectorize them
10863         // after processing BB.
10864         if (BB == P->getIncomingBlock(I) ||
10865             !DT->isReachableFromEntry(P->getIncomingBlock(I)))
10866           continue;
10867 
10868         Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I),
10869                                             P->getIncomingBlock(I), R, TTI);
10870       }
10871       continue;
10872     }
10873 
10874     // Ran into an instruction without users, like terminator, or function call
10875     // with ignored return value, store. Ignore unused instructions (basing on
10876     // instruction type, except for CallInst and InvokeInst).
10877     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
10878                             isa<InvokeInst>(it))) {
10879       KeyNodes.insert(&*it);
10880       bool OpsChanged = false;
10881       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
10882         for (auto *V : it->operand_values()) {
10883           // Try to match and vectorize a horizontal reduction.
10884           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
10885         }
10886       }
10887       // Start vectorization of post-process list of instructions from the
10888       // top-tree instructions to try to vectorize as many instructions as
10889       // possible.
10890       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10891                                                 it->isTerminator());
10892       if (OpsChanged) {
10893         // We would like to start over since some instructions are deleted
10894         // and the iterator may become invalid value.
10895         Changed = true;
10896         it = BB->begin();
10897         e = BB->end();
10898         continue;
10899       }
10900     }
10901 
10902     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
10903         isa<InsertValueInst>(it))
10904       PostProcessInstructions.push_back(&*it);
10905   }
10906 
10907   return Changed;
10908 }
10909 
10910 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
10911   auto Changed = false;
10912   for (auto &Entry : GEPs) {
10913     // If the getelementptr list has fewer than two elements, there's nothing
10914     // to do.
10915     if (Entry.second.size() < 2)
10916       continue;
10917 
10918     LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
10919                       << Entry.second.size() << ".\n");
10920 
10921     // Process the GEP list in chunks suitable for the target's supported
10922     // vector size. If a vector register can't hold 1 element, we are done. We
10923     // are trying to vectorize the index computations, so the maximum number of
10924     // elements is based on the size of the index expression, rather than the
10925     // size of the GEP itself (the target's pointer size).
10926     unsigned MaxVecRegSize = R.getMaxVecRegSize();
10927     unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin());
10928     if (MaxVecRegSize < EltSize)
10929       continue;
10930 
10931     unsigned MaxElts = MaxVecRegSize / EltSize;
10932     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
10933       auto Len = std::min<unsigned>(BE - BI, MaxElts);
10934       ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len);
10935 
10936       // Initialize a set a candidate getelementptrs. Note that we use a
10937       // SetVector here to preserve program order. If the index computations
10938       // are vectorizable and begin with loads, we want to minimize the chance
10939       // of having to reorder them later.
10940       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
10941 
10942       // Some of the candidates may have already been vectorized after we
10943       // initially collected them. If so, they are marked as deleted, so remove
10944       // them from the set of candidates.
10945       Candidates.remove_if(
10946           [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
10947 
10948       // Remove from the set of candidates all pairs of getelementptrs with
10949       // constant differences. Such getelementptrs are likely not good
10950       // candidates for vectorization in a bottom-up phase since one can be
10951       // computed from the other. We also ensure all candidate getelementptr
10952       // indices are unique.
10953       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
10954         auto *GEPI = GEPList[I];
10955         if (!Candidates.count(GEPI))
10956           continue;
10957         auto *SCEVI = SE->getSCEV(GEPList[I]);
10958         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
10959           auto *GEPJ = GEPList[J];
10960           auto *SCEVJ = SE->getSCEV(GEPList[J]);
10961           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
10962             Candidates.remove(GEPI);
10963             Candidates.remove(GEPJ);
10964           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
10965             Candidates.remove(GEPJ);
10966           }
10967         }
10968       }
10969 
10970       // We break out of the above computation as soon as we know there are
10971       // fewer than two candidates remaining.
10972       if (Candidates.size() < 2)
10973         continue;
10974 
10975       // Add the single, non-constant index of each candidate to the bundle. We
10976       // ensured the indices met these constraints when we originally collected
10977       // the getelementptrs.
10978       SmallVector<Value *, 16> Bundle(Candidates.size());
10979       auto BundleIndex = 0u;
10980       for (auto *V : Candidates) {
10981         auto *GEP = cast<GetElementPtrInst>(V);
10982         auto *GEPIdx = GEP->idx_begin()->get();
10983         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
10984         Bundle[BundleIndex++] = GEPIdx;
10985       }
10986 
10987       // Try and vectorize the indices. We are currently only interested in
10988       // gather-like cases of the form:
10989       //
10990       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
10991       //
10992       // where the loads of "a", the loads of "b", and the subtractions can be
10993       // performed in parallel. It's likely that detecting this pattern in a
10994       // bottom-up phase will be simpler and less costly than building a
10995       // full-blown top-down phase beginning at the consecutive loads.
10996       Changed |= tryToVectorizeList(Bundle, R);
10997     }
10998   }
10999   return Changed;
11000 }
11001 
11002 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
11003   bool Changed = false;
11004   // Sort by type, base pointers and values operand. Value operands must be
11005   // compatible (have the same opcode, same parent), otherwise it is
11006   // definitely not profitable to try to vectorize them.
11007   auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) {
11008     if (V->getPointerOperandType()->getTypeID() <
11009         V2->getPointerOperandType()->getTypeID())
11010       return true;
11011     if (V->getPointerOperandType()->getTypeID() >
11012         V2->getPointerOperandType()->getTypeID())
11013       return false;
11014     // UndefValues are compatible with all other values.
11015     if (isa<UndefValue>(V->getValueOperand()) ||
11016         isa<UndefValue>(V2->getValueOperand()))
11017       return false;
11018     if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand()))
11019       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
11020         DomTreeNodeBase<llvm::BasicBlock> *NodeI1 =
11021             DT->getNode(I1->getParent());
11022         DomTreeNodeBase<llvm::BasicBlock> *NodeI2 =
11023             DT->getNode(I2->getParent());
11024         assert(NodeI1 && "Should only process reachable instructions");
11025         assert(NodeI1 && "Should only process reachable instructions");
11026         assert((NodeI1 == NodeI2) ==
11027                    (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
11028                "Different nodes should have different DFS numbers");
11029         if (NodeI1 != NodeI2)
11030           return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
11031         InstructionsState S = getSameOpcode({I1, I2});
11032         if (S.getOpcode())
11033           return false;
11034         return I1->getOpcode() < I2->getOpcode();
11035       }
11036     if (isa<Constant>(V->getValueOperand()) &&
11037         isa<Constant>(V2->getValueOperand()))
11038       return false;
11039     return V->getValueOperand()->getValueID() <
11040            V2->getValueOperand()->getValueID();
11041   };
11042 
11043   auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) {
11044     if (V1 == V2)
11045       return true;
11046     if (V1->getPointerOperandType() != V2->getPointerOperandType())
11047       return false;
11048     // Undefs are compatible with any other value.
11049     if (isa<UndefValue>(V1->getValueOperand()) ||
11050         isa<UndefValue>(V2->getValueOperand()))
11051       return true;
11052     if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand()))
11053       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
11054         if (I1->getParent() != I2->getParent())
11055           return false;
11056         InstructionsState S = getSameOpcode({I1, I2});
11057         return S.getOpcode() > 0;
11058       }
11059     if (isa<Constant>(V1->getValueOperand()) &&
11060         isa<Constant>(V2->getValueOperand()))
11061       return true;
11062     return V1->getValueOperand()->getValueID() ==
11063            V2->getValueOperand()->getValueID();
11064   };
11065   auto Limit = [&R, this](StoreInst *SI) {
11066     unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
11067     return R.getMinVF(EltSize);
11068   };
11069 
11070   // Attempt to sort and vectorize each of the store-groups.
11071   for (auto &Pair : Stores) {
11072     if (Pair.second.size() < 2)
11073       continue;
11074 
11075     LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
11076                       << Pair.second.size() << ".\n");
11077 
11078     if (!isValidElementType(Pair.second.front()->getValueOperand()->getType()))
11079       continue;
11080 
11081     Changed |= tryToVectorizeSequence<StoreInst>(
11082         Pair.second, Limit, StoreSorter, AreCompatibleStores,
11083         [this, &R](ArrayRef<StoreInst *> Candidates, bool) {
11084           return vectorizeStores(Candidates, R);
11085         },
11086         /*LimitForRegisterSize=*/false);
11087   }
11088   return Changed;
11089 }
11090 
11091 char SLPVectorizer::ID = 0;
11092 
11093 static const char lv_name[] = "SLP Vectorizer";
11094 
11095 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
11096 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
11097 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
11098 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
11099 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
11100 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
11101 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
11102 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
11103 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
11104 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
11105 
11106 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
11107