1 //===- SLPVectorizer.cpp - A bottom up SLP Vectorizer ---------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass implements the Bottom Up SLP vectorizer. It detects consecutive
10 // stores that can be put together into vector-stores. Next, it attempts to
11 // construct vectorizable tree using the use-def chains. If a profitable tree
12 // was found, the SLP vectorizer performs vectorization on the tree.
13 //
14 // The pass is inspired by the work described in the paper:
15 //  "Loop-Aware SLP in GCC" by Ira Rosen, Dorit Nuzman, Ayal Zaks.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "llvm/Transforms/Vectorize/SLPVectorizer.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/DenseSet.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/ADT/PostOrderIterator.h"
24 #include "llvm/ADT/PriorityQueue.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SetOperations.h"
27 #include "llvm/ADT/SetVector.h"
28 #include "llvm/ADT/SmallBitVector.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/iterator.h"
34 #include "llvm/ADT/iterator_range.h"
35 #include "llvm/Analysis/AliasAnalysis.h"
36 #include "llvm/Analysis/AssumptionCache.h"
37 #include "llvm/Analysis/CodeMetrics.h"
38 #include "llvm/Analysis/DemandedBits.h"
39 #include "llvm/Analysis/GlobalsModRef.h"
40 #include "llvm/Analysis/IVDescriptors.h"
41 #include "llvm/Analysis/LoopAccessAnalysis.h"
42 #include "llvm/Analysis/LoopInfo.h"
43 #include "llvm/Analysis/MemoryLocation.h"
44 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
45 #include "llvm/Analysis/ScalarEvolution.h"
46 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
47 #include "llvm/Analysis/TargetLibraryInfo.h"
48 #include "llvm/Analysis/TargetTransformInfo.h"
49 #include "llvm/Analysis/ValueTracking.h"
50 #include "llvm/Analysis/VectorUtils.h"
51 #include "llvm/IR/Attributes.h"
52 #include "llvm/IR/BasicBlock.h"
53 #include "llvm/IR/Constant.h"
54 #include "llvm/IR/Constants.h"
55 #include "llvm/IR/DataLayout.h"
56 #include "llvm/IR/DerivedTypes.h"
57 #include "llvm/IR/Dominators.h"
58 #include "llvm/IR/Function.h"
59 #include "llvm/IR/IRBuilder.h"
60 #include "llvm/IR/InstrTypes.h"
61 #include "llvm/IR/Instruction.h"
62 #include "llvm/IR/Instructions.h"
63 #include "llvm/IR/IntrinsicInst.h"
64 #include "llvm/IR/Intrinsics.h"
65 #include "llvm/IR/Module.h"
66 #include "llvm/IR/Operator.h"
67 #include "llvm/IR/PatternMatch.h"
68 #include "llvm/IR/Type.h"
69 #include "llvm/IR/Use.h"
70 #include "llvm/IR/User.h"
71 #include "llvm/IR/Value.h"
72 #include "llvm/IR/ValueHandle.h"
73 #ifdef EXPENSIVE_CHECKS
74 #include "llvm/IR/Verifier.h"
75 #endif
76 #include "llvm/Pass.h"
77 #include "llvm/Support/Casting.h"
78 #include "llvm/Support/CommandLine.h"
79 #include "llvm/Support/Compiler.h"
80 #include "llvm/Support/DOTGraphTraits.h"
81 #include "llvm/Support/Debug.h"
82 #include "llvm/Support/ErrorHandling.h"
83 #include "llvm/Support/GraphWriter.h"
84 #include "llvm/Support/InstructionCost.h"
85 #include "llvm/Support/KnownBits.h"
86 #include "llvm/Support/MathExtras.h"
87 #include "llvm/Support/raw_ostream.h"
88 #include "llvm/Transforms/Utils/InjectTLIMappings.h"
89 #include "llvm/Transforms/Utils/Local.h"
90 #include "llvm/Transforms/Utils/LoopUtils.h"
91 #include "llvm/Transforms/Vectorize.h"
92 #include <algorithm>
93 #include <cassert>
94 #include <cstdint>
95 #include <iterator>
96 #include <memory>
97 #include <set>
98 #include <string>
99 #include <tuple>
100 #include <utility>
101 #include <vector>
102 
103 using namespace llvm;
104 using namespace llvm::PatternMatch;
105 using namespace slpvectorizer;
106 
107 #define SV_NAME "slp-vectorizer"
108 #define DEBUG_TYPE "SLP"
109 
110 STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
111 
112 cl::opt<bool> RunSLPVectorization("vectorize-slp", cl::init(true), cl::Hidden,
113                                   cl::desc("Run the SLP vectorization passes"));
114 
115 static cl::opt<int>
116     SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
117                      cl::desc("Only vectorize if you gain more than this "
118                               "number "));
119 
120 static cl::opt<bool>
121 ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden,
122                    cl::desc("Attempt to vectorize horizontal reductions"));
123 
124 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
125     "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
126     cl::desc(
127         "Attempt to vectorize horizontal reductions feeding into a store"));
128 
129 static cl::opt<int>
130 MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden,
131     cl::desc("Attempt to vectorize for this register size in bits"));
132 
133 static cl::opt<unsigned>
134 MaxVFOption("slp-max-vf", cl::init(0), cl::Hidden,
135     cl::desc("Maximum SLP vectorization factor (0=unlimited)"));
136 
137 static cl::opt<int>
138 MaxStoreLookup("slp-max-store-lookup", cl::init(32), cl::Hidden,
139     cl::desc("Maximum depth of the lookup for consecutive stores."));
140 
141 /// Limits the size of scheduling regions in a block.
142 /// It avoid long compile times for _very_ large blocks where vector
143 /// instructions are spread over a wide range.
144 /// This limit is way higher than needed by real-world functions.
145 static cl::opt<int>
146 ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden,
147     cl::desc("Limit the size of the SLP scheduling region per block"));
148 
149 static cl::opt<int> MinVectorRegSizeOption(
150     "slp-min-reg-size", cl::init(128), cl::Hidden,
151     cl::desc("Attempt to vectorize for this register size in bits"));
152 
153 static cl::opt<unsigned> RecursionMaxDepth(
154     "slp-recursion-max-depth", cl::init(12), cl::Hidden,
155     cl::desc("Limit the recursion depth when building a vectorizable tree"));
156 
157 static cl::opt<unsigned> MinTreeSize(
158     "slp-min-tree-size", cl::init(3), cl::Hidden,
159     cl::desc("Only vectorize small trees if they are fully vectorizable"));
160 
161 // The maximum depth that the look-ahead score heuristic will explore.
162 // The higher this value, the higher the compilation time overhead.
163 static cl::opt<int> LookAheadMaxDepth(
164     "slp-max-look-ahead-depth", cl::init(2), cl::Hidden,
165     cl::desc("The maximum look-ahead depth for operand reordering scores"));
166 
167 // The maximum depth that the look-ahead score heuristic will explore
168 // when it probing among candidates for vectorization tree roots.
169 // The higher this value, the higher the compilation time overhead but unlike
170 // similar limit for operands ordering this is less frequently used, hence
171 // impact of higher value is less noticeable.
172 static cl::opt<int> RootLookAheadMaxDepth(
173     "slp-max-root-look-ahead-depth", cl::init(2), cl::Hidden,
174     cl::desc("The maximum look-ahead depth for searching best rooting option"));
175 
176 static cl::opt<bool>
177     ViewSLPTree("view-slp-tree", cl::Hidden,
178                 cl::desc("Display the SLP trees with Graphviz"));
179 
180 // Limit the number of alias checks. The limit is chosen so that
181 // it has no negative effect on the llvm benchmarks.
182 static const unsigned AliasedCheckLimit = 10;
183 
184 // Another limit for the alias checks: The maximum distance between load/store
185 // instructions where alias checks are done.
186 // This limit is useful for very large basic blocks.
187 static const unsigned MaxMemDepDistance = 160;
188 
189 /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
190 /// regions to be handled.
191 static const int MinScheduleRegionSize = 16;
192 
193 /// Predicate for the element types that the SLP vectorizer supports.
194 ///
195 /// The most important thing to filter here are types which are invalid in LLVM
196 /// vectors. We also filter target specific types which have absolutely no
197 /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
198 /// avoids spending time checking the cost model and realizing that they will
199 /// be inevitably scalarized.
200 static bool isValidElementType(Type *Ty) {
201   return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() &&
202          !Ty->isPPC_FP128Ty();
203 }
204 
205 /// \returns True if the value is a constant (but not globals/constant
206 /// expressions).
207 static bool isConstant(Value *V) {
208   return isa<Constant>(V) && !isa<ConstantExpr>(V) && !isa<GlobalValue>(V);
209 }
210 
211 /// Checks if \p V is one of vector-like instructions, i.e. undef,
212 /// insertelement/extractelement with constant indices for fixed vector type or
213 /// extractvalue instruction.
214 static bool isVectorLikeInstWithConstOps(Value *V) {
215   if (!isa<InsertElementInst, ExtractElementInst>(V) &&
216       !isa<ExtractValueInst, UndefValue>(V))
217     return false;
218   auto *I = dyn_cast<Instruction>(V);
219   if (!I || isa<ExtractValueInst>(I))
220     return true;
221   if (!isa<FixedVectorType>(I->getOperand(0)->getType()))
222     return false;
223   if (isa<ExtractElementInst>(I))
224     return isConstant(I->getOperand(1));
225   assert(isa<InsertElementInst>(V) && "Expected only insertelement.");
226   return isConstant(I->getOperand(2));
227 }
228 
229 /// \returns true if all of the instructions in \p VL are in the same block or
230 /// false otherwise.
231 static bool allSameBlock(ArrayRef<Value *> VL) {
232   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
233   if (!I0)
234     return false;
235   if (all_of(VL, isVectorLikeInstWithConstOps))
236     return true;
237 
238   BasicBlock *BB = I0->getParent();
239   for (int I = 1, E = VL.size(); I < E; I++) {
240     auto *II = dyn_cast<Instruction>(VL[I]);
241     if (!II)
242       return false;
243 
244     if (BB != II->getParent())
245       return false;
246   }
247   return true;
248 }
249 
250 /// \returns True if all of the values in \p VL are constants (but not
251 /// globals/constant expressions).
252 static bool allConstant(ArrayRef<Value *> VL) {
253   // Constant expressions and globals can't be vectorized like normal integer/FP
254   // constants.
255   return all_of(VL, isConstant);
256 }
257 
258 /// \returns True if all of the values in \p VL are identical or some of them
259 /// are UndefValue.
260 static bool isSplat(ArrayRef<Value *> VL) {
261   Value *FirstNonUndef = nullptr;
262   for (Value *V : VL) {
263     if (isa<UndefValue>(V))
264       continue;
265     if (!FirstNonUndef) {
266       FirstNonUndef = V;
267       continue;
268     }
269     if (V != FirstNonUndef)
270       return false;
271   }
272   return FirstNonUndef != nullptr;
273 }
274 
275 /// \returns True if \p I is commutative, handles CmpInst and BinaryOperator.
276 static bool isCommutative(Instruction *I) {
277   if (auto *Cmp = dyn_cast<CmpInst>(I))
278     return Cmp->isCommutative();
279   if (auto *BO = dyn_cast<BinaryOperator>(I))
280     return BO->isCommutative();
281   // TODO: This should check for generic Instruction::isCommutative(), but
282   //       we need to confirm that the caller code correctly handles Intrinsics
283   //       for example (does not have 2 operands).
284   return false;
285 }
286 
287 /// Checks if the given value is actually an undefined constant vector.
288 static bool isUndefVector(const Value *V) {
289   if (isa<UndefValue>(V))
290     return true;
291   auto *C = dyn_cast<Constant>(V);
292   if (!C)
293     return false;
294   if (!C->containsUndefOrPoisonElement())
295     return false;
296   auto *VecTy = dyn_cast<FixedVectorType>(C->getType());
297   if (!VecTy)
298     return false;
299   for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
300     if (Constant *Elem = C->getAggregateElement(I))
301       if (!isa<UndefValue>(Elem))
302         return false;
303   }
304   return true;
305 }
306 
307 /// Checks if the vector of instructions can be represented as a shuffle, like:
308 /// %x0 = extractelement <4 x i8> %x, i32 0
309 /// %x3 = extractelement <4 x i8> %x, i32 3
310 /// %y1 = extractelement <4 x i8> %y, i32 1
311 /// %y2 = extractelement <4 x i8> %y, i32 2
312 /// %x0x0 = mul i8 %x0, %x0
313 /// %x3x3 = mul i8 %x3, %x3
314 /// %y1y1 = mul i8 %y1, %y1
315 /// %y2y2 = mul i8 %y2, %y2
316 /// %ins1 = insertelement <4 x i8> poison, i8 %x0x0, i32 0
317 /// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1
318 /// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2
319 /// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3
320 /// ret <4 x i8> %ins4
321 /// can be transformed into:
322 /// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5,
323 ///                                                         i32 6>
324 /// %2 = mul <4 x i8> %1, %1
325 /// ret <4 x i8> %2
326 /// We convert this initially to something like:
327 /// %x0 = extractelement <4 x i8> %x, i32 0
328 /// %x3 = extractelement <4 x i8> %x, i32 3
329 /// %y1 = extractelement <4 x i8> %y, i32 1
330 /// %y2 = extractelement <4 x i8> %y, i32 2
331 /// %1 = insertelement <4 x i8> poison, i8 %x0, i32 0
332 /// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1
333 /// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2
334 /// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3
335 /// %5 = mul <4 x i8> %4, %4
336 /// %6 = extractelement <4 x i8> %5, i32 0
337 /// %ins1 = insertelement <4 x i8> poison, i8 %6, i32 0
338 /// %7 = extractelement <4 x i8> %5, i32 1
339 /// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1
340 /// %8 = extractelement <4 x i8> %5, i32 2
341 /// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2
342 /// %9 = extractelement <4 x i8> %5, i32 3
343 /// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3
344 /// ret <4 x i8> %ins4
345 /// InstCombiner transforms this into a shuffle and vector mul
346 /// Mask will return the Shuffle Mask equivalent to the extracted elements.
347 /// TODO: Can we split off and reuse the shuffle mask detection from
348 /// TargetTransformInfo::getInstructionThroughput?
349 static Optional<TargetTransformInfo::ShuffleKind>
350 isFixedVectorShuffle(ArrayRef<Value *> VL, SmallVectorImpl<int> &Mask) {
351   const auto *It =
352       find_if(VL, [](Value *V) { return isa<ExtractElementInst>(V); });
353   if (It == VL.end())
354     return None;
355   auto *EI0 = cast<ExtractElementInst>(*It);
356   if (isa<ScalableVectorType>(EI0->getVectorOperandType()))
357     return None;
358   unsigned Size =
359       cast<FixedVectorType>(EI0->getVectorOperandType())->getNumElements();
360   Value *Vec1 = nullptr;
361   Value *Vec2 = nullptr;
362   enum ShuffleMode { Unknown, Select, Permute };
363   ShuffleMode CommonShuffleMode = Unknown;
364   Mask.assign(VL.size(), UndefMaskElem);
365   for (unsigned I = 0, E = VL.size(); I < E; ++I) {
366     // Undef can be represented as an undef element in a vector.
367     if (isa<UndefValue>(VL[I]))
368       continue;
369     auto *EI = cast<ExtractElementInst>(VL[I]);
370     if (isa<ScalableVectorType>(EI->getVectorOperandType()))
371       return None;
372     auto *Vec = EI->getVectorOperand();
373     // We can extractelement from undef or poison vector.
374     if (isUndefVector(Vec))
375       continue;
376     // All vector operands must have the same number of vector elements.
377     if (cast<FixedVectorType>(Vec->getType())->getNumElements() != Size)
378       return None;
379     if (isa<UndefValue>(EI->getIndexOperand()))
380       continue;
381     auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand());
382     if (!Idx)
383       return None;
384     // Undefined behavior if Idx is negative or >= Size.
385     if (Idx->getValue().uge(Size))
386       continue;
387     unsigned IntIdx = Idx->getValue().getZExtValue();
388     Mask[I] = IntIdx;
389     // For correct shuffling we have to have at most 2 different vector operands
390     // in all extractelement instructions.
391     if (!Vec1 || Vec1 == Vec) {
392       Vec1 = Vec;
393     } else if (!Vec2 || Vec2 == Vec) {
394       Vec2 = Vec;
395       Mask[I] += Size;
396     } else {
397       return None;
398     }
399     if (CommonShuffleMode == Permute)
400       continue;
401     // If the extract index is not the same as the operation number, it is a
402     // permutation.
403     if (IntIdx != I) {
404       CommonShuffleMode = Permute;
405       continue;
406     }
407     CommonShuffleMode = Select;
408   }
409   // If we're not crossing lanes in different vectors, consider it as blending.
410   if (CommonShuffleMode == Select && Vec2)
411     return TargetTransformInfo::SK_Select;
412   // If Vec2 was never used, we have a permutation of a single vector, otherwise
413   // we have permutation of 2 vectors.
414   return Vec2 ? TargetTransformInfo::SK_PermuteTwoSrc
415               : TargetTransformInfo::SK_PermuteSingleSrc;
416 }
417 
418 namespace {
419 
420 /// Main data required for vectorization of instructions.
421 struct InstructionsState {
422   /// The very first instruction in the list with the main opcode.
423   Value *OpValue = nullptr;
424 
425   /// The main/alternate instruction.
426   Instruction *MainOp = nullptr;
427   Instruction *AltOp = nullptr;
428 
429   /// The main/alternate opcodes for the list of instructions.
430   unsigned getOpcode() const {
431     return MainOp ? MainOp->getOpcode() : 0;
432   }
433 
434   unsigned getAltOpcode() const {
435     return AltOp ? AltOp->getOpcode() : 0;
436   }
437 
438   /// Some of the instructions in the list have alternate opcodes.
439   bool isAltShuffle() const { return AltOp != MainOp; }
440 
441   bool isOpcodeOrAlt(Instruction *I) const {
442     unsigned CheckedOpcode = I->getOpcode();
443     return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode;
444   }
445 
446   InstructionsState() = delete;
447   InstructionsState(Value *OpValue, Instruction *MainOp, Instruction *AltOp)
448       : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {}
449 };
450 
451 } // end anonymous namespace
452 
453 /// Chooses the correct key for scheduling data. If \p Op has the same (or
454 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p
455 /// OpValue.
456 static Value *isOneOf(const InstructionsState &S, Value *Op) {
457   auto *I = dyn_cast<Instruction>(Op);
458   if (I && S.isOpcodeOrAlt(I))
459     return Op;
460   return S.OpValue;
461 }
462 
463 /// \returns true if \p Opcode is allowed as part of of the main/alternate
464 /// instruction for SLP vectorization.
465 ///
466 /// Example of unsupported opcode is SDIV that can potentially cause UB if the
467 /// "shuffled out" lane would result in division by zero.
468 static bool isValidForAlternation(unsigned Opcode) {
469   if (Instruction::isIntDivRem(Opcode))
470     return false;
471 
472   return true;
473 }
474 
475 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
476                                        unsigned BaseIndex = 0);
477 
478 /// Checks if the provided operands of 2 cmp instructions are compatible, i.e.
479 /// compatible instructions or constants, or just some other regular values.
480 static bool areCompatibleCmpOps(Value *BaseOp0, Value *BaseOp1, Value *Op0,
481                                 Value *Op1) {
482   return (isConstant(BaseOp0) && isConstant(Op0)) ||
483          (isConstant(BaseOp1) && isConstant(Op1)) ||
484          (!isa<Instruction>(BaseOp0) && !isa<Instruction>(Op0) &&
485           !isa<Instruction>(BaseOp1) && !isa<Instruction>(Op1)) ||
486          getSameOpcode({BaseOp0, Op0}).getOpcode() ||
487          getSameOpcode({BaseOp1, Op1}).getOpcode();
488 }
489 
490 /// \returns analysis of the Instructions in \p VL described in
491 /// InstructionsState, the Opcode that we suppose the whole list
492 /// could be vectorized even if its structure is diverse.
493 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
494                                        unsigned BaseIndex) {
495   // Make sure these are all Instructions.
496   if (llvm::any_of(VL, [](Value *V) { return !isa<Instruction>(V); }))
497     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
498 
499   bool IsCastOp = isa<CastInst>(VL[BaseIndex]);
500   bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]);
501   bool IsCmpOp = isa<CmpInst>(VL[BaseIndex]);
502   CmpInst::Predicate BasePred =
503       IsCmpOp ? cast<CmpInst>(VL[BaseIndex])->getPredicate()
504               : CmpInst::BAD_ICMP_PREDICATE;
505   unsigned Opcode = cast<Instruction>(VL[BaseIndex])->getOpcode();
506   unsigned AltOpcode = Opcode;
507   unsigned AltIndex = BaseIndex;
508 
509   // Check for one alternate opcode from another BinaryOperator.
510   // TODO - generalize to support all operators (types, calls etc.).
511   for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) {
512     unsigned InstOpcode = cast<Instruction>(VL[Cnt])->getOpcode();
513     if (IsBinOp && isa<BinaryOperator>(VL[Cnt])) {
514       if (InstOpcode == Opcode || InstOpcode == AltOpcode)
515         continue;
516       if (Opcode == AltOpcode && isValidForAlternation(InstOpcode) &&
517           isValidForAlternation(Opcode)) {
518         AltOpcode = InstOpcode;
519         AltIndex = Cnt;
520         continue;
521       }
522     } else if (IsCastOp && isa<CastInst>(VL[Cnt])) {
523       Type *Ty0 = cast<Instruction>(VL[BaseIndex])->getOperand(0)->getType();
524       Type *Ty1 = cast<Instruction>(VL[Cnt])->getOperand(0)->getType();
525       if (Ty0 == Ty1) {
526         if (InstOpcode == Opcode || InstOpcode == AltOpcode)
527           continue;
528         if (Opcode == AltOpcode) {
529           assert(isValidForAlternation(Opcode) &&
530                  isValidForAlternation(InstOpcode) &&
531                  "Cast isn't safe for alternation, logic needs to be updated!");
532           AltOpcode = InstOpcode;
533           AltIndex = Cnt;
534           continue;
535         }
536       }
537     } else if (IsCmpOp && isa<CmpInst>(VL[Cnt])) {
538       auto *BaseInst = cast<Instruction>(VL[BaseIndex]);
539       auto *Inst = cast<Instruction>(VL[Cnt]);
540       Type *Ty0 = BaseInst->getOperand(0)->getType();
541       Type *Ty1 = Inst->getOperand(0)->getType();
542       if (Ty0 == Ty1) {
543         Value *BaseOp0 = BaseInst->getOperand(0);
544         Value *BaseOp1 = BaseInst->getOperand(1);
545         Value *Op0 = Inst->getOperand(0);
546         Value *Op1 = Inst->getOperand(1);
547         CmpInst::Predicate CurrentPred =
548             cast<CmpInst>(VL[Cnt])->getPredicate();
549         CmpInst::Predicate SwappedCurrentPred =
550             CmpInst::getSwappedPredicate(CurrentPred);
551         // Check for compatible operands. If the corresponding operands are not
552         // compatible - need to perform alternate vectorization.
553         if (InstOpcode == Opcode) {
554           if (BasePred == CurrentPred &&
555               areCompatibleCmpOps(BaseOp0, BaseOp1, Op0, Op1))
556             continue;
557           if (BasePred == SwappedCurrentPred &&
558               areCompatibleCmpOps(BaseOp0, BaseOp1, Op1, Op0))
559             continue;
560           if (E == 2 &&
561               (BasePred == CurrentPred || BasePred == SwappedCurrentPred))
562             continue;
563           auto *AltInst = cast<CmpInst>(VL[AltIndex]);
564           CmpInst::Predicate AltPred = AltInst->getPredicate();
565           Value *AltOp0 = AltInst->getOperand(0);
566           Value *AltOp1 = AltInst->getOperand(1);
567           // Check if operands are compatible with alternate operands.
568           if (AltPred == CurrentPred &&
569               areCompatibleCmpOps(AltOp0, AltOp1, Op0, Op1))
570             continue;
571           if (AltPred == SwappedCurrentPred &&
572               areCompatibleCmpOps(AltOp0, AltOp1, Op1, Op0))
573             continue;
574         }
575         if (BaseIndex == AltIndex && BasePred != CurrentPred) {
576           assert(isValidForAlternation(Opcode) &&
577                  isValidForAlternation(InstOpcode) &&
578                  "Cast isn't safe for alternation, logic needs to be updated!");
579           AltIndex = Cnt;
580           continue;
581         }
582         auto *AltInst = cast<CmpInst>(VL[AltIndex]);
583         CmpInst::Predicate AltPred = AltInst->getPredicate();
584         if (BasePred == CurrentPred || BasePred == SwappedCurrentPred ||
585             AltPred == CurrentPred || AltPred == SwappedCurrentPred)
586           continue;
587       }
588     } else if (InstOpcode == Opcode || InstOpcode == AltOpcode)
589       continue;
590     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
591   }
592 
593   return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]),
594                            cast<Instruction>(VL[AltIndex]));
595 }
596 
597 /// \returns true if all of the values in \p VL have the same type or false
598 /// otherwise.
599 static bool allSameType(ArrayRef<Value *> VL) {
600   Type *Ty = VL[0]->getType();
601   for (int i = 1, e = VL.size(); i < e; i++)
602     if (VL[i]->getType() != Ty)
603       return false;
604 
605   return true;
606 }
607 
608 /// \returns True if Extract{Value,Element} instruction extracts element Idx.
609 static Optional<unsigned> getExtractIndex(Instruction *E) {
610   unsigned Opcode = E->getOpcode();
611   assert((Opcode == Instruction::ExtractElement ||
612           Opcode == Instruction::ExtractValue) &&
613          "Expected extractelement or extractvalue instruction.");
614   if (Opcode == Instruction::ExtractElement) {
615     auto *CI = dyn_cast<ConstantInt>(E->getOperand(1));
616     if (!CI)
617       return None;
618     return CI->getZExtValue();
619   }
620   ExtractValueInst *EI = cast<ExtractValueInst>(E);
621   if (EI->getNumIndices() != 1)
622     return None;
623   return *EI->idx_begin();
624 }
625 
626 /// \returns True if in-tree use also needs extract. This refers to
627 /// possible scalar operand in vectorized instruction.
628 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
629                                     TargetLibraryInfo *TLI) {
630   unsigned Opcode = UserInst->getOpcode();
631   switch (Opcode) {
632   case Instruction::Load: {
633     LoadInst *LI = cast<LoadInst>(UserInst);
634     return (LI->getPointerOperand() == Scalar);
635   }
636   case Instruction::Store: {
637     StoreInst *SI = cast<StoreInst>(UserInst);
638     return (SI->getPointerOperand() == Scalar);
639   }
640   case Instruction::Call: {
641     CallInst *CI = cast<CallInst>(UserInst);
642     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
643     for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
644       if (isVectorIntrinsicWithScalarOpAtArg(ID, i))
645         return (CI->getArgOperand(i) == Scalar);
646     }
647     LLVM_FALLTHROUGH;
648   }
649   default:
650     return false;
651   }
652 }
653 
654 /// \returns the AA location that is being access by the instruction.
655 static MemoryLocation getLocation(Instruction *I) {
656   if (StoreInst *SI = dyn_cast<StoreInst>(I))
657     return MemoryLocation::get(SI);
658   if (LoadInst *LI = dyn_cast<LoadInst>(I))
659     return MemoryLocation::get(LI);
660   return MemoryLocation();
661 }
662 
663 /// \returns True if the instruction is not a volatile or atomic load/store.
664 static bool isSimple(Instruction *I) {
665   if (LoadInst *LI = dyn_cast<LoadInst>(I))
666     return LI->isSimple();
667   if (StoreInst *SI = dyn_cast<StoreInst>(I))
668     return SI->isSimple();
669   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
670     return !MI->isVolatile();
671   return true;
672 }
673 
674 /// Shuffles \p Mask in accordance with the given \p SubMask.
675 static void addMask(SmallVectorImpl<int> &Mask, ArrayRef<int> SubMask) {
676   if (SubMask.empty())
677     return;
678   if (Mask.empty()) {
679     Mask.append(SubMask.begin(), SubMask.end());
680     return;
681   }
682   SmallVector<int> NewMask(SubMask.size(), UndefMaskElem);
683   int TermValue = std::min(Mask.size(), SubMask.size());
684   for (int I = 0, E = SubMask.size(); I < E; ++I) {
685     if (SubMask[I] >= TermValue || SubMask[I] == UndefMaskElem ||
686         Mask[SubMask[I]] >= TermValue)
687       continue;
688     NewMask[I] = Mask[SubMask[I]];
689   }
690   Mask.swap(NewMask);
691 }
692 
693 /// Order may have elements assigned special value (size) which is out of
694 /// bounds. Such indices only appear on places which correspond to undef values
695 /// (see canReuseExtract for details) and used in order to avoid undef values
696 /// have effect on operands ordering.
697 /// The first loop below simply finds all unused indices and then the next loop
698 /// nest assigns these indices for undef values positions.
699 /// As an example below Order has two undef positions and they have assigned
700 /// values 3 and 7 respectively:
701 /// before:  6 9 5 4 9 2 1 0
702 /// after:   6 3 5 4 7 2 1 0
703 static void fixupOrderingIndices(SmallVectorImpl<unsigned> &Order) {
704   const unsigned Sz = Order.size();
705   SmallBitVector UnusedIndices(Sz, /*t=*/true);
706   SmallBitVector MaskedIndices(Sz);
707   for (unsigned I = 0; I < Sz; ++I) {
708     if (Order[I] < Sz)
709       UnusedIndices.reset(Order[I]);
710     else
711       MaskedIndices.set(I);
712   }
713   if (MaskedIndices.none())
714     return;
715   assert(UnusedIndices.count() == MaskedIndices.count() &&
716          "Non-synced masked/available indices.");
717   int Idx = UnusedIndices.find_first();
718   int MIdx = MaskedIndices.find_first();
719   while (MIdx >= 0) {
720     assert(Idx >= 0 && "Indices must be synced.");
721     Order[MIdx] = Idx;
722     Idx = UnusedIndices.find_next(Idx);
723     MIdx = MaskedIndices.find_next(MIdx);
724   }
725 }
726 
727 namespace llvm {
728 
729 static void inversePermutation(ArrayRef<unsigned> Indices,
730                                SmallVectorImpl<int> &Mask) {
731   Mask.clear();
732   const unsigned E = Indices.size();
733   Mask.resize(E, UndefMaskElem);
734   for (unsigned I = 0; I < E; ++I)
735     Mask[Indices[I]] = I;
736 }
737 
738 /// \returns inserting index of InsertElement or InsertValue instruction,
739 /// using Offset as base offset for index.
740 static Optional<unsigned> getInsertIndex(Value *InsertInst,
741                                          unsigned Offset = 0) {
742   int Index = Offset;
743   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst)) {
744     if (auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2))) {
745       auto *VT = cast<FixedVectorType>(IE->getType());
746       if (CI->getValue().uge(VT->getNumElements()))
747         return None;
748       Index *= VT->getNumElements();
749       Index += CI->getZExtValue();
750       return Index;
751     }
752     return None;
753   }
754 
755   auto *IV = cast<InsertValueInst>(InsertInst);
756   Type *CurrentType = IV->getType();
757   for (unsigned I : IV->indices()) {
758     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
759       Index *= ST->getNumElements();
760       CurrentType = ST->getElementType(I);
761     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
762       Index *= AT->getNumElements();
763       CurrentType = AT->getElementType();
764     } else {
765       return None;
766     }
767     Index += I;
768   }
769   return Index;
770 }
771 
772 /// Reorders the list of scalars in accordance with the given \p Mask.
773 static void reorderScalars(SmallVectorImpl<Value *> &Scalars,
774                            ArrayRef<int> Mask) {
775   assert(!Mask.empty() && "Expected non-empty mask.");
776   SmallVector<Value *> Prev(Scalars.size(),
777                             UndefValue::get(Scalars.front()->getType()));
778   Prev.swap(Scalars);
779   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
780     if (Mask[I] != UndefMaskElem)
781       Scalars[Mask[I]] = Prev[I];
782 }
783 
784 /// Checks if the provided value does not require scheduling. It does not
785 /// require scheduling if this is not an instruction or it is an instruction
786 /// that does not read/write memory and all operands are either not instructions
787 /// or phi nodes or instructions from different blocks.
788 static bool areAllOperandsNonInsts(Value *V) {
789   auto *I = dyn_cast<Instruction>(V);
790   if (!I)
791     return true;
792   return !mayHaveNonDefUseDependency(*I) &&
793     all_of(I->operands(), [I](Value *V) {
794       auto *IO = dyn_cast<Instruction>(V);
795       if (!IO)
796         return true;
797       return isa<PHINode>(IO) || IO->getParent() != I->getParent();
798     });
799 }
800 
801 /// Checks if the provided value does not require scheduling. It does not
802 /// require scheduling if this is not an instruction or it is an instruction
803 /// that does not read/write memory and all users are phi nodes or instructions
804 /// from the different blocks.
805 static bool isUsedOutsideBlock(Value *V) {
806   auto *I = dyn_cast<Instruction>(V);
807   if (!I)
808     return true;
809   // Limits the number of uses to save compile time.
810   constexpr int UsesLimit = 8;
811   return !I->mayReadOrWriteMemory() && !I->hasNUsesOrMore(UsesLimit) &&
812          all_of(I->users(), [I](User *U) {
813            auto *IU = dyn_cast<Instruction>(U);
814            if (!IU)
815              return true;
816            return IU->getParent() != I->getParent() || isa<PHINode>(IU);
817          });
818 }
819 
820 /// Checks if the specified value does not require scheduling. It does not
821 /// require scheduling if all operands and all users do not need to be scheduled
822 /// in the current basic block.
823 static bool doesNotNeedToBeScheduled(Value *V) {
824   return areAllOperandsNonInsts(V) && isUsedOutsideBlock(V);
825 }
826 
827 /// Checks if the specified array of instructions does not require scheduling.
828 /// It is so if all either instructions have operands that do not require
829 /// scheduling or their users do not require scheduling since they are phis or
830 /// in other basic blocks.
831 static bool doesNotNeedToSchedule(ArrayRef<Value *> VL) {
832   return !VL.empty() &&
833          (all_of(VL, isUsedOutsideBlock) || all_of(VL, areAllOperandsNonInsts));
834 }
835 
836 namespace slpvectorizer {
837 
838 /// Bottom Up SLP Vectorizer.
839 class BoUpSLP {
840   struct TreeEntry;
841   struct ScheduleData;
842 
843 public:
844   using ValueList = SmallVector<Value *, 8>;
845   using InstrList = SmallVector<Instruction *, 16>;
846   using ValueSet = SmallPtrSet<Value *, 16>;
847   using StoreList = SmallVector<StoreInst *, 8>;
848   using ExtraValueToDebugLocsMap =
849       MapVector<Value *, SmallVector<Instruction *, 2>>;
850   using OrdersType = SmallVector<unsigned, 4>;
851 
852   BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
853           TargetLibraryInfo *TLi, AAResults *Aa, LoopInfo *Li,
854           DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB,
855           const DataLayout *DL, OptimizationRemarkEmitter *ORE)
856       : BatchAA(*Aa), F(Func), SE(Se), TTI(Tti), TLI(TLi), LI(Li),
857         DT(Dt), AC(AC), DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) {
858     CodeMetrics::collectEphemeralValues(F, AC, EphValues);
859     // Use the vector register size specified by the target unless overridden
860     // by a command-line option.
861     // TODO: It would be better to limit the vectorization factor based on
862     //       data type rather than just register size. For example, x86 AVX has
863     //       256-bit registers, but it does not support integer operations
864     //       at that width (that requires AVX2).
865     if (MaxVectorRegSizeOption.getNumOccurrences())
866       MaxVecRegSize = MaxVectorRegSizeOption;
867     else
868       MaxVecRegSize =
869           TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
870               .getFixedSize();
871 
872     if (MinVectorRegSizeOption.getNumOccurrences())
873       MinVecRegSize = MinVectorRegSizeOption;
874     else
875       MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
876   }
877 
878   /// Vectorize the tree that starts with the elements in \p VL.
879   /// Returns the vectorized root.
880   Value *vectorizeTree();
881 
882   /// Vectorize the tree but with the list of externally used values \p
883   /// ExternallyUsedValues. Values in this MapVector can be replaced but the
884   /// generated extractvalue instructions.
885   Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues);
886 
887   /// \returns the cost incurred by unwanted spills and fills, caused by
888   /// holding live values over call sites.
889   InstructionCost getSpillCost() const;
890 
891   /// \returns the vectorization cost of the subtree that starts at \p VL.
892   /// A negative number means that this is profitable.
893   InstructionCost getTreeCost(ArrayRef<Value *> VectorizedVals = None);
894 
895   /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
896   /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
897   void buildTree(ArrayRef<Value *> Roots,
898                  ArrayRef<Value *> UserIgnoreLst = None);
899 
900   /// Builds external uses of the vectorized scalars, i.e. the list of
901   /// vectorized scalars to be extracted, their lanes and their scalar users. \p
902   /// ExternallyUsedValues contains additional list of external uses to handle
903   /// vectorization of reductions.
904   void
905   buildExternalUses(const ExtraValueToDebugLocsMap &ExternallyUsedValues = {});
906 
907   /// Clear the internal data structures that are created by 'buildTree'.
908   void deleteTree() {
909     VectorizableTree.clear();
910     ScalarToTreeEntry.clear();
911     MustGather.clear();
912     ExternalUses.clear();
913     for (auto &Iter : BlocksSchedules) {
914       BlockScheduling *BS = Iter.second.get();
915       BS->clear();
916     }
917     MinBWs.clear();
918     InstrElementSize.clear();
919   }
920 
921   unsigned getTreeSize() const { return VectorizableTree.size(); }
922 
923   /// Perform LICM and CSE on the newly generated gather sequences.
924   void optimizeGatherSequence();
925 
926   /// Checks if the specified gather tree entry \p TE can be represented as a
927   /// shuffled vector entry + (possibly) permutation with other gathers. It
928   /// implements the checks only for possibly ordered scalars (Loads,
929   /// ExtractElement, ExtractValue), which can be part of the graph.
930   Optional<OrdersType> findReusedOrderedScalars(const TreeEntry &TE);
931 
932   /// Sort loads into increasing pointers offsets to allow greater clustering.
933   Optional<OrdersType> findPartiallyOrderedLoads(const TreeEntry &TE);
934 
935   /// Gets reordering data for the given tree entry. If the entry is vectorized
936   /// - just return ReorderIndices, otherwise check if the scalars can be
937   /// reordered and return the most optimal order.
938   /// \param TopToBottom If true, include the order of vectorized stores and
939   /// insertelement nodes, otherwise skip them.
940   Optional<OrdersType> getReorderingData(const TreeEntry &TE, bool TopToBottom);
941 
942   /// Reorders the current graph to the most profitable order starting from the
943   /// root node to the leaf nodes. The best order is chosen only from the nodes
944   /// of the same size (vectorization factor). Smaller nodes are considered
945   /// parts of subgraph with smaller VF and they are reordered independently. We
946   /// can make it because we still need to extend smaller nodes to the wider VF
947   /// and we can merge reordering shuffles with the widening shuffles.
948   void reorderTopToBottom();
949 
950   /// Reorders the current graph to the most profitable order starting from
951   /// leaves to the root. It allows to rotate small subgraphs and reduce the
952   /// number of reshuffles if the leaf nodes use the same order. In this case we
953   /// can merge the orders and just shuffle user node instead of shuffling its
954   /// operands. Plus, even the leaf nodes have different orders, it allows to
955   /// sink reordering in the graph closer to the root node and merge it later
956   /// during analysis.
957   void reorderBottomToTop(bool IgnoreReorder = false);
958 
959   /// \return The vector element size in bits to use when vectorizing the
960   /// expression tree ending at \p V. If V is a store, the size is the width of
961   /// the stored value. Otherwise, the size is the width of the largest loaded
962   /// value reaching V. This method is used by the vectorizer to calculate
963   /// vectorization factors.
964   unsigned getVectorElementSize(Value *V);
965 
966   /// Compute the minimum type sizes required to represent the entries in a
967   /// vectorizable tree.
968   void computeMinimumValueSizes();
969 
970   // \returns maximum vector register size as set by TTI or overridden by cl::opt.
971   unsigned getMaxVecRegSize() const {
972     return MaxVecRegSize;
973   }
974 
975   // \returns minimum vector register size as set by cl::opt.
976   unsigned getMinVecRegSize() const {
977     return MinVecRegSize;
978   }
979 
980   unsigned getMinVF(unsigned Sz) const {
981     return std::max(2U, getMinVecRegSize() / Sz);
982   }
983 
984   unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const {
985     unsigned MaxVF = MaxVFOption.getNumOccurrences() ?
986       MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode);
987     return MaxVF ? MaxVF : UINT_MAX;
988   }
989 
990   /// Check if homogeneous aggregate is isomorphic to some VectorType.
991   /// Accepts homogeneous multidimensional aggregate of scalars/vectors like
992   /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> },
993   /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on.
994   ///
995   /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
996   unsigned canMapToVector(Type *T, const DataLayout &DL) const;
997 
998   /// \returns True if the VectorizableTree is both tiny and not fully
999   /// vectorizable. We do not vectorize such trees.
1000   bool isTreeTinyAndNotFullyVectorizable(bool ForReduction = false) const;
1001 
1002   /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values
1003   /// can be load combined in the backend. Load combining may not be allowed in
1004   /// the IR optimizer, so we do not want to alter the pattern. For example,
1005   /// partially transforming a scalar bswap() pattern into vector code is
1006   /// effectively impossible for the backend to undo.
1007   /// TODO: If load combining is allowed in the IR optimizer, this analysis
1008   ///       may not be necessary.
1009   bool isLoadCombineReductionCandidate(RecurKind RdxKind) const;
1010 
1011   /// Assume that a vector of stores of bitwise-or/shifted/zexted loaded values
1012   /// can be load combined in the backend. Load combining may not be allowed in
1013   /// the IR optimizer, so we do not want to alter the pattern. For example,
1014   /// partially transforming a scalar bswap() pattern into vector code is
1015   /// effectively impossible for the backend to undo.
1016   /// TODO: If load combining is allowed in the IR optimizer, this analysis
1017   ///       may not be necessary.
1018   bool isLoadCombineCandidate() const;
1019 
1020   OptimizationRemarkEmitter *getORE() { return ORE; }
1021 
1022   /// This structure holds any data we need about the edges being traversed
1023   /// during buildTree_rec(). We keep track of:
1024   /// (i) the user TreeEntry index, and
1025   /// (ii) the index of the edge.
1026   struct EdgeInfo {
1027     EdgeInfo() = default;
1028     EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx)
1029         : UserTE(UserTE), EdgeIdx(EdgeIdx) {}
1030     /// The user TreeEntry.
1031     TreeEntry *UserTE = nullptr;
1032     /// The operand index of the use.
1033     unsigned EdgeIdx = UINT_MAX;
1034 #ifndef NDEBUG
1035     friend inline raw_ostream &operator<<(raw_ostream &OS,
1036                                           const BoUpSLP::EdgeInfo &EI) {
1037       EI.dump(OS);
1038       return OS;
1039     }
1040     /// Debug print.
1041     void dump(raw_ostream &OS) const {
1042       OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null")
1043          << " EdgeIdx:" << EdgeIdx << "}";
1044     }
1045     LLVM_DUMP_METHOD void dump() const { dump(dbgs()); }
1046 #endif
1047   };
1048 
1049   /// A helper class used for scoring candidates for two consecutive lanes.
1050   class LookAheadHeuristics {
1051     const DataLayout &DL;
1052     ScalarEvolution &SE;
1053     const BoUpSLP &R;
1054     int NumLanes; // Total number of lanes (aka vectorization factor).
1055     int MaxLevel; // The maximum recursion depth for accumulating score.
1056 
1057   public:
1058     LookAheadHeuristics(const DataLayout &DL, ScalarEvolution &SE,
1059                         const BoUpSLP &R, int NumLanes, int MaxLevel)
1060         : DL(DL), SE(SE), R(R), NumLanes(NumLanes), MaxLevel(MaxLevel) {}
1061 
1062     // The hard-coded scores listed here are not very important, though it shall
1063     // be higher for better matches to improve the resulting cost. When
1064     // computing the scores of matching one sub-tree with another, we are
1065     // basically counting the number of values that are matching. So even if all
1066     // scores are set to 1, we would still get a decent matching result.
1067     // However, sometimes we have to break ties. For example we may have to
1068     // choose between matching loads vs matching opcodes. This is what these
1069     // scores are helping us with: they provide the order of preference. Also,
1070     // this is important if the scalar is externally used or used in another
1071     // tree entry node in the different lane.
1072 
1073     /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]).
1074     static const int ScoreConsecutiveLoads = 4;
1075     /// The same load multiple times. This should have a better score than
1076     /// `ScoreSplat` because it in x86 for a 2-lane vector we can represent it
1077     /// with `movddup (%reg), xmm0` which has a throughput of 0.5 versus 0.5 for
1078     /// a vector load and 1.0 for a broadcast.
1079     static const int ScoreSplatLoads = 3;
1080     /// Loads from reversed memory addresses, e.g. load(A[i+1]), load(A[i]).
1081     static const int ScoreReversedLoads = 3;
1082     /// ExtractElementInst from same vector and consecutive indexes.
1083     static const int ScoreConsecutiveExtracts = 4;
1084     /// ExtractElementInst from same vector and reversed indices.
1085     static const int ScoreReversedExtracts = 3;
1086     /// Constants.
1087     static const int ScoreConstants = 2;
1088     /// Instructions with the same opcode.
1089     static const int ScoreSameOpcode = 2;
1090     /// Instructions with alt opcodes (e.g, add + sub).
1091     static const int ScoreAltOpcodes = 1;
1092     /// Identical instructions (a.k.a. splat or broadcast).
1093     static const int ScoreSplat = 1;
1094     /// Matching with an undef is preferable to failing.
1095     static const int ScoreUndef = 1;
1096     /// Score for failing to find a decent match.
1097     static const int ScoreFail = 0;
1098     /// Score if all users are vectorized.
1099     static const int ScoreAllUserVectorized = 1;
1100 
1101     /// \returns the score of placing \p V1 and \p V2 in consecutive lanes.
1102     /// \p U1 and \p U2 are the users of \p V1 and \p V2.
1103     /// Also, checks if \p V1 and \p V2 are compatible with instructions in \p
1104     /// MainAltOps.
1105     int getShallowScore(Value *V1, Value *V2, Instruction *U1, Instruction *U2,
1106                         ArrayRef<Value *> MainAltOps) const {
1107       if (V1 == V2) {
1108         if (isa<LoadInst>(V1)) {
1109           // Retruns true if the users of V1 and V2 won't need to be extracted.
1110           auto AllUsersAreInternal = [U1, U2, this](Value *V1, Value *V2) {
1111             // Bail out if we have too many uses to save compilation time.
1112             static constexpr unsigned Limit = 8;
1113             if (V1->hasNUsesOrMore(Limit) || V2->hasNUsesOrMore(Limit))
1114               return false;
1115 
1116             auto AllUsersVectorized = [U1, U2, this](Value *V) {
1117               return llvm::all_of(V->users(), [U1, U2, this](Value *U) {
1118                 return U == U1 || U == U2 || R.getTreeEntry(U) != nullptr;
1119               });
1120             };
1121             return AllUsersVectorized(V1) && AllUsersVectorized(V2);
1122           };
1123           // A broadcast of a load can be cheaper on some targets.
1124           if (R.TTI->isLegalBroadcastLoad(V1->getType(),
1125                                           ElementCount::getFixed(NumLanes)) &&
1126               ((int)V1->getNumUses() == NumLanes ||
1127                AllUsersAreInternal(V1, V2)))
1128             return LookAheadHeuristics::ScoreSplatLoads;
1129         }
1130         return LookAheadHeuristics::ScoreSplat;
1131       }
1132 
1133       auto *LI1 = dyn_cast<LoadInst>(V1);
1134       auto *LI2 = dyn_cast<LoadInst>(V2);
1135       if (LI1 && LI2) {
1136         if (LI1->getParent() != LI2->getParent())
1137           return LookAheadHeuristics::ScoreFail;
1138 
1139         Optional<int> Dist = getPointersDiff(
1140             LI1->getType(), LI1->getPointerOperand(), LI2->getType(),
1141             LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true);
1142         if (!Dist || *Dist == 0)
1143           return LookAheadHeuristics::ScoreFail;
1144         // The distance is too large - still may be profitable to use masked
1145         // loads/gathers.
1146         if (std::abs(*Dist) > NumLanes / 2)
1147           return LookAheadHeuristics::ScoreAltOpcodes;
1148         // This still will detect consecutive loads, but we might have "holes"
1149         // in some cases. It is ok for non-power-2 vectorization and may produce
1150         // better results. It should not affect current vectorization.
1151         return (*Dist > 0) ? LookAheadHeuristics::ScoreConsecutiveLoads
1152                            : LookAheadHeuristics::ScoreReversedLoads;
1153       }
1154 
1155       auto *C1 = dyn_cast<Constant>(V1);
1156       auto *C2 = dyn_cast<Constant>(V2);
1157       if (C1 && C2)
1158         return LookAheadHeuristics::ScoreConstants;
1159 
1160       // Extracts from consecutive indexes of the same vector better score as
1161       // the extracts could be optimized away.
1162       Value *EV1;
1163       ConstantInt *Ex1Idx;
1164       if (match(V1, m_ExtractElt(m_Value(EV1), m_ConstantInt(Ex1Idx)))) {
1165         // Undefs are always profitable for extractelements.
1166         if (isa<UndefValue>(V2))
1167           return LookAheadHeuristics::ScoreConsecutiveExtracts;
1168         Value *EV2 = nullptr;
1169         ConstantInt *Ex2Idx = nullptr;
1170         if (match(V2,
1171                   m_ExtractElt(m_Value(EV2), m_CombineOr(m_ConstantInt(Ex2Idx),
1172                                                          m_Undef())))) {
1173           // Undefs are always profitable for extractelements.
1174           if (!Ex2Idx)
1175             return LookAheadHeuristics::ScoreConsecutiveExtracts;
1176           if (isUndefVector(EV2) && EV2->getType() == EV1->getType())
1177             return LookAheadHeuristics::ScoreConsecutiveExtracts;
1178           if (EV2 == EV1) {
1179             int Idx1 = Ex1Idx->getZExtValue();
1180             int Idx2 = Ex2Idx->getZExtValue();
1181             int Dist = Idx2 - Idx1;
1182             // The distance is too large - still may be profitable to use
1183             // shuffles.
1184             if (std::abs(Dist) == 0)
1185               return LookAheadHeuristics::ScoreSplat;
1186             if (std::abs(Dist) > NumLanes / 2)
1187               return LookAheadHeuristics::ScoreSameOpcode;
1188             return (Dist > 0) ? LookAheadHeuristics::ScoreConsecutiveExtracts
1189                               : LookAheadHeuristics::ScoreReversedExtracts;
1190           }
1191           return LookAheadHeuristics::ScoreAltOpcodes;
1192         }
1193         return LookAheadHeuristics::ScoreFail;
1194       }
1195 
1196       auto *I1 = dyn_cast<Instruction>(V1);
1197       auto *I2 = dyn_cast<Instruction>(V2);
1198       if (I1 && I2) {
1199         if (I1->getParent() != I2->getParent())
1200           return LookAheadHeuristics::ScoreFail;
1201         SmallVector<Value *, 4> Ops(MainAltOps.begin(), MainAltOps.end());
1202         Ops.push_back(I1);
1203         Ops.push_back(I2);
1204         InstructionsState S = getSameOpcode(Ops);
1205         // Note: Only consider instructions with <= 2 operands to avoid
1206         // complexity explosion.
1207         if (S.getOpcode() &&
1208             (S.MainOp->getNumOperands() <= 2 || !MainAltOps.empty() ||
1209              !S.isAltShuffle()) &&
1210             all_of(Ops, [&S](Value *V) {
1211               return cast<Instruction>(V)->getNumOperands() ==
1212                      S.MainOp->getNumOperands();
1213             }))
1214           return S.isAltShuffle() ? LookAheadHeuristics::ScoreAltOpcodes
1215                                   : LookAheadHeuristics::ScoreSameOpcode;
1216       }
1217 
1218       if (isa<UndefValue>(V2))
1219         return LookAheadHeuristics::ScoreUndef;
1220 
1221       return LookAheadHeuristics::ScoreFail;
1222     }
1223 
1224     /// Go through the operands of \p LHS and \p RHS recursively until
1225     /// MaxLevel, and return the cummulative score. \p U1 and \p U2 are
1226     /// the users of \p LHS and \p RHS (that is \p LHS and \p RHS are operands
1227     /// of \p U1 and \p U2), except at the beginning of the recursion where
1228     /// these are set to nullptr.
1229     ///
1230     /// For example:
1231     /// \verbatim
1232     ///  A[0]  B[0]  A[1]  B[1]  C[0] D[0]  B[1] A[1]
1233     ///     \ /         \ /         \ /        \ /
1234     ///      +           +           +          +
1235     ///     G1          G2          G3         G4
1236     /// \endverbatim
1237     /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at
1238     /// each level recursively, accumulating the score. It starts from matching
1239     /// the additions at level 0, then moves on to the loads (level 1). The
1240     /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and
1241     /// {B[0],B[1]} match with LookAheadHeuristics::ScoreConsecutiveLoads, while
1242     /// {A[0],C[0]} has a score of LookAheadHeuristics::ScoreFail.
1243     /// Please note that the order of the operands does not matter, as we
1244     /// evaluate the score of all profitable combinations of operands. In
1245     /// other words the score of G1 and G4 is the same as G1 and G2. This
1246     /// heuristic is based on ideas described in:
1247     ///   Look-ahead SLP: Auto-vectorization in the presence of commutative
1248     ///   operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha,
1249     ///   Luís F. W. Góes
1250     int getScoreAtLevelRec(Value *LHS, Value *RHS, Instruction *U1,
1251                            Instruction *U2, int CurrLevel,
1252                            ArrayRef<Value *> MainAltOps) const {
1253 
1254       // Get the shallow score of V1 and V2.
1255       int ShallowScoreAtThisLevel =
1256           getShallowScore(LHS, RHS, U1, U2, MainAltOps);
1257 
1258       // If reached MaxLevel,
1259       //  or if V1 and V2 are not instructions,
1260       //  or if they are SPLAT,
1261       //  or if they are not consecutive,
1262       //  or if profitable to vectorize loads or extractelements, early return
1263       //  the current cost.
1264       auto *I1 = dyn_cast<Instruction>(LHS);
1265       auto *I2 = dyn_cast<Instruction>(RHS);
1266       if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 ||
1267           ShallowScoreAtThisLevel == LookAheadHeuristics::ScoreFail ||
1268           (((isa<LoadInst>(I1) && isa<LoadInst>(I2)) ||
1269             (I1->getNumOperands() > 2 && I2->getNumOperands() > 2) ||
1270             (isa<ExtractElementInst>(I1) && isa<ExtractElementInst>(I2))) &&
1271            ShallowScoreAtThisLevel))
1272         return ShallowScoreAtThisLevel;
1273       assert(I1 && I2 && "Should have early exited.");
1274 
1275       // Contains the I2 operand indexes that got matched with I1 operands.
1276       SmallSet<unsigned, 4> Op2Used;
1277 
1278       // Recursion towards the operands of I1 and I2. We are trying all possible
1279       // operand pairs, and keeping track of the best score.
1280       for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands();
1281            OpIdx1 != NumOperands1; ++OpIdx1) {
1282         // Try to pair op1I with the best operand of I2.
1283         int MaxTmpScore = 0;
1284         unsigned MaxOpIdx2 = 0;
1285         bool FoundBest = false;
1286         // If I2 is commutative try all combinations.
1287         unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1;
1288         unsigned ToIdx = isCommutative(I2)
1289                              ? I2->getNumOperands()
1290                              : std::min(I2->getNumOperands(), OpIdx1 + 1);
1291         assert(FromIdx <= ToIdx && "Bad index");
1292         for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) {
1293           // Skip operands already paired with OpIdx1.
1294           if (Op2Used.count(OpIdx2))
1295             continue;
1296           // Recursively calculate the cost at each level
1297           int TmpScore =
1298               getScoreAtLevelRec(I1->getOperand(OpIdx1), I2->getOperand(OpIdx2),
1299                                  I1, I2, CurrLevel + 1, None);
1300           // Look for the best score.
1301           if (TmpScore > LookAheadHeuristics::ScoreFail &&
1302               TmpScore > MaxTmpScore) {
1303             MaxTmpScore = TmpScore;
1304             MaxOpIdx2 = OpIdx2;
1305             FoundBest = true;
1306           }
1307         }
1308         if (FoundBest) {
1309           // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it.
1310           Op2Used.insert(MaxOpIdx2);
1311           ShallowScoreAtThisLevel += MaxTmpScore;
1312         }
1313       }
1314       return ShallowScoreAtThisLevel;
1315     }
1316   };
1317   /// A helper data structure to hold the operands of a vector of instructions.
1318   /// This supports a fixed vector length for all operand vectors.
1319   class VLOperands {
1320     /// For each operand we need (i) the value, and (ii) the opcode that it
1321     /// would be attached to if the expression was in a left-linearized form.
1322     /// This is required to avoid illegal operand reordering.
1323     /// For example:
1324     /// \verbatim
1325     ///                         0 Op1
1326     ///                         |/
1327     /// Op1 Op2   Linearized    + Op2
1328     ///   \ /     ---------->   |/
1329     ///    -                    -
1330     ///
1331     /// Op1 - Op2            (0 + Op1) - Op2
1332     /// \endverbatim
1333     ///
1334     /// Value Op1 is attached to a '+' operation, and Op2 to a '-'.
1335     ///
1336     /// Another way to think of this is to track all the operations across the
1337     /// path from the operand all the way to the root of the tree and to
1338     /// calculate the operation that corresponds to this path. For example, the
1339     /// path from Op2 to the root crosses the RHS of the '-', therefore the
1340     /// corresponding operation is a '-' (which matches the one in the
1341     /// linearized tree, as shown above).
1342     ///
1343     /// For lack of a better term, we refer to this operation as Accumulated
1344     /// Path Operation (APO).
1345     struct OperandData {
1346       OperandData() = default;
1347       OperandData(Value *V, bool APO, bool IsUsed)
1348           : V(V), APO(APO), IsUsed(IsUsed) {}
1349       /// The operand value.
1350       Value *V = nullptr;
1351       /// TreeEntries only allow a single opcode, or an alternate sequence of
1352       /// them (e.g, +, -). Therefore, we can safely use a boolean value for the
1353       /// APO. It is set to 'true' if 'V' is attached to an inverse operation
1354       /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise
1355       /// (e.g., Add/Mul)
1356       bool APO = false;
1357       /// Helper data for the reordering function.
1358       bool IsUsed = false;
1359     };
1360 
1361     /// During operand reordering, we are trying to select the operand at lane
1362     /// that matches best with the operand at the neighboring lane. Our
1363     /// selection is based on the type of value we are looking for. For example,
1364     /// if the neighboring lane has a load, we need to look for a load that is
1365     /// accessing a consecutive address. These strategies are summarized in the
1366     /// 'ReorderingMode' enumerator.
1367     enum class ReorderingMode {
1368       Load,     ///< Matching loads to consecutive memory addresses
1369       Opcode,   ///< Matching instructions based on opcode (same or alternate)
1370       Constant, ///< Matching constants
1371       Splat,    ///< Matching the same instruction multiple times (broadcast)
1372       Failed,   ///< We failed to create a vectorizable group
1373     };
1374 
1375     using OperandDataVec = SmallVector<OperandData, 2>;
1376 
1377     /// A vector of operand vectors.
1378     SmallVector<OperandDataVec, 4> OpsVec;
1379 
1380     const DataLayout &DL;
1381     ScalarEvolution &SE;
1382     const BoUpSLP &R;
1383 
1384     /// \returns the operand data at \p OpIdx and \p Lane.
1385     OperandData &getData(unsigned OpIdx, unsigned Lane) {
1386       return OpsVec[OpIdx][Lane];
1387     }
1388 
1389     /// \returns the operand data at \p OpIdx and \p Lane. Const version.
1390     const OperandData &getData(unsigned OpIdx, unsigned Lane) const {
1391       return OpsVec[OpIdx][Lane];
1392     }
1393 
1394     /// Clears the used flag for all entries.
1395     void clearUsed() {
1396       for (unsigned OpIdx = 0, NumOperands = getNumOperands();
1397            OpIdx != NumOperands; ++OpIdx)
1398         for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
1399              ++Lane)
1400           OpsVec[OpIdx][Lane].IsUsed = false;
1401     }
1402 
1403     /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2.
1404     void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) {
1405       std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]);
1406     }
1407 
1408     /// \param Lane lane of the operands under analysis.
1409     /// \param OpIdx operand index in \p Lane lane we're looking the best
1410     /// candidate for.
1411     /// \param Idx operand index of the current candidate value.
1412     /// \returns The additional score due to possible broadcasting of the
1413     /// elements in the lane. It is more profitable to have power-of-2 unique
1414     /// elements in the lane, it will be vectorized with higher probability
1415     /// after removing duplicates. Currently the SLP vectorizer supports only
1416     /// vectorization of the power-of-2 number of unique scalars.
1417     int getSplatScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1418       Value *IdxLaneV = getData(Idx, Lane).V;
1419       if (!isa<Instruction>(IdxLaneV) || IdxLaneV == getData(OpIdx, Lane).V)
1420         return 0;
1421       SmallPtrSet<Value *, 4> Uniques;
1422       for (unsigned Ln = 0, E = getNumLanes(); Ln < E; ++Ln) {
1423         if (Ln == Lane)
1424           continue;
1425         Value *OpIdxLnV = getData(OpIdx, Ln).V;
1426         if (!isa<Instruction>(OpIdxLnV))
1427           return 0;
1428         Uniques.insert(OpIdxLnV);
1429       }
1430       int UniquesCount = Uniques.size();
1431       int UniquesCntWithIdxLaneV =
1432           Uniques.contains(IdxLaneV) ? UniquesCount : UniquesCount + 1;
1433       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1434       int UniquesCntWithOpIdxLaneV =
1435           Uniques.contains(OpIdxLaneV) ? UniquesCount : UniquesCount + 1;
1436       if (UniquesCntWithIdxLaneV == UniquesCntWithOpIdxLaneV)
1437         return 0;
1438       return (PowerOf2Ceil(UniquesCntWithOpIdxLaneV) -
1439               UniquesCntWithOpIdxLaneV) -
1440              (PowerOf2Ceil(UniquesCntWithIdxLaneV) - UniquesCntWithIdxLaneV);
1441     }
1442 
1443     /// \param Lane lane of the operands under analysis.
1444     /// \param OpIdx operand index in \p Lane lane we're looking the best
1445     /// candidate for.
1446     /// \param Idx operand index of the current candidate value.
1447     /// \returns The additional score for the scalar which users are all
1448     /// vectorized.
1449     int getExternalUseScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1450       Value *IdxLaneV = getData(Idx, Lane).V;
1451       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1452       // Do not care about number of uses for vector-like instructions
1453       // (extractelement/extractvalue with constant indices), they are extracts
1454       // themselves and already externally used. Vectorization of such
1455       // instructions does not add extra extractelement instruction, just may
1456       // remove it.
1457       if (isVectorLikeInstWithConstOps(IdxLaneV) &&
1458           isVectorLikeInstWithConstOps(OpIdxLaneV))
1459         return LookAheadHeuristics::ScoreAllUserVectorized;
1460       auto *IdxLaneI = dyn_cast<Instruction>(IdxLaneV);
1461       if (!IdxLaneI || !isa<Instruction>(OpIdxLaneV))
1462         return 0;
1463       return R.areAllUsersVectorized(IdxLaneI, None)
1464                  ? LookAheadHeuristics::ScoreAllUserVectorized
1465                  : 0;
1466     }
1467 
1468     /// Score scaling factor for fully compatible instructions but with
1469     /// different number of external uses. Allows better selection of the
1470     /// instructions with less external uses.
1471     static const int ScoreScaleFactor = 10;
1472 
1473     /// \Returns the look-ahead score, which tells us how much the sub-trees
1474     /// rooted at \p LHS and \p RHS match, the more they match the higher the
1475     /// score. This helps break ties in an informed way when we cannot decide on
1476     /// the order of the operands by just considering the immediate
1477     /// predecessors.
1478     int getLookAheadScore(Value *LHS, Value *RHS, ArrayRef<Value *> MainAltOps,
1479                           int Lane, unsigned OpIdx, unsigned Idx,
1480                           bool &IsUsed) {
1481       LookAheadHeuristics LookAhead(DL, SE, R, getNumLanes(),
1482                                     LookAheadMaxDepth);
1483       // Keep track of the instruction stack as we recurse into the operands
1484       // during the look-ahead score exploration.
1485       int Score =
1486           LookAhead.getScoreAtLevelRec(LHS, RHS, /*U1=*/nullptr, /*U2=*/nullptr,
1487                                        /*CurrLevel=*/1, MainAltOps);
1488       if (Score) {
1489         int SplatScore = getSplatScore(Lane, OpIdx, Idx);
1490         if (Score <= -SplatScore) {
1491           // Set the minimum score for splat-like sequence to avoid setting
1492           // failed state.
1493           Score = 1;
1494         } else {
1495           Score += SplatScore;
1496           // Scale score to see the difference between different operands
1497           // and similar operands but all vectorized/not all vectorized
1498           // uses. It does not affect actual selection of the best
1499           // compatible operand in general, just allows to select the
1500           // operand with all vectorized uses.
1501           Score *= ScoreScaleFactor;
1502           Score += getExternalUseScore(Lane, OpIdx, Idx);
1503           IsUsed = true;
1504         }
1505       }
1506       return Score;
1507     }
1508 
1509     /// Best defined scores per lanes between the passes. Used to choose the
1510     /// best operand (with the highest score) between the passes.
1511     /// The key - {Operand Index, Lane}.
1512     /// The value - the best score between the passes for the lane and the
1513     /// operand.
1514     SmallDenseMap<std::pair<unsigned, unsigned>, unsigned, 8>
1515         BestScoresPerLanes;
1516 
1517     // Search all operands in Ops[*][Lane] for the one that matches best
1518     // Ops[OpIdx][LastLane] and return its opreand index.
1519     // If no good match can be found, return None.
1520     Optional<unsigned> getBestOperand(unsigned OpIdx, int Lane, int LastLane,
1521                                       ArrayRef<ReorderingMode> ReorderingModes,
1522                                       ArrayRef<Value *> MainAltOps) {
1523       unsigned NumOperands = getNumOperands();
1524 
1525       // The operand of the previous lane at OpIdx.
1526       Value *OpLastLane = getData(OpIdx, LastLane).V;
1527 
1528       // Our strategy mode for OpIdx.
1529       ReorderingMode RMode = ReorderingModes[OpIdx];
1530       if (RMode == ReorderingMode::Failed)
1531         return None;
1532 
1533       // The linearized opcode of the operand at OpIdx, Lane.
1534       bool OpIdxAPO = getData(OpIdx, Lane).APO;
1535 
1536       // The best operand index and its score.
1537       // Sometimes we have more than one option (e.g., Opcode and Undefs), so we
1538       // are using the score to differentiate between the two.
1539       struct BestOpData {
1540         Optional<unsigned> Idx = None;
1541         unsigned Score = 0;
1542       } BestOp;
1543       BestOp.Score =
1544           BestScoresPerLanes.try_emplace(std::make_pair(OpIdx, Lane), 0)
1545               .first->second;
1546 
1547       // Track if the operand must be marked as used. If the operand is set to
1548       // Score 1 explicitly (because of non power-of-2 unique scalars, we may
1549       // want to reestimate the operands again on the following iterations).
1550       bool IsUsed =
1551           RMode == ReorderingMode::Splat || RMode == ReorderingMode::Constant;
1552       // Iterate through all unused operands and look for the best.
1553       for (unsigned Idx = 0; Idx != NumOperands; ++Idx) {
1554         // Get the operand at Idx and Lane.
1555         OperandData &OpData = getData(Idx, Lane);
1556         Value *Op = OpData.V;
1557         bool OpAPO = OpData.APO;
1558 
1559         // Skip already selected operands.
1560         if (OpData.IsUsed)
1561           continue;
1562 
1563         // Skip if we are trying to move the operand to a position with a
1564         // different opcode in the linearized tree form. This would break the
1565         // semantics.
1566         if (OpAPO != OpIdxAPO)
1567           continue;
1568 
1569         // Look for an operand that matches the current mode.
1570         switch (RMode) {
1571         case ReorderingMode::Load:
1572         case ReorderingMode::Constant:
1573         case ReorderingMode::Opcode: {
1574           bool LeftToRight = Lane > LastLane;
1575           Value *OpLeft = (LeftToRight) ? OpLastLane : Op;
1576           Value *OpRight = (LeftToRight) ? Op : OpLastLane;
1577           int Score = getLookAheadScore(OpLeft, OpRight, MainAltOps, Lane,
1578                                         OpIdx, Idx, IsUsed);
1579           if (Score > static_cast<int>(BestOp.Score)) {
1580             BestOp.Idx = Idx;
1581             BestOp.Score = Score;
1582             BestScoresPerLanes[std::make_pair(OpIdx, Lane)] = Score;
1583           }
1584           break;
1585         }
1586         case ReorderingMode::Splat:
1587           if (Op == OpLastLane)
1588             BestOp.Idx = Idx;
1589           break;
1590         case ReorderingMode::Failed:
1591           llvm_unreachable("Not expected Failed reordering mode.");
1592         }
1593       }
1594 
1595       if (BestOp.Idx) {
1596         getData(BestOp.Idx.getValue(), Lane).IsUsed = IsUsed;
1597         return BestOp.Idx;
1598       }
1599       // If we could not find a good match return None.
1600       return None;
1601     }
1602 
1603     /// Helper for reorderOperandVecs.
1604     /// \returns the lane that we should start reordering from. This is the one
1605     /// which has the least number of operands that can freely move about or
1606     /// less profitable because it already has the most optimal set of operands.
1607     unsigned getBestLaneToStartReordering() const {
1608       unsigned Min = UINT_MAX;
1609       unsigned SameOpNumber = 0;
1610       // std::pair<unsigned, unsigned> is used to implement a simple voting
1611       // algorithm and choose the lane with the least number of operands that
1612       // can freely move about or less profitable because it already has the
1613       // most optimal set of operands. The first unsigned is a counter for
1614       // voting, the second unsigned is the counter of lanes with instructions
1615       // with same/alternate opcodes and same parent basic block.
1616       MapVector<unsigned, std::pair<unsigned, unsigned>> HashMap;
1617       // Try to be closer to the original results, if we have multiple lanes
1618       // with same cost. If 2 lanes have the same cost, use the one with the
1619       // lowest index.
1620       for (int I = getNumLanes(); I > 0; --I) {
1621         unsigned Lane = I - 1;
1622         OperandsOrderData NumFreeOpsHash =
1623             getMaxNumOperandsThatCanBeReordered(Lane);
1624         // Compare the number of operands that can move and choose the one with
1625         // the least number.
1626         if (NumFreeOpsHash.NumOfAPOs < Min) {
1627           Min = NumFreeOpsHash.NumOfAPOs;
1628           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1629           HashMap.clear();
1630           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1631         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1632                    NumFreeOpsHash.NumOpsWithSameOpcodeParent < SameOpNumber) {
1633           // Select the most optimal lane in terms of number of operands that
1634           // should be moved around.
1635           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1636           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1637         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1638                    NumFreeOpsHash.NumOpsWithSameOpcodeParent == SameOpNumber) {
1639           auto It = HashMap.find(NumFreeOpsHash.Hash);
1640           if (It == HashMap.end())
1641             HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1642           else
1643             ++It->second.first;
1644         }
1645       }
1646       // Select the lane with the minimum counter.
1647       unsigned BestLane = 0;
1648       unsigned CntMin = UINT_MAX;
1649       for (const auto &Data : reverse(HashMap)) {
1650         if (Data.second.first < CntMin) {
1651           CntMin = Data.second.first;
1652           BestLane = Data.second.second;
1653         }
1654       }
1655       return BestLane;
1656     }
1657 
1658     /// Data structure that helps to reorder operands.
1659     struct OperandsOrderData {
1660       /// The best number of operands with the same APOs, which can be
1661       /// reordered.
1662       unsigned NumOfAPOs = UINT_MAX;
1663       /// Number of operands with the same/alternate instruction opcode and
1664       /// parent.
1665       unsigned NumOpsWithSameOpcodeParent = 0;
1666       /// Hash for the actual operands ordering.
1667       /// Used to count operands, actually their position id and opcode
1668       /// value. It is used in the voting mechanism to find the lane with the
1669       /// least number of operands that can freely move about or less profitable
1670       /// because it already has the most optimal set of operands. Can be
1671       /// replaced with SmallVector<unsigned> instead but hash code is faster
1672       /// and requires less memory.
1673       unsigned Hash = 0;
1674     };
1675     /// \returns the maximum number of operands that are allowed to be reordered
1676     /// for \p Lane and the number of compatible instructions(with the same
1677     /// parent/opcode). This is used as a heuristic for selecting the first lane
1678     /// to start operand reordering.
1679     OperandsOrderData getMaxNumOperandsThatCanBeReordered(unsigned Lane) const {
1680       unsigned CntTrue = 0;
1681       unsigned NumOperands = getNumOperands();
1682       // Operands with the same APO can be reordered. We therefore need to count
1683       // how many of them we have for each APO, like this: Cnt[APO] = x.
1684       // Since we only have two APOs, namely true and false, we can avoid using
1685       // a map. Instead we can simply count the number of operands that
1686       // correspond to one of them (in this case the 'true' APO), and calculate
1687       // the other by subtracting it from the total number of operands.
1688       // Operands with the same instruction opcode and parent are more
1689       // profitable since we don't need to move them in many cases, with a high
1690       // probability such lane already can be vectorized effectively.
1691       bool AllUndefs = true;
1692       unsigned NumOpsWithSameOpcodeParent = 0;
1693       Instruction *OpcodeI = nullptr;
1694       BasicBlock *Parent = nullptr;
1695       unsigned Hash = 0;
1696       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1697         const OperandData &OpData = getData(OpIdx, Lane);
1698         if (OpData.APO)
1699           ++CntTrue;
1700         // Use Boyer-Moore majority voting for finding the majority opcode and
1701         // the number of times it occurs.
1702         if (auto *I = dyn_cast<Instruction>(OpData.V)) {
1703           if (!OpcodeI || !getSameOpcode({OpcodeI, I}).getOpcode() ||
1704               I->getParent() != Parent) {
1705             if (NumOpsWithSameOpcodeParent == 0) {
1706               NumOpsWithSameOpcodeParent = 1;
1707               OpcodeI = I;
1708               Parent = I->getParent();
1709             } else {
1710               --NumOpsWithSameOpcodeParent;
1711             }
1712           } else {
1713             ++NumOpsWithSameOpcodeParent;
1714           }
1715         }
1716         Hash = hash_combine(
1717             Hash, hash_value((OpIdx + 1) * (OpData.V->getValueID() + 1)));
1718         AllUndefs = AllUndefs && isa<UndefValue>(OpData.V);
1719       }
1720       if (AllUndefs)
1721         return {};
1722       OperandsOrderData Data;
1723       Data.NumOfAPOs = std::max(CntTrue, NumOperands - CntTrue);
1724       Data.NumOpsWithSameOpcodeParent = NumOpsWithSameOpcodeParent;
1725       Data.Hash = Hash;
1726       return Data;
1727     }
1728 
1729     /// Go through the instructions in VL and append their operands.
1730     void appendOperandsOfVL(ArrayRef<Value *> VL) {
1731       assert(!VL.empty() && "Bad VL");
1732       assert((empty() || VL.size() == getNumLanes()) &&
1733              "Expected same number of lanes");
1734       assert(isa<Instruction>(VL[0]) && "Expected instruction");
1735       unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands();
1736       OpsVec.resize(NumOperands);
1737       unsigned NumLanes = VL.size();
1738       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1739         OpsVec[OpIdx].resize(NumLanes);
1740         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1741           assert(isa<Instruction>(VL[Lane]) && "Expected instruction");
1742           // Our tree has just 3 nodes: the root and two operands.
1743           // It is therefore trivial to get the APO. We only need to check the
1744           // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or
1745           // RHS operand. The LHS operand of both add and sub is never attached
1746           // to an inversese operation in the linearized form, therefore its APO
1747           // is false. The RHS is true only if VL[Lane] is an inverse operation.
1748 
1749           // Since operand reordering is performed on groups of commutative
1750           // operations or alternating sequences (e.g., +, -), we can safely
1751           // tell the inverse operations by checking commutativity.
1752           bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane]));
1753           bool APO = (OpIdx == 0) ? false : IsInverseOperation;
1754           OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx),
1755                                  APO, false};
1756         }
1757       }
1758     }
1759 
1760     /// \returns the number of operands.
1761     unsigned getNumOperands() const { return OpsVec.size(); }
1762 
1763     /// \returns the number of lanes.
1764     unsigned getNumLanes() const { return OpsVec[0].size(); }
1765 
1766     /// \returns the operand value at \p OpIdx and \p Lane.
1767     Value *getValue(unsigned OpIdx, unsigned Lane) const {
1768       return getData(OpIdx, Lane).V;
1769     }
1770 
1771     /// \returns true if the data structure is empty.
1772     bool empty() const { return OpsVec.empty(); }
1773 
1774     /// Clears the data.
1775     void clear() { OpsVec.clear(); }
1776 
1777     /// \Returns true if there are enough operands identical to \p Op to fill
1778     /// the whole vector.
1779     /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow.
1780     bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) {
1781       bool OpAPO = getData(OpIdx, Lane).APO;
1782       for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) {
1783         if (Ln == Lane)
1784           continue;
1785         // This is set to true if we found a candidate for broadcast at Lane.
1786         bool FoundCandidate = false;
1787         for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) {
1788           OperandData &Data = getData(OpI, Ln);
1789           if (Data.APO != OpAPO || Data.IsUsed)
1790             continue;
1791           if (Data.V == Op) {
1792             FoundCandidate = true;
1793             Data.IsUsed = true;
1794             break;
1795           }
1796         }
1797         if (!FoundCandidate)
1798           return false;
1799       }
1800       return true;
1801     }
1802 
1803   public:
1804     /// Initialize with all the operands of the instruction vector \p RootVL.
1805     VLOperands(ArrayRef<Value *> RootVL, const DataLayout &DL,
1806                ScalarEvolution &SE, const BoUpSLP &R)
1807         : DL(DL), SE(SE), R(R) {
1808       // Append all the operands of RootVL.
1809       appendOperandsOfVL(RootVL);
1810     }
1811 
1812     /// \Returns a value vector with the operands across all lanes for the
1813     /// opearnd at \p OpIdx.
1814     ValueList getVL(unsigned OpIdx) const {
1815       ValueList OpVL(OpsVec[OpIdx].size());
1816       assert(OpsVec[OpIdx].size() == getNumLanes() &&
1817              "Expected same num of lanes across all operands");
1818       for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane)
1819         OpVL[Lane] = OpsVec[OpIdx][Lane].V;
1820       return OpVL;
1821     }
1822 
1823     // Performs operand reordering for 2 or more operands.
1824     // The original operands are in OrigOps[OpIdx][Lane].
1825     // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'.
1826     void reorder() {
1827       unsigned NumOperands = getNumOperands();
1828       unsigned NumLanes = getNumLanes();
1829       // Each operand has its own mode. We are using this mode to help us select
1830       // the instructions for each lane, so that they match best with the ones
1831       // we have selected so far.
1832       SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands);
1833 
1834       // This is a greedy single-pass algorithm. We are going over each lane
1835       // once and deciding on the best order right away with no back-tracking.
1836       // However, in order to increase its effectiveness, we start with the lane
1837       // that has operands that can move the least. For example, given the
1838       // following lanes:
1839       //  Lane 0 : A[0] = B[0] + C[0]   // Visited 3rd
1840       //  Lane 1 : A[1] = C[1] - B[1]   // Visited 1st
1841       //  Lane 2 : A[2] = B[2] + C[2]   // Visited 2nd
1842       //  Lane 3 : A[3] = C[3] - B[3]   // Visited 4th
1843       // we will start at Lane 1, since the operands of the subtraction cannot
1844       // be reordered. Then we will visit the rest of the lanes in a circular
1845       // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3.
1846 
1847       // Find the first lane that we will start our search from.
1848       unsigned FirstLane = getBestLaneToStartReordering();
1849 
1850       // Initialize the modes.
1851       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1852         Value *OpLane0 = getValue(OpIdx, FirstLane);
1853         // Keep track if we have instructions with all the same opcode on one
1854         // side.
1855         if (isa<LoadInst>(OpLane0))
1856           ReorderingModes[OpIdx] = ReorderingMode::Load;
1857         else if (isa<Instruction>(OpLane0)) {
1858           // Check if OpLane0 should be broadcast.
1859           if (shouldBroadcast(OpLane0, OpIdx, FirstLane))
1860             ReorderingModes[OpIdx] = ReorderingMode::Splat;
1861           else
1862             ReorderingModes[OpIdx] = ReorderingMode::Opcode;
1863         }
1864         else if (isa<Constant>(OpLane0))
1865           ReorderingModes[OpIdx] = ReorderingMode::Constant;
1866         else if (isa<Argument>(OpLane0))
1867           // Our best hope is a Splat. It may save some cost in some cases.
1868           ReorderingModes[OpIdx] = ReorderingMode::Splat;
1869         else
1870           // NOTE: This should be unreachable.
1871           ReorderingModes[OpIdx] = ReorderingMode::Failed;
1872       }
1873 
1874       // Check that we don't have same operands. No need to reorder if operands
1875       // are just perfect diamond or shuffled diamond match. Do not do it only
1876       // for possible broadcasts or non-power of 2 number of scalars (just for
1877       // now).
1878       auto &&SkipReordering = [this]() {
1879         SmallPtrSet<Value *, 4> UniqueValues;
1880         ArrayRef<OperandData> Op0 = OpsVec.front();
1881         for (const OperandData &Data : Op0)
1882           UniqueValues.insert(Data.V);
1883         for (ArrayRef<OperandData> Op : drop_begin(OpsVec, 1)) {
1884           if (any_of(Op, [&UniqueValues](const OperandData &Data) {
1885                 return !UniqueValues.contains(Data.V);
1886               }))
1887             return false;
1888         }
1889         // TODO: Check if we can remove a check for non-power-2 number of
1890         // scalars after full support of non-power-2 vectorization.
1891         return UniqueValues.size() != 2 && isPowerOf2_32(UniqueValues.size());
1892       };
1893 
1894       // If the initial strategy fails for any of the operand indexes, then we
1895       // perform reordering again in a second pass. This helps avoid assigning
1896       // high priority to the failed strategy, and should improve reordering for
1897       // the non-failed operand indexes.
1898       for (int Pass = 0; Pass != 2; ++Pass) {
1899         // Check if no need to reorder operands since they're are perfect or
1900         // shuffled diamond match.
1901         // Need to to do it to avoid extra external use cost counting for
1902         // shuffled matches, which may cause regressions.
1903         if (SkipReordering())
1904           break;
1905         // Skip the second pass if the first pass did not fail.
1906         bool StrategyFailed = false;
1907         // Mark all operand data as free to use.
1908         clearUsed();
1909         // We keep the original operand order for the FirstLane, so reorder the
1910         // rest of the lanes. We are visiting the nodes in a circular fashion,
1911         // using FirstLane as the center point and increasing the radius
1912         // distance.
1913         SmallVector<SmallVector<Value *, 2>> MainAltOps(NumOperands);
1914         for (unsigned I = 0; I < NumOperands; ++I)
1915           MainAltOps[I].push_back(getData(I, FirstLane).V);
1916 
1917         for (unsigned Distance = 1; Distance != NumLanes; ++Distance) {
1918           // Visit the lane on the right and then the lane on the left.
1919           for (int Direction : {+1, -1}) {
1920             int Lane = FirstLane + Direction * Distance;
1921             if (Lane < 0 || Lane >= (int)NumLanes)
1922               continue;
1923             int LastLane = Lane - Direction;
1924             assert(LastLane >= 0 && LastLane < (int)NumLanes &&
1925                    "Out of bounds");
1926             // Look for a good match for each operand.
1927             for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1928               // Search for the operand that matches SortedOps[OpIdx][Lane-1].
1929               Optional<unsigned> BestIdx = getBestOperand(
1930                   OpIdx, Lane, LastLane, ReorderingModes, MainAltOps[OpIdx]);
1931               // By not selecting a value, we allow the operands that follow to
1932               // select a better matching value. We will get a non-null value in
1933               // the next run of getBestOperand().
1934               if (BestIdx) {
1935                 // Swap the current operand with the one returned by
1936                 // getBestOperand().
1937                 swap(OpIdx, BestIdx.getValue(), Lane);
1938               } else {
1939                 // We failed to find a best operand, set mode to 'Failed'.
1940                 ReorderingModes[OpIdx] = ReorderingMode::Failed;
1941                 // Enable the second pass.
1942                 StrategyFailed = true;
1943               }
1944               // Try to get the alternate opcode and follow it during analysis.
1945               if (MainAltOps[OpIdx].size() != 2) {
1946                 OperandData &AltOp = getData(OpIdx, Lane);
1947                 InstructionsState OpS =
1948                     getSameOpcode({MainAltOps[OpIdx].front(), AltOp.V});
1949                 if (OpS.getOpcode() && OpS.isAltShuffle())
1950                   MainAltOps[OpIdx].push_back(AltOp.V);
1951               }
1952             }
1953           }
1954         }
1955         // Skip second pass if the strategy did not fail.
1956         if (!StrategyFailed)
1957           break;
1958       }
1959     }
1960 
1961 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1962     LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) {
1963       switch (RMode) {
1964       case ReorderingMode::Load:
1965         return "Load";
1966       case ReorderingMode::Opcode:
1967         return "Opcode";
1968       case ReorderingMode::Constant:
1969         return "Constant";
1970       case ReorderingMode::Splat:
1971         return "Splat";
1972       case ReorderingMode::Failed:
1973         return "Failed";
1974       }
1975       llvm_unreachable("Unimplemented Reordering Type");
1976     }
1977 
1978     LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode,
1979                                                    raw_ostream &OS) {
1980       return OS << getModeStr(RMode);
1981     }
1982 
1983     /// Debug print.
1984     LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) {
1985       printMode(RMode, dbgs());
1986     }
1987 
1988     friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) {
1989       return printMode(RMode, OS);
1990     }
1991 
1992     LLVM_DUMP_METHOD raw_ostream &print(raw_ostream &OS) const {
1993       const unsigned Indent = 2;
1994       unsigned Cnt = 0;
1995       for (const OperandDataVec &OpDataVec : OpsVec) {
1996         OS << "Operand " << Cnt++ << "\n";
1997         for (const OperandData &OpData : OpDataVec) {
1998           OS.indent(Indent) << "{";
1999           if (Value *V = OpData.V)
2000             OS << *V;
2001           else
2002             OS << "null";
2003           OS << ", APO:" << OpData.APO << "}\n";
2004         }
2005         OS << "\n";
2006       }
2007       return OS;
2008     }
2009 
2010     /// Debug print.
2011     LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
2012 #endif
2013   };
2014 
2015   /// Evaluate each pair in \p Candidates and return index into \p Candidates
2016   /// for a pair which have highest score deemed to have best chance to form
2017   /// root of profitable tree to vectorize. Return None if no candidate scored
2018   /// above the LookAheadHeuristics::ScoreFail.
2019   Optional<int>
2020   findBestRootPair(ArrayRef<std::pair<Value *, Value *>> Candidates) {
2021     LookAheadHeuristics LookAhead(*DL, *SE, *this, /*NumLanes=*/2,
2022                                   RootLookAheadMaxDepth);
2023     int BestScore = LookAheadHeuristics::ScoreFail;
2024     Optional<int> Index = None;
2025     for (int I : seq<int>(0, Candidates.size())) {
2026       int Score = LookAhead.getScoreAtLevelRec(Candidates[I].first,
2027                                                Candidates[I].second,
2028                                                /*U1=*/nullptr, /*U2=*/nullptr,
2029                                                /*Level=*/1, None);
2030       if (Score > BestScore) {
2031         BestScore = Score;
2032         Index = I;
2033       }
2034     }
2035     return Index;
2036   }
2037 
2038   /// Checks if the instruction is marked for deletion.
2039   bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); }
2040 
2041   /// Removes an instruction from its block and eventually deletes it.
2042   /// It's like Instruction::eraseFromParent() except that the actual deletion
2043   /// is delayed until BoUpSLP is destructed.
2044   void eraseInstruction(Instruction *I) {
2045     DeletedInstructions.insert(I);
2046   }
2047 
2048   /// Checks if the instruction was already analyzed for being possible
2049   /// reduction root.
2050   bool isAnalizedReductionRoot(Instruction *I) const {
2051     return AnalizedReductionsRoots.count(I);
2052   }
2053   /// Register given instruction as already analyzed for being possible
2054   /// reduction root.
2055   void analyzedReductionRoot(Instruction *I) {
2056     AnalizedReductionsRoots.insert(I);
2057   }
2058   /// Checks if the provided list of reduced values was checked already for
2059   /// vectorization.
2060   bool areAnalyzedReductionVals(ArrayRef<Value *> VL) {
2061     return AnalyzedReductionVals.contains(hash_value(VL));
2062   }
2063   /// Adds the list of reduced values to list of already checked values for the
2064   /// vectorization.
2065   void analyzedReductionVals(ArrayRef<Value *> VL) {
2066     AnalyzedReductionVals.insert(hash_value(VL));
2067   }
2068   /// Clear the list of the analyzed reduction root instructions.
2069   void clearReductionData() {
2070     AnalizedReductionsRoots.clear();
2071     AnalyzedReductionVals.clear();
2072   }
2073   /// Checks if the given value is gathered in one of the nodes.
2074   bool isGathered(Value *V) const {
2075     return MustGather.contains(V);
2076   }
2077 
2078   ~BoUpSLP();
2079 
2080 private:
2081   /// Check if the operands on the edges \p Edges of the \p UserTE allows
2082   /// reordering (i.e. the operands can be reordered because they have only one
2083   /// user and reordarable).
2084   /// \param ReorderableGathers List of all gather nodes that require reordering
2085   /// (e.g., gather of extractlements or partially vectorizable loads).
2086   /// \param GatherOps List of gather operand nodes for \p UserTE that require
2087   /// reordering, subset of \p NonVectorized.
2088   bool
2089   canReorderOperands(TreeEntry *UserTE,
2090                      SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
2091                      ArrayRef<TreeEntry *> ReorderableGathers,
2092                      SmallVectorImpl<TreeEntry *> &GatherOps);
2093 
2094   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
2095   /// if any. If it is not vectorized (gather node), returns nullptr.
2096   TreeEntry *getVectorizedOperand(TreeEntry *UserTE, unsigned OpIdx) {
2097     ArrayRef<Value *> VL = UserTE->getOperand(OpIdx);
2098     TreeEntry *TE = nullptr;
2099     const auto *It = find_if(VL, [this, &TE](Value *V) {
2100       TE = getTreeEntry(V);
2101       return TE;
2102     });
2103     if (It != VL.end() && TE->isSame(VL))
2104       return TE;
2105     return nullptr;
2106   }
2107 
2108   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
2109   /// if any. If it is not vectorized (gather node), returns nullptr.
2110   const TreeEntry *getVectorizedOperand(const TreeEntry *UserTE,
2111                                         unsigned OpIdx) const {
2112     return const_cast<BoUpSLP *>(this)->getVectorizedOperand(
2113         const_cast<TreeEntry *>(UserTE), OpIdx);
2114   }
2115 
2116   /// Checks if all users of \p I are the part of the vectorization tree.
2117   bool areAllUsersVectorized(Instruction *I,
2118                              ArrayRef<Value *> VectorizedVals) const;
2119 
2120   /// \returns the cost of the vectorizable entry.
2121   InstructionCost getEntryCost(const TreeEntry *E,
2122                                ArrayRef<Value *> VectorizedVals);
2123 
2124   /// This is the recursive part of buildTree.
2125   void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth,
2126                      const EdgeInfo &EI);
2127 
2128   /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
2129   /// be vectorized to use the original vector (or aggregate "bitcast" to a
2130   /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
2131   /// returns false, setting \p CurrentOrder to either an empty vector or a
2132   /// non-identity permutation that allows to reuse extract instructions.
2133   bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
2134                        SmallVectorImpl<unsigned> &CurrentOrder) const;
2135 
2136   /// Vectorize a single entry in the tree.
2137   Value *vectorizeTree(TreeEntry *E);
2138 
2139   /// Vectorize a single entry in the tree, starting in \p VL.
2140   Value *vectorizeTree(ArrayRef<Value *> VL);
2141 
2142   /// Create a new vector from a list of scalar values.  Produces a sequence
2143   /// which exploits values reused across lanes, and arranges the inserts
2144   /// for ease of later optimization.
2145   Value *createBuildVector(ArrayRef<Value *> VL);
2146 
2147   /// \returns the scalarization cost for this type. Scalarization in this
2148   /// context means the creation of vectors from a group of scalars. If \p
2149   /// NeedToShuffle is true, need to add a cost of reshuffling some of the
2150   /// vector elements.
2151   InstructionCost getGatherCost(FixedVectorType *Ty,
2152                                 const APInt &ShuffledIndices,
2153                                 bool NeedToShuffle) const;
2154 
2155   /// Checks if the gathered \p VL can be represented as shuffle(s) of previous
2156   /// tree entries.
2157   /// \returns ShuffleKind, if gathered values can be represented as shuffles of
2158   /// previous tree entries. \p Mask is filled with the shuffle mask.
2159   Optional<TargetTransformInfo::ShuffleKind>
2160   isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
2161                         SmallVectorImpl<const TreeEntry *> &Entries);
2162 
2163   /// \returns the scalarization cost for this list of values. Assuming that
2164   /// this subtree gets vectorized, we may need to extract the values from the
2165   /// roots. This method calculates the cost of extracting the values.
2166   InstructionCost getGatherCost(ArrayRef<Value *> VL) const;
2167 
2168   /// Set the Builder insert point to one after the last instruction in
2169   /// the bundle
2170   void setInsertPointAfterBundle(const TreeEntry *E);
2171 
2172   /// \returns a vector from a collection of scalars in \p VL.
2173   Value *gather(ArrayRef<Value *> VL);
2174 
2175   /// \returns whether the VectorizableTree is fully vectorizable and will
2176   /// be beneficial even the tree height is tiny.
2177   bool isFullyVectorizableTinyTree(bool ForReduction) const;
2178 
2179   /// Reorder commutative or alt operands to get better probability of
2180   /// generating vectorized code.
2181   static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
2182                                              SmallVectorImpl<Value *> &Left,
2183                                              SmallVectorImpl<Value *> &Right,
2184                                              const DataLayout &DL,
2185                                              ScalarEvolution &SE,
2186                                              const BoUpSLP &R);
2187   struct TreeEntry {
2188     using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>;
2189     TreeEntry(VecTreeTy &Container) : Container(Container) {}
2190 
2191     /// \returns true if the scalars in VL are equal to this entry.
2192     bool isSame(ArrayRef<Value *> VL) const {
2193       auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) {
2194         if (Mask.size() != VL.size() && VL.size() == Scalars.size())
2195           return std::equal(VL.begin(), VL.end(), Scalars.begin());
2196         return VL.size() == Mask.size() &&
2197                std::equal(VL.begin(), VL.end(), Mask.begin(),
2198                           [Scalars](Value *V, int Idx) {
2199                             return (isa<UndefValue>(V) &&
2200                                     Idx == UndefMaskElem) ||
2201                                    (Idx != UndefMaskElem && V == Scalars[Idx]);
2202                           });
2203       };
2204       if (!ReorderIndices.empty()) {
2205         // TODO: implement matching if the nodes are just reordered, still can
2206         // treat the vector as the same if the list of scalars matches VL
2207         // directly, without reordering.
2208         SmallVector<int> Mask;
2209         inversePermutation(ReorderIndices, Mask);
2210         if (VL.size() == Scalars.size())
2211           return IsSame(Scalars, Mask);
2212         if (VL.size() == ReuseShuffleIndices.size()) {
2213           ::addMask(Mask, ReuseShuffleIndices);
2214           return IsSame(Scalars, Mask);
2215         }
2216         return false;
2217       }
2218       return IsSame(Scalars, ReuseShuffleIndices);
2219     }
2220 
2221     /// \returns true if current entry has same operands as \p TE.
2222     bool hasEqualOperands(const TreeEntry &TE) const {
2223       if (TE.getNumOperands() != getNumOperands())
2224         return false;
2225       SmallBitVector Used(getNumOperands());
2226       for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
2227         unsigned PrevCount = Used.count();
2228         for (unsigned K = 0; K < E; ++K) {
2229           if (Used.test(K))
2230             continue;
2231           if (getOperand(K) == TE.getOperand(I)) {
2232             Used.set(K);
2233             break;
2234           }
2235         }
2236         // Check if we actually found the matching operand.
2237         if (PrevCount == Used.count())
2238           return false;
2239       }
2240       return true;
2241     }
2242 
2243     /// \return Final vectorization factor for the node. Defined by the total
2244     /// number of vectorized scalars, including those, used several times in the
2245     /// entry and counted in the \a ReuseShuffleIndices, if any.
2246     unsigned getVectorFactor() const {
2247       if (!ReuseShuffleIndices.empty())
2248         return ReuseShuffleIndices.size();
2249       return Scalars.size();
2250     };
2251 
2252     /// A vector of scalars.
2253     ValueList Scalars;
2254 
2255     /// The Scalars are vectorized into this value. It is initialized to Null.
2256     Value *VectorizedValue = nullptr;
2257 
2258     /// Do we need to gather this sequence or vectorize it
2259     /// (either with vector instruction or with scatter/gather
2260     /// intrinsics for store/load)?
2261     enum EntryState { Vectorize, ScatterVectorize, NeedToGather };
2262     EntryState State;
2263 
2264     /// Does this sequence require some shuffling?
2265     SmallVector<int, 4> ReuseShuffleIndices;
2266 
2267     /// Does this entry require reordering?
2268     SmallVector<unsigned, 4> ReorderIndices;
2269 
2270     /// Points back to the VectorizableTree.
2271     ///
2272     /// Only used for Graphviz right now.  Unfortunately GraphTrait::NodeRef has
2273     /// to be a pointer and needs to be able to initialize the child iterator.
2274     /// Thus we need a reference back to the container to translate the indices
2275     /// to entries.
2276     VecTreeTy &Container;
2277 
2278     /// The TreeEntry index containing the user of this entry.  We can actually
2279     /// have multiple users so the data structure is not truly a tree.
2280     SmallVector<EdgeInfo, 1> UserTreeIndices;
2281 
2282     /// The index of this treeEntry in VectorizableTree.
2283     int Idx = -1;
2284 
2285   private:
2286     /// The operands of each instruction in each lane Operands[op_index][lane].
2287     /// Note: This helps avoid the replication of the code that performs the
2288     /// reordering of operands during buildTree_rec() and vectorizeTree().
2289     SmallVector<ValueList, 2> Operands;
2290 
2291     /// The main/alternate instruction.
2292     Instruction *MainOp = nullptr;
2293     Instruction *AltOp = nullptr;
2294 
2295   public:
2296     /// Set this bundle's \p OpIdx'th operand to \p OpVL.
2297     void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) {
2298       if (Operands.size() < OpIdx + 1)
2299         Operands.resize(OpIdx + 1);
2300       assert(Operands[OpIdx].empty() && "Already resized?");
2301       assert(OpVL.size() <= Scalars.size() &&
2302              "Number of operands is greater than the number of scalars.");
2303       Operands[OpIdx].resize(OpVL.size());
2304       copy(OpVL, Operands[OpIdx].begin());
2305     }
2306 
2307     /// Set the operands of this bundle in their original order.
2308     void setOperandsInOrder() {
2309       assert(Operands.empty() && "Already initialized?");
2310       auto *I0 = cast<Instruction>(Scalars[0]);
2311       Operands.resize(I0->getNumOperands());
2312       unsigned NumLanes = Scalars.size();
2313       for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands();
2314            OpIdx != NumOperands; ++OpIdx) {
2315         Operands[OpIdx].resize(NumLanes);
2316         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
2317           auto *I = cast<Instruction>(Scalars[Lane]);
2318           assert(I->getNumOperands() == NumOperands &&
2319                  "Expected same number of operands");
2320           Operands[OpIdx][Lane] = I->getOperand(OpIdx);
2321         }
2322       }
2323     }
2324 
2325     /// Reorders operands of the node to the given mask \p Mask.
2326     void reorderOperands(ArrayRef<int> Mask) {
2327       for (ValueList &Operand : Operands)
2328         reorderScalars(Operand, Mask);
2329     }
2330 
2331     /// \returns the \p OpIdx operand of this TreeEntry.
2332     ValueList &getOperand(unsigned OpIdx) {
2333       assert(OpIdx < Operands.size() && "Off bounds");
2334       return Operands[OpIdx];
2335     }
2336 
2337     /// \returns the \p OpIdx operand of this TreeEntry.
2338     ArrayRef<Value *> getOperand(unsigned OpIdx) const {
2339       assert(OpIdx < Operands.size() && "Off bounds");
2340       return Operands[OpIdx];
2341     }
2342 
2343     /// \returns the number of operands.
2344     unsigned getNumOperands() const { return Operands.size(); }
2345 
2346     /// \return the single \p OpIdx operand.
2347     Value *getSingleOperand(unsigned OpIdx) const {
2348       assert(OpIdx < Operands.size() && "Off bounds");
2349       assert(!Operands[OpIdx].empty() && "No operand available");
2350       return Operands[OpIdx][0];
2351     }
2352 
2353     /// Some of the instructions in the list have alternate opcodes.
2354     bool isAltShuffle() const { return MainOp != AltOp; }
2355 
2356     bool isOpcodeOrAlt(Instruction *I) const {
2357       unsigned CheckedOpcode = I->getOpcode();
2358       return (getOpcode() == CheckedOpcode ||
2359               getAltOpcode() == CheckedOpcode);
2360     }
2361 
2362     /// Chooses the correct key for scheduling data. If \p Op has the same (or
2363     /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is
2364     /// \p OpValue.
2365     Value *isOneOf(Value *Op) const {
2366       auto *I = dyn_cast<Instruction>(Op);
2367       if (I && isOpcodeOrAlt(I))
2368         return Op;
2369       return MainOp;
2370     }
2371 
2372     void setOperations(const InstructionsState &S) {
2373       MainOp = S.MainOp;
2374       AltOp = S.AltOp;
2375     }
2376 
2377     Instruction *getMainOp() const {
2378       return MainOp;
2379     }
2380 
2381     Instruction *getAltOp() const {
2382       return AltOp;
2383     }
2384 
2385     /// The main/alternate opcodes for the list of instructions.
2386     unsigned getOpcode() const {
2387       return MainOp ? MainOp->getOpcode() : 0;
2388     }
2389 
2390     unsigned getAltOpcode() const {
2391       return AltOp ? AltOp->getOpcode() : 0;
2392     }
2393 
2394     /// When ReuseReorderShuffleIndices is empty it just returns position of \p
2395     /// V within vector of Scalars. Otherwise, try to remap on its reuse index.
2396     int findLaneForValue(Value *V) const {
2397       unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V));
2398       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2399       if (!ReorderIndices.empty())
2400         FoundLane = ReorderIndices[FoundLane];
2401       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2402       if (!ReuseShuffleIndices.empty()) {
2403         FoundLane = std::distance(ReuseShuffleIndices.begin(),
2404                                   find(ReuseShuffleIndices, FoundLane));
2405       }
2406       return FoundLane;
2407     }
2408 
2409 #ifndef NDEBUG
2410     /// Debug printer.
2411     LLVM_DUMP_METHOD void dump() const {
2412       dbgs() << Idx << ".\n";
2413       for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) {
2414         dbgs() << "Operand " << OpI << ":\n";
2415         for (const Value *V : Operands[OpI])
2416           dbgs().indent(2) << *V << "\n";
2417       }
2418       dbgs() << "Scalars: \n";
2419       for (Value *V : Scalars)
2420         dbgs().indent(2) << *V << "\n";
2421       dbgs() << "State: ";
2422       switch (State) {
2423       case Vectorize:
2424         dbgs() << "Vectorize\n";
2425         break;
2426       case ScatterVectorize:
2427         dbgs() << "ScatterVectorize\n";
2428         break;
2429       case NeedToGather:
2430         dbgs() << "NeedToGather\n";
2431         break;
2432       }
2433       dbgs() << "MainOp: ";
2434       if (MainOp)
2435         dbgs() << *MainOp << "\n";
2436       else
2437         dbgs() << "NULL\n";
2438       dbgs() << "AltOp: ";
2439       if (AltOp)
2440         dbgs() << *AltOp << "\n";
2441       else
2442         dbgs() << "NULL\n";
2443       dbgs() << "VectorizedValue: ";
2444       if (VectorizedValue)
2445         dbgs() << *VectorizedValue << "\n";
2446       else
2447         dbgs() << "NULL\n";
2448       dbgs() << "ReuseShuffleIndices: ";
2449       if (ReuseShuffleIndices.empty())
2450         dbgs() << "Empty";
2451       else
2452         for (int ReuseIdx : ReuseShuffleIndices)
2453           dbgs() << ReuseIdx << ", ";
2454       dbgs() << "\n";
2455       dbgs() << "ReorderIndices: ";
2456       for (unsigned ReorderIdx : ReorderIndices)
2457         dbgs() << ReorderIdx << ", ";
2458       dbgs() << "\n";
2459       dbgs() << "UserTreeIndices: ";
2460       for (const auto &EInfo : UserTreeIndices)
2461         dbgs() << EInfo << ", ";
2462       dbgs() << "\n";
2463     }
2464 #endif
2465   };
2466 
2467 #ifndef NDEBUG
2468   void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost,
2469                      InstructionCost VecCost,
2470                      InstructionCost ScalarCost) const {
2471     dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump();
2472     dbgs() << "SLP: Costs:\n";
2473     dbgs() << "SLP:     ReuseShuffleCost = " << ReuseShuffleCost << "\n";
2474     dbgs() << "SLP:     VectorCost = " << VecCost << "\n";
2475     dbgs() << "SLP:     ScalarCost = " << ScalarCost << "\n";
2476     dbgs() << "SLP:     ReuseShuffleCost + VecCost - ScalarCost = " <<
2477                ReuseShuffleCost + VecCost - ScalarCost << "\n";
2478   }
2479 #endif
2480 
2481   /// Create a new VectorizableTree entry.
2482   TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle,
2483                           const InstructionsState &S,
2484                           const EdgeInfo &UserTreeIdx,
2485                           ArrayRef<int> ReuseShuffleIndices = None,
2486                           ArrayRef<unsigned> ReorderIndices = None) {
2487     TreeEntry::EntryState EntryState =
2488         Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather;
2489     return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx,
2490                         ReuseShuffleIndices, ReorderIndices);
2491   }
2492 
2493   TreeEntry *newTreeEntry(ArrayRef<Value *> VL,
2494                           TreeEntry::EntryState EntryState,
2495                           Optional<ScheduleData *> Bundle,
2496                           const InstructionsState &S,
2497                           const EdgeInfo &UserTreeIdx,
2498                           ArrayRef<int> ReuseShuffleIndices = None,
2499                           ArrayRef<unsigned> ReorderIndices = None) {
2500     assert(((!Bundle && EntryState == TreeEntry::NeedToGather) ||
2501             (Bundle && EntryState != TreeEntry::NeedToGather)) &&
2502            "Need to vectorize gather entry?");
2503     VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree));
2504     TreeEntry *Last = VectorizableTree.back().get();
2505     Last->Idx = VectorizableTree.size() - 1;
2506     Last->State = EntryState;
2507     Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
2508                                      ReuseShuffleIndices.end());
2509     if (ReorderIndices.empty()) {
2510       Last->Scalars.assign(VL.begin(), VL.end());
2511       Last->setOperations(S);
2512     } else {
2513       // Reorder scalars and build final mask.
2514       Last->Scalars.assign(VL.size(), nullptr);
2515       transform(ReorderIndices, Last->Scalars.begin(),
2516                 [VL](unsigned Idx) -> Value * {
2517                   if (Idx >= VL.size())
2518                     return UndefValue::get(VL.front()->getType());
2519                   return VL[Idx];
2520                 });
2521       InstructionsState S = getSameOpcode(Last->Scalars);
2522       Last->setOperations(S);
2523       Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end());
2524     }
2525     if (Last->State != TreeEntry::NeedToGather) {
2526       for (Value *V : VL) {
2527         assert(!getTreeEntry(V) && "Scalar already in tree!");
2528         ScalarToTreeEntry[V] = Last;
2529       }
2530       // Update the scheduler bundle to point to this TreeEntry.
2531       ScheduleData *BundleMember = Bundle.getValue();
2532       assert((BundleMember || isa<PHINode>(S.MainOp) ||
2533               isVectorLikeInstWithConstOps(S.MainOp) ||
2534               doesNotNeedToSchedule(VL)) &&
2535              "Bundle and VL out of sync");
2536       if (BundleMember) {
2537         for (Value *V : VL) {
2538           if (doesNotNeedToBeScheduled(V))
2539             continue;
2540           assert(BundleMember && "Unexpected end of bundle.");
2541           BundleMember->TE = Last;
2542           BundleMember = BundleMember->NextInBundle;
2543         }
2544       }
2545       assert(!BundleMember && "Bundle and VL out of sync");
2546     } else {
2547       MustGather.insert(VL.begin(), VL.end());
2548     }
2549 
2550     if (UserTreeIdx.UserTE)
2551       Last->UserTreeIndices.push_back(UserTreeIdx);
2552 
2553     return Last;
2554   }
2555 
2556   /// -- Vectorization State --
2557   /// Holds all of the tree entries.
2558   TreeEntry::VecTreeTy VectorizableTree;
2559 
2560 #ifndef NDEBUG
2561   /// Debug printer.
2562   LLVM_DUMP_METHOD void dumpVectorizableTree() const {
2563     for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) {
2564       VectorizableTree[Id]->dump();
2565       dbgs() << "\n";
2566     }
2567   }
2568 #endif
2569 
2570   TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); }
2571 
2572   const TreeEntry *getTreeEntry(Value *V) const {
2573     return ScalarToTreeEntry.lookup(V);
2574   }
2575 
2576   /// Maps a specific scalar to its tree entry.
2577   SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry;
2578 
2579   /// Maps a value to the proposed vectorizable size.
2580   SmallDenseMap<Value *, unsigned> InstrElementSize;
2581 
2582   /// A list of scalars that we found that we need to keep as scalars.
2583   ValueSet MustGather;
2584 
2585   /// This POD struct describes one external user in the vectorized tree.
2586   struct ExternalUser {
2587     ExternalUser(Value *S, llvm::User *U, int L)
2588         : Scalar(S), User(U), Lane(L) {}
2589 
2590     // Which scalar in our function.
2591     Value *Scalar;
2592 
2593     // Which user that uses the scalar.
2594     llvm::User *User;
2595 
2596     // Which lane does the scalar belong to.
2597     int Lane;
2598   };
2599   using UserList = SmallVector<ExternalUser, 16>;
2600 
2601   /// Checks if two instructions may access the same memory.
2602   ///
2603   /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
2604   /// is invariant in the calling loop.
2605   bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
2606                  Instruction *Inst2) {
2607     // First check if the result is already in the cache.
2608     AliasCacheKey key = std::make_pair(Inst1, Inst2);
2609     Optional<bool> &result = AliasCache[key];
2610     if (result.hasValue()) {
2611       return result.getValue();
2612     }
2613     bool aliased = true;
2614     if (Loc1.Ptr && isSimple(Inst1))
2615       aliased = isModOrRefSet(BatchAA.getModRefInfo(Inst2, Loc1));
2616     // Store the result in the cache.
2617     result = aliased;
2618     return aliased;
2619   }
2620 
2621   using AliasCacheKey = std::pair<Instruction *, Instruction *>;
2622 
2623   /// Cache for alias results.
2624   /// TODO: consider moving this to the AliasAnalysis itself.
2625   DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
2626 
2627   // Cache for pointerMayBeCaptured calls inside AA.  This is preserved
2628   // globally through SLP because we don't perform any action which
2629   // invalidates capture results.
2630   BatchAAResults BatchAA;
2631 
2632   /// Temporary store for deleted instructions. Instructions will be deleted
2633   /// eventually when the BoUpSLP is destructed.  The deferral is required to
2634   /// ensure that there are no incorrect collisions in the AliasCache, which
2635   /// can happen if a new instruction is allocated at the same address as a
2636   /// previously deleted instruction.
2637   DenseSet<Instruction *> DeletedInstructions;
2638 
2639   /// Set of the instruction, being analyzed already for reductions.
2640   SmallPtrSet<Instruction *, 16> AnalizedReductionsRoots;
2641 
2642   /// Set of hashes for the list of reduction values already being analyzed.
2643   DenseSet<size_t> AnalyzedReductionVals;
2644 
2645   /// A list of values that need to extracted out of the tree.
2646   /// This list holds pairs of (Internal Scalar : External User). External User
2647   /// can be nullptr, it means that this Internal Scalar will be used later,
2648   /// after vectorization.
2649   UserList ExternalUses;
2650 
2651   /// Values used only by @llvm.assume calls.
2652   SmallPtrSet<const Value *, 32> EphValues;
2653 
2654   /// Holds all of the instructions that we gathered.
2655   SetVector<Instruction *> GatherShuffleSeq;
2656 
2657   /// A list of blocks that we are going to CSE.
2658   SetVector<BasicBlock *> CSEBlocks;
2659 
2660   /// Contains all scheduling relevant data for an instruction.
2661   /// A ScheduleData either represents a single instruction or a member of an
2662   /// instruction bundle (= a group of instructions which is combined into a
2663   /// vector instruction).
2664   struct ScheduleData {
2665     // The initial value for the dependency counters. It means that the
2666     // dependencies are not calculated yet.
2667     enum { InvalidDeps = -1 };
2668 
2669     ScheduleData() = default;
2670 
2671     void init(int BlockSchedulingRegionID, Value *OpVal) {
2672       FirstInBundle = this;
2673       NextInBundle = nullptr;
2674       NextLoadStore = nullptr;
2675       IsScheduled = false;
2676       SchedulingRegionID = BlockSchedulingRegionID;
2677       clearDependencies();
2678       OpValue = OpVal;
2679       TE = nullptr;
2680     }
2681 
2682     /// Verify basic self consistency properties
2683     void verify() {
2684       if (hasValidDependencies()) {
2685         assert(UnscheduledDeps <= Dependencies && "invariant");
2686       } else {
2687         assert(UnscheduledDeps == Dependencies && "invariant");
2688       }
2689 
2690       if (IsScheduled) {
2691         assert(isSchedulingEntity() &&
2692                 "unexpected scheduled state");
2693         for (const ScheduleData *BundleMember = this; BundleMember;
2694              BundleMember = BundleMember->NextInBundle) {
2695           assert(BundleMember->hasValidDependencies() &&
2696                  BundleMember->UnscheduledDeps == 0 &&
2697                  "unexpected scheduled state");
2698           assert((BundleMember == this || !BundleMember->IsScheduled) &&
2699                  "only bundle is marked scheduled");
2700         }
2701       }
2702 
2703       assert(Inst->getParent() == FirstInBundle->Inst->getParent() &&
2704              "all bundle members must be in same basic block");
2705     }
2706 
2707     /// Returns true if the dependency information has been calculated.
2708     /// Note that depenendency validity can vary between instructions within
2709     /// a single bundle.
2710     bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
2711 
2712     /// Returns true for single instructions and for bundle representatives
2713     /// (= the head of a bundle).
2714     bool isSchedulingEntity() const { return FirstInBundle == this; }
2715 
2716     /// Returns true if it represents an instruction bundle and not only a
2717     /// single instruction.
2718     bool isPartOfBundle() const {
2719       return NextInBundle != nullptr || FirstInBundle != this || TE;
2720     }
2721 
2722     /// Returns true if it is ready for scheduling, i.e. it has no more
2723     /// unscheduled depending instructions/bundles.
2724     bool isReady() const {
2725       assert(isSchedulingEntity() &&
2726              "can't consider non-scheduling entity for ready list");
2727       return unscheduledDepsInBundle() == 0 && !IsScheduled;
2728     }
2729 
2730     /// Modifies the number of unscheduled dependencies for this instruction,
2731     /// and returns the number of remaining dependencies for the containing
2732     /// bundle.
2733     int incrementUnscheduledDeps(int Incr) {
2734       assert(hasValidDependencies() &&
2735              "increment of unscheduled deps would be meaningless");
2736       UnscheduledDeps += Incr;
2737       return FirstInBundle->unscheduledDepsInBundle();
2738     }
2739 
2740     /// Sets the number of unscheduled dependencies to the number of
2741     /// dependencies.
2742     void resetUnscheduledDeps() {
2743       UnscheduledDeps = Dependencies;
2744     }
2745 
2746     /// Clears all dependency information.
2747     void clearDependencies() {
2748       Dependencies = InvalidDeps;
2749       resetUnscheduledDeps();
2750       MemoryDependencies.clear();
2751       ControlDependencies.clear();
2752     }
2753 
2754     int unscheduledDepsInBundle() const {
2755       assert(isSchedulingEntity() && "only meaningful on the bundle");
2756       int Sum = 0;
2757       for (const ScheduleData *BundleMember = this; BundleMember;
2758            BundleMember = BundleMember->NextInBundle) {
2759         if (BundleMember->UnscheduledDeps == InvalidDeps)
2760           return InvalidDeps;
2761         Sum += BundleMember->UnscheduledDeps;
2762       }
2763       return Sum;
2764     }
2765 
2766     void dump(raw_ostream &os) const {
2767       if (!isSchedulingEntity()) {
2768         os << "/ " << *Inst;
2769       } else if (NextInBundle) {
2770         os << '[' << *Inst;
2771         ScheduleData *SD = NextInBundle;
2772         while (SD) {
2773           os << ';' << *SD->Inst;
2774           SD = SD->NextInBundle;
2775         }
2776         os << ']';
2777       } else {
2778         os << *Inst;
2779       }
2780     }
2781 
2782     Instruction *Inst = nullptr;
2783 
2784     /// Opcode of the current instruction in the schedule data.
2785     Value *OpValue = nullptr;
2786 
2787     /// The TreeEntry that this instruction corresponds to.
2788     TreeEntry *TE = nullptr;
2789 
2790     /// Points to the head in an instruction bundle (and always to this for
2791     /// single instructions).
2792     ScheduleData *FirstInBundle = nullptr;
2793 
2794     /// Single linked list of all instructions in a bundle. Null if it is a
2795     /// single instruction.
2796     ScheduleData *NextInBundle = nullptr;
2797 
2798     /// Single linked list of all memory instructions (e.g. load, store, call)
2799     /// in the block - until the end of the scheduling region.
2800     ScheduleData *NextLoadStore = nullptr;
2801 
2802     /// The dependent memory instructions.
2803     /// This list is derived on demand in calculateDependencies().
2804     SmallVector<ScheduleData *, 4> MemoryDependencies;
2805 
2806     /// List of instructions which this instruction could be control dependent
2807     /// on.  Allowing such nodes to be scheduled below this one could introduce
2808     /// a runtime fault which didn't exist in the original program.
2809     /// ex: this is a load or udiv following a readonly call which inf loops
2810     SmallVector<ScheduleData *, 4> ControlDependencies;
2811 
2812     /// This ScheduleData is in the current scheduling region if this matches
2813     /// the current SchedulingRegionID of BlockScheduling.
2814     int SchedulingRegionID = 0;
2815 
2816     /// Used for getting a "good" final ordering of instructions.
2817     int SchedulingPriority = 0;
2818 
2819     /// The number of dependencies. Constitutes of the number of users of the
2820     /// instruction plus the number of dependent memory instructions (if any).
2821     /// This value is calculated on demand.
2822     /// If InvalidDeps, the number of dependencies is not calculated yet.
2823     int Dependencies = InvalidDeps;
2824 
2825     /// The number of dependencies minus the number of dependencies of scheduled
2826     /// instructions. As soon as this is zero, the instruction/bundle gets ready
2827     /// for scheduling.
2828     /// Note that this is negative as long as Dependencies is not calculated.
2829     int UnscheduledDeps = InvalidDeps;
2830 
2831     /// True if this instruction is scheduled (or considered as scheduled in the
2832     /// dry-run).
2833     bool IsScheduled = false;
2834   };
2835 
2836 #ifndef NDEBUG
2837   friend inline raw_ostream &operator<<(raw_ostream &os,
2838                                         const BoUpSLP::ScheduleData &SD) {
2839     SD.dump(os);
2840     return os;
2841   }
2842 #endif
2843 
2844   friend struct GraphTraits<BoUpSLP *>;
2845   friend struct DOTGraphTraits<BoUpSLP *>;
2846 
2847   /// Contains all scheduling data for a basic block.
2848   /// It does not schedules instructions, which are not memory read/write
2849   /// instructions and their operands are either constants, or arguments, or
2850   /// phis, or instructions from others blocks, or their users are phis or from
2851   /// the other blocks. The resulting vector instructions can be placed at the
2852   /// beginning of the basic block without scheduling (if operands does not need
2853   /// to be scheduled) or at the end of the block (if users are outside of the
2854   /// block). It allows to save some compile time and memory used by the
2855   /// compiler.
2856   /// ScheduleData is assigned for each instruction in between the boundaries of
2857   /// the tree entry, even for those, which are not part of the graph. It is
2858   /// required to correctly follow the dependencies between the instructions and
2859   /// their correct scheduling. The ScheduleData is not allocated for the
2860   /// instructions, which do not require scheduling, like phis, nodes with
2861   /// extractelements/insertelements only or nodes with instructions, with
2862   /// uses/operands outside of the block.
2863   struct BlockScheduling {
2864     BlockScheduling(BasicBlock *BB)
2865         : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
2866 
2867     void clear() {
2868       ReadyInsts.clear();
2869       ScheduleStart = nullptr;
2870       ScheduleEnd = nullptr;
2871       FirstLoadStoreInRegion = nullptr;
2872       LastLoadStoreInRegion = nullptr;
2873       RegionHasStackSave = false;
2874 
2875       // Reduce the maximum schedule region size by the size of the
2876       // previous scheduling run.
2877       ScheduleRegionSizeLimit -= ScheduleRegionSize;
2878       if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
2879         ScheduleRegionSizeLimit = MinScheduleRegionSize;
2880       ScheduleRegionSize = 0;
2881 
2882       // Make a new scheduling region, i.e. all existing ScheduleData is not
2883       // in the new region yet.
2884       ++SchedulingRegionID;
2885     }
2886 
2887     ScheduleData *getScheduleData(Instruction *I) {
2888       if (BB != I->getParent())
2889         // Avoid lookup if can't possibly be in map.
2890         return nullptr;
2891       ScheduleData *SD = ScheduleDataMap.lookup(I);
2892       if (SD && isInSchedulingRegion(SD))
2893         return SD;
2894       return nullptr;
2895     }
2896 
2897     ScheduleData *getScheduleData(Value *V) {
2898       if (auto *I = dyn_cast<Instruction>(V))
2899         return getScheduleData(I);
2900       return nullptr;
2901     }
2902 
2903     ScheduleData *getScheduleData(Value *V, Value *Key) {
2904       if (V == Key)
2905         return getScheduleData(V);
2906       auto I = ExtraScheduleDataMap.find(V);
2907       if (I != ExtraScheduleDataMap.end()) {
2908         ScheduleData *SD = I->second.lookup(Key);
2909         if (SD && isInSchedulingRegion(SD))
2910           return SD;
2911       }
2912       return nullptr;
2913     }
2914 
2915     bool isInSchedulingRegion(ScheduleData *SD) const {
2916       return SD->SchedulingRegionID == SchedulingRegionID;
2917     }
2918 
2919     /// Marks an instruction as scheduled and puts all dependent ready
2920     /// instructions into the ready-list.
2921     template <typename ReadyListType>
2922     void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
2923       SD->IsScheduled = true;
2924       LLVM_DEBUG(dbgs() << "SLP:   schedule " << *SD << "\n");
2925 
2926       for (ScheduleData *BundleMember = SD; BundleMember;
2927            BundleMember = BundleMember->NextInBundle) {
2928         if (BundleMember->Inst != BundleMember->OpValue)
2929           continue;
2930 
2931         // Handle the def-use chain dependencies.
2932 
2933         // Decrement the unscheduled counter and insert to ready list if ready.
2934         auto &&DecrUnsched = [this, &ReadyList](Instruction *I) {
2935           doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
2936             if (OpDef && OpDef->hasValidDependencies() &&
2937                 OpDef->incrementUnscheduledDeps(-1) == 0) {
2938               // There are no more unscheduled dependencies after
2939               // decrementing, so we can put the dependent instruction
2940               // into the ready list.
2941               ScheduleData *DepBundle = OpDef->FirstInBundle;
2942               assert(!DepBundle->IsScheduled &&
2943                      "already scheduled bundle gets ready");
2944               ReadyList.insert(DepBundle);
2945               LLVM_DEBUG(dbgs()
2946                          << "SLP:    gets ready (def): " << *DepBundle << "\n");
2947             }
2948           });
2949         };
2950 
2951         // If BundleMember is a vector bundle, its operands may have been
2952         // reordered during buildTree(). We therefore need to get its operands
2953         // through the TreeEntry.
2954         if (TreeEntry *TE = BundleMember->TE) {
2955           // Need to search for the lane since the tree entry can be reordered.
2956           int Lane = std::distance(TE->Scalars.begin(),
2957                                    find(TE->Scalars, BundleMember->Inst));
2958           assert(Lane >= 0 && "Lane not set");
2959 
2960           // Since vectorization tree is being built recursively this assertion
2961           // ensures that the tree entry has all operands set before reaching
2962           // this code. Couple of exceptions known at the moment are extracts
2963           // where their second (immediate) operand is not added. Since
2964           // immediates do not affect scheduler behavior this is considered
2965           // okay.
2966           auto *In = BundleMember->Inst;
2967           assert(In &&
2968                  (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) ||
2969                   In->getNumOperands() == TE->getNumOperands()) &&
2970                  "Missed TreeEntry operands?");
2971           (void)In; // fake use to avoid build failure when assertions disabled
2972 
2973           for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands();
2974                OpIdx != NumOperands; ++OpIdx)
2975             if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane]))
2976               DecrUnsched(I);
2977         } else {
2978           // If BundleMember is a stand-alone instruction, no operand reordering
2979           // has taken place, so we directly access its operands.
2980           for (Use &U : BundleMember->Inst->operands())
2981             if (auto *I = dyn_cast<Instruction>(U.get()))
2982               DecrUnsched(I);
2983         }
2984         // Handle the memory dependencies.
2985         for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
2986           if (MemoryDepSD->hasValidDependencies() &&
2987               MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
2988             // There are no more unscheduled dependencies after decrementing,
2989             // so we can put the dependent instruction into the ready list.
2990             ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
2991             assert(!DepBundle->IsScheduled &&
2992                    "already scheduled bundle gets ready");
2993             ReadyList.insert(DepBundle);
2994             LLVM_DEBUG(dbgs()
2995                        << "SLP:    gets ready (mem): " << *DepBundle << "\n");
2996           }
2997         }
2998         // Handle the control dependencies.
2999         for (ScheduleData *DepSD : BundleMember->ControlDependencies) {
3000           if (DepSD->incrementUnscheduledDeps(-1) == 0) {
3001             // There are no more unscheduled dependencies after decrementing,
3002             // so we can put the dependent instruction into the ready list.
3003             ScheduleData *DepBundle = DepSD->FirstInBundle;
3004             assert(!DepBundle->IsScheduled &&
3005                    "already scheduled bundle gets ready");
3006             ReadyList.insert(DepBundle);
3007             LLVM_DEBUG(dbgs()
3008                        << "SLP:    gets ready (ctl): " << *DepBundle << "\n");
3009           }
3010         }
3011 
3012       }
3013     }
3014 
3015     /// Verify basic self consistency properties of the data structure.
3016     void verify() {
3017       if (!ScheduleStart)
3018         return;
3019 
3020       assert(ScheduleStart->getParent() == ScheduleEnd->getParent() &&
3021              ScheduleStart->comesBefore(ScheduleEnd) &&
3022              "Not a valid scheduling region?");
3023 
3024       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
3025         auto *SD = getScheduleData(I);
3026         if (!SD)
3027           continue;
3028         assert(isInSchedulingRegion(SD) &&
3029                "primary schedule data not in window?");
3030         assert(isInSchedulingRegion(SD->FirstInBundle) &&
3031                "entire bundle in window!");
3032         (void)SD;
3033         doForAllOpcodes(I, [](ScheduleData *SD) { SD->verify(); });
3034       }
3035 
3036       for (auto *SD : ReadyInsts) {
3037         assert(SD->isSchedulingEntity() && SD->isReady() &&
3038                "item in ready list not ready?");
3039         (void)SD;
3040       }
3041     }
3042 
3043     void doForAllOpcodes(Value *V,
3044                          function_ref<void(ScheduleData *SD)> Action) {
3045       if (ScheduleData *SD = getScheduleData(V))
3046         Action(SD);
3047       auto I = ExtraScheduleDataMap.find(V);
3048       if (I != ExtraScheduleDataMap.end())
3049         for (auto &P : I->second)
3050           if (isInSchedulingRegion(P.second))
3051             Action(P.second);
3052     }
3053 
3054     /// Put all instructions into the ReadyList which are ready for scheduling.
3055     template <typename ReadyListType>
3056     void initialFillReadyList(ReadyListType &ReadyList) {
3057       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
3058         doForAllOpcodes(I, [&](ScheduleData *SD) {
3059           if (SD->isSchedulingEntity() && SD->hasValidDependencies() &&
3060               SD->isReady()) {
3061             ReadyList.insert(SD);
3062             LLVM_DEBUG(dbgs()
3063                        << "SLP:    initially in ready list: " << *SD << "\n");
3064           }
3065         });
3066       }
3067     }
3068 
3069     /// Build a bundle from the ScheduleData nodes corresponding to the
3070     /// scalar instruction for each lane.
3071     ScheduleData *buildBundle(ArrayRef<Value *> VL);
3072 
3073     /// Checks if a bundle of instructions can be scheduled, i.e. has no
3074     /// cyclic dependencies. This is only a dry-run, no instructions are
3075     /// actually moved at this stage.
3076     /// \returns the scheduling bundle. The returned Optional value is non-None
3077     /// if \p VL is allowed to be scheduled.
3078     Optional<ScheduleData *>
3079     tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
3080                       const InstructionsState &S);
3081 
3082     /// Un-bundles a group of instructions.
3083     void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
3084 
3085     /// Allocates schedule data chunk.
3086     ScheduleData *allocateScheduleDataChunks();
3087 
3088     /// Extends the scheduling region so that V is inside the region.
3089     /// \returns true if the region size is within the limit.
3090     bool extendSchedulingRegion(Value *V, const InstructionsState &S);
3091 
3092     /// Initialize the ScheduleData structures for new instructions in the
3093     /// scheduling region.
3094     void initScheduleData(Instruction *FromI, Instruction *ToI,
3095                           ScheduleData *PrevLoadStore,
3096                           ScheduleData *NextLoadStore);
3097 
3098     /// Updates the dependency information of a bundle and of all instructions/
3099     /// bundles which depend on the original bundle.
3100     void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
3101                                BoUpSLP *SLP);
3102 
3103     /// Sets all instruction in the scheduling region to un-scheduled.
3104     void resetSchedule();
3105 
3106     BasicBlock *BB;
3107 
3108     /// Simple memory allocation for ScheduleData.
3109     std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
3110 
3111     /// The size of a ScheduleData array in ScheduleDataChunks.
3112     int ChunkSize;
3113 
3114     /// The allocator position in the current chunk, which is the last entry
3115     /// of ScheduleDataChunks.
3116     int ChunkPos;
3117 
3118     /// Attaches ScheduleData to Instruction.
3119     /// Note that the mapping survives during all vectorization iterations, i.e.
3120     /// ScheduleData structures are recycled.
3121     DenseMap<Instruction *, ScheduleData *> ScheduleDataMap;
3122 
3123     /// Attaches ScheduleData to Instruction with the leading key.
3124     DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
3125         ExtraScheduleDataMap;
3126 
3127     /// The ready-list for scheduling (only used for the dry-run).
3128     SetVector<ScheduleData *> ReadyInsts;
3129 
3130     /// The first instruction of the scheduling region.
3131     Instruction *ScheduleStart = nullptr;
3132 
3133     /// The first instruction _after_ the scheduling region.
3134     Instruction *ScheduleEnd = nullptr;
3135 
3136     /// The first memory accessing instruction in the scheduling region
3137     /// (can be null).
3138     ScheduleData *FirstLoadStoreInRegion = nullptr;
3139 
3140     /// The last memory accessing instruction in the scheduling region
3141     /// (can be null).
3142     ScheduleData *LastLoadStoreInRegion = nullptr;
3143 
3144     /// Is there an llvm.stacksave or llvm.stackrestore in the scheduling
3145     /// region?  Used to optimize the dependence calculation for the
3146     /// common case where there isn't.
3147     bool RegionHasStackSave = false;
3148 
3149     /// The current size of the scheduling region.
3150     int ScheduleRegionSize = 0;
3151 
3152     /// The maximum size allowed for the scheduling region.
3153     int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
3154 
3155     /// The ID of the scheduling region. For a new vectorization iteration this
3156     /// is incremented which "removes" all ScheduleData from the region.
3157     /// Make sure that the initial SchedulingRegionID is greater than the
3158     /// initial SchedulingRegionID in ScheduleData (which is 0).
3159     int SchedulingRegionID = 1;
3160   };
3161 
3162   /// Attaches the BlockScheduling structures to basic blocks.
3163   MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
3164 
3165   /// Performs the "real" scheduling. Done before vectorization is actually
3166   /// performed in a basic block.
3167   void scheduleBlock(BlockScheduling *BS);
3168 
3169   /// List of users to ignore during scheduling and that don't need extracting.
3170   ArrayRef<Value *> UserIgnoreList;
3171 
3172   /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
3173   /// sorted SmallVectors of unsigned.
3174   struct OrdersTypeDenseMapInfo {
3175     static OrdersType getEmptyKey() {
3176       OrdersType V;
3177       V.push_back(~1U);
3178       return V;
3179     }
3180 
3181     static OrdersType getTombstoneKey() {
3182       OrdersType V;
3183       V.push_back(~2U);
3184       return V;
3185     }
3186 
3187     static unsigned getHashValue(const OrdersType &V) {
3188       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
3189     }
3190 
3191     static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
3192       return LHS == RHS;
3193     }
3194   };
3195 
3196   // Analysis and block reference.
3197   Function *F;
3198   ScalarEvolution *SE;
3199   TargetTransformInfo *TTI;
3200   TargetLibraryInfo *TLI;
3201   LoopInfo *LI;
3202   DominatorTree *DT;
3203   AssumptionCache *AC;
3204   DemandedBits *DB;
3205   const DataLayout *DL;
3206   OptimizationRemarkEmitter *ORE;
3207 
3208   unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
3209   unsigned MinVecRegSize; // Set by cl::opt (default: 128).
3210 
3211   /// Instruction builder to construct the vectorized tree.
3212   IRBuilder<> Builder;
3213 
3214   /// A map of scalar integer values to the smallest bit width with which they
3215   /// can legally be represented. The values map to (width, signed) pairs,
3216   /// where "width" indicates the minimum bit width and "signed" is True if the
3217   /// value must be signed-extended, rather than zero-extended, back to its
3218   /// original width.
3219   MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
3220 };
3221 
3222 } // end namespace slpvectorizer
3223 
3224 template <> struct GraphTraits<BoUpSLP *> {
3225   using TreeEntry = BoUpSLP::TreeEntry;
3226 
3227   /// NodeRef has to be a pointer per the GraphWriter.
3228   using NodeRef = TreeEntry *;
3229 
3230   using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy;
3231 
3232   /// Add the VectorizableTree to the index iterator to be able to return
3233   /// TreeEntry pointers.
3234   struct ChildIteratorType
3235       : public iterator_adaptor_base<
3236             ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
3237     ContainerTy &VectorizableTree;
3238 
3239     ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W,
3240                       ContainerTy &VT)
3241         : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
3242 
3243     NodeRef operator*() { return I->UserTE; }
3244   };
3245 
3246   static NodeRef getEntryNode(BoUpSLP &R) {
3247     return R.VectorizableTree[0].get();
3248   }
3249 
3250   static ChildIteratorType child_begin(NodeRef N) {
3251     return {N->UserTreeIndices.begin(), N->Container};
3252   }
3253 
3254   static ChildIteratorType child_end(NodeRef N) {
3255     return {N->UserTreeIndices.end(), N->Container};
3256   }
3257 
3258   /// For the node iterator we just need to turn the TreeEntry iterator into a
3259   /// TreeEntry* iterator so that it dereferences to NodeRef.
3260   class nodes_iterator {
3261     using ItTy = ContainerTy::iterator;
3262     ItTy It;
3263 
3264   public:
3265     nodes_iterator(const ItTy &It2) : It(It2) {}
3266     NodeRef operator*() { return It->get(); }
3267     nodes_iterator operator++() {
3268       ++It;
3269       return *this;
3270     }
3271     bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
3272   };
3273 
3274   static nodes_iterator nodes_begin(BoUpSLP *R) {
3275     return nodes_iterator(R->VectorizableTree.begin());
3276   }
3277 
3278   static nodes_iterator nodes_end(BoUpSLP *R) {
3279     return nodes_iterator(R->VectorizableTree.end());
3280   }
3281 
3282   static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
3283 };
3284 
3285 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
3286   using TreeEntry = BoUpSLP::TreeEntry;
3287 
3288   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
3289 
3290   std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
3291     std::string Str;
3292     raw_string_ostream OS(Str);
3293     if (isSplat(Entry->Scalars))
3294       OS << "<splat> ";
3295     for (auto V : Entry->Scalars) {
3296       OS << *V;
3297       if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) {
3298             return EU.Scalar == V;
3299           }))
3300         OS << " <extract>";
3301       OS << "\n";
3302     }
3303     return Str;
3304   }
3305 
3306   static std::string getNodeAttributes(const TreeEntry *Entry,
3307                                        const BoUpSLP *) {
3308     if (Entry->State == TreeEntry::NeedToGather)
3309       return "color=red";
3310     return "";
3311   }
3312 };
3313 
3314 } // end namespace llvm
3315 
3316 BoUpSLP::~BoUpSLP() {
3317   SmallVector<WeakTrackingVH> DeadInsts;
3318   for (auto *I : DeletedInstructions) {
3319     for (Use &U : I->operands()) {
3320       auto *Op = dyn_cast<Instruction>(U.get());
3321       if (Op && !DeletedInstructions.count(Op) && Op->hasOneUser() &&
3322           wouldInstructionBeTriviallyDead(Op, TLI))
3323         DeadInsts.emplace_back(Op);
3324     }
3325     I->dropAllReferences();
3326   }
3327   for (auto *I : DeletedInstructions) {
3328     assert(I->use_empty() &&
3329            "trying to erase instruction with users.");
3330     I->eraseFromParent();
3331   }
3332 
3333   // Cleanup any dead scalar code feeding the vectorized instructions
3334   RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI);
3335 
3336 #ifdef EXPENSIVE_CHECKS
3337   // If we could guarantee that this call is not extremely slow, we could
3338   // remove the ifdef limitation (see PR47712).
3339   assert(!verifyFunction(*F, &dbgs()));
3340 #endif
3341 }
3342 
3343 /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses
3344 /// contains original mask for the scalars reused in the node. Procedure
3345 /// transform this mask in accordance with the given \p Mask.
3346 static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) {
3347   assert(!Mask.empty() && Reuses.size() == Mask.size() &&
3348          "Expected non-empty mask.");
3349   SmallVector<int> Prev(Reuses.begin(), Reuses.end());
3350   Prev.swap(Reuses);
3351   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
3352     if (Mask[I] != UndefMaskElem)
3353       Reuses[Mask[I]] = Prev[I];
3354 }
3355 
3356 /// Reorders the given \p Order according to the given \p Mask. \p Order - is
3357 /// the original order of the scalars. Procedure transforms the provided order
3358 /// in accordance with the given \p Mask. If the resulting \p Order is just an
3359 /// identity order, \p Order is cleared.
3360 static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) {
3361   assert(!Mask.empty() && "Expected non-empty mask.");
3362   SmallVector<int> MaskOrder;
3363   if (Order.empty()) {
3364     MaskOrder.resize(Mask.size());
3365     std::iota(MaskOrder.begin(), MaskOrder.end(), 0);
3366   } else {
3367     inversePermutation(Order, MaskOrder);
3368   }
3369   reorderReuses(MaskOrder, Mask);
3370   if (ShuffleVectorInst::isIdentityMask(MaskOrder)) {
3371     Order.clear();
3372     return;
3373   }
3374   Order.assign(Mask.size(), Mask.size());
3375   for (unsigned I = 0, E = Mask.size(); I < E; ++I)
3376     if (MaskOrder[I] != UndefMaskElem)
3377       Order[MaskOrder[I]] = I;
3378   fixupOrderingIndices(Order);
3379 }
3380 
3381 Optional<BoUpSLP::OrdersType>
3382 BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) {
3383   assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
3384   unsigned NumScalars = TE.Scalars.size();
3385   OrdersType CurrentOrder(NumScalars, NumScalars);
3386   SmallVector<int> Positions;
3387   SmallBitVector UsedPositions(NumScalars);
3388   const TreeEntry *STE = nullptr;
3389   // Try to find all gathered scalars that are gets vectorized in other
3390   // vectorize node. Here we can have only one single tree vector node to
3391   // correctly identify order of the gathered scalars.
3392   for (unsigned I = 0; I < NumScalars; ++I) {
3393     Value *V = TE.Scalars[I];
3394     if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V))
3395       continue;
3396     if (const auto *LocalSTE = getTreeEntry(V)) {
3397       if (!STE)
3398         STE = LocalSTE;
3399       else if (STE != LocalSTE)
3400         // Take the order only from the single vector node.
3401         return None;
3402       unsigned Lane =
3403           std::distance(STE->Scalars.begin(), find(STE->Scalars, V));
3404       if (Lane >= NumScalars)
3405         return None;
3406       if (CurrentOrder[Lane] != NumScalars) {
3407         if (Lane != I)
3408           continue;
3409         UsedPositions.reset(CurrentOrder[Lane]);
3410       }
3411       // The partial identity (where only some elements of the gather node are
3412       // in the identity order) is good.
3413       CurrentOrder[Lane] = I;
3414       UsedPositions.set(I);
3415     }
3416   }
3417   // Need to keep the order if we have a vector entry and at least 2 scalars or
3418   // the vectorized entry has just 2 scalars.
3419   if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) {
3420     auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) {
3421       for (unsigned I = 0; I < NumScalars; ++I)
3422         if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars)
3423           return false;
3424       return true;
3425     };
3426     if (IsIdentityOrder(CurrentOrder)) {
3427       CurrentOrder.clear();
3428       return CurrentOrder;
3429     }
3430     auto *It = CurrentOrder.begin();
3431     for (unsigned I = 0; I < NumScalars;) {
3432       if (UsedPositions.test(I)) {
3433         ++I;
3434         continue;
3435       }
3436       if (*It == NumScalars) {
3437         *It = I;
3438         ++I;
3439       }
3440       ++It;
3441     }
3442     return CurrentOrder;
3443   }
3444   return None;
3445 }
3446 
3447 bool clusterSortPtrAccesses(ArrayRef<Value *> VL, Type *ElemTy,
3448                             const DataLayout &DL, ScalarEvolution &SE,
3449                             SmallVectorImpl<unsigned> &SortedIndices) {
3450   assert(llvm::all_of(
3451              VL, [](const Value *V) { return V->getType()->isPointerTy(); }) &&
3452          "Expected list of pointer operands.");
3453   // Map from bases to a vector of (Ptr, Offset, OrigIdx), which we insert each
3454   // Ptr into, sort and return the sorted indices with values next to one
3455   // another.
3456   MapVector<Value *, SmallVector<std::tuple<Value *, int, unsigned>>> Bases;
3457   Bases[VL[0]].push_back(std::make_tuple(VL[0], 0U, 0U));
3458 
3459   unsigned Cnt = 1;
3460   for (Value *Ptr : VL.drop_front()) {
3461     bool Found = any_of(Bases, [&](auto &Base) {
3462       Optional<int> Diff =
3463           getPointersDiff(ElemTy, Base.first, ElemTy, Ptr, DL, SE,
3464                           /*StrictCheck=*/true);
3465       if (!Diff)
3466         return false;
3467 
3468       Base.second.emplace_back(Ptr, *Diff, Cnt++);
3469       return true;
3470     });
3471 
3472     if (!Found) {
3473       // If we haven't found enough to usefully cluster, return early.
3474       if (Bases.size() > VL.size() / 2 - 1)
3475         return false;
3476 
3477       // Not found already - add a new Base
3478       Bases[Ptr].emplace_back(Ptr, 0, Cnt++);
3479     }
3480   }
3481 
3482   // For each of the bases sort the pointers by Offset and check if any of the
3483   // base become consecutively allocated.
3484   bool AnyConsecutive = false;
3485   for (auto &Base : Bases) {
3486     auto &Vec = Base.second;
3487     if (Vec.size() > 1) {
3488       llvm::stable_sort(Vec, [](const std::tuple<Value *, int, unsigned> &X,
3489                                 const std::tuple<Value *, int, unsigned> &Y) {
3490         return std::get<1>(X) < std::get<1>(Y);
3491       });
3492       int InitialOffset = std::get<1>(Vec[0]);
3493       AnyConsecutive |= all_of(enumerate(Vec), [InitialOffset](auto &P) {
3494         return std::get<1>(P.value()) == int(P.index()) + InitialOffset;
3495       });
3496     }
3497   }
3498 
3499   // Fill SortedIndices array only if it looks worth-while to sort the ptrs.
3500   SortedIndices.clear();
3501   if (!AnyConsecutive)
3502     return false;
3503 
3504   for (auto &Base : Bases) {
3505     for (auto &T : Base.second)
3506       SortedIndices.push_back(std::get<2>(T));
3507   }
3508 
3509   assert(SortedIndices.size() == VL.size() &&
3510          "Expected SortedIndices to be the size of VL");
3511   return true;
3512 }
3513 
3514 Optional<BoUpSLP::OrdersType>
3515 BoUpSLP::findPartiallyOrderedLoads(const BoUpSLP::TreeEntry &TE) {
3516   assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
3517   Type *ScalarTy = TE.Scalars[0]->getType();
3518 
3519   SmallVector<Value *> Ptrs;
3520   Ptrs.reserve(TE.Scalars.size());
3521   for (Value *V : TE.Scalars) {
3522     auto *L = dyn_cast<LoadInst>(V);
3523     if (!L || !L->isSimple())
3524       return None;
3525     Ptrs.push_back(L->getPointerOperand());
3526   }
3527 
3528   BoUpSLP::OrdersType Order;
3529   if (clusterSortPtrAccesses(Ptrs, ScalarTy, *DL, *SE, Order))
3530     return Order;
3531   return None;
3532 }
3533 
3534 Optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE,
3535                                                          bool TopToBottom) {
3536   // No need to reorder if need to shuffle reuses, still need to shuffle the
3537   // node.
3538   if (!TE.ReuseShuffleIndices.empty())
3539     return None;
3540   if (TE.State == TreeEntry::Vectorize &&
3541       (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) ||
3542        (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) &&
3543       !TE.isAltShuffle())
3544     return TE.ReorderIndices;
3545   if (TE.State == TreeEntry::NeedToGather) {
3546     // TODO: add analysis of other gather nodes with extractelement
3547     // instructions and other values/instructions, not only undefs.
3548     if (((TE.getOpcode() == Instruction::ExtractElement &&
3549           !TE.isAltShuffle()) ||
3550          (all_of(TE.Scalars,
3551                  [](Value *V) {
3552                    return isa<UndefValue, ExtractElementInst>(V);
3553                  }) &&
3554           any_of(TE.Scalars,
3555                  [](Value *V) { return isa<ExtractElementInst>(V); }))) &&
3556         all_of(TE.Scalars,
3557                [](Value *V) {
3558                  auto *EE = dyn_cast<ExtractElementInst>(V);
3559                  return !EE || isa<FixedVectorType>(EE->getVectorOperandType());
3560                }) &&
3561         allSameType(TE.Scalars)) {
3562       // Check that gather of extractelements can be represented as
3563       // just a shuffle of a single vector.
3564       OrdersType CurrentOrder;
3565       bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder);
3566       if (Reuse || !CurrentOrder.empty()) {
3567         if (!CurrentOrder.empty())
3568           fixupOrderingIndices(CurrentOrder);
3569         return CurrentOrder;
3570       }
3571     }
3572     if (Optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE))
3573       return CurrentOrder;
3574     if (TE.Scalars.size() >= 4)
3575       if (Optional<OrdersType> Order = findPartiallyOrderedLoads(TE))
3576         return Order;
3577   }
3578   return None;
3579 }
3580 
3581 void BoUpSLP::reorderTopToBottom() {
3582   // Maps VF to the graph nodes.
3583   DenseMap<unsigned, SetVector<TreeEntry *>> VFToOrderedEntries;
3584   // ExtractElement gather nodes which can be vectorized and need to handle
3585   // their ordering.
3586   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3587   // Find all reorderable nodes with the given VF.
3588   // Currently the are vectorized stores,loads,extracts + some gathering of
3589   // extracts.
3590   for_each(VectorizableTree, [this, &VFToOrderedEntries, &GathersToOrders](
3591                                  const std::unique_ptr<TreeEntry> &TE) {
3592     if (Optional<OrdersType> CurrentOrder =
3593             getReorderingData(*TE, /*TopToBottom=*/true)) {
3594       // Do not include ordering for nodes used in the alt opcode vectorization,
3595       // better to reorder them during bottom-to-top stage. If follow the order
3596       // here, it causes reordering of the whole graph though actually it is
3597       // profitable just to reorder the subgraph that starts from the alternate
3598       // opcode vectorization node. Such nodes already end-up with the shuffle
3599       // instruction and it is just enough to change this shuffle rather than
3600       // rotate the scalars for the whole graph.
3601       unsigned Cnt = 0;
3602       const TreeEntry *UserTE = TE.get();
3603       while (UserTE && Cnt < RecursionMaxDepth) {
3604         if (UserTE->UserTreeIndices.size() != 1)
3605           break;
3606         if (all_of(UserTE->UserTreeIndices, [](const EdgeInfo &EI) {
3607               return EI.UserTE->State == TreeEntry::Vectorize &&
3608                      EI.UserTE->isAltShuffle() && EI.UserTE->Idx != 0;
3609             }))
3610           return;
3611         if (UserTE->UserTreeIndices.empty())
3612           UserTE = nullptr;
3613         else
3614           UserTE = UserTE->UserTreeIndices.back().UserTE;
3615         ++Cnt;
3616       }
3617       VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
3618       if (TE->State != TreeEntry::Vectorize)
3619         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3620     }
3621   });
3622 
3623   // Reorder the graph nodes according to their vectorization factor.
3624   for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1;
3625        VF /= 2) {
3626     auto It = VFToOrderedEntries.find(VF);
3627     if (It == VFToOrderedEntries.end())
3628       continue;
3629     // Try to find the most profitable order. We just are looking for the most
3630     // used order and reorder scalar elements in the nodes according to this
3631     // mostly used order.
3632     ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef();
3633     // All operands are reordered and used only in this node - propagate the
3634     // most used order to the user node.
3635     MapVector<OrdersType, unsigned,
3636               DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3637         OrdersUses;
3638     SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3639     for (const TreeEntry *OpTE : OrderedEntries) {
3640       // No need to reorder this nodes, still need to extend and to use shuffle,
3641       // just need to merge reordering shuffle and the reuse shuffle.
3642       if (!OpTE->ReuseShuffleIndices.empty())
3643         continue;
3644       // Count number of orders uses.
3645       const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3646         if (OpTE->State == TreeEntry::NeedToGather)
3647           return GathersToOrders.find(OpTE)->second;
3648         return OpTE->ReorderIndices;
3649       }();
3650       // Stores actually store the mask, not the order, need to invert.
3651       if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3652           OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3653         SmallVector<int> Mask;
3654         inversePermutation(Order, Mask);
3655         unsigned E = Order.size();
3656         OrdersType CurrentOrder(E, E);
3657         transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3658           return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3659         });
3660         fixupOrderingIndices(CurrentOrder);
3661         ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
3662       } else {
3663         ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
3664       }
3665     }
3666     // Set order of the user node.
3667     if (OrdersUses.empty())
3668       continue;
3669     // Choose the most used order.
3670     ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3671     unsigned Cnt = OrdersUses.front().second;
3672     for (const auto &Pair : drop_begin(OrdersUses)) {
3673       if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3674         BestOrder = Pair.first;
3675         Cnt = Pair.second;
3676       }
3677     }
3678     // Set order of the user node.
3679     if (BestOrder.empty())
3680       continue;
3681     SmallVector<int> Mask;
3682     inversePermutation(BestOrder, Mask);
3683     SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3684     unsigned E = BestOrder.size();
3685     transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3686       return I < E ? static_cast<int>(I) : UndefMaskElem;
3687     });
3688     // Do an actual reordering, if profitable.
3689     for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
3690       // Just do the reordering for the nodes with the given VF.
3691       if (TE->Scalars.size() != VF) {
3692         if (TE->ReuseShuffleIndices.size() == VF) {
3693           // Need to reorder the reuses masks of the operands with smaller VF to
3694           // be able to find the match between the graph nodes and scalar
3695           // operands of the given node during vectorization/cost estimation.
3696           assert(all_of(TE->UserTreeIndices,
3697                         [VF, &TE](const EdgeInfo &EI) {
3698                           return EI.UserTE->Scalars.size() == VF ||
3699                                  EI.UserTE->Scalars.size() ==
3700                                      TE->Scalars.size();
3701                         }) &&
3702                  "All users must be of VF size.");
3703           // Update ordering of the operands with the smaller VF than the given
3704           // one.
3705           reorderReuses(TE->ReuseShuffleIndices, Mask);
3706         }
3707         continue;
3708       }
3709       if (TE->State == TreeEntry::Vectorize &&
3710           isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst,
3711               InsertElementInst>(TE->getMainOp()) &&
3712           !TE->isAltShuffle()) {
3713         // Build correct orders for extract{element,value}, loads and
3714         // stores.
3715         reorderOrder(TE->ReorderIndices, Mask);
3716         if (isa<InsertElementInst, StoreInst>(TE->getMainOp()))
3717           TE->reorderOperands(Mask);
3718       } else {
3719         // Reorder the node and its operands.
3720         TE->reorderOperands(Mask);
3721         assert(TE->ReorderIndices.empty() &&
3722                "Expected empty reorder sequence.");
3723         reorderScalars(TE->Scalars, Mask);
3724       }
3725       if (!TE->ReuseShuffleIndices.empty()) {
3726         // Apply reversed order to keep the original ordering of the reused
3727         // elements to avoid extra reorder indices shuffling.
3728         OrdersType CurrentOrder;
3729         reorderOrder(CurrentOrder, MaskOrder);
3730         SmallVector<int> NewReuses;
3731         inversePermutation(CurrentOrder, NewReuses);
3732         addMask(NewReuses, TE->ReuseShuffleIndices);
3733         TE->ReuseShuffleIndices.swap(NewReuses);
3734       }
3735     }
3736   }
3737 }
3738 
3739 bool BoUpSLP::canReorderOperands(
3740     TreeEntry *UserTE, SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
3741     ArrayRef<TreeEntry *> ReorderableGathers,
3742     SmallVectorImpl<TreeEntry *> &GatherOps) {
3743   for (unsigned I = 0, E = UserTE->getNumOperands(); I < E; ++I) {
3744     if (any_of(Edges, [I](const std::pair<unsigned, TreeEntry *> &OpData) {
3745           return OpData.first == I &&
3746                  OpData.second->State == TreeEntry::Vectorize;
3747         }))
3748       continue;
3749     if (TreeEntry *TE = getVectorizedOperand(UserTE, I)) {
3750       // Do not reorder if operand node is used by many user nodes.
3751       if (any_of(TE->UserTreeIndices,
3752                  [UserTE](const EdgeInfo &EI) { return EI.UserTE != UserTE; }))
3753         return false;
3754       // Add the node to the list of the ordered nodes with the identity
3755       // order.
3756       Edges.emplace_back(I, TE);
3757       continue;
3758     }
3759     ArrayRef<Value *> VL = UserTE->getOperand(I);
3760     TreeEntry *Gather = nullptr;
3761     if (count_if(ReorderableGathers, [VL, &Gather](TreeEntry *TE) {
3762           assert(TE->State != TreeEntry::Vectorize &&
3763                  "Only non-vectorized nodes are expected.");
3764           if (TE->isSame(VL)) {
3765             Gather = TE;
3766             return true;
3767           }
3768           return false;
3769         }) > 1)
3770       return false;
3771     if (Gather)
3772       GatherOps.push_back(Gather);
3773   }
3774   return true;
3775 }
3776 
3777 void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) {
3778   SetVector<TreeEntry *> OrderedEntries;
3779   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3780   // Find all reorderable leaf nodes with the given VF.
3781   // Currently the are vectorized loads,extracts without alternate operands +
3782   // some gathering of extracts.
3783   SmallVector<TreeEntry *> NonVectorized;
3784   for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders,
3785                               &NonVectorized](
3786                                  const std::unique_ptr<TreeEntry> &TE) {
3787     if (TE->State != TreeEntry::Vectorize)
3788       NonVectorized.push_back(TE.get());
3789     if (Optional<OrdersType> CurrentOrder =
3790             getReorderingData(*TE, /*TopToBottom=*/false)) {
3791       OrderedEntries.insert(TE.get());
3792       if (TE->State != TreeEntry::Vectorize)
3793         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3794     }
3795   });
3796 
3797   // 1. Propagate order to the graph nodes, which use only reordered nodes.
3798   // I.e., if the node has operands, that are reordered, try to make at least
3799   // one operand order in the natural order and reorder others + reorder the
3800   // user node itself.
3801   SmallPtrSet<const TreeEntry *, 4> Visited;
3802   while (!OrderedEntries.empty()) {
3803     // 1. Filter out only reordered nodes.
3804     // 2. If the entry has multiple uses - skip it and jump to the next node.
3805     MapVector<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users;
3806     SmallVector<TreeEntry *> Filtered;
3807     for (TreeEntry *TE : OrderedEntries) {
3808       if (!(TE->State == TreeEntry::Vectorize ||
3809             (TE->State == TreeEntry::NeedToGather &&
3810              GathersToOrders.count(TE))) ||
3811           TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3812           !all_of(drop_begin(TE->UserTreeIndices),
3813                   [TE](const EdgeInfo &EI) {
3814                     return EI.UserTE == TE->UserTreeIndices.front().UserTE;
3815                   }) ||
3816           !Visited.insert(TE).second) {
3817         Filtered.push_back(TE);
3818         continue;
3819       }
3820       // Build a map between user nodes and their operands order to speedup
3821       // search. The graph currently does not provide this dependency directly.
3822       for (EdgeInfo &EI : TE->UserTreeIndices) {
3823         TreeEntry *UserTE = EI.UserTE;
3824         auto It = Users.find(UserTE);
3825         if (It == Users.end())
3826           It = Users.insert({UserTE, {}}).first;
3827         It->second.emplace_back(EI.EdgeIdx, TE);
3828       }
3829     }
3830     // Erase filtered entries.
3831     for_each(Filtered,
3832              [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); });
3833     for (auto &Data : Users) {
3834       // Check that operands are used only in the User node.
3835       SmallVector<TreeEntry *> GatherOps;
3836       if (!canReorderOperands(Data.first, Data.second, NonVectorized,
3837                               GatherOps)) {
3838         for_each(Data.second,
3839                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3840                    OrderedEntries.remove(Op.second);
3841                  });
3842         continue;
3843       }
3844       // All operands are reordered and used only in this node - propagate the
3845       // most used order to the user node.
3846       MapVector<OrdersType, unsigned,
3847                 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3848           OrdersUses;
3849       // Do the analysis for each tree entry only once, otherwise the order of
3850       // the same node my be considered several times, though might be not
3851       // profitable.
3852       SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3853       SmallPtrSet<const TreeEntry *, 4> VisitedUsers;
3854       for (const auto &Op : Data.second) {
3855         TreeEntry *OpTE = Op.second;
3856         if (!VisitedOps.insert(OpTE).second)
3857           continue;
3858         if (!OpTE->ReuseShuffleIndices.empty() ||
3859             (IgnoreReorder && OpTE == VectorizableTree.front().get()))
3860           continue;
3861         const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3862           if (OpTE->State == TreeEntry::NeedToGather)
3863             return GathersToOrders.find(OpTE)->second;
3864           return OpTE->ReorderIndices;
3865         }();
3866         unsigned NumOps = count_if(
3867             Data.second, [OpTE](const std::pair<unsigned, TreeEntry *> &P) {
3868               return P.second == OpTE;
3869             });
3870         // Stores actually store the mask, not the order, need to invert.
3871         if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3872             OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3873           SmallVector<int> Mask;
3874           inversePermutation(Order, Mask);
3875           unsigned E = Order.size();
3876           OrdersType CurrentOrder(E, E);
3877           transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3878             return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3879           });
3880           fixupOrderingIndices(CurrentOrder);
3881           OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second +=
3882               NumOps;
3883         } else {
3884           OrdersUses.insert(std::make_pair(Order, 0)).first->second += NumOps;
3885         }
3886         auto Res = OrdersUses.insert(std::make_pair(OrdersType(), 0));
3887         const auto &&AllowsReordering = [IgnoreReorder, &GathersToOrders](
3888                                             const TreeEntry *TE) {
3889           if (!TE->ReorderIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3890               (TE->State == TreeEntry::Vectorize && TE->isAltShuffle()) ||
3891               (IgnoreReorder && TE->Idx == 0))
3892             return true;
3893           if (TE->State == TreeEntry::NeedToGather) {
3894             auto It = GathersToOrders.find(TE);
3895             if (It != GathersToOrders.end())
3896               return !It->second.empty();
3897             return true;
3898           }
3899           return false;
3900         };
3901         for (const EdgeInfo &EI : OpTE->UserTreeIndices) {
3902           TreeEntry *UserTE = EI.UserTE;
3903           if (!VisitedUsers.insert(UserTE).second)
3904             continue;
3905           // May reorder user node if it requires reordering, has reused
3906           // scalars, is an alternate op vectorize node or its op nodes require
3907           // reordering.
3908           if (AllowsReordering(UserTE))
3909             continue;
3910           // Check if users allow reordering.
3911           // Currently look up just 1 level of operands to avoid increase of
3912           // the compile time.
3913           // Profitable to reorder if definitely more operands allow
3914           // reordering rather than those with natural order.
3915           ArrayRef<std::pair<unsigned, TreeEntry *>> Ops = Users[UserTE];
3916           if (static_cast<unsigned>(count_if(
3917                   Ops, [UserTE, &AllowsReordering](
3918                            const std::pair<unsigned, TreeEntry *> &Op) {
3919                     return AllowsReordering(Op.second) &&
3920                            all_of(Op.second->UserTreeIndices,
3921                                   [UserTE](const EdgeInfo &EI) {
3922                                     return EI.UserTE == UserTE;
3923                                   });
3924                   })) <= Ops.size() / 2)
3925             ++Res.first->second;
3926         }
3927       }
3928       // If no orders - skip current nodes and jump to the next one, if any.
3929       if (OrdersUses.empty()) {
3930         for_each(Data.second,
3931                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3932                    OrderedEntries.remove(Op.second);
3933                  });
3934         continue;
3935       }
3936       // Choose the best order.
3937       ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3938       unsigned Cnt = OrdersUses.front().second;
3939       for (const auto &Pair : drop_begin(OrdersUses)) {
3940         if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3941           BestOrder = Pair.first;
3942           Cnt = Pair.second;
3943         }
3944       }
3945       // Set order of the user node (reordering of operands and user nodes).
3946       if (BestOrder.empty()) {
3947         for_each(Data.second,
3948                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3949                    OrderedEntries.remove(Op.second);
3950                  });
3951         continue;
3952       }
3953       // Erase operands from OrderedEntries list and adjust their orders.
3954       VisitedOps.clear();
3955       SmallVector<int> Mask;
3956       inversePermutation(BestOrder, Mask);
3957       SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3958       unsigned E = BestOrder.size();
3959       transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3960         return I < E ? static_cast<int>(I) : UndefMaskElem;
3961       });
3962       for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) {
3963         TreeEntry *TE = Op.second;
3964         OrderedEntries.remove(TE);
3965         if (!VisitedOps.insert(TE).second)
3966           continue;
3967         if (TE->ReuseShuffleIndices.size() == BestOrder.size()) {
3968           // Just reorder reuses indices.
3969           reorderReuses(TE->ReuseShuffleIndices, Mask);
3970           continue;
3971         }
3972         // Gathers are processed separately.
3973         if (TE->State != TreeEntry::Vectorize)
3974           continue;
3975         assert((BestOrder.size() == TE->ReorderIndices.size() ||
3976                 TE->ReorderIndices.empty()) &&
3977                "Non-matching sizes of user/operand entries.");
3978         reorderOrder(TE->ReorderIndices, Mask);
3979       }
3980       // For gathers just need to reorder its scalars.
3981       for (TreeEntry *Gather : GatherOps) {
3982         assert(Gather->ReorderIndices.empty() &&
3983                "Unexpected reordering of gathers.");
3984         if (!Gather->ReuseShuffleIndices.empty()) {
3985           // Just reorder reuses indices.
3986           reorderReuses(Gather->ReuseShuffleIndices, Mask);
3987           continue;
3988         }
3989         reorderScalars(Gather->Scalars, Mask);
3990         OrderedEntries.remove(Gather);
3991       }
3992       // Reorder operands of the user node and set the ordering for the user
3993       // node itself.
3994       if (Data.first->State != TreeEntry::Vectorize ||
3995           !isa<ExtractElementInst, ExtractValueInst, LoadInst>(
3996               Data.first->getMainOp()) ||
3997           Data.first->isAltShuffle())
3998         Data.first->reorderOperands(Mask);
3999       if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) ||
4000           Data.first->isAltShuffle()) {
4001         reorderScalars(Data.first->Scalars, Mask);
4002         reorderOrder(Data.first->ReorderIndices, MaskOrder);
4003         if (Data.first->ReuseShuffleIndices.empty() &&
4004             !Data.first->ReorderIndices.empty() &&
4005             !Data.first->isAltShuffle()) {
4006           // Insert user node to the list to try to sink reordering deeper in
4007           // the graph.
4008           OrderedEntries.insert(Data.first);
4009         }
4010       } else {
4011         reorderOrder(Data.first->ReorderIndices, Mask);
4012       }
4013     }
4014   }
4015   // If the reordering is unnecessary, just remove the reorder.
4016   if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() &&
4017       VectorizableTree.front()->ReuseShuffleIndices.empty())
4018     VectorizableTree.front()->ReorderIndices.clear();
4019 }
4020 
4021 void BoUpSLP::buildExternalUses(
4022     const ExtraValueToDebugLocsMap &ExternallyUsedValues) {
4023   // Collect the values that we need to extract from the tree.
4024   for (auto &TEPtr : VectorizableTree) {
4025     TreeEntry *Entry = TEPtr.get();
4026 
4027     // No need to handle users of gathered values.
4028     if (Entry->State == TreeEntry::NeedToGather)
4029       continue;
4030 
4031     // For each lane:
4032     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
4033       Value *Scalar = Entry->Scalars[Lane];
4034       int FoundLane = Entry->findLaneForValue(Scalar);
4035 
4036       // Check if the scalar is externally used as an extra arg.
4037       auto ExtI = ExternallyUsedValues.find(Scalar);
4038       if (ExtI != ExternallyUsedValues.end()) {
4039         LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
4040                           << Lane << " from " << *Scalar << ".\n");
4041         ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
4042       }
4043       for (User *U : Scalar->users()) {
4044         LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
4045 
4046         Instruction *UserInst = dyn_cast<Instruction>(U);
4047         if (!UserInst)
4048           continue;
4049 
4050         if (isDeleted(UserInst))
4051           continue;
4052 
4053         // Skip in-tree scalars that become vectors
4054         if (TreeEntry *UseEntry = getTreeEntry(U)) {
4055           Value *UseScalar = UseEntry->Scalars[0];
4056           // Some in-tree scalars will remain as scalar in vectorized
4057           // instructions. If that is the case, the one in Lane 0 will
4058           // be used.
4059           if (UseScalar != U ||
4060               UseEntry->State == TreeEntry::ScatterVectorize ||
4061               !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
4062             LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
4063                               << ".\n");
4064             assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state");
4065             continue;
4066           }
4067         }
4068 
4069         // Ignore users in the user ignore list.
4070         if (is_contained(UserIgnoreList, UserInst))
4071           continue;
4072 
4073         LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
4074                           << Lane << " from " << *Scalar << ".\n");
4075         ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
4076       }
4077     }
4078   }
4079 }
4080 
4081 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
4082                         ArrayRef<Value *> UserIgnoreLst) {
4083   deleteTree();
4084   UserIgnoreList = UserIgnoreLst;
4085   if (!allSameType(Roots))
4086     return;
4087   buildTree_rec(Roots, 0, EdgeInfo());
4088 }
4089 
4090 namespace {
4091 /// Tracks the state we can represent the loads in the given sequence.
4092 enum class LoadsState { Gather, Vectorize, ScatterVectorize };
4093 } // anonymous namespace
4094 
4095 /// Checks if the given array of loads can be represented as a vectorized,
4096 /// scatter or just simple gather.
4097 static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0,
4098                                     const TargetTransformInfo &TTI,
4099                                     const DataLayout &DL, ScalarEvolution &SE,
4100                                     SmallVectorImpl<unsigned> &Order,
4101                                     SmallVectorImpl<Value *> &PointerOps) {
4102   // Check that a vectorized load would load the same memory as a scalar
4103   // load. For example, we don't want to vectorize loads that are smaller
4104   // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
4105   // treats loading/storing it as an i8 struct. If we vectorize loads/stores
4106   // from such a struct, we read/write packed bits disagreeing with the
4107   // unvectorized version.
4108   Type *ScalarTy = VL0->getType();
4109 
4110   if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy))
4111     return LoadsState::Gather;
4112 
4113   // Make sure all loads in the bundle are simple - we can't vectorize
4114   // atomic or volatile loads.
4115   PointerOps.clear();
4116   PointerOps.resize(VL.size());
4117   auto *POIter = PointerOps.begin();
4118   for (Value *V : VL) {
4119     auto *L = cast<LoadInst>(V);
4120     if (!L->isSimple())
4121       return LoadsState::Gather;
4122     *POIter = L->getPointerOperand();
4123     ++POIter;
4124   }
4125 
4126   Order.clear();
4127   // Check the order of pointer operands.
4128   if (llvm::sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order)) {
4129     Value *Ptr0;
4130     Value *PtrN;
4131     if (Order.empty()) {
4132       Ptr0 = PointerOps.front();
4133       PtrN = PointerOps.back();
4134     } else {
4135       Ptr0 = PointerOps[Order.front()];
4136       PtrN = PointerOps[Order.back()];
4137     }
4138     Optional<int> Diff =
4139         getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE);
4140     // Check that the sorted loads are consecutive.
4141     if (static_cast<unsigned>(*Diff) == VL.size() - 1)
4142       return LoadsState::Vectorize;
4143     Align CommonAlignment = cast<LoadInst>(VL0)->getAlign();
4144     for (Value *V : VL)
4145       CommonAlignment =
4146           commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
4147     if (TTI.isLegalMaskedGather(FixedVectorType::get(ScalarTy, VL.size()),
4148                                 CommonAlignment))
4149       return LoadsState::ScatterVectorize;
4150   }
4151 
4152   return LoadsState::Gather;
4153 }
4154 
4155 /// \return true if the specified list of values has only one instruction that
4156 /// requires scheduling, false otherwise.
4157 #ifndef NDEBUG
4158 static bool needToScheduleSingleInstruction(ArrayRef<Value *> VL) {
4159   Value *NeedsScheduling = nullptr;
4160   for (Value *V : VL) {
4161     if (doesNotNeedToBeScheduled(V))
4162       continue;
4163     if (!NeedsScheduling) {
4164       NeedsScheduling = V;
4165       continue;
4166     }
4167     return false;
4168   }
4169   return NeedsScheduling;
4170 }
4171 #endif
4172 
4173 /// Generates key/subkey pair for the given value to provide effective sorting
4174 /// of the values and better detection of the vectorizable values sequences. The
4175 /// keys/subkeys can be used for better sorting of the values themselves (keys)
4176 /// and in values subgroups (subkeys).
4177 static std::pair<size_t, size_t> generateKeySubkey(
4178     Value *V, const TargetLibraryInfo *TLI,
4179     function_ref<hash_code(size_t, LoadInst *)> LoadsSubkeyGenerator,
4180     bool AllowAlternate) {
4181   hash_code Key = hash_value(V->getValueID() + 2);
4182   hash_code SubKey = hash_value(0);
4183   // Sort the loads by the distance between the pointers.
4184   if (auto *LI = dyn_cast<LoadInst>(V)) {
4185     Key = hash_combine(hash_value(Instruction::Load), Key);
4186     if (LI->isSimple())
4187       SubKey = hash_value(LoadsSubkeyGenerator(Key, LI));
4188     else
4189       SubKey = hash_value(LI);
4190   } else if (isVectorLikeInstWithConstOps(V)) {
4191     // Sort extracts by the vector operands.
4192     if (isa<ExtractElementInst, UndefValue>(V))
4193       Key = hash_value(Value::UndefValueVal + 1);
4194     if (auto *EI = dyn_cast<ExtractElementInst>(V)) {
4195       if (!isUndefVector(EI->getVectorOperand()) &&
4196           !isa<UndefValue>(EI->getIndexOperand()))
4197         SubKey = hash_value(EI->getVectorOperand());
4198     }
4199   } else if (auto *I = dyn_cast<Instruction>(V)) {
4200     // Sort other instructions just by the opcodes except for CMPInst.
4201     // For CMP also sort by the predicate kind.
4202     if ((isa<BinaryOperator>(I) || isa<CastInst>(I)) &&
4203         isValidForAlternation(I->getOpcode())) {
4204       if (AllowAlternate)
4205         Key = hash_value(isa<BinaryOperator>(I) ? 1 : 0);
4206       else
4207         Key = hash_combine(hash_value(I->getOpcode()), Key);
4208       SubKey = hash_combine(
4209           hash_value(I->getOpcode()), hash_value(I->getType()),
4210           hash_value(isa<BinaryOperator>(I)
4211                          ? I->getType()
4212                          : cast<CastInst>(I)->getOperand(0)->getType()));
4213     } else if (auto *CI = dyn_cast<CmpInst>(I)) {
4214       CmpInst::Predicate Pred = CI->getPredicate();
4215       if (CI->isCommutative())
4216         Pred = std::min(Pred, CmpInst::getInversePredicate(Pred));
4217       CmpInst::Predicate SwapPred = CmpInst::getSwappedPredicate(Pred);
4218       SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(Pred),
4219                             hash_value(SwapPred),
4220                             hash_value(CI->getOperand(0)->getType()));
4221     } else if (auto *Call = dyn_cast<CallInst>(I)) {
4222       Intrinsic::ID ID = getVectorIntrinsicIDForCall(Call, TLI);
4223       if (isTriviallyVectorizable(ID))
4224         SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(ID));
4225       else if (!VFDatabase(*Call).getMappings(*Call).empty())
4226         SubKey = hash_combine(hash_value(I->getOpcode()),
4227                               hash_value(Call->getCalledFunction()));
4228       else
4229         SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(Call));
4230       for (const CallBase::BundleOpInfo &Op : Call->bundle_op_infos())
4231         SubKey = hash_combine(hash_value(Op.Begin), hash_value(Op.End),
4232                               hash_value(Op.Tag), SubKey);
4233     } else if (auto *Gep = dyn_cast<GetElementPtrInst>(I)) {
4234       if (Gep->getNumOperands() == 2 && isa<ConstantInt>(Gep->getOperand(1)))
4235         SubKey = hash_value(Gep->getPointerOperand());
4236       else
4237         SubKey = hash_value(Gep);
4238     } else if (BinaryOperator::isIntDivRem(I->getOpcode()) &&
4239                !isa<ConstantInt>(I->getOperand(1))) {
4240       // Do not try to vectorize instructions with potentially high cost.
4241       SubKey = hash_value(I);
4242     } else {
4243       SubKey = hash_value(I->getOpcode());
4244     }
4245     Key = hash_combine(hash_value(I->getParent()), Key);
4246   }
4247   return std::make_pair(Key, SubKey);
4248 }
4249 
4250 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
4251                             const EdgeInfo &UserTreeIdx) {
4252   assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
4253 
4254   SmallVector<int> ReuseShuffleIndicies;
4255   SmallVector<Value *> UniqueValues;
4256   auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues,
4257                                 &UserTreeIdx,
4258                                 this](const InstructionsState &S) {
4259     // Check that every instruction appears once in this bundle.
4260     DenseMap<Value *, unsigned> UniquePositions;
4261     for (Value *V : VL) {
4262       if (isConstant(V)) {
4263         ReuseShuffleIndicies.emplace_back(
4264             isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size());
4265         UniqueValues.emplace_back(V);
4266         continue;
4267       }
4268       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
4269       ReuseShuffleIndicies.emplace_back(Res.first->second);
4270       if (Res.second)
4271         UniqueValues.emplace_back(V);
4272     }
4273     size_t NumUniqueScalarValues = UniqueValues.size();
4274     if (NumUniqueScalarValues == VL.size()) {
4275       ReuseShuffleIndicies.clear();
4276     } else {
4277       LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
4278       if (NumUniqueScalarValues <= 1 ||
4279           (UniquePositions.size() == 1 && all_of(UniqueValues,
4280                                                  [](Value *V) {
4281                                                    return isa<UndefValue>(V) ||
4282                                                           !isConstant(V);
4283                                                  })) ||
4284           !llvm::isPowerOf2_32(NumUniqueScalarValues)) {
4285         LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
4286         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4287         return false;
4288       }
4289       VL = UniqueValues;
4290     }
4291     return true;
4292   };
4293 
4294   InstructionsState S = getSameOpcode(VL);
4295   if (Depth == RecursionMaxDepth) {
4296     LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
4297     if (TryToFindDuplicates(S))
4298       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4299                    ReuseShuffleIndicies);
4300     return;
4301   }
4302 
4303   // Don't handle scalable vectors
4304   if (S.getOpcode() == Instruction::ExtractElement &&
4305       isa<ScalableVectorType>(
4306           cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) {
4307     LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n");
4308     if (TryToFindDuplicates(S))
4309       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4310                    ReuseShuffleIndicies);
4311     return;
4312   }
4313 
4314   // Don't handle vectors.
4315   if (S.OpValue->getType()->isVectorTy() &&
4316       !isa<InsertElementInst>(S.OpValue)) {
4317     LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
4318     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4319     return;
4320   }
4321 
4322   if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
4323     if (SI->getValueOperand()->getType()->isVectorTy()) {
4324       LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
4325       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4326       return;
4327     }
4328 
4329   // If all of the operands are identical or constant we have a simple solution.
4330   // If we deal with insert/extract instructions, they all must have constant
4331   // indices, otherwise we should gather them, not try to vectorize.
4332   if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode() ||
4333       (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(S.MainOp) &&
4334        !all_of(VL, isVectorLikeInstWithConstOps))) {
4335     LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
4336     if (TryToFindDuplicates(S))
4337       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4338                    ReuseShuffleIndicies);
4339     return;
4340   }
4341 
4342   // We now know that this is a vector of instructions of the same type from
4343   // the same block.
4344 
4345   // Don't vectorize ephemeral values.
4346   for (Value *V : VL) {
4347     if (EphValues.count(V)) {
4348       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
4349                         << ") is ephemeral.\n");
4350       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4351       return;
4352     }
4353   }
4354 
4355   // Check if this is a duplicate of another entry.
4356   if (TreeEntry *E = getTreeEntry(S.OpValue)) {
4357     LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n");
4358     if (!E->isSame(VL)) {
4359       LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
4360       if (TryToFindDuplicates(S))
4361         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4362                      ReuseShuffleIndicies);
4363       return;
4364     }
4365     // Record the reuse of the tree node.  FIXME, currently this is only used to
4366     // properly draw the graph rather than for the actual vectorization.
4367     E->UserTreeIndices.push_back(UserTreeIdx);
4368     LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue
4369                       << ".\n");
4370     return;
4371   }
4372 
4373   // Check that none of the instructions in the bundle are already in the tree.
4374   for (Value *V : VL) {
4375     auto *I = dyn_cast<Instruction>(V);
4376     if (!I)
4377       continue;
4378     if (getTreeEntry(I)) {
4379       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
4380                         << ") is already in tree.\n");
4381       if (TryToFindDuplicates(S))
4382         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4383                      ReuseShuffleIndicies);
4384       return;
4385     }
4386   }
4387 
4388   // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
4389   for (Value *V : VL) {
4390     if (is_contained(UserIgnoreList, V)) {
4391       LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
4392       if (TryToFindDuplicates(S))
4393         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4394                      ReuseShuffleIndicies);
4395       return;
4396     }
4397   }
4398 
4399   // Check that all of the users of the scalars that we want to vectorize are
4400   // schedulable.
4401   auto *VL0 = cast<Instruction>(S.OpValue);
4402   BasicBlock *BB = VL0->getParent();
4403 
4404   if (!DT->isReachableFromEntry(BB)) {
4405     // Don't go into unreachable blocks. They may contain instructions with
4406     // dependency cycles which confuse the final scheduling.
4407     LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
4408     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4409     return;
4410   }
4411 
4412   // Check that every instruction appears once in this bundle.
4413   if (!TryToFindDuplicates(S))
4414     return;
4415 
4416   auto &BSRef = BlocksSchedules[BB];
4417   if (!BSRef)
4418     BSRef = std::make_unique<BlockScheduling>(BB);
4419 
4420   BlockScheduling &BS = *BSRef;
4421 
4422   Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S);
4423 #ifdef EXPENSIVE_CHECKS
4424   // Make sure we didn't break any internal invariants
4425   BS.verify();
4426 #endif
4427   if (!Bundle) {
4428     LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
4429     assert((!BS.getScheduleData(VL0) ||
4430             !BS.getScheduleData(VL0)->isPartOfBundle()) &&
4431            "tryScheduleBundle should cancelScheduling on failure");
4432     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4433                  ReuseShuffleIndicies);
4434     return;
4435   }
4436   LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
4437 
4438   unsigned ShuffleOrOp = S.isAltShuffle() ?
4439                 (unsigned) Instruction::ShuffleVector : S.getOpcode();
4440   switch (ShuffleOrOp) {
4441     case Instruction::PHI: {
4442       auto *PH = cast<PHINode>(VL0);
4443 
4444       // Check for terminator values (e.g. invoke).
4445       for (Value *V : VL)
4446         for (Value *Incoming : cast<PHINode>(V)->incoming_values()) {
4447           Instruction *Term = dyn_cast<Instruction>(Incoming);
4448           if (Term && Term->isTerminator()) {
4449             LLVM_DEBUG(dbgs()
4450                        << "SLP: Need to swizzle PHINodes (terminator use).\n");
4451             BS.cancelScheduling(VL, VL0);
4452             newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4453                          ReuseShuffleIndicies);
4454             return;
4455           }
4456         }
4457 
4458       TreeEntry *TE =
4459           newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies);
4460       LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
4461 
4462       // Keeps the reordered operands to avoid code duplication.
4463       SmallVector<ValueList, 2> OperandsVec;
4464       for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
4465         if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) {
4466           ValueList Operands(VL.size(), PoisonValue::get(PH->getType()));
4467           TE->setOperand(I, Operands);
4468           OperandsVec.push_back(Operands);
4469           continue;
4470         }
4471         ValueList Operands;
4472         // Prepare the operand vector.
4473         for (Value *V : VL)
4474           Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(
4475               PH->getIncomingBlock(I)));
4476         TE->setOperand(I, Operands);
4477         OperandsVec.push_back(Operands);
4478       }
4479       for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx)
4480         buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx});
4481       return;
4482     }
4483     case Instruction::ExtractValue:
4484     case Instruction::ExtractElement: {
4485       OrdersType CurrentOrder;
4486       bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
4487       if (Reuse) {
4488         LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
4489         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4490                      ReuseShuffleIndicies);
4491         // This is a special case, as it does not gather, but at the same time
4492         // we are not extending buildTree_rec() towards the operands.
4493         ValueList Op0;
4494         Op0.assign(VL.size(), VL0->getOperand(0));
4495         VectorizableTree.back()->setOperand(0, Op0);
4496         return;
4497       }
4498       if (!CurrentOrder.empty()) {
4499         LLVM_DEBUG({
4500           dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
4501                     "with order";
4502           for (unsigned Idx : CurrentOrder)
4503             dbgs() << " " << Idx;
4504           dbgs() << "\n";
4505         });
4506         fixupOrderingIndices(CurrentOrder);
4507         // Insert new order with initial value 0, if it does not exist,
4508         // otherwise return the iterator to the existing one.
4509         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4510                      ReuseShuffleIndicies, CurrentOrder);
4511         // This is a special case, as it does not gather, but at the same time
4512         // we are not extending buildTree_rec() towards the operands.
4513         ValueList Op0;
4514         Op0.assign(VL.size(), VL0->getOperand(0));
4515         VectorizableTree.back()->setOperand(0, Op0);
4516         return;
4517       }
4518       LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
4519       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4520                    ReuseShuffleIndicies);
4521       BS.cancelScheduling(VL, VL0);
4522       return;
4523     }
4524     case Instruction::InsertElement: {
4525       assert(ReuseShuffleIndicies.empty() && "All inserts should be unique");
4526 
4527       // Check that we have a buildvector and not a shuffle of 2 or more
4528       // different vectors.
4529       ValueSet SourceVectors;
4530       for (Value *V : VL) {
4531         SourceVectors.insert(cast<Instruction>(V)->getOperand(0));
4532         assert(getInsertIndex(V) != None && "Non-constant or undef index?");
4533       }
4534 
4535       if (count_if(VL, [&SourceVectors](Value *V) {
4536             return !SourceVectors.contains(V);
4537           }) >= 2) {
4538         // Found 2nd source vector - cancel.
4539         LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with "
4540                              "different source vectors.\n");
4541         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4542         BS.cancelScheduling(VL, VL0);
4543         return;
4544       }
4545 
4546       auto OrdCompare = [](const std::pair<int, int> &P1,
4547                            const std::pair<int, int> &P2) {
4548         return P1.first > P2.first;
4549       };
4550       PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>,
4551                     decltype(OrdCompare)>
4552           Indices(OrdCompare);
4553       for (int I = 0, E = VL.size(); I < E; ++I) {
4554         unsigned Idx = *getInsertIndex(VL[I]);
4555         Indices.emplace(Idx, I);
4556       }
4557       OrdersType CurrentOrder(VL.size(), VL.size());
4558       bool IsIdentity = true;
4559       for (int I = 0, E = VL.size(); I < E; ++I) {
4560         CurrentOrder[Indices.top().second] = I;
4561         IsIdentity &= Indices.top().second == I;
4562         Indices.pop();
4563       }
4564       if (IsIdentity)
4565         CurrentOrder.clear();
4566       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4567                                    None, CurrentOrder);
4568       LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n");
4569 
4570       constexpr int NumOps = 2;
4571       ValueList VectorOperands[NumOps];
4572       for (int I = 0; I < NumOps; ++I) {
4573         for (Value *V : VL)
4574           VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I));
4575 
4576         TE->setOperand(I, VectorOperands[I]);
4577       }
4578       buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1});
4579       return;
4580     }
4581     case Instruction::Load: {
4582       // Check that a vectorized load would load the same memory as a scalar
4583       // load. For example, we don't want to vectorize loads that are smaller
4584       // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
4585       // treats loading/storing it as an i8 struct. If we vectorize loads/stores
4586       // from such a struct, we read/write packed bits disagreeing with the
4587       // unvectorized version.
4588       SmallVector<Value *> PointerOps;
4589       OrdersType CurrentOrder;
4590       TreeEntry *TE = nullptr;
4591       switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, CurrentOrder,
4592                                 PointerOps)) {
4593       case LoadsState::Vectorize:
4594         if (CurrentOrder.empty()) {
4595           // Original loads are consecutive and does not require reordering.
4596           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4597                             ReuseShuffleIndicies);
4598           LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
4599         } else {
4600           fixupOrderingIndices(CurrentOrder);
4601           // Need to reorder.
4602           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4603                             ReuseShuffleIndicies, CurrentOrder);
4604           LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
4605         }
4606         TE->setOperandsInOrder();
4607         break;
4608       case LoadsState::ScatterVectorize:
4609         // Vectorizing non-consecutive loads with `llvm.masked.gather`.
4610         TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S,
4611                           UserTreeIdx, ReuseShuffleIndicies);
4612         TE->setOperandsInOrder();
4613         buildTree_rec(PointerOps, Depth + 1, {TE, 0});
4614         LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n");
4615         break;
4616       case LoadsState::Gather:
4617         BS.cancelScheduling(VL, VL0);
4618         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4619                      ReuseShuffleIndicies);
4620 #ifndef NDEBUG
4621         Type *ScalarTy = VL0->getType();
4622         if (DL->getTypeSizeInBits(ScalarTy) !=
4623             DL->getTypeAllocSizeInBits(ScalarTy))
4624           LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
4625         else if (any_of(VL, [](Value *V) {
4626                    return !cast<LoadInst>(V)->isSimple();
4627                  }))
4628           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
4629         else
4630           LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
4631 #endif // NDEBUG
4632         break;
4633       }
4634       return;
4635     }
4636     case Instruction::ZExt:
4637     case Instruction::SExt:
4638     case Instruction::FPToUI:
4639     case Instruction::FPToSI:
4640     case Instruction::FPExt:
4641     case Instruction::PtrToInt:
4642     case Instruction::IntToPtr:
4643     case Instruction::SIToFP:
4644     case Instruction::UIToFP:
4645     case Instruction::Trunc:
4646     case Instruction::FPTrunc:
4647     case Instruction::BitCast: {
4648       Type *SrcTy = VL0->getOperand(0)->getType();
4649       for (Value *V : VL) {
4650         Type *Ty = cast<Instruction>(V)->getOperand(0)->getType();
4651         if (Ty != SrcTy || !isValidElementType(Ty)) {
4652           BS.cancelScheduling(VL, VL0);
4653           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4654                        ReuseShuffleIndicies);
4655           LLVM_DEBUG(dbgs()
4656                      << "SLP: Gathering casts with different src types.\n");
4657           return;
4658         }
4659       }
4660       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4661                                    ReuseShuffleIndicies);
4662       LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
4663 
4664       TE->setOperandsInOrder();
4665       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4666         ValueList Operands;
4667         // Prepare the operand vector.
4668         for (Value *V : VL)
4669           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4670 
4671         buildTree_rec(Operands, Depth + 1, {TE, i});
4672       }
4673       return;
4674     }
4675     case Instruction::ICmp:
4676     case Instruction::FCmp: {
4677       // Check that all of the compares have the same predicate.
4678       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
4679       CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0);
4680       Type *ComparedTy = VL0->getOperand(0)->getType();
4681       for (Value *V : VL) {
4682         CmpInst *Cmp = cast<CmpInst>(V);
4683         if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) ||
4684             Cmp->getOperand(0)->getType() != ComparedTy) {
4685           BS.cancelScheduling(VL, VL0);
4686           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4687                        ReuseShuffleIndicies);
4688           LLVM_DEBUG(dbgs()
4689                      << "SLP: Gathering cmp with different predicate.\n");
4690           return;
4691         }
4692       }
4693 
4694       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4695                                    ReuseShuffleIndicies);
4696       LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
4697 
4698       ValueList Left, Right;
4699       if (cast<CmpInst>(VL0)->isCommutative()) {
4700         // Commutative predicate - collect + sort operands of the instructions
4701         // so that each side is more likely to have the same opcode.
4702         assert(P0 == SwapP0 && "Commutative Predicate mismatch");
4703         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4704       } else {
4705         // Collect operands - commute if it uses the swapped predicate.
4706         for (Value *V : VL) {
4707           auto *Cmp = cast<CmpInst>(V);
4708           Value *LHS = Cmp->getOperand(0);
4709           Value *RHS = Cmp->getOperand(1);
4710           if (Cmp->getPredicate() != P0)
4711             std::swap(LHS, RHS);
4712           Left.push_back(LHS);
4713           Right.push_back(RHS);
4714         }
4715       }
4716       TE->setOperand(0, Left);
4717       TE->setOperand(1, Right);
4718       buildTree_rec(Left, Depth + 1, {TE, 0});
4719       buildTree_rec(Right, Depth + 1, {TE, 1});
4720       return;
4721     }
4722     case Instruction::Select:
4723     case Instruction::FNeg:
4724     case Instruction::Add:
4725     case Instruction::FAdd:
4726     case Instruction::Sub:
4727     case Instruction::FSub:
4728     case Instruction::Mul:
4729     case Instruction::FMul:
4730     case Instruction::UDiv:
4731     case Instruction::SDiv:
4732     case Instruction::FDiv:
4733     case Instruction::URem:
4734     case Instruction::SRem:
4735     case Instruction::FRem:
4736     case Instruction::Shl:
4737     case Instruction::LShr:
4738     case Instruction::AShr:
4739     case Instruction::And:
4740     case Instruction::Or:
4741     case Instruction::Xor: {
4742       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4743                                    ReuseShuffleIndicies);
4744       LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n");
4745 
4746       // Sort operands of the instructions so that each side is more likely to
4747       // have the same opcode.
4748       if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
4749         ValueList Left, Right;
4750         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4751         TE->setOperand(0, Left);
4752         TE->setOperand(1, Right);
4753         buildTree_rec(Left, Depth + 1, {TE, 0});
4754         buildTree_rec(Right, Depth + 1, {TE, 1});
4755         return;
4756       }
4757 
4758       TE->setOperandsInOrder();
4759       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4760         ValueList Operands;
4761         // Prepare the operand vector.
4762         for (Value *V : VL)
4763           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4764 
4765         buildTree_rec(Operands, Depth + 1, {TE, i});
4766       }
4767       return;
4768     }
4769     case Instruction::GetElementPtr: {
4770       // We don't combine GEPs with complicated (nested) indexing.
4771       for (Value *V : VL) {
4772         if (cast<Instruction>(V)->getNumOperands() != 2) {
4773           LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
4774           BS.cancelScheduling(VL, VL0);
4775           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4776                        ReuseShuffleIndicies);
4777           return;
4778         }
4779       }
4780 
4781       // We can't combine several GEPs into one vector if they operate on
4782       // different types.
4783       Type *Ty0 = cast<GEPOperator>(VL0)->getSourceElementType();
4784       for (Value *V : VL) {
4785         Type *CurTy = cast<GEPOperator>(V)->getSourceElementType();
4786         if (Ty0 != CurTy) {
4787           LLVM_DEBUG(dbgs()
4788                      << "SLP: not-vectorizable GEP (different types).\n");
4789           BS.cancelScheduling(VL, VL0);
4790           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4791                        ReuseShuffleIndicies);
4792           return;
4793         }
4794       }
4795 
4796       // We don't combine GEPs with non-constant indexes.
4797       Type *Ty1 = VL0->getOperand(1)->getType();
4798       for (Value *V : VL) {
4799         auto Op = cast<Instruction>(V)->getOperand(1);
4800         if (!isa<ConstantInt>(Op) ||
4801             (Op->getType() != Ty1 &&
4802              Op->getType()->getScalarSizeInBits() >
4803                  DL->getIndexSizeInBits(
4804                      V->getType()->getPointerAddressSpace()))) {
4805           LLVM_DEBUG(dbgs()
4806                      << "SLP: not-vectorizable GEP (non-constant indexes).\n");
4807           BS.cancelScheduling(VL, VL0);
4808           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4809                        ReuseShuffleIndicies);
4810           return;
4811         }
4812       }
4813 
4814       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4815                                    ReuseShuffleIndicies);
4816       LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
4817       SmallVector<ValueList, 2> Operands(2);
4818       // Prepare the operand vector for pointer operands.
4819       for (Value *V : VL)
4820         Operands.front().push_back(
4821             cast<GetElementPtrInst>(V)->getPointerOperand());
4822       TE->setOperand(0, Operands.front());
4823       // Need to cast all indices to the same type before vectorization to
4824       // avoid crash.
4825       // Required to be able to find correct matches between different gather
4826       // nodes and reuse the vectorized values rather than trying to gather them
4827       // again.
4828       int IndexIdx = 1;
4829       Type *VL0Ty = VL0->getOperand(IndexIdx)->getType();
4830       Type *Ty = all_of(VL,
4831                         [VL0Ty, IndexIdx](Value *V) {
4832                           return VL0Ty == cast<GetElementPtrInst>(V)
4833                                               ->getOperand(IndexIdx)
4834                                               ->getType();
4835                         })
4836                      ? VL0Ty
4837                      : DL->getIndexType(cast<GetElementPtrInst>(VL0)
4838                                             ->getPointerOperandType()
4839                                             ->getScalarType());
4840       // Prepare the operand vector.
4841       for (Value *V : VL) {
4842         auto *Op = cast<Instruction>(V)->getOperand(IndexIdx);
4843         auto *CI = cast<ConstantInt>(Op);
4844         Operands.back().push_back(ConstantExpr::getIntegerCast(
4845             CI, Ty, CI->getValue().isSignBitSet()));
4846       }
4847       TE->setOperand(IndexIdx, Operands.back());
4848 
4849       for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I)
4850         buildTree_rec(Operands[I], Depth + 1, {TE, I});
4851       return;
4852     }
4853     case Instruction::Store: {
4854       // Check if the stores are consecutive or if we need to swizzle them.
4855       llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType();
4856       // Avoid types that are padded when being allocated as scalars, while
4857       // being packed together in a vector (such as i1).
4858       if (DL->getTypeSizeInBits(ScalarTy) !=
4859           DL->getTypeAllocSizeInBits(ScalarTy)) {
4860         BS.cancelScheduling(VL, VL0);
4861         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4862                      ReuseShuffleIndicies);
4863         LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n");
4864         return;
4865       }
4866       // Make sure all stores in the bundle are simple - we can't vectorize
4867       // atomic or volatile stores.
4868       SmallVector<Value *, 4> PointerOps(VL.size());
4869       ValueList Operands(VL.size());
4870       auto POIter = PointerOps.begin();
4871       auto OIter = Operands.begin();
4872       for (Value *V : VL) {
4873         auto *SI = cast<StoreInst>(V);
4874         if (!SI->isSimple()) {
4875           BS.cancelScheduling(VL, VL0);
4876           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4877                        ReuseShuffleIndicies);
4878           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n");
4879           return;
4880         }
4881         *POIter = SI->getPointerOperand();
4882         *OIter = SI->getValueOperand();
4883         ++POIter;
4884         ++OIter;
4885       }
4886 
4887       OrdersType CurrentOrder;
4888       // Check the order of pointer operands.
4889       if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) {
4890         Value *Ptr0;
4891         Value *PtrN;
4892         if (CurrentOrder.empty()) {
4893           Ptr0 = PointerOps.front();
4894           PtrN = PointerOps.back();
4895         } else {
4896           Ptr0 = PointerOps[CurrentOrder.front()];
4897           PtrN = PointerOps[CurrentOrder.back()];
4898         }
4899         Optional<int> Dist =
4900             getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE);
4901         // Check that the sorted pointer operands are consecutive.
4902         if (static_cast<unsigned>(*Dist) == VL.size() - 1) {
4903           if (CurrentOrder.empty()) {
4904             // Original stores are consecutive and does not require reordering.
4905             TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
4906                                          UserTreeIdx, ReuseShuffleIndicies);
4907             TE->setOperandsInOrder();
4908             buildTree_rec(Operands, Depth + 1, {TE, 0});
4909             LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
4910           } else {
4911             fixupOrderingIndices(CurrentOrder);
4912             TreeEntry *TE =
4913                 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4914                              ReuseShuffleIndicies, CurrentOrder);
4915             TE->setOperandsInOrder();
4916             buildTree_rec(Operands, Depth + 1, {TE, 0});
4917             LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n");
4918           }
4919           return;
4920         }
4921       }
4922 
4923       BS.cancelScheduling(VL, VL0);
4924       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4925                    ReuseShuffleIndicies);
4926       LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
4927       return;
4928     }
4929     case Instruction::Call: {
4930       // Check if the calls are all to the same vectorizable intrinsic or
4931       // library function.
4932       CallInst *CI = cast<CallInst>(VL0);
4933       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4934 
4935       VFShape Shape = VFShape::get(
4936           *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())),
4937           false /*HasGlobalPred*/);
4938       Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4939 
4940       if (!VecFunc && !isTriviallyVectorizable(ID)) {
4941         BS.cancelScheduling(VL, VL0);
4942         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4943                      ReuseShuffleIndicies);
4944         LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
4945         return;
4946       }
4947       Function *F = CI->getCalledFunction();
4948       unsigned NumArgs = CI->arg_size();
4949       SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr);
4950       for (unsigned j = 0; j != NumArgs; ++j)
4951         if (isVectorIntrinsicWithScalarOpAtArg(ID, j))
4952           ScalarArgs[j] = CI->getArgOperand(j);
4953       for (Value *V : VL) {
4954         CallInst *CI2 = dyn_cast<CallInst>(V);
4955         if (!CI2 || CI2->getCalledFunction() != F ||
4956             getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
4957             (VecFunc &&
4958              VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) ||
4959             !CI->hasIdenticalOperandBundleSchema(*CI2)) {
4960           BS.cancelScheduling(VL, VL0);
4961           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4962                        ReuseShuffleIndicies);
4963           LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V
4964                             << "\n");
4965           return;
4966         }
4967         // Some intrinsics have scalar arguments and should be same in order for
4968         // them to be vectorized.
4969         for (unsigned j = 0; j != NumArgs; ++j) {
4970           if (isVectorIntrinsicWithScalarOpAtArg(ID, j)) {
4971             Value *A1J = CI2->getArgOperand(j);
4972             if (ScalarArgs[j] != A1J) {
4973               BS.cancelScheduling(VL, VL0);
4974               newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4975                            ReuseShuffleIndicies);
4976               LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
4977                                 << " argument " << ScalarArgs[j] << "!=" << A1J
4978                                 << "\n");
4979               return;
4980             }
4981           }
4982         }
4983         // Verify that the bundle operands are identical between the two calls.
4984         if (CI->hasOperandBundles() &&
4985             !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
4986                         CI->op_begin() + CI->getBundleOperandsEndIndex(),
4987                         CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
4988           BS.cancelScheduling(VL, VL0);
4989           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4990                        ReuseShuffleIndicies);
4991           LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
4992                             << *CI << "!=" << *V << '\n');
4993           return;
4994         }
4995       }
4996 
4997       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4998                                    ReuseShuffleIndicies);
4999       TE->setOperandsInOrder();
5000       for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
5001         // For scalar operands no need to to create an entry since no need to
5002         // vectorize it.
5003         if (isVectorIntrinsicWithScalarOpAtArg(ID, i))
5004           continue;
5005         ValueList Operands;
5006         // Prepare the operand vector.
5007         for (Value *V : VL) {
5008           auto *CI2 = cast<CallInst>(V);
5009           Operands.push_back(CI2->getArgOperand(i));
5010         }
5011         buildTree_rec(Operands, Depth + 1, {TE, i});
5012       }
5013       return;
5014     }
5015     case Instruction::ShuffleVector: {
5016       // If this is not an alternate sequence of opcode like add-sub
5017       // then do not vectorize this instruction.
5018       if (!S.isAltShuffle()) {
5019         BS.cancelScheduling(VL, VL0);
5020         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5021                      ReuseShuffleIndicies);
5022         LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
5023         return;
5024       }
5025       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
5026                                    ReuseShuffleIndicies);
5027       LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
5028 
5029       // Reorder operands if reordering would enable vectorization.
5030       auto *CI = dyn_cast<CmpInst>(VL0);
5031       if (isa<BinaryOperator>(VL0) || CI) {
5032         ValueList Left, Right;
5033         if (!CI || all_of(VL, [](Value *V) {
5034               return cast<CmpInst>(V)->isCommutative();
5035             })) {
5036           reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
5037         } else {
5038           CmpInst::Predicate P0 = CI->getPredicate();
5039           CmpInst::Predicate AltP0 = cast<CmpInst>(S.AltOp)->getPredicate();
5040           assert(P0 != AltP0 &&
5041                  "Expected different main/alternate predicates.");
5042           CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
5043           Value *BaseOp0 = VL0->getOperand(0);
5044           Value *BaseOp1 = VL0->getOperand(1);
5045           // Collect operands - commute if it uses the swapped predicate or
5046           // alternate operation.
5047           for (Value *V : VL) {
5048             auto *Cmp = cast<CmpInst>(V);
5049             Value *LHS = Cmp->getOperand(0);
5050             Value *RHS = Cmp->getOperand(1);
5051             CmpInst::Predicate CurrentPred = Cmp->getPredicate();
5052             if (P0 == AltP0Swapped) {
5053               if (CI != Cmp && S.AltOp != Cmp &&
5054                   ((P0 == CurrentPred &&
5055                     !areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)) ||
5056                    (AltP0 == CurrentPred &&
5057                     areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS))))
5058                 std::swap(LHS, RHS);
5059             } else if (P0 != CurrentPred && AltP0 != CurrentPred) {
5060               std::swap(LHS, RHS);
5061             }
5062             Left.push_back(LHS);
5063             Right.push_back(RHS);
5064           }
5065         }
5066         TE->setOperand(0, Left);
5067         TE->setOperand(1, Right);
5068         buildTree_rec(Left, Depth + 1, {TE, 0});
5069         buildTree_rec(Right, Depth + 1, {TE, 1});
5070         return;
5071       }
5072 
5073       TE->setOperandsInOrder();
5074       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
5075         ValueList Operands;
5076         // Prepare the operand vector.
5077         for (Value *V : VL)
5078           Operands.push_back(cast<Instruction>(V)->getOperand(i));
5079 
5080         buildTree_rec(Operands, Depth + 1, {TE, i});
5081       }
5082       return;
5083     }
5084     default:
5085       BS.cancelScheduling(VL, VL0);
5086       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5087                    ReuseShuffleIndicies);
5088       LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
5089       return;
5090   }
5091 }
5092 
5093 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
5094   unsigned N = 1;
5095   Type *EltTy = T;
5096 
5097   while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) ||
5098          isa<VectorType>(EltTy)) {
5099     if (auto *ST = dyn_cast<StructType>(EltTy)) {
5100       // Check that struct is homogeneous.
5101       for (const auto *Ty : ST->elements())
5102         if (Ty != *ST->element_begin())
5103           return 0;
5104       N *= ST->getNumElements();
5105       EltTy = *ST->element_begin();
5106     } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) {
5107       N *= AT->getNumElements();
5108       EltTy = AT->getElementType();
5109     } else {
5110       auto *VT = cast<FixedVectorType>(EltTy);
5111       N *= VT->getNumElements();
5112       EltTy = VT->getElementType();
5113     }
5114   }
5115 
5116   if (!isValidElementType(EltTy))
5117     return 0;
5118   uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N));
5119   if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
5120     return 0;
5121   return N;
5122 }
5123 
5124 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
5125                               SmallVectorImpl<unsigned> &CurrentOrder) const {
5126   const auto *It = find_if(VL, [](Value *V) {
5127     return isa<ExtractElementInst, ExtractValueInst>(V);
5128   });
5129   assert(It != VL.end() && "Expected at least one extract instruction.");
5130   auto *E0 = cast<Instruction>(*It);
5131   assert(all_of(VL,
5132                 [](Value *V) {
5133                   return isa<UndefValue, ExtractElementInst, ExtractValueInst>(
5134                       V);
5135                 }) &&
5136          "Invalid opcode");
5137   // Check if all of the extracts come from the same vector and from the
5138   // correct offset.
5139   Value *Vec = E0->getOperand(0);
5140 
5141   CurrentOrder.clear();
5142 
5143   // We have to extract from a vector/aggregate with the same number of elements.
5144   unsigned NElts;
5145   if (E0->getOpcode() == Instruction::ExtractValue) {
5146     const DataLayout &DL = E0->getModule()->getDataLayout();
5147     NElts = canMapToVector(Vec->getType(), DL);
5148     if (!NElts)
5149       return false;
5150     // Check if load can be rewritten as load of vector.
5151     LoadInst *LI = dyn_cast<LoadInst>(Vec);
5152     if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
5153       return false;
5154   } else {
5155     NElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
5156   }
5157 
5158   if (NElts != VL.size())
5159     return false;
5160 
5161   // Check that all of the indices extract from the correct offset.
5162   bool ShouldKeepOrder = true;
5163   unsigned E = VL.size();
5164   // Assign to all items the initial value E + 1 so we can check if the extract
5165   // instruction index was used already.
5166   // Also, later we can check that all the indices are used and we have a
5167   // consecutive access in the extract instructions, by checking that no
5168   // element of CurrentOrder still has value E + 1.
5169   CurrentOrder.assign(E, E);
5170   unsigned I = 0;
5171   for (; I < E; ++I) {
5172     auto *Inst = dyn_cast<Instruction>(VL[I]);
5173     if (!Inst)
5174       continue;
5175     if (Inst->getOperand(0) != Vec)
5176       break;
5177     if (auto *EE = dyn_cast<ExtractElementInst>(Inst))
5178       if (isa<UndefValue>(EE->getIndexOperand()))
5179         continue;
5180     Optional<unsigned> Idx = getExtractIndex(Inst);
5181     if (!Idx)
5182       break;
5183     const unsigned ExtIdx = *Idx;
5184     if (ExtIdx != I) {
5185       if (ExtIdx >= E || CurrentOrder[ExtIdx] != E)
5186         break;
5187       ShouldKeepOrder = false;
5188       CurrentOrder[ExtIdx] = I;
5189     } else {
5190       if (CurrentOrder[I] != E)
5191         break;
5192       CurrentOrder[I] = I;
5193     }
5194   }
5195   if (I < E) {
5196     CurrentOrder.clear();
5197     return false;
5198   }
5199   if (ShouldKeepOrder)
5200     CurrentOrder.clear();
5201 
5202   return ShouldKeepOrder;
5203 }
5204 
5205 bool BoUpSLP::areAllUsersVectorized(Instruction *I,
5206                                     ArrayRef<Value *> VectorizedVals) const {
5207   return (I->hasOneUse() && is_contained(VectorizedVals, I)) ||
5208          all_of(I->users(), [this](User *U) {
5209            return ScalarToTreeEntry.count(U) > 0 ||
5210                   isVectorLikeInstWithConstOps(U) ||
5211                   (isa<ExtractElementInst>(U) && MustGather.contains(U));
5212          });
5213 }
5214 
5215 static std::pair<InstructionCost, InstructionCost>
5216 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy,
5217                    TargetTransformInfo *TTI, TargetLibraryInfo *TLI) {
5218   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5219 
5220   // Calculate the cost of the scalar and vector calls.
5221   SmallVector<Type *, 4> VecTys;
5222   for (Use &Arg : CI->args())
5223     VecTys.push_back(
5224         FixedVectorType::get(Arg->getType(), VecTy->getNumElements()));
5225   FastMathFlags FMF;
5226   if (auto *FPCI = dyn_cast<FPMathOperator>(CI))
5227     FMF = FPCI->getFastMathFlags();
5228   SmallVector<const Value *> Arguments(CI->args());
5229   IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF,
5230                                     dyn_cast<IntrinsicInst>(CI));
5231   auto IntrinsicCost =
5232     TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput);
5233 
5234   auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
5235                                      VecTy->getNumElements())),
5236                             false /*HasGlobalPred*/);
5237   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
5238   auto LibCost = IntrinsicCost;
5239   if (!CI->isNoBuiltin() && VecFunc) {
5240     // Calculate the cost of the vector library call.
5241     // If the corresponding vector call is cheaper, return its cost.
5242     LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys,
5243                                     TTI::TCK_RecipThroughput);
5244   }
5245   return {IntrinsicCost, LibCost};
5246 }
5247 
5248 /// Compute the cost of creating a vector of type \p VecTy containing the
5249 /// extracted values from \p VL.
5250 static InstructionCost
5251 computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy,
5252                    TargetTransformInfo::ShuffleKind ShuffleKind,
5253                    ArrayRef<int> Mask, TargetTransformInfo &TTI) {
5254   unsigned NumOfParts = TTI.getNumberOfParts(VecTy);
5255 
5256   if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts ||
5257       VecTy->getNumElements() < NumOfParts)
5258     return TTI.getShuffleCost(ShuffleKind, VecTy, Mask);
5259 
5260   bool AllConsecutive = true;
5261   unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts;
5262   unsigned Idx = -1;
5263   InstructionCost Cost = 0;
5264 
5265   // Process extracts in blocks of EltsPerVector to check if the source vector
5266   // operand can be re-used directly. If not, add the cost of creating a shuffle
5267   // to extract the values into a vector register.
5268   SmallVector<int> RegMask(EltsPerVector, UndefMaskElem);
5269   for (auto *V : VL) {
5270     ++Idx;
5271 
5272     // Need to exclude undefs from analysis.
5273     if (isa<UndefValue>(V) || Mask[Idx] == UndefMaskElem)
5274       continue;
5275 
5276     // Reached the start of a new vector registers.
5277     if (Idx % EltsPerVector == 0) {
5278       RegMask.assign(EltsPerVector, UndefMaskElem);
5279       AllConsecutive = true;
5280       continue;
5281     }
5282 
5283     // Check all extracts for a vector register on the target directly
5284     // extract values in order.
5285     unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V));
5286     if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != UndefMaskElem) {
5287       unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1]));
5288       AllConsecutive &= PrevIdx + 1 == CurrentIdx &&
5289                         CurrentIdx % EltsPerVector == Idx % EltsPerVector;
5290       RegMask[Idx % EltsPerVector] = CurrentIdx % EltsPerVector;
5291     }
5292 
5293     if (AllConsecutive)
5294       continue;
5295 
5296     // Skip all indices, except for the last index per vector block.
5297     if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size())
5298       continue;
5299 
5300     // If we have a series of extracts which are not consecutive and hence
5301     // cannot re-use the source vector register directly, compute the shuffle
5302     // cost to extract the vector with EltsPerVector elements.
5303     Cost += TTI.getShuffleCost(
5304         TargetTransformInfo::SK_PermuteSingleSrc,
5305         FixedVectorType::get(VecTy->getElementType(), EltsPerVector), RegMask);
5306   }
5307   return Cost;
5308 }
5309 
5310 /// Build shuffle mask for shuffle graph entries and lists of main and alternate
5311 /// operations operands.
5312 static void
5313 buildShuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices,
5314                       ArrayRef<int> ReusesIndices,
5315                       const function_ref<bool(Instruction *)> IsAltOp,
5316                       SmallVectorImpl<int> &Mask,
5317                       SmallVectorImpl<Value *> *OpScalars = nullptr,
5318                       SmallVectorImpl<Value *> *AltScalars = nullptr) {
5319   unsigned Sz = VL.size();
5320   Mask.assign(Sz, UndefMaskElem);
5321   SmallVector<int> OrderMask;
5322   if (!ReorderIndices.empty())
5323     inversePermutation(ReorderIndices, OrderMask);
5324   for (unsigned I = 0; I < Sz; ++I) {
5325     unsigned Idx = I;
5326     if (!ReorderIndices.empty())
5327       Idx = OrderMask[I];
5328     auto *OpInst = cast<Instruction>(VL[Idx]);
5329     if (IsAltOp(OpInst)) {
5330       Mask[I] = Sz + Idx;
5331       if (AltScalars)
5332         AltScalars->push_back(OpInst);
5333     } else {
5334       Mask[I] = Idx;
5335       if (OpScalars)
5336         OpScalars->push_back(OpInst);
5337     }
5338   }
5339   if (!ReusesIndices.empty()) {
5340     SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem);
5341     transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) {
5342       return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem;
5343     });
5344     Mask.swap(NewMask);
5345   }
5346 }
5347 
5348 /// Checks if the specified instruction \p I is an alternate operation for the
5349 /// given \p MainOp and \p AltOp instructions.
5350 static bool isAlternateInstruction(const Instruction *I,
5351                                    const Instruction *MainOp,
5352                                    const Instruction *AltOp) {
5353   if (auto *CI0 = dyn_cast<CmpInst>(MainOp)) {
5354     auto *AltCI0 = cast<CmpInst>(AltOp);
5355     auto *CI = cast<CmpInst>(I);
5356     CmpInst::Predicate P0 = CI0->getPredicate();
5357     CmpInst::Predicate AltP0 = AltCI0->getPredicate();
5358     assert(P0 != AltP0 && "Expected different main/alternate predicates.");
5359     CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
5360     CmpInst::Predicate CurrentPred = CI->getPredicate();
5361     if (P0 == AltP0Swapped)
5362       return I == AltCI0 ||
5363              (I != MainOp &&
5364               !areCompatibleCmpOps(CI0->getOperand(0), CI0->getOperand(1),
5365                                    CI->getOperand(0), CI->getOperand(1)));
5366     return AltP0 == CurrentPred || AltP0Swapped == CurrentPred;
5367   }
5368   return I->getOpcode() == AltOp->getOpcode();
5369 }
5370 
5371 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E,
5372                                       ArrayRef<Value *> VectorizedVals) {
5373   ArrayRef<Value*> VL = E->Scalars;
5374 
5375   Type *ScalarTy = VL[0]->getType();
5376   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
5377     ScalarTy = SI->getValueOperand()->getType();
5378   else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
5379     ScalarTy = CI->getOperand(0)->getType();
5380   else if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
5381     ScalarTy = IE->getOperand(1)->getType();
5382   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
5383   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
5384 
5385   // If we have computed a smaller type for the expression, update VecTy so
5386   // that the costs will be accurate.
5387   if (MinBWs.count(VL[0]))
5388     VecTy = FixedVectorType::get(
5389         IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
5390   unsigned EntryVF = E->getVectorFactor();
5391   auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF);
5392 
5393   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
5394   // FIXME: it tries to fix a problem with MSVC buildbots.
5395   TargetTransformInfo &TTIRef = *TTI;
5396   auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy,
5397                                VectorizedVals, E](InstructionCost &Cost) {
5398     DenseMap<Value *, int> ExtractVectorsTys;
5399     SmallPtrSet<Value *, 4> CheckedExtracts;
5400     for (auto *V : VL) {
5401       if (isa<UndefValue>(V))
5402         continue;
5403       // If all users of instruction are going to be vectorized and this
5404       // instruction itself is not going to be vectorized, consider this
5405       // instruction as dead and remove its cost from the final cost of the
5406       // vectorized tree.
5407       // Also, avoid adjusting the cost for extractelements with multiple uses
5408       // in different graph entries.
5409       const TreeEntry *VE = getTreeEntry(V);
5410       if (!CheckedExtracts.insert(V).second ||
5411           !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) ||
5412           (VE && VE != E))
5413         continue;
5414       auto *EE = cast<ExtractElementInst>(V);
5415       Optional<unsigned> EEIdx = getExtractIndex(EE);
5416       if (!EEIdx)
5417         continue;
5418       unsigned Idx = *EEIdx;
5419       if (TTIRef.getNumberOfParts(VecTy) !=
5420           TTIRef.getNumberOfParts(EE->getVectorOperandType())) {
5421         auto It =
5422             ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first;
5423         It->getSecond() = std::min<int>(It->second, Idx);
5424       }
5425       // Take credit for instruction that will become dead.
5426       if (EE->hasOneUse()) {
5427         Instruction *Ext = EE->user_back();
5428         if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5429             all_of(Ext->users(),
5430                    [](User *U) { return isa<GetElementPtrInst>(U); })) {
5431           // Use getExtractWithExtendCost() to calculate the cost of
5432           // extractelement/ext pair.
5433           Cost -=
5434               TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(),
5435                                               EE->getVectorOperandType(), Idx);
5436           // Add back the cost of s|zext which is subtracted separately.
5437           Cost += TTIRef.getCastInstrCost(
5438               Ext->getOpcode(), Ext->getType(), EE->getType(),
5439               TTI::getCastContextHint(Ext), CostKind, Ext);
5440           continue;
5441         }
5442       }
5443       Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement,
5444                                         EE->getVectorOperandType(), Idx);
5445     }
5446     // Add a cost for subvector extracts/inserts if required.
5447     for (const auto &Data : ExtractVectorsTys) {
5448       auto *EEVTy = cast<FixedVectorType>(Data.first->getType());
5449       unsigned NumElts = VecTy->getNumElements();
5450       if (Data.second % NumElts == 0)
5451         continue;
5452       if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) {
5453         unsigned Idx = (Data.second / NumElts) * NumElts;
5454         unsigned EENumElts = EEVTy->getNumElements();
5455         if (Idx + NumElts <= EENumElts) {
5456           Cost +=
5457               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5458                                     EEVTy, None, Idx, VecTy);
5459         } else {
5460           // Need to round up the subvector type vectorization factor to avoid a
5461           // crash in cost model functions. Make SubVT so that Idx + VF of SubVT
5462           // <= EENumElts.
5463           auto *SubVT =
5464               FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx);
5465           Cost +=
5466               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5467                                     EEVTy, None, Idx, SubVT);
5468         }
5469       } else {
5470         Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector,
5471                                       VecTy, None, 0, EEVTy);
5472       }
5473     }
5474   };
5475   if (E->State == TreeEntry::NeedToGather) {
5476     if (allConstant(VL))
5477       return 0;
5478     if (isa<InsertElementInst>(VL[0]))
5479       return InstructionCost::getInvalid();
5480     SmallVector<int> Mask;
5481     SmallVector<const TreeEntry *> Entries;
5482     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
5483         isGatherShuffledEntry(E, Mask, Entries);
5484     if (Shuffle.hasValue()) {
5485       InstructionCost GatherCost = 0;
5486       if (ShuffleVectorInst::isIdentityMask(Mask)) {
5487         // Perfect match in the graph, will reuse the previously vectorized
5488         // node. Cost is 0.
5489         LLVM_DEBUG(
5490             dbgs()
5491             << "SLP: perfect diamond match for gather bundle that starts with "
5492             << *VL.front() << ".\n");
5493         if (NeedToShuffleReuses)
5494           GatherCost =
5495               TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5496                                   FinalVecTy, E->ReuseShuffleIndices);
5497       } else {
5498         LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size()
5499                           << " entries for bundle that starts with "
5500                           << *VL.front() << ".\n");
5501         // Detected that instead of gather we can emit a shuffle of single/two
5502         // previously vectorized nodes. Add the cost of the permutation rather
5503         // than gather.
5504         ::addMask(Mask, E->ReuseShuffleIndices);
5505         GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask);
5506       }
5507       return GatherCost;
5508     }
5509     if ((E->getOpcode() == Instruction::ExtractElement ||
5510          all_of(E->Scalars,
5511                 [](Value *V) {
5512                   return isa<ExtractElementInst, UndefValue>(V);
5513                 })) &&
5514         allSameType(VL)) {
5515       // Check that gather of extractelements can be represented as just a
5516       // shuffle of a single/two vectors the scalars are extracted from.
5517       SmallVector<int> Mask;
5518       Optional<TargetTransformInfo::ShuffleKind> ShuffleKind =
5519           isFixedVectorShuffle(VL, Mask);
5520       if (ShuffleKind.hasValue()) {
5521         // Found the bunch of extractelement instructions that must be gathered
5522         // into a vector and can be represented as a permutation elements in a
5523         // single input vector or of 2 input vectors.
5524         InstructionCost Cost =
5525             computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI);
5526         AdjustExtractsCost(Cost);
5527         if (NeedToShuffleReuses)
5528           Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5529                                       FinalVecTy, E->ReuseShuffleIndices);
5530         return Cost;
5531       }
5532     }
5533     if (isSplat(VL)) {
5534       // Found the broadcasting of the single scalar, calculate the cost as the
5535       // broadcast.
5536       assert(VecTy == FinalVecTy &&
5537              "No reused scalars expected for broadcast.");
5538       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy,
5539                                  /*Mask=*/None, /*Index=*/0,
5540                                  /*SubTp=*/nullptr, /*Args=*/VL[0]);
5541     }
5542     InstructionCost ReuseShuffleCost = 0;
5543     if (NeedToShuffleReuses)
5544       ReuseShuffleCost = TTI->getShuffleCost(
5545           TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices);
5546     // Improve gather cost for gather of loads, if we can group some of the
5547     // loads into vector loads.
5548     if (VL.size() > 2 && E->getOpcode() == Instruction::Load &&
5549         !E->isAltShuffle()) {
5550       BoUpSLP::ValueSet VectorizedLoads;
5551       unsigned StartIdx = 0;
5552       unsigned VF = VL.size() / 2;
5553       unsigned VectorizedCnt = 0;
5554       unsigned ScatterVectorizeCnt = 0;
5555       const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType());
5556       for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) {
5557         for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End;
5558              Cnt += VF) {
5559           ArrayRef<Value *> Slice = VL.slice(Cnt, VF);
5560           if (!VectorizedLoads.count(Slice.front()) &&
5561               !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) {
5562             SmallVector<Value *> PointerOps;
5563             OrdersType CurrentOrder;
5564             LoadsState LS = canVectorizeLoads(Slice, Slice.front(), *TTI, *DL,
5565                                               *SE, CurrentOrder, PointerOps);
5566             switch (LS) {
5567             case LoadsState::Vectorize:
5568             case LoadsState::ScatterVectorize:
5569               // Mark the vectorized loads so that we don't vectorize them
5570               // again.
5571               if (LS == LoadsState::Vectorize)
5572                 ++VectorizedCnt;
5573               else
5574                 ++ScatterVectorizeCnt;
5575               VectorizedLoads.insert(Slice.begin(), Slice.end());
5576               // If we vectorized initial block, no need to try to vectorize it
5577               // again.
5578               if (Cnt == StartIdx)
5579                 StartIdx += VF;
5580               break;
5581             case LoadsState::Gather:
5582               break;
5583             }
5584           }
5585         }
5586         // Check if the whole array was vectorized already - exit.
5587         if (StartIdx >= VL.size())
5588           break;
5589         // Found vectorizable parts - exit.
5590         if (!VectorizedLoads.empty())
5591           break;
5592       }
5593       if (!VectorizedLoads.empty()) {
5594         InstructionCost GatherCost = 0;
5595         unsigned NumParts = TTI->getNumberOfParts(VecTy);
5596         bool NeedInsertSubvectorAnalysis =
5597             !NumParts || (VL.size() / VF) > NumParts;
5598         // Get the cost for gathered loads.
5599         for (unsigned I = 0, End = VL.size(); I < End; I += VF) {
5600           if (VectorizedLoads.contains(VL[I]))
5601             continue;
5602           GatherCost += getGatherCost(VL.slice(I, VF));
5603         }
5604         // The cost for vectorized loads.
5605         InstructionCost ScalarsCost = 0;
5606         for (Value *V : VectorizedLoads) {
5607           auto *LI = cast<LoadInst>(V);
5608           ScalarsCost += TTI->getMemoryOpCost(
5609               Instruction::Load, LI->getType(), LI->getAlign(),
5610               LI->getPointerAddressSpace(), CostKind, LI);
5611         }
5612         auto *LI = cast<LoadInst>(E->getMainOp());
5613         auto *LoadTy = FixedVectorType::get(LI->getType(), VF);
5614         Align Alignment = LI->getAlign();
5615         GatherCost +=
5616             VectorizedCnt *
5617             TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment,
5618                                  LI->getPointerAddressSpace(), CostKind, LI);
5619         GatherCost += ScatterVectorizeCnt *
5620                       TTI->getGatherScatterOpCost(
5621                           Instruction::Load, LoadTy, LI->getPointerOperand(),
5622                           /*VariableMask=*/false, Alignment, CostKind, LI);
5623         if (NeedInsertSubvectorAnalysis) {
5624           // Add the cost for the subvectors insert.
5625           for (int I = VF, E = VL.size(); I < E; I += VF)
5626             GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy,
5627                                               None, I, LoadTy);
5628         }
5629         return ReuseShuffleCost + GatherCost - ScalarsCost;
5630       }
5631     }
5632     return ReuseShuffleCost + getGatherCost(VL);
5633   }
5634   InstructionCost CommonCost = 0;
5635   SmallVector<int> Mask;
5636   if (!E->ReorderIndices.empty()) {
5637     SmallVector<int> NewMask;
5638     if (E->getOpcode() == Instruction::Store) {
5639       // For stores the order is actually a mask.
5640       NewMask.resize(E->ReorderIndices.size());
5641       copy(E->ReorderIndices, NewMask.begin());
5642     } else {
5643       inversePermutation(E->ReorderIndices, NewMask);
5644     }
5645     ::addMask(Mask, NewMask);
5646   }
5647   if (NeedToShuffleReuses)
5648     ::addMask(Mask, E->ReuseShuffleIndices);
5649   if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask))
5650     CommonCost =
5651         TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask);
5652   assert((E->State == TreeEntry::Vectorize ||
5653           E->State == TreeEntry::ScatterVectorize) &&
5654          "Unhandled state");
5655   assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
5656   Instruction *VL0 = E->getMainOp();
5657   unsigned ShuffleOrOp =
5658       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
5659   switch (ShuffleOrOp) {
5660     case Instruction::PHI:
5661       return 0;
5662 
5663     case Instruction::ExtractValue:
5664     case Instruction::ExtractElement: {
5665       // The common cost of removal ExtractElement/ExtractValue instructions +
5666       // the cost of shuffles, if required to resuffle the original vector.
5667       if (NeedToShuffleReuses) {
5668         unsigned Idx = 0;
5669         for (unsigned I : E->ReuseShuffleIndices) {
5670           if (ShuffleOrOp == Instruction::ExtractElement) {
5671             auto *EE = cast<ExtractElementInst>(VL[I]);
5672             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5673                                                   EE->getVectorOperandType(),
5674                                                   *getExtractIndex(EE));
5675           } else {
5676             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5677                                                   VecTy, Idx);
5678             ++Idx;
5679           }
5680         }
5681         Idx = EntryVF;
5682         for (Value *V : VL) {
5683           if (ShuffleOrOp == Instruction::ExtractElement) {
5684             auto *EE = cast<ExtractElementInst>(V);
5685             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5686                                                   EE->getVectorOperandType(),
5687                                                   *getExtractIndex(EE));
5688           } else {
5689             --Idx;
5690             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5691                                                   VecTy, Idx);
5692           }
5693         }
5694       }
5695       if (ShuffleOrOp == Instruction::ExtractValue) {
5696         for (unsigned I = 0, E = VL.size(); I < E; ++I) {
5697           auto *EI = cast<Instruction>(VL[I]);
5698           // Take credit for instruction that will become dead.
5699           if (EI->hasOneUse()) {
5700             Instruction *Ext = EI->user_back();
5701             if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5702                 all_of(Ext->users(),
5703                        [](User *U) { return isa<GetElementPtrInst>(U); })) {
5704               // Use getExtractWithExtendCost() to calculate the cost of
5705               // extractelement/ext pair.
5706               CommonCost -= TTI->getExtractWithExtendCost(
5707                   Ext->getOpcode(), Ext->getType(), VecTy, I);
5708               // Add back the cost of s|zext which is subtracted separately.
5709               CommonCost += TTI->getCastInstrCost(
5710                   Ext->getOpcode(), Ext->getType(), EI->getType(),
5711                   TTI::getCastContextHint(Ext), CostKind, Ext);
5712               continue;
5713             }
5714           }
5715           CommonCost -=
5716               TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I);
5717         }
5718       } else {
5719         AdjustExtractsCost(CommonCost);
5720       }
5721       return CommonCost;
5722     }
5723     case Instruction::InsertElement: {
5724       assert(E->ReuseShuffleIndices.empty() &&
5725              "Unique insertelements only are expected.");
5726       auto *SrcVecTy = cast<FixedVectorType>(VL0->getType());
5727 
5728       unsigned const NumElts = SrcVecTy->getNumElements();
5729       unsigned const NumScalars = VL.size();
5730       APInt DemandedElts = APInt::getZero(NumElts);
5731       // TODO: Add support for Instruction::InsertValue.
5732       SmallVector<int> Mask;
5733       if (!E->ReorderIndices.empty()) {
5734         inversePermutation(E->ReorderIndices, Mask);
5735         Mask.append(NumElts - NumScalars, UndefMaskElem);
5736       } else {
5737         Mask.assign(NumElts, UndefMaskElem);
5738         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
5739       }
5740       unsigned Offset = *getInsertIndex(VL0);
5741       bool IsIdentity = true;
5742       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
5743       Mask.swap(PrevMask);
5744       for (unsigned I = 0; I < NumScalars; ++I) {
5745         unsigned InsertIdx = *getInsertIndex(VL[PrevMask[I]]);
5746         DemandedElts.setBit(InsertIdx);
5747         IsIdentity &= InsertIdx - Offset == I;
5748         Mask[InsertIdx - Offset] = I;
5749       }
5750       assert(Offset < NumElts && "Failed to find vector index offset");
5751 
5752       InstructionCost Cost = 0;
5753       Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts,
5754                                             /*Insert*/ true, /*Extract*/ false);
5755 
5756       if (IsIdentity && NumElts != NumScalars && Offset % NumScalars != 0) {
5757         // FIXME: Replace with SK_InsertSubvector once it is properly supported.
5758         unsigned Sz = PowerOf2Ceil(Offset + NumScalars);
5759         Cost += TTI->getShuffleCost(
5760             TargetTransformInfo::SK_PermuteSingleSrc,
5761             FixedVectorType::get(SrcVecTy->getElementType(), Sz));
5762       } else if (!IsIdentity) {
5763         auto *FirstInsert =
5764             cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
5765               return !is_contained(E->Scalars,
5766                                    cast<Instruction>(V)->getOperand(0));
5767             }));
5768         if (isUndefVector(FirstInsert->getOperand(0))) {
5769           Cost += TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, SrcVecTy, Mask);
5770         } else {
5771           SmallVector<int> InsertMask(NumElts);
5772           std::iota(InsertMask.begin(), InsertMask.end(), 0);
5773           for (unsigned I = 0; I < NumElts; I++) {
5774             if (Mask[I] != UndefMaskElem)
5775               InsertMask[Offset + I] = NumElts + I;
5776           }
5777           Cost +=
5778               TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVecTy, InsertMask);
5779         }
5780       }
5781 
5782       return Cost;
5783     }
5784     case Instruction::ZExt:
5785     case Instruction::SExt:
5786     case Instruction::FPToUI:
5787     case Instruction::FPToSI:
5788     case Instruction::FPExt:
5789     case Instruction::PtrToInt:
5790     case Instruction::IntToPtr:
5791     case Instruction::SIToFP:
5792     case Instruction::UIToFP:
5793     case Instruction::Trunc:
5794     case Instruction::FPTrunc:
5795     case Instruction::BitCast: {
5796       Type *SrcTy = VL0->getOperand(0)->getType();
5797       InstructionCost ScalarEltCost =
5798           TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy,
5799                                 TTI::getCastContextHint(VL0), CostKind, VL0);
5800       if (NeedToShuffleReuses) {
5801         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5802       }
5803 
5804       // Calculate the cost of this instruction.
5805       InstructionCost ScalarCost = VL.size() * ScalarEltCost;
5806 
5807       auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size());
5808       InstructionCost VecCost = 0;
5809       // Check if the values are candidates to demote.
5810       if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
5811         VecCost = CommonCost + TTI->getCastInstrCost(
5812                                    E->getOpcode(), VecTy, SrcVecTy,
5813                                    TTI::getCastContextHint(VL0), CostKind, VL0);
5814       }
5815       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5816       return VecCost - ScalarCost;
5817     }
5818     case Instruction::FCmp:
5819     case Instruction::ICmp:
5820     case Instruction::Select: {
5821       // Calculate the cost of this instruction.
5822       InstructionCost ScalarEltCost =
5823           TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5824                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0);
5825       if (NeedToShuffleReuses) {
5826         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5827       }
5828       auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size());
5829       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5830 
5831       // Check if all entries in VL are either compares or selects with compares
5832       // as condition that have the same predicates.
5833       CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE;
5834       bool First = true;
5835       for (auto *V : VL) {
5836         CmpInst::Predicate CurrentPred;
5837         auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value());
5838         if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) &&
5839              !match(V, MatchCmp)) ||
5840             (!First && VecPred != CurrentPred)) {
5841           VecPred = CmpInst::BAD_ICMP_PREDICATE;
5842           break;
5843         }
5844         First = false;
5845         VecPred = CurrentPred;
5846       }
5847 
5848       InstructionCost VecCost = TTI->getCmpSelInstrCost(
5849           E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0);
5850       // Check if it is possible and profitable to use min/max for selects in
5851       // VL.
5852       //
5853       auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL);
5854       if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) {
5855         IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy,
5856                                           {VecTy, VecTy});
5857         InstructionCost IntrinsicCost =
5858             TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5859         // If the selects are the only uses of the compares, they will be dead
5860         // and we can adjust the cost by removing their cost.
5861         if (IntrinsicAndUse.second)
5862           IntrinsicCost -= TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy,
5863                                                    MaskTy, VecPred, CostKind);
5864         VecCost = std::min(VecCost, IntrinsicCost);
5865       }
5866       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5867       return CommonCost + VecCost - ScalarCost;
5868     }
5869     case Instruction::FNeg:
5870     case Instruction::Add:
5871     case Instruction::FAdd:
5872     case Instruction::Sub:
5873     case Instruction::FSub:
5874     case Instruction::Mul:
5875     case Instruction::FMul:
5876     case Instruction::UDiv:
5877     case Instruction::SDiv:
5878     case Instruction::FDiv:
5879     case Instruction::URem:
5880     case Instruction::SRem:
5881     case Instruction::FRem:
5882     case Instruction::Shl:
5883     case Instruction::LShr:
5884     case Instruction::AShr:
5885     case Instruction::And:
5886     case Instruction::Or:
5887     case Instruction::Xor: {
5888       // Certain instructions can be cheaper to vectorize if they have a
5889       // constant second vector operand.
5890       TargetTransformInfo::OperandValueKind Op1VK =
5891           TargetTransformInfo::OK_AnyValue;
5892       TargetTransformInfo::OperandValueKind Op2VK =
5893           TargetTransformInfo::OK_UniformConstantValue;
5894       TargetTransformInfo::OperandValueProperties Op1VP =
5895           TargetTransformInfo::OP_None;
5896       TargetTransformInfo::OperandValueProperties Op2VP =
5897           TargetTransformInfo::OP_PowerOf2;
5898 
5899       // If all operands are exactly the same ConstantInt then set the
5900       // operand kind to OK_UniformConstantValue.
5901       // If instead not all operands are constants, then set the operand kind
5902       // to OK_AnyValue. If all operands are constants but not the same,
5903       // then set the operand kind to OK_NonUniformConstantValue.
5904       ConstantInt *CInt0 = nullptr;
5905       for (unsigned i = 0, e = VL.size(); i < e; ++i) {
5906         const Instruction *I = cast<Instruction>(VL[i]);
5907         unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0;
5908         ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx));
5909         if (!CInt) {
5910           Op2VK = TargetTransformInfo::OK_AnyValue;
5911           Op2VP = TargetTransformInfo::OP_None;
5912           break;
5913         }
5914         if (Op2VP == TargetTransformInfo::OP_PowerOf2 &&
5915             !CInt->getValue().isPowerOf2())
5916           Op2VP = TargetTransformInfo::OP_None;
5917         if (i == 0) {
5918           CInt0 = CInt;
5919           continue;
5920         }
5921         if (CInt0 != CInt)
5922           Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5923       }
5924 
5925       SmallVector<const Value *, 4> Operands(VL0->operand_values());
5926       InstructionCost ScalarEltCost =
5927           TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK,
5928                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5929       if (NeedToShuffleReuses) {
5930         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5931       }
5932       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5933       InstructionCost VecCost =
5934           TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK,
5935                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5936       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5937       return CommonCost + VecCost - ScalarCost;
5938     }
5939     case Instruction::GetElementPtr: {
5940       TargetTransformInfo::OperandValueKind Op1VK =
5941           TargetTransformInfo::OK_AnyValue;
5942       TargetTransformInfo::OperandValueKind Op2VK =
5943           TargetTransformInfo::OK_UniformConstantValue;
5944 
5945       InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost(
5946           Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK);
5947       if (NeedToShuffleReuses) {
5948         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5949       }
5950       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5951       InstructionCost VecCost = TTI->getArithmeticInstrCost(
5952           Instruction::Add, VecTy, CostKind, Op1VK, Op2VK);
5953       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5954       return CommonCost + VecCost - ScalarCost;
5955     }
5956     case Instruction::Load: {
5957       // Cost of wide load - cost of scalar loads.
5958       Align Alignment = cast<LoadInst>(VL0)->getAlign();
5959       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5960           Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0);
5961       if (NeedToShuffleReuses) {
5962         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5963       }
5964       InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost;
5965       InstructionCost VecLdCost;
5966       if (E->State == TreeEntry::Vectorize) {
5967         VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0,
5968                                          CostKind, VL0);
5969       } else {
5970         assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState");
5971         Align CommonAlignment = Alignment;
5972         for (Value *V : VL)
5973           CommonAlignment =
5974               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
5975         VecLdCost = TTI->getGatherScatterOpCost(
5976             Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(),
5977             /*VariableMask=*/false, CommonAlignment, CostKind, VL0);
5978       }
5979       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost));
5980       return CommonCost + VecLdCost - ScalarLdCost;
5981     }
5982     case Instruction::Store: {
5983       // We know that we can merge the stores. Calculate the cost.
5984       bool IsReorder = !E->ReorderIndices.empty();
5985       auto *SI =
5986           cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0);
5987       Align Alignment = SI->getAlign();
5988       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5989           Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0);
5990       InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost;
5991       InstructionCost VecStCost = TTI->getMemoryOpCost(
5992           Instruction::Store, VecTy, Alignment, 0, CostKind, VL0);
5993       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost));
5994       return CommonCost + VecStCost - ScalarStCost;
5995     }
5996     case Instruction::Call: {
5997       CallInst *CI = cast<CallInst>(VL0);
5998       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5999 
6000       // Calculate the cost of the scalar and vector calls.
6001       IntrinsicCostAttributes CostAttrs(ID, *CI, 1);
6002       InstructionCost ScalarEltCost =
6003           TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
6004       if (NeedToShuffleReuses) {
6005         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
6006       }
6007       InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
6008 
6009       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
6010       InstructionCost VecCallCost =
6011           std::min(VecCallCosts.first, VecCallCosts.second);
6012 
6013       LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
6014                         << " (" << VecCallCost << "-" << ScalarCallCost << ")"
6015                         << " for " << *CI << "\n");
6016 
6017       return CommonCost + VecCallCost - ScalarCallCost;
6018     }
6019     case Instruction::ShuffleVector: {
6020       assert(E->isAltShuffle() &&
6021              ((Instruction::isBinaryOp(E->getOpcode()) &&
6022                Instruction::isBinaryOp(E->getAltOpcode())) ||
6023               (Instruction::isCast(E->getOpcode()) &&
6024                Instruction::isCast(E->getAltOpcode())) ||
6025               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
6026              "Invalid Shuffle Vector Operand");
6027       InstructionCost ScalarCost = 0;
6028       if (NeedToShuffleReuses) {
6029         for (unsigned Idx : E->ReuseShuffleIndices) {
6030           Instruction *I = cast<Instruction>(VL[Idx]);
6031           CommonCost -= TTI->getInstructionCost(I, CostKind);
6032         }
6033         for (Value *V : VL) {
6034           Instruction *I = cast<Instruction>(V);
6035           CommonCost += TTI->getInstructionCost(I, CostKind);
6036         }
6037       }
6038       for (Value *V : VL) {
6039         Instruction *I = cast<Instruction>(V);
6040         assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
6041         ScalarCost += TTI->getInstructionCost(I, CostKind);
6042       }
6043       // VecCost is equal to sum of the cost of creating 2 vectors
6044       // and the cost of creating shuffle.
6045       InstructionCost VecCost = 0;
6046       // Try to find the previous shuffle node with the same operands and same
6047       // main/alternate ops.
6048       auto &&TryFindNodeWithEqualOperands = [this, E]() {
6049         for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
6050           if (TE.get() == E)
6051             break;
6052           if (TE->isAltShuffle() &&
6053               ((TE->getOpcode() == E->getOpcode() &&
6054                 TE->getAltOpcode() == E->getAltOpcode()) ||
6055                (TE->getOpcode() == E->getAltOpcode() &&
6056                 TE->getAltOpcode() == E->getOpcode())) &&
6057               TE->hasEqualOperands(*E))
6058             return true;
6059         }
6060         return false;
6061       };
6062       if (TryFindNodeWithEqualOperands()) {
6063         LLVM_DEBUG({
6064           dbgs() << "SLP: diamond match for alternate node found.\n";
6065           E->dump();
6066         });
6067         // No need to add new vector costs here since we're going to reuse
6068         // same main/alternate vector ops, just do different shuffling.
6069       } else if (Instruction::isBinaryOp(E->getOpcode())) {
6070         VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind);
6071         VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy,
6072                                                CostKind);
6073       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
6074         VecCost = TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy,
6075                                           Builder.getInt1Ty(),
6076                                           CI0->getPredicate(), CostKind, VL0);
6077         VecCost += TTI->getCmpSelInstrCost(
6078             E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
6079             cast<CmpInst>(E->getAltOp())->getPredicate(), CostKind,
6080             E->getAltOp());
6081       } else {
6082         Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
6083         Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
6084         auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size());
6085         auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size());
6086         VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty,
6087                                         TTI::CastContextHint::None, CostKind);
6088         VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty,
6089                                          TTI::CastContextHint::None, CostKind);
6090       }
6091 
6092       if (E->ReuseShuffleIndices.empty()) {
6093         CommonCost =
6094             TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy);
6095       } else {
6096         SmallVector<int> Mask;
6097         buildShuffleEntryMask(
6098             E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
6099             [E](Instruction *I) {
6100               assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
6101               return I->getOpcode() == E->getAltOpcode();
6102             },
6103             Mask);
6104         CommonCost = TTI->getShuffleCost(TargetTransformInfo::SK_PermuteTwoSrc,
6105                                          FinalVecTy, Mask);
6106       }
6107       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
6108       return CommonCost + VecCost - ScalarCost;
6109     }
6110     default:
6111       llvm_unreachable("Unknown instruction");
6112   }
6113 }
6114 
6115 bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const {
6116   LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
6117                     << VectorizableTree.size() << " is fully vectorizable .\n");
6118 
6119   auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) {
6120     SmallVector<int> Mask;
6121     return TE->State == TreeEntry::NeedToGather &&
6122            !any_of(TE->Scalars,
6123                    [this](Value *V) { return EphValues.contains(V); }) &&
6124            (allConstant(TE->Scalars) || isSplat(TE->Scalars) ||
6125             TE->Scalars.size() < Limit ||
6126             ((TE->getOpcode() == Instruction::ExtractElement ||
6127               all_of(TE->Scalars,
6128                      [](Value *V) {
6129                        return isa<ExtractElementInst, UndefValue>(V);
6130                      })) &&
6131              isFixedVectorShuffle(TE->Scalars, Mask)) ||
6132             (TE->State == TreeEntry::NeedToGather &&
6133              TE->getOpcode() == Instruction::Load && !TE->isAltShuffle()));
6134   };
6135 
6136   // We only handle trees of heights 1 and 2.
6137   if (VectorizableTree.size() == 1 &&
6138       (VectorizableTree[0]->State == TreeEntry::Vectorize ||
6139        (ForReduction &&
6140         AreVectorizableGathers(VectorizableTree[0].get(),
6141                                VectorizableTree[0]->Scalars.size()) &&
6142         VectorizableTree[0]->getVectorFactor() > 2)))
6143     return true;
6144 
6145   if (VectorizableTree.size() != 2)
6146     return false;
6147 
6148   // Handle splat and all-constants stores. Also try to vectorize tiny trees
6149   // with the second gather nodes if they have less scalar operands rather than
6150   // the initial tree element (may be profitable to shuffle the second gather)
6151   // or they are extractelements, which form shuffle.
6152   SmallVector<int> Mask;
6153   if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
6154       AreVectorizableGathers(VectorizableTree[1].get(),
6155                              VectorizableTree[0]->Scalars.size()))
6156     return true;
6157 
6158   // Gathering cost would be too much for tiny trees.
6159   if (VectorizableTree[0]->State == TreeEntry::NeedToGather ||
6160       (VectorizableTree[1]->State == TreeEntry::NeedToGather &&
6161        VectorizableTree[0]->State != TreeEntry::ScatterVectorize))
6162     return false;
6163 
6164   return true;
6165 }
6166 
6167 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts,
6168                                        TargetTransformInfo *TTI,
6169                                        bool MustMatchOrInst) {
6170   // Look past the root to find a source value. Arbitrarily follow the
6171   // path through operand 0 of any 'or'. Also, peek through optional
6172   // shift-left-by-multiple-of-8-bits.
6173   Value *ZextLoad = Root;
6174   const APInt *ShAmtC;
6175   bool FoundOr = false;
6176   while (!isa<ConstantExpr>(ZextLoad) &&
6177          (match(ZextLoad, m_Or(m_Value(), m_Value())) ||
6178           (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) &&
6179            ShAmtC->urem(8) == 0))) {
6180     auto *BinOp = cast<BinaryOperator>(ZextLoad);
6181     ZextLoad = BinOp->getOperand(0);
6182     if (BinOp->getOpcode() == Instruction::Or)
6183       FoundOr = true;
6184   }
6185   // Check if the input is an extended load of the required or/shift expression.
6186   Value *Load;
6187   if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root ||
6188       !match(ZextLoad, m_ZExt(m_Value(Load))) || !isa<LoadInst>(Load))
6189     return false;
6190 
6191   // Require that the total load bit width is a legal integer type.
6192   // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
6193   // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
6194   Type *SrcTy = Load->getType();
6195   unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts;
6196   if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth)))
6197     return false;
6198 
6199   // Everything matched - assume that we can fold the whole sequence using
6200   // load combining.
6201   LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "
6202              << *(cast<Instruction>(Root)) << "\n");
6203 
6204   return true;
6205 }
6206 
6207 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const {
6208   if (RdxKind != RecurKind::Or)
6209     return false;
6210 
6211   unsigned NumElts = VectorizableTree[0]->Scalars.size();
6212   Value *FirstReduced = VectorizableTree[0]->Scalars[0];
6213   return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI,
6214                                     /* MatchOr */ false);
6215 }
6216 
6217 bool BoUpSLP::isLoadCombineCandidate() const {
6218   // Peek through a final sequence of stores and check if all operations are
6219   // likely to be load-combined.
6220   unsigned NumElts = VectorizableTree[0]->Scalars.size();
6221   for (Value *Scalar : VectorizableTree[0]->Scalars) {
6222     Value *X;
6223     if (!match(Scalar, m_Store(m_Value(X), m_Value())) ||
6224         !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true))
6225       return false;
6226   }
6227   return true;
6228 }
6229 
6230 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const {
6231   // No need to vectorize inserts of gathered values.
6232   if (VectorizableTree.size() == 2 &&
6233       isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) &&
6234       VectorizableTree[1]->State == TreeEntry::NeedToGather)
6235     return true;
6236 
6237   // We can vectorize the tree if its size is greater than or equal to the
6238   // minimum size specified by the MinTreeSize command line option.
6239   if (VectorizableTree.size() >= MinTreeSize)
6240     return false;
6241 
6242   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
6243   // can vectorize it if we can prove it fully vectorizable.
6244   if (isFullyVectorizableTinyTree(ForReduction))
6245     return false;
6246 
6247   assert(VectorizableTree.empty()
6248              ? ExternalUses.empty()
6249              : true && "We shouldn't have any external users");
6250 
6251   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
6252   // vectorizable.
6253   return true;
6254 }
6255 
6256 InstructionCost BoUpSLP::getSpillCost() const {
6257   // Walk from the bottom of the tree to the top, tracking which values are
6258   // live. When we see a call instruction that is not part of our tree,
6259   // query TTI to see if there is a cost to keeping values live over it
6260   // (for example, if spills and fills are required).
6261   unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
6262   InstructionCost Cost = 0;
6263 
6264   SmallPtrSet<Instruction*, 4> LiveValues;
6265   Instruction *PrevInst = nullptr;
6266 
6267   // The entries in VectorizableTree are not necessarily ordered by their
6268   // position in basic blocks. Collect them and order them by dominance so later
6269   // instructions are guaranteed to be visited first. For instructions in
6270   // different basic blocks, we only scan to the beginning of the block, so
6271   // their order does not matter, as long as all instructions in a basic block
6272   // are grouped together. Using dominance ensures a deterministic order.
6273   SmallVector<Instruction *, 16> OrderedScalars;
6274   for (const auto &TEPtr : VectorizableTree) {
6275     Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
6276     if (!Inst)
6277       continue;
6278     OrderedScalars.push_back(Inst);
6279   }
6280   llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) {
6281     auto *NodeA = DT->getNode(A->getParent());
6282     auto *NodeB = DT->getNode(B->getParent());
6283     assert(NodeA && "Should only process reachable instructions");
6284     assert(NodeB && "Should only process reachable instructions");
6285     assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
6286            "Different nodes should have different DFS numbers");
6287     if (NodeA != NodeB)
6288       return NodeA->getDFSNumIn() < NodeB->getDFSNumIn();
6289     return B->comesBefore(A);
6290   });
6291 
6292   for (Instruction *Inst : OrderedScalars) {
6293     if (!PrevInst) {
6294       PrevInst = Inst;
6295       continue;
6296     }
6297 
6298     // Update LiveValues.
6299     LiveValues.erase(PrevInst);
6300     for (auto &J : PrevInst->operands()) {
6301       if (isa<Instruction>(&*J) && getTreeEntry(&*J))
6302         LiveValues.insert(cast<Instruction>(&*J));
6303     }
6304 
6305     LLVM_DEBUG({
6306       dbgs() << "SLP: #LV: " << LiveValues.size();
6307       for (auto *X : LiveValues)
6308         dbgs() << " " << X->getName();
6309       dbgs() << ", Looking at ";
6310       Inst->dump();
6311     });
6312 
6313     // Now find the sequence of instructions between PrevInst and Inst.
6314     unsigned NumCalls = 0;
6315     BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
6316                                  PrevInstIt =
6317                                      PrevInst->getIterator().getReverse();
6318     while (InstIt != PrevInstIt) {
6319       if (PrevInstIt == PrevInst->getParent()->rend()) {
6320         PrevInstIt = Inst->getParent()->rbegin();
6321         continue;
6322       }
6323 
6324       // Debug information does not impact spill cost.
6325       if ((isa<CallInst>(&*PrevInstIt) &&
6326            !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
6327           &*PrevInstIt != PrevInst)
6328         NumCalls++;
6329 
6330       ++PrevInstIt;
6331     }
6332 
6333     if (NumCalls) {
6334       SmallVector<Type*, 4> V;
6335       for (auto *II : LiveValues) {
6336         auto *ScalarTy = II->getType();
6337         if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy))
6338           ScalarTy = VectorTy->getElementType();
6339         V.push_back(FixedVectorType::get(ScalarTy, BundleWidth));
6340       }
6341       Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
6342     }
6343 
6344     PrevInst = Inst;
6345   }
6346 
6347   return Cost;
6348 }
6349 
6350 /// Check if two insertelement instructions are from the same buildvector.
6351 static bool areTwoInsertFromSameBuildVector(InsertElementInst *VU,
6352                                             InsertElementInst *V) {
6353   // Instructions must be from the same basic blocks.
6354   if (VU->getParent() != V->getParent())
6355     return false;
6356   // Checks if 2 insertelements are from the same buildvector.
6357   if (VU->getType() != V->getType())
6358     return false;
6359   // Multiple used inserts are separate nodes.
6360   if (!VU->hasOneUse() && !V->hasOneUse())
6361     return false;
6362   auto *IE1 = VU;
6363   auto *IE2 = V;
6364   // Go through the vector operand of insertelement instructions trying to find
6365   // either VU as the original vector for IE2 or V as the original vector for
6366   // IE1.
6367   do {
6368     if (IE2 == VU || IE1 == V)
6369       return true;
6370     if (IE1) {
6371       if (IE1 != VU && !IE1->hasOneUse())
6372         IE1 = nullptr;
6373       else
6374         IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0));
6375     }
6376     if (IE2) {
6377       if (IE2 != V && !IE2->hasOneUse())
6378         IE2 = nullptr;
6379       else
6380         IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0));
6381     }
6382   } while (IE1 || IE2);
6383   return false;
6384 }
6385 
6386 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) {
6387   InstructionCost Cost = 0;
6388   LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
6389                     << VectorizableTree.size() << ".\n");
6390 
6391   unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
6392 
6393   for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
6394     TreeEntry &TE = *VectorizableTree[I];
6395 
6396     InstructionCost C = getEntryCost(&TE, VectorizedVals);
6397     Cost += C;
6398     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6399                       << " for bundle that starts with " << *TE.Scalars[0]
6400                       << ".\n"
6401                       << "SLP: Current total cost = " << Cost << "\n");
6402   }
6403 
6404   SmallPtrSet<Value *, 16> ExtractCostCalculated;
6405   InstructionCost ExtractCost = 0;
6406   SmallVector<unsigned> VF;
6407   SmallVector<SmallVector<int>> ShuffleMask;
6408   SmallVector<Value *> FirstUsers;
6409   SmallVector<APInt> DemandedElts;
6410   for (ExternalUser &EU : ExternalUses) {
6411     // We only add extract cost once for the same scalar.
6412     if (!isa_and_nonnull<InsertElementInst>(EU.User) &&
6413         !ExtractCostCalculated.insert(EU.Scalar).second)
6414       continue;
6415 
6416     // Uses by ephemeral values are free (because the ephemeral value will be
6417     // removed prior to code generation, and so the extraction will be
6418     // removed as well).
6419     if (EphValues.count(EU.User))
6420       continue;
6421 
6422     // No extract cost for vector "scalar"
6423     if (isa<FixedVectorType>(EU.Scalar->getType()))
6424       continue;
6425 
6426     // Already counted the cost for external uses when tried to adjust the cost
6427     // for extractelements, no need to add it again.
6428     if (isa<ExtractElementInst>(EU.Scalar))
6429       continue;
6430 
6431     // If found user is an insertelement, do not calculate extract cost but try
6432     // to detect it as a final shuffled/identity match.
6433     if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) {
6434       if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) {
6435         Optional<unsigned> InsertIdx = getInsertIndex(VU);
6436         if (InsertIdx) {
6437           auto *It = find_if(FirstUsers, [VU](Value *V) {
6438             return areTwoInsertFromSameBuildVector(VU,
6439                                                    cast<InsertElementInst>(V));
6440           });
6441           int VecId = -1;
6442           if (It == FirstUsers.end()) {
6443             VF.push_back(FTy->getNumElements());
6444             ShuffleMask.emplace_back(VF.back(), UndefMaskElem);
6445             // Find the insertvector, vectorized in tree, if any.
6446             Value *Base = VU;
6447             while (auto *IEBase = dyn_cast<InsertElementInst>(Base)) {
6448               // Build the mask for the vectorized insertelement instructions.
6449               if (const TreeEntry *E = getTreeEntry(IEBase)) {
6450                 VU = IEBase;
6451                 do {
6452                   int Idx = E->findLaneForValue(Base);
6453                   ShuffleMask.back()[Idx] = Idx;
6454                   Base = cast<InsertElementInst>(Base)->getOperand(0);
6455                 } while (E == getTreeEntry(Base));
6456                 break;
6457               }
6458               Base = cast<InsertElementInst>(Base)->getOperand(0);
6459             }
6460             FirstUsers.push_back(VU);
6461             DemandedElts.push_back(APInt::getZero(VF.back()));
6462             VecId = FirstUsers.size() - 1;
6463           } else {
6464             VecId = std::distance(FirstUsers.begin(), It);
6465           }
6466           int InIdx = *InsertIdx;
6467           ShuffleMask[VecId][InIdx] = EU.Lane;
6468           DemandedElts[VecId].setBit(InIdx);
6469           continue;
6470         }
6471       }
6472     }
6473 
6474     // If we plan to rewrite the tree in a smaller type, we will need to sign
6475     // extend the extracted value back to the original type. Here, we account
6476     // for the extract and the added cost of the sign extend if needed.
6477     auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth);
6478     auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
6479     if (MinBWs.count(ScalarRoot)) {
6480       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
6481       auto Extend =
6482           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
6483       VecTy = FixedVectorType::get(MinTy, BundleWidth);
6484       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
6485                                                    VecTy, EU.Lane);
6486     } else {
6487       ExtractCost +=
6488           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
6489     }
6490   }
6491 
6492   InstructionCost SpillCost = getSpillCost();
6493   Cost += SpillCost + ExtractCost;
6494   if (FirstUsers.size() == 1) {
6495     int Limit = ShuffleMask.front().size() * 2;
6496     if (!all_of(ShuffleMask.front(),
6497                 [Limit](int Idx) { return Idx < Limit; }) ||
6498         !ShuffleVectorInst::isIdentityMask(ShuffleMask.front())) {
6499       InstructionCost C = TTI->getShuffleCost(
6500           TTI::SK_PermuteSingleSrc,
6501           cast<FixedVectorType>(FirstUsers.front()->getType()),
6502           ShuffleMask.front());
6503       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6504                         << " for final shuffle of insertelement external users "
6505                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6506                         << "SLP: Current total cost = " << Cost << "\n");
6507       Cost += C;
6508     }
6509     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6510         cast<FixedVectorType>(FirstUsers.front()->getType()),
6511         DemandedElts.front(), /*Insert*/ true, /*Extract*/ false);
6512     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6513                       << " for insertelements gather.\n"
6514                       << "SLP: Current total cost = " << Cost << "\n");
6515     Cost -= InsertCost;
6516   } else if (FirstUsers.size() >= 2) {
6517     unsigned MaxVF = *std::max_element(VF.begin(), VF.end());
6518     // Combined masks of the first 2 vectors.
6519     SmallVector<int> CombinedMask(MaxVF, UndefMaskElem);
6520     copy(ShuffleMask.front(), CombinedMask.begin());
6521     APInt CombinedDemandedElts = DemandedElts.front().zextOrSelf(MaxVF);
6522     auto *VecTy = FixedVectorType::get(
6523         cast<VectorType>(FirstUsers.front()->getType())->getElementType(),
6524         MaxVF);
6525     for (int I = 0, E = ShuffleMask[1].size(); I < E; ++I) {
6526       if (ShuffleMask[1][I] != UndefMaskElem) {
6527         CombinedMask[I] = ShuffleMask[1][I] + MaxVF;
6528         CombinedDemandedElts.setBit(I);
6529       }
6530     }
6531     InstructionCost C =
6532         TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6533     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6534                       << " for final shuffle of vector node and external "
6535                          "insertelement users "
6536                       << *VectorizableTree.front()->Scalars.front() << ".\n"
6537                       << "SLP: Current total cost = " << Cost << "\n");
6538     Cost += C;
6539     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6540         VecTy, CombinedDemandedElts, /*Insert*/ true, /*Extract*/ false);
6541     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6542                       << " for insertelements gather.\n"
6543                       << "SLP: Current total cost = " << Cost << "\n");
6544     Cost -= InsertCost;
6545     for (int I = 2, E = FirstUsers.size(); I < E; ++I) {
6546       if (ShuffleMask[I].empty())
6547         continue;
6548       // Other elements - permutation of 2 vectors (the initial one and the
6549       // next Ith incoming vector).
6550       unsigned VF = ShuffleMask[I].size();
6551       for (unsigned Idx = 0; Idx < VF; ++Idx) {
6552         int Mask = ShuffleMask[I][Idx];
6553         if (Mask != UndefMaskElem)
6554           CombinedMask[Idx] = MaxVF + Mask;
6555         else if (CombinedMask[Idx] != UndefMaskElem)
6556           CombinedMask[Idx] = Idx;
6557       }
6558       for (unsigned Idx = VF; Idx < MaxVF; ++Idx)
6559         if (CombinedMask[Idx] != UndefMaskElem)
6560           CombinedMask[Idx] = Idx;
6561       InstructionCost C =
6562           TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6563       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6564                         << " for final shuffle of vector node and external "
6565                            "insertelement users "
6566                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6567                         << "SLP: Current total cost = " << Cost << "\n");
6568       Cost += C;
6569       InstructionCost InsertCost = TTI->getScalarizationOverhead(
6570           cast<FixedVectorType>(FirstUsers[I]->getType()), DemandedElts[I],
6571           /*Insert*/ true, /*Extract*/ false);
6572       LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6573                         << " for insertelements gather.\n"
6574                         << "SLP: Current total cost = " << Cost << "\n");
6575       Cost -= InsertCost;
6576     }
6577   }
6578 
6579 #ifndef NDEBUG
6580   SmallString<256> Str;
6581   {
6582     raw_svector_ostream OS(Str);
6583     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
6584        << "SLP: Extract Cost = " << ExtractCost << ".\n"
6585        << "SLP: Total Cost = " << Cost << ".\n";
6586   }
6587   LLVM_DEBUG(dbgs() << Str);
6588   if (ViewSLPTree)
6589     ViewGraph(this, "SLP" + F->getName(), false, Str);
6590 #endif
6591 
6592   return Cost;
6593 }
6594 
6595 Optional<TargetTransformInfo::ShuffleKind>
6596 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
6597                                SmallVectorImpl<const TreeEntry *> &Entries) {
6598   // TODO: currently checking only for Scalars in the tree entry, need to count
6599   // reused elements too for better cost estimation.
6600   Mask.assign(TE->Scalars.size(), UndefMaskElem);
6601   Entries.clear();
6602   // Build a lists of values to tree entries.
6603   DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs;
6604   for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) {
6605     if (EntryPtr.get() == TE)
6606       break;
6607     if (EntryPtr->State != TreeEntry::NeedToGather)
6608       continue;
6609     for (Value *V : EntryPtr->Scalars)
6610       ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get());
6611   }
6612   // Find all tree entries used by the gathered values. If no common entries
6613   // found - not a shuffle.
6614   // Here we build a set of tree nodes for each gathered value and trying to
6615   // find the intersection between these sets. If we have at least one common
6616   // tree node for each gathered value - we have just a permutation of the
6617   // single vector. If we have 2 different sets, we're in situation where we
6618   // have a permutation of 2 input vectors.
6619   SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs;
6620   DenseMap<Value *, int> UsedValuesEntry;
6621   for (Value *V : TE->Scalars) {
6622     if (isa<UndefValue>(V))
6623       continue;
6624     // Build a list of tree entries where V is used.
6625     SmallPtrSet<const TreeEntry *, 4> VToTEs;
6626     auto It = ValueToTEs.find(V);
6627     if (It != ValueToTEs.end())
6628       VToTEs = It->second;
6629     if (const TreeEntry *VTE = getTreeEntry(V))
6630       VToTEs.insert(VTE);
6631     if (VToTEs.empty())
6632       return None;
6633     if (UsedTEs.empty()) {
6634       // The first iteration, just insert the list of nodes to vector.
6635       UsedTEs.push_back(VToTEs);
6636     } else {
6637       // Need to check if there are any previously used tree nodes which use V.
6638       // If there are no such nodes, consider that we have another one input
6639       // vector.
6640       SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs);
6641       unsigned Idx = 0;
6642       for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) {
6643         // Do we have a non-empty intersection of previously listed tree entries
6644         // and tree entries using current V?
6645         set_intersect(VToTEs, Set);
6646         if (!VToTEs.empty()) {
6647           // Yes, write the new subset and continue analysis for the next
6648           // scalar.
6649           Set.swap(VToTEs);
6650           break;
6651         }
6652         VToTEs = SavedVToTEs;
6653         ++Idx;
6654       }
6655       // No non-empty intersection found - need to add a second set of possible
6656       // source vectors.
6657       if (Idx == UsedTEs.size()) {
6658         // If the number of input vectors is greater than 2 - not a permutation,
6659         // fallback to the regular gather.
6660         if (UsedTEs.size() == 2)
6661           return None;
6662         UsedTEs.push_back(SavedVToTEs);
6663         Idx = UsedTEs.size() - 1;
6664       }
6665       UsedValuesEntry.try_emplace(V, Idx);
6666     }
6667   }
6668 
6669   if (UsedTEs.empty()) {
6670     assert(all_of(TE->Scalars, UndefValue::classof) &&
6671            "Expected vector of undefs only.");
6672     return None;
6673   }
6674 
6675   unsigned VF = 0;
6676   if (UsedTEs.size() == 1) {
6677     // Try to find the perfect match in another gather node at first.
6678     auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) {
6679       return EntryPtr->isSame(TE->Scalars);
6680     });
6681     if (It != UsedTEs.front().end()) {
6682       Entries.push_back(*It);
6683       std::iota(Mask.begin(), Mask.end(), 0);
6684       return TargetTransformInfo::SK_PermuteSingleSrc;
6685     }
6686     // No perfect match, just shuffle, so choose the first tree node.
6687     Entries.push_back(*UsedTEs.front().begin());
6688   } else {
6689     // Try to find nodes with the same vector factor.
6690     assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries.");
6691     DenseMap<int, const TreeEntry *> VFToTE;
6692     for (const TreeEntry *TE : UsedTEs.front())
6693       VFToTE.try_emplace(TE->getVectorFactor(), TE);
6694     for (const TreeEntry *TE : UsedTEs.back()) {
6695       auto It = VFToTE.find(TE->getVectorFactor());
6696       if (It != VFToTE.end()) {
6697         VF = It->first;
6698         Entries.push_back(It->second);
6699         Entries.push_back(TE);
6700         break;
6701       }
6702     }
6703     // No 2 source vectors with the same vector factor - give up and do regular
6704     // gather.
6705     if (Entries.empty())
6706       return None;
6707   }
6708 
6709   // Build a shuffle mask for better cost estimation and vector emission.
6710   for (int I = 0, E = TE->Scalars.size(); I < E; ++I) {
6711     Value *V = TE->Scalars[I];
6712     if (isa<UndefValue>(V))
6713       continue;
6714     unsigned Idx = UsedValuesEntry.lookup(V);
6715     const TreeEntry *VTE = Entries[Idx];
6716     int FoundLane = VTE->findLaneForValue(V);
6717     Mask[I] = Idx * VF + FoundLane;
6718     // Extra check required by isSingleSourceMaskImpl function (called by
6719     // ShuffleVectorInst::isSingleSourceMask).
6720     if (Mask[I] >= 2 * E)
6721       return None;
6722   }
6723   switch (Entries.size()) {
6724   case 1:
6725     return TargetTransformInfo::SK_PermuteSingleSrc;
6726   case 2:
6727     return TargetTransformInfo::SK_PermuteTwoSrc;
6728   default:
6729     break;
6730   }
6731   return None;
6732 }
6733 
6734 InstructionCost BoUpSLP::getGatherCost(FixedVectorType *Ty,
6735                                        const APInt &ShuffledIndices,
6736                                        bool NeedToShuffle) const {
6737   InstructionCost Cost =
6738       TTI->getScalarizationOverhead(Ty, ~ShuffledIndices, /*Insert*/ true,
6739                                     /*Extract*/ false);
6740   if (NeedToShuffle)
6741     Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
6742   return Cost;
6743 }
6744 
6745 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
6746   // Find the type of the operands in VL.
6747   Type *ScalarTy = VL[0]->getType();
6748   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
6749     ScalarTy = SI->getValueOperand()->getType();
6750   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
6751   bool DuplicateNonConst = false;
6752   // Find the cost of inserting/extracting values from the vector.
6753   // Check if the same elements are inserted several times and count them as
6754   // shuffle candidates.
6755   APInt ShuffledElements = APInt::getZero(VL.size());
6756   DenseSet<Value *> UniqueElements;
6757   // Iterate in reverse order to consider insert elements with the high cost.
6758   for (unsigned I = VL.size(); I > 0; --I) {
6759     unsigned Idx = I - 1;
6760     // No need to shuffle duplicates for constants.
6761     if (isConstant(VL[Idx])) {
6762       ShuffledElements.setBit(Idx);
6763       continue;
6764     }
6765     if (!UniqueElements.insert(VL[Idx]).second) {
6766       DuplicateNonConst = true;
6767       ShuffledElements.setBit(Idx);
6768     }
6769   }
6770   return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst);
6771 }
6772 
6773 // Perform operand reordering on the instructions in VL and return the reordered
6774 // operands in Left and Right.
6775 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
6776                                              SmallVectorImpl<Value *> &Left,
6777                                              SmallVectorImpl<Value *> &Right,
6778                                              const DataLayout &DL,
6779                                              ScalarEvolution &SE,
6780                                              const BoUpSLP &R) {
6781   if (VL.empty())
6782     return;
6783   VLOperands Ops(VL, DL, SE, R);
6784   // Reorder the operands in place.
6785   Ops.reorder();
6786   Left = Ops.getVL(0);
6787   Right = Ops.getVL(1);
6788 }
6789 
6790 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) {
6791   // Get the basic block this bundle is in. All instructions in the bundle
6792   // should be in this block.
6793   auto *Front = E->getMainOp();
6794   auto *BB = Front->getParent();
6795   assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool {
6796     auto *I = cast<Instruction>(V);
6797     return !E->isOpcodeOrAlt(I) || I->getParent() == BB;
6798   }));
6799 
6800   auto &&FindLastInst = [E, Front]() {
6801     Instruction *LastInst = Front;
6802     for (Value *V : E->Scalars) {
6803       auto *I = dyn_cast<Instruction>(V);
6804       if (!I)
6805         continue;
6806       if (LastInst->comesBefore(I))
6807         LastInst = I;
6808     }
6809     return LastInst;
6810   };
6811 
6812   auto &&FindFirstInst = [E, Front]() {
6813     Instruction *FirstInst = Front;
6814     for (Value *V : E->Scalars) {
6815       auto *I = dyn_cast<Instruction>(V);
6816       if (!I)
6817         continue;
6818       if (I->comesBefore(FirstInst))
6819         FirstInst = I;
6820     }
6821     return FirstInst;
6822   };
6823 
6824   // Set the insert point to the beginning of the basic block if the entry
6825   // should not be scheduled.
6826   if (E->State != TreeEntry::NeedToGather &&
6827       doesNotNeedToSchedule(E->Scalars)) {
6828     Instruction *InsertInst;
6829     if (all_of(E->Scalars, isUsedOutsideBlock))
6830       InsertInst = FindLastInst();
6831     else
6832       InsertInst = FindFirstInst();
6833     // If the instruction is PHI, set the insert point after all the PHIs.
6834     if (isa<PHINode>(InsertInst))
6835       InsertInst = BB->getFirstNonPHI();
6836     BasicBlock::iterator InsertPt = InsertInst->getIterator();
6837     Builder.SetInsertPoint(BB, InsertPt);
6838     Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6839     return;
6840   }
6841 
6842   // The last instruction in the bundle in program order.
6843   Instruction *LastInst = nullptr;
6844 
6845   // Find the last instruction. The common case should be that BB has been
6846   // scheduled, and the last instruction is VL.back(). So we start with
6847   // VL.back() and iterate over schedule data until we reach the end of the
6848   // bundle. The end of the bundle is marked by null ScheduleData.
6849   if (BlocksSchedules.count(BB)) {
6850     Value *V = E->isOneOf(E->Scalars.back());
6851     if (doesNotNeedToBeScheduled(V))
6852       V = *find_if_not(E->Scalars, doesNotNeedToBeScheduled);
6853     auto *Bundle = BlocksSchedules[BB]->getScheduleData(V);
6854     if (Bundle && Bundle->isPartOfBundle())
6855       for (; Bundle; Bundle = Bundle->NextInBundle)
6856         if (Bundle->OpValue == Bundle->Inst)
6857           LastInst = Bundle->Inst;
6858   }
6859 
6860   // LastInst can still be null at this point if there's either not an entry
6861   // for BB in BlocksSchedules or there's no ScheduleData available for
6862   // VL.back(). This can be the case if buildTree_rec aborts for various
6863   // reasons (e.g., the maximum recursion depth is reached, the maximum region
6864   // size is reached, etc.). ScheduleData is initialized in the scheduling
6865   // "dry-run".
6866   //
6867   // If this happens, we can still find the last instruction by brute force. We
6868   // iterate forwards from Front (inclusive) until we either see all
6869   // instructions in the bundle or reach the end of the block. If Front is the
6870   // last instruction in program order, LastInst will be set to Front, and we
6871   // will visit all the remaining instructions in the block.
6872   //
6873   // One of the reasons we exit early from buildTree_rec is to place an upper
6874   // bound on compile-time. Thus, taking an additional compile-time hit here is
6875   // not ideal. However, this should be exceedingly rare since it requires that
6876   // we both exit early from buildTree_rec and that the bundle be out-of-order
6877   // (causing us to iterate all the way to the end of the block).
6878   if (!LastInst) {
6879     LastInst = FindLastInst();
6880     // If the instruction is PHI, set the insert point after all the PHIs.
6881     if (isa<PHINode>(LastInst))
6882       LastInst = BB->getFirstNonPHI()->getPrevNode();
6883   }
6884   assert(LastInst && "Failed to find last instruction in bundle");
6885 
6886   // Set the insertion point after the last instruction in the bundle. Set the
6887   // debug location to Front.
6888   Builder.SetInsertPoint(BB, std::next(LastInst->getIterator()));
6889   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6890 }
6891 
6892 Value *BoUpSLP::gather(ArrayRef<Value *> VL) {
6893   // List of instructions/lanes from current block and/or the blocks which are
6894   // part of the current loop. These instructions will be inserted at the end to
6895   // make it possible to optimize loops and hoist invariant instructions out of
6896   // the loops body with better chances for success.
6897   SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts;
6898   SmallSet<int, 4> PostponedIndices;
6899   Loop *L = LI->getLoopFor(Builder.GetInsertBlock());
6900   auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) {
6901     SmallPtrSet<BasicBlock *, 4> Visited;
6902     while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second)
6903       InsertBB = InsertBB->getSinglePredecessor();
6904     return InsertBB && InsertBB == InstBB;
6905   };
6906   for (int I = 0, E = VL.size(); I < E; ++I) {
6907     if (auto *Inst = dyn_cast<Instruction>(VL[I]))
6908       if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) ||
6909            getTreeEntry(Inst) || (L && (L->contains(Inst)))) &&
6910           PostponedIndices.insert(I).second)
6911         PostponedInsts.emplace_back(Inst, I);
6912   }
6913 
6914   auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) {
6915     Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos));
6916     auto *InsElt = dyn_cast<InsertElementInst>(Vec);
6917     if (!InsElt)
6918       return Vec;
6919     GatherShuffleSeq.insert(InsElt);
6920     CSEBlocks.insert(InsElt->getParent());
6921     // Add to our 'need-to-extract' list.
6922     if (TreeEntry *Entry = getTreeEntry(V)) {
6923       // Find which lane we need to extract.
6924       unsigned FoundLane = Entry->findLaneForValue(V);
6925       ExternalUses.emplace_back(V, InsElt, FoundLane);
6926     }
6927     return Vec;
6928   };
6929   Value *Val0 =
6930       isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0];
6931   FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size());
6932   Value *Vec = PoisonValue::get(VecTy);
6933   SmallVector<int> NonConsts;
6934   // Insert constant values at first.
6935   for (int I = 0, E = VL.size(); I < E; ++I) {
6936     if (PostponedIndices.contains(I))
6937       continue;
6938     if (!isConstant(VL[I])) {
6939       NonConsts.push_back(I);
6940       continue;
6941     }
6942     Vec = CreateInsertElement(Vec, VL[I], I);
6943   }
6944   // Insert non-constant values.
6945   for (int I : NonConsts)
6946     Vec = CreateInsertElement(Vec, VL[I], I);
6947   // Append instructions, which are/may be part of the loop, in the end to make
6948   // it possible to hoist non-loop-based instructions.
6949   for (const std::pair<Value *, unsigned> &Pair : PostponedInsts)
6950     Vec = CreateInsertElement(Vec, Pair.first, Pair.second);
6951 
6952   return Vec;
6953 }
6954 
6955 namespace {
6956 /// Merges shuffle masks and emits final shuffle instruction, if required.
6957 class ShuffleInstructionBuilder {
6958   IRBuilderBase &Builder;
6959   const unsigned VF = 0;
6960   bool IsFinalized = false;
6961   SmallVector<int, 4> Mask;
6962   /// Holds all of the instructions that we gathered.
6963   SetVector<Instruction *> &GatherShuffleSeq;
6964   /// A list of blocks that we are going to CSE.
6965   SetVector<BasicBlock *> &CSEBlocks;
6966 
6967 public:
6968   ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF,
6969                             SetVector<Instruction *> &GatherShuffleSeq,
6970                             SetVector<BasicBlock *> &CSEBlocks)
6971       : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq),
6972         CSEBlocks(CSEBlocks) {}
6973 
6974   /// Adds a mask, inverting it before applying.
6975   void addInversedMask(ArrayRef<unsigned> SubMask) {
6976     if (SubMask.empty())
6977       return;
6978     SmallVector<int, 4> NewMask;
6979     inversePermutation(SubMask, NewMask);
6980     addMask(NewMask);
6981   }
6982 
6983   /// Functions adds masks, merging them into  single one.
6984   void addMask(ArrayRef<unsigned> SubMask) {
6985     SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end());
6986     addMask(NewMask);
6987   }
6988 
6989   void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); }
6990 
6991   Value *finalize(Value *V) {
6992     IsFinalized = true;
6993     unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements();
6994     if (VF == ValueVF && Mask.empty())
6995       return V;
6996     SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem);
6997     std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0);
6998     addMask(NormalizedMask);
6999 
7000     if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask))
7001       return V;
7002     Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle");
7003     if (auto *I = dyn_cast<Instruction>(Vec)) {
7004       GatherShuffleSeq.insert(I);
7005       CSEBlocks.insert(I->getParent());
7006     }
7007     return Vec;
7008   }
7009 
7010   ~ShuffleInstructionBuilder() {
7011     assert((IsFinalized || Mask.empty()) &&
7012            "Shuffle construction must be finalized.");
7013   }
7014 };
7015 } // namespace
7016 
7017 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
7018   const unsigned VF = VL.size();
7019   InstructionsState S = getSameOpcode(VL);
7020   if (S.getOpcode()) {
7021     if (TreeEntry *E = getTreeEntry(S.OpValue))
7022       if (E->isSame(VL)) {
7023         Value *V = vectorizeTree(E);
7024         if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) {
7025           if (!E->ReuseShuffleIndices.empty()) {
7026             // Reshuffle to get only unique values.
7027             // If some of the scalars are duplicated in the vectorization tree
7028             // entry, we do not vectorize them but instead generate a mask for
7029             // the reuses. But if there are several users of the same entry,
7030             // they may have different vectorization factors. This is especially
7031             // important for PHI nodes. In this case, we need to adapt the
7032             // resulting instruction for the user vectorization factor and have
7033             // to reshuffle it again to take only unique elements of the vector.
7034             // Without this code the function incorrectly returns reduced vector
7035             // instruction with the same elements, not with the unique ones.
7036 
7037             // block:
7038             // %phi = phi <2 x > { .., %entry} {%shuffle, %block}
7039             // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0>
7040             // ... (use %2)
7041             // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0}
7042             // br %block
7043             SmallVector<int> UniqueIdxs(VF, UndefMaskElem);
7044             SmallSet<int, 4> UsedIdxs;
7045             int Pos = 0;
7046             int Sz = VL.size();
7047             for (int Idx : E->ReuseShuffleIndices) {
7048               if (Idx != Sz && Idx != UndefMaskElem &&
7049                   UsedIdxs.insert(Idx).second)
7050                 UniqueIdxs[Idx] = Pos;
7051               ++Pos;
7052             }
7053             assert(VF >= UsedIdxs.size() && "Expected vectorization factor "
7054                                             "less than original vector size.");
7055             UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem);
7056             V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle");
7057           } else {
7058             assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() &&
7059                    "Expected vectorization factor less "
7060                    "than original vector size.");
7061             SmallVector<int> UniformMask(VF, 0);
7062             std::iota(UniformMask.begin(), UniformMask.end(), 0);
7063             V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle");
7064           }
7065           if (auto *I = dyn_cast<Instruction>(V)) {
7066             GatherShuffleSeq.insert(I);
7067             CSEBlocks.insert(I->getParent());
7068           }
7069         }
7070         return V;
7071       }
7072   }
7073 
7074   // Can't vectorize this, so simply build a new vector with each lane
7075   // corresponding to the requested value.
7076   return createBuildVector(VL);
7077 }
7078 Value *BoUpSLP::createBuildVector(ArrayRef<Value *> VL) {
7079   unsigned VF = VL.size();
7080   // Exploit possible reuse of values across lanes.
7081   SmallVector<int> ReuseShuffleIndicies;
7082   SmallVector<Value *> UniqueValues;
7083   if (VL.size() > 2) {
7084     DenseMap<Value *, unsigned> UniquePositions;
7085     unsigned NumValues =
7086         std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) {
7087                                     return !isa<UndefValue>(V);
7088                                   }).base());
7089     VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues));
7090     int UniqueVals = 0;
7091     for (Value *V : VL.drop_back(VL.size() - VF)) {
7092       if (isa<UndefValue>(V)) {
7093         ReuseShuffleIndicies.emplace_back(UndefMaskElem);
7094         continue;
7095       }
7096       if (isConstant(V)) {
7097         ReuseShuffleIndicies.emplace_back(UniqueValues.size());
7098         UniqueValues.emplace_back(V);
7099         continue;
7100       }
7101       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
7102       ReuseShuffleIndicies.emplace_back(Res.first->second);
7103       if (Res.second) {
7104         UniqueValues.emplace_back(V);
7105         ++UniqueVals;
7106       }
7107     }
7108     if (UniqueVals == 1 && UniqueValues.size() == 1) {
7109       // Emit pure splat vector.
7110       ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(),
7111                                   UndefMaskElem);
7112     } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) {
7113       ReuseShuffleIndicies.clear();
7114       UniqueValues.clear();
7115       UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues));
7116     }
7117     UniqueValues.append(VF - UniqueValues.size(),
7118                         PoisonValue::get(VL[0]->getType()));
7119     VL = UniqueValues;
7120   }
7121 
7122   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
7123                                            CSEBlocks);
7124   Value *Vec = gather(VL);
7125   if (!ReuseShuffleIndicies.empty()) {
7126     ShuffleBuilder.addMask(ReuseShuffleIndicies);
7127     Vec = ShuffleBuilder.finalize(Vec);
7128   }
7129   return Vec;
7130 }
7131 
7132 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
7133   IRBuilder<>::InsertPointGuard Guard(Builder);
7134 
7135   if (E->VectorizedValue) {
7136     LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
7137     return E->VectorizedValue;
7138   }
7139 
7140   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
7141   unsigned VF = E->getVectorFactor();
7142   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
7143                                            CSEBlocks);
7144   if (E->State == TreeEntry::NeedToGather) {
7145     if (E->getMainOp())
7146       setInsertPointAfterBundle(E);
7147     Value *Vec;
7148     SmallVector<int> Mask;
7149     SmallVector<const TreeEntry *> Entries;
7150     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
7151         isGatherShuffledEntry(E, Mask, Entries);
7152     if (Shuffle.hasValue()) {
7153       assert((Entries.size() == 1 || Entries.size() == 2) &&
7154              "Expected shuffle of 1 or 2 entries.");
7155       Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue,
7156                                         Entries.back()->VectorizedValue, Mask);
7157       if (auto *I = dyn_cast<Instruction>(Vec)) {
7158         GatherShuffleSeq.insert(I);
7159         CSEBlocks.insert(I->getParent());
7160       }
7161     } else {
7162       Vec = gather(E->Scalars);
7163     }
7164     if (NeedToShuffleReuses) {
7165       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7166       Vec = ShuffleBuilder.finalize(Vec);
7167     }
7168     E->VectorizedValue = Vec;
7169     return Vec;
7170   }
7171 
7172   assert((E->State == TreeEntry::Vectorize ||
7173           E->State == TreeEntry::ScatterVectorize) &&
7174          "Unhandled state");
7175   unsigned ShuffleOrOp =
7176       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
7177   Instruction *VL0 = E->getMainOp();
7178   Type *ScalarTy = VL0->getType();
7179   if (auto *Store = dyn_cast<StoreInst>(VL0))
7180     ScalarTy = Store->getValueOperand()->getType();
7181   else if (auto *IE = dyn_cast<InsertElementInst>(VL0))
7182     ScalarTy = IE->getOperand(1)->getType();
7183   auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
7184   switch (ShuffleOrOp) {
7185     case Instruction::PHI: {
7186       assert(
7187           (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) &&
7188           "PHI reordering is free.");
7189       auto *PH = cast<PHINode>(VL0);
7190       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
7191       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
7192       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
7193       Value *V = NewPhi;
7194 
7195       // Adjust insertion point once all PHI's have been generated.
7196       Builder.SetInsertPoint(&*PH->getParent()->getFirstInsertionPt());
7197       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
7198 
7199       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7200       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7201       V = ShuffleBuilder.finalize(V);
7202 
7203       E->VectorizedValue = V;
7204 
7205       // PHINodes may have multiple entries from the same block. We want to
7206       // visit every block once.
7207       SmallPtrSet<BasicBlock*, 4> VisitedBBs;
7208 
7209       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
7210         ValueList Operands;
7211         BasicBlock *IBB = PH->getIncomingBlock(i);
7212 
7213         if (!VisitedBBs.insert(IBB).second) {
7214           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
7215           continue;
7216         }
7217 
7218         Builder.SetInsertPoint(IBB->getTerminator());
7219         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
7220         Value *Vec = vectorizeTree(E->getOperand(i));
7221         NewPhi->addIncoming(Vec, IBB);
7222       }
7223 
7224       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
7225              "Invalid number of incoming values");
7226       return V;
7227     }
7228 
7229     case Instruction::ExtractElement: {
7230       Value *V = E->getSingleOperand(0);
7231       Builder.SetInsertPoint(VL0);
7232       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7233       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7234       V = ShuffleBuilder.finalize(V);
7235       E->VectorizedValue = V;
7236       return V;
7237     }
7238     case Instruction::ExtractValue: {
7239       auto *LI = cast<LoadInst>(E->getSingleOperand(0));
7240       Builder.SetInsertPoint(LI);
7241       auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
7242       Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
7243       LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
7244       Value *NewV = propagateMetadata(V, E->Scalars);
7245       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7246       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7247       NewV = ShuffleBuilder.finalize(NewV);
7248       E->VectorizedValue = NewV;
7249       return NewV;
7250     }
7251     case Instruction::InsertElement: {
7252       assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique");
7253       Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back()));
7254       Value *V = vectorizeTree(E->getOperand(1));
7255 
7256       // Create InsertVector shuffle if necessary
7257       auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
7258         return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0));
7259       }));
7260       const unsigned NumElts =
7261           cast<FixedVectorType>(FirstInsert->getType())->getNumElements();
7262       const unsigned NumScalars = E->Scalars.size();
7263 
7264       unsigned Offset = *getInsertIndex(VL0);
7265       assert(Offset < NumElts && "Failed to find vector index offset");
7266 
7267       // Create shuffle to resize vector
7268       SmallVector<int> Mask;
7269       if (!E->ReorderIndices.empty()) {
7270         inversePermutation(E->ReorderIndices, Mask);
7271         Mask.append(NumElts - NumScalars, UndefMaskElem);
7272       } else {
7273         Mask.assign(NumElts, UndefMaskElem);
7274         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
7275       }
7276       // Create InsertVector shuffle if necessary
7277       bool IsIdentity = true;
7278       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
7279       Mask.swap(PrevMask);
7280       for (unsigned I = 0; I < NumScalars; ++I) {
7281         Value *Scalar = E->Scalars[PrevMask[I]];
7282         unsigned InsertIdx = *getInsertIndex(Scalar);
7283         IsIdentity &= InsertIdx - Offset == I;
7284         Mask[InsertIdx - Offset] = I;
7285       }
7286       if (!IsIdentity || NumElts != NumScalars) {
7287         V = Builder.CreateShuffleVector(V, Mask);
7288         if (auto *I = dyn_cast<Instruction>(V)) {
7289           GatherShuffleSeq.insert(I);
7290           CSEBlocks.insert(I->getParent());
7291         }
7292       }
7293 
7294       if ((!IsIdentity || Offset != 0 ||
7295            !isUndefVector(FirstInsert->getOperand(0))) &&
7296           NumElts != NumScalars) {
7297         SmallVector<int> InsertMask(NumElts);
7298         std::iota(InsertMask.begin(), InsertMask.end(), 0);
7299         for (unsigned I = 0; I < NumElts; I++) {
7300           if (Mask[I] != UndefMaskElem)
7301             InsertMask[Offset + I] = NumElts + I;
7302         }
7303 
7304         V = Builder.CreateShuffleVector(
7305             FirstInsert->getOperand(0), V, InsertMask,
7306             cast<Instruction>(E->Scalars.back())->getName());
7307         if (auto *I = dyn_cast<Instruction>(V)) {
7308           GatherShuffleSeq.insert(I);
7309           CSEBlocks.insert(I->getParent());
7310         }
7311       }
7312 
7313       ++NumVectorInstructions;
7314       E->VectorizedValue = V;
7315       return V;
7316     }
7317     case Instruction::ZExt:
7318     case Instruction::SExt:
7319     case Instruction::FPToUI:
7320     case Instruction::FPToSI:
7321     case Instruction::FPExt:
7322     case Instruction::PtrToInt:
7323     case Instruction::IntToPtr:
7324     case Instruction::SIToFP:
7325     case Instruction::UIToFP:
7326     case Instruction::Trunc:
7327     case Instruction::FPTrunc:
7328     case Instruction::BitCast: {
7329       setInsertPointAfterBundle(E);
7330 
7331       Value *InVec = vectorizeTree(E->getOperand(0));
7332 
7333       if (E->VectorizedValue) {
7334         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7335         return E->VectorizedValue;
7336       }
7337 
7338       auto *CI = cast<CastInst>(VL0);
7339       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
7340       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7341       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7342       V = ShuffleBuilder.finalize(V);
7343 
7344       E->VectorizedValue = V;
7345       ++NumVectorInstructions;
7346       return V;
7347     }
7348     case Instruction::FCmp:
7349     case Instruction::ICmp: {
7350       setInsertPointAfterBundle(E);
7351 
7352       Value *L = vectorizeTree(E->getOperand(0));
7353       Value *R = vectorizeTree(E->getOperand(1));
7354 
7355       if (E->VectorizedValue) {
7356         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7357         return E->VectorizedValue;
7358       }
7359 
7360       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
7361       Value *V = Builder.CreateCmp(P0, L, R);
7362       propagateIRFlags(V, E->Scalars, VL0);
7363       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7364       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7365       V = ShuffleBuilder.finalize(V);
7366 
7367       E->VectorizedValue = V;
7368       ++NumVectorInstructions;
7369       return V;
7370     }
7371     case Instruction::Select: {
7372       setInsertPointAfterBundle(E);
7373 
7374       Value *Cond = vectorizeTree(E->getOperand(0));
7375       Value *True = vectorizeTree(E->getOperand(1));
7376       Value *False = vectorizeTree(E->getOperand(2));
7377 
7378       if (E->VectorizedValue) {
7379         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7380         return E->VectorizedValue;
7381       }
7382 
7383       Value *V = Builder.CreateSelect(Cond, True, False);
7384       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7385       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7386       V = ShuffleBuilder.finalize(V);
7387 
7388       E->VectorizedValue = V;
7389       ++NumVectorInstructions;
7390       return V;
7391     }
7392     case Instruction::FNeg: {
7393       setInsertPointAfterBundle(E);
7394 
7395       Value *Op = vectorizeTree(E->getOperand(0));
7396 
7397       if (E->VectorizedValue) {
7398         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7399         return E->VectorizedValue;
7400       }
7401 
7402       Value *V = Builder.CreateUnOp(
7403           static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
7404       propagateIRFlags(V, E->Scalars, VL0);
7405       if (auto *I = dyn_cast<Instruction>(V))
7406         V = propagateMetadata(I, E->Scalars);
7407 
7408       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7409       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7410       V = ShuffleBuilder.finalize(V);
7411 
7412       E->VectorizedValue = V;
7413       ++NumVectorInstructions;
7414 
7415       return V;
7416     }
7417     case Instruction::Add:
7418     case Instruction::FAdd:
7419     case Instruction::Sub:
7420     case Instruction::FSub:
7421     case Instruction::Mul:
7422     case Instruction::FMul:
7423     case Instruction::UDiv:
7424     case Instruction::SDiv:
7425     case Instruction::FDiv:
7426     case Instruction::URem:
7427     case Instruction::SRem:
7428     case Instruction::FRem:
7429     case Instruction::Shl:
7430     case Instruction::LShr:
7431     case Instruction::AShr:
7432     case Instruction::And:
7433     case Instruction::Or:
7434     case Instruction::Xor: {
7435       setInsertPointAfterBundle(E);
7436 
7437       Value *LHS = vectorizeTree(E->getOperand(0));
7438       Value *RHS = vectorizeTree(E->getOperand(1));
7439 
7440       if (E->VectorizedValue) {
7441         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7442         return E->VectorizedValue;
7443       }
7444 
7445       Value *V = Builder.CreateBinOp(
7446           static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
7447           RHS);
7448       propagateIRFlags(V, E->Scalars, VL0);
7449       if (auto *I = dyn_cast<Instruction>(V))
7450         V = propagateMetadata(I, E->Scalars);
7451 
7452       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7453       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7454       V = ShuffleBuilder.finalize(V);
7455 
7456       E->VectorizedValue = V;
7457       ++NumVectorInstructions;
7458 
7459       return V;
7460     }
7461     case Instruction::Load: {
7462       // Loads are inserted at the head of the tree because we don't want to
7463       // sink them all the way down past store instructions.
7464       setInsertPointAfterBundle(E);
7465 
7466       LoadInst *LI = cast<LoadInst>(VL0);
7467       Instruction *NewLI;
7468       unsigned AS = LI->getPointerAddressSpace();
7469       Value *PO = LI->getPointerOperand();
7470       if (E->State == TreeEntry::Vectorize) {
7471         Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS));
7472         NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
7473 
7474         // The pointer operand uses an in-tree scalar so we add the new BitCast
7475         // or LoadInst to ExternalUses list to make sure that an extract will
7476         // be generated in the future.
7477         if (TreeEntry *Entry = getTreeEntry(PO)) {
7478           // Find which lane we need to extract.
7479           unsigned FoundLane = Entry->findLaneForValue(PO);
7480           ExternalUses.emplace_back(
7481               PO, PO != VecPtr ? cast<User>(VecPtr) : NewLI, FoundLane);
7482         }
7483       } else {
7484         assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state");
7485         Value *VecPtr = vectorizeTree(E->getOperand(0));
7486         // Use the minimum alignment of the gathered loads.
7487         Align CommonAlignment = LI->getAlign();
7488         for (Value *V : E->Scalars)
7489           CommonAlignment =
7490               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
7491         NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment);
7492       }
7493       Value *V = propagateMetadata(NewLI, E->Scalars);
7494 
7495       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7496       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7497       V = ShuffleBuilder.finalize(V);
7498       E->VectorizedValue = V;
7499       ++NumVectorInstructions;
7500       return V;
7501     }
7502     case Instruction::Store: {
7503       auto *SI = cast<StoreInst>(VL0);
7504       unsigned AS = SI->getPointerAddressSpace();
7505 
7506       setInsertPointAfterBundle(E);
7507 
7508       Value *VecValue = vectorizeTree(E->getOperand(0));
7509       ShuffleBuilder.addMask(E->ReorderIndices);
7510       VecValue = ShuffleBuilder.finalize(VecValue);
7511 
7512       Value *ScalarPtr = SI->getPointerOperand();
7513       Value *VecPtr = Builder.CreateBitCast(
7514           ScalarPtr, VecValue->getType()->getPointerTo(AS));
7515       StoreInst *ST =
7516           Builder.CreateAlignedStore(VecValue, VecPtr, SI->getAlign());
7517 
7518       // The pointer operand uses an in-tree scalar, so add the new BitCast or
7519       // StoreInst to ExternalUses to make sure that an extract will be
7520       // generated in the future.
7521       if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) {
7522         // Find which lane we need to extract.
7523         unsigned FoundLane = Entry->findLaneForValue(ScalarPtr);
7524         ExternalUses.push_back(ExternalUser(
7525             ScalarPtr, ScalarPtr != VecPtr ? cast<User>(VecPtr) : ST,
7526             FoundLane));
7527       }
7528 
7529       Value *V = propagateMetadata(ST, E->Scalars);
7530 
7531       E->VectorizedValue = V;
7532       ++NumVectorInstructions;
7533       return V;
7534     }
7535     case Instruction::GetElementPtr: {
7536       auto *GEP0 = cast<GetElementPtrInst>(VL0);
7537       setInsertPointAfterBundle(E);
7538 
7539       Value *Op0 = vectorizeTree(E->getOperand(0));
7540 
7541       SmallVector<Value *> OpVecs;
7542       for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) {
7543         Value *OpVec = vectorizeTree(E->getOperand(J));
7544         OpVecs.push_back(OpVec);
7545       }
7546 
7547       Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs);
7548       if (Instruction *I = dyn_cast<Instruction>(V))
7549         V = propagateMetadata(I, E->Scalars);
7550 
7551       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7552       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7553       V = ShuffleBuilder.finalize(V);
7554 
7555       E->VectorizedValue = V;
7556       ++NumVectorInstructions;
7557 
7558       return V;
7559     }
7560     case Instruction::Call: {
7561       CallInst *CI = cast<CallInst>(VL0);
7562       setInsertPointAfterBundle(E);
7563 
7564       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
7565       if (Function *FI = CI->getCalledFunction())
7566         IID = FI->getIntrinsicID();
7567 
7568       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
7569 
7570       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
7571       bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
7572                           VecCallCosts.first <= VecCallCosts.second;
7573 
7574       Value *ScalarArg = nullptr;
7575       std::vector<Value *> OpVecs;
7576       SmallVector<Type *, 2> TysForDecl =
7577           {FixedVectorType::get(CI->getType(), E->Scalars.size())};
7578       for (int j = 0, e = CI->arg_size(); j < e; ++j) {
7579         ValueList OpVL;
7580         // Some intrinsics have scalar arguments. This argument should not be
7581         // vectorized.
7582         if (UseIntrinsic && isVectorIntrinsicWithScalarOpAtArg(IID, j)) {
7583           CallInst *CEI = cast<CallInst>(VL0);
7584           ScalarArg = CEI->getArgOperand(j);
7585           OpVecs.push_back(CEI->getArgOperand(j));
7586           if (isVectorIntrinsicWithOverloadTypeAtArg(IID, j))
7587             TysForDecl.push_back(ScalarArg->getType());
7588           continue;
7589         }
7590 
7591         Value *OpVec = vectorizeTree(E->getOperand(j));
7592         LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
7593         OpVecs.push_back(OpVec);
7594         if (isVectorIntrinsicWithOverloadTypeAtArg(IID, j))
7595           TysForDecl.push_back(OpVec->getType());
7596       }
7597 
7598       Function *CF;
7599       if (!UseIntrinsic) {
7600         VFShape Shape =
7601             VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
7602                                   VecTy->getNumElements())),
7603                          false /*HasGlobalPred*/);
7604         CF = VFDatabase(*CI).getVectorizedFunction(Shape);
7605       } else {
7606         CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl);
7607       }
7608 
7609       SmallVector<OperandBundleDef, 1> OpBundles;
7610       CI->getOperandBundlesAsDefs(OpBundles);
7611       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
7612 
7613       // The scalar argument uses an in-tree scalar so we add the new vectorized
7614       // call to ExternalUses list to make sure that an extract will be
7615       // generated in the future.
7616       if (ScalarArg) {
7617         if (TreeEntry *Entry = getTreeEntry(ScalarArg)) {
7618           // Find which lane we need to extract.
7619           unsigned FoundLane = Entry->findLaneForValue(ScalarArg);
7620           ExternalUses.push_back(
7621               ExternalUser(ScalarArg, cast<User>(V), FoundLane));
7622         }
7623       }
7624 
7625       propagateIRFlags(V, E->Scalars, VL0);
7626       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7627       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7628       V = ShuffleBuilder.finalize(V);
7629 
7630       E->VectorizedValue = V;
7631       ++NumVectorInstructions;
7632       return V;
7633     }
7634     case Instruction::ShuffleVector: {
7635       assert(E->isAltShuffle() &&
7636              ((Instruction::isBinaryOp(E->getOpcode()) &&
7637                Instruction::isBinaryOp(E->getAltOpcode())) ||
7638               (Instruction::isCast(E->getOpcode()) &&
7639                Instruction::isCast(E->getAltOpcode())) ||
7640               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
7641              "Invalid Shuffle Vector Operand");
7642 
7643       Value *LHS = nullptr, *RHS = nullptr;
7644       if (Instruction::isBinaryOp(E->getOpcode()) || isa<CmpInst>(VL0)) {
7645         setInsertPointAfterBundle(E);
7646         LHS = vectorizeTree(E->getOperand(0));
7647         RHS = vectorizeTree(E->getOperand(1));
7648       } else {
7649         setInsertPointAfterBundle(E);
7650         LHS = vectorizeTree(E->getOperand(0));
7651       }
7652 
7653       if (E->VectorizedValue) {
7654         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7655         return E->VectorizedValue;
7656       }
7657 
7658       Value *V0, *V1;
7659       if (Instruction::isBinaryOp(E->getOpcode())) {
7660         V0 = Builder.CreateBinOp(
7661             static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
7662         V1 = Builder.CreateBinOp(
7663             static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
7664       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
7665         V0 = Builder.CreateCmp(CI0->getPredicate(), LHS, RHS);
7666         auto *AltCI = cast<CmpInst>(E->getAltOp());
7667         CmpInst::Predicate AltPred = AltCI->getPredicate();
7668         V1 = Builder.CreateCmp(AltPred, LHS, RHS);
7669       } else {
7670         V0 = Builder.CreateCast(
7671             static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
7672         V1 = Builder.CreateCast(
7673             static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
7674       }
7675       // Add V0 and V1 to later analysis to try to find and remove matching
7676       // instruction, if any.
7677       for (Value *V : {V0, V1}) {
7678         if (auto *I = dyn_cast<Instruction>(V)) {
7679           GatherShuffleSeq.insert(I);
7680           CSEBlocks.insert(I->getParent());
7681         }
7682       }
7683 
7684       // Create shuffle to take alternate operations from the vector.
7685       // Also, gather up main and alt scalar ops to propagate IR flags to
7686       // each vector operation.
7687       ValueList OpScalars, AltScalars;
7688       SmallVector<int> Mask;
7689       buildShuffleEntryMask(
7690           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
7691           [E](Instruction *I) {
7692             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
7693             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
7694           },
7695           Mask, &OpScalars, &AltScalars);
7696 
7697       propagateIRFlags(V0, OpScalars);
7698       propagateIRFlags(V1, AltScalars);
7699 
7700       Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
7701       if (auto *I = dyn_cast<Instruction>(V)) {
7702         V = propagateMetadata(I, E->Scalars);
7703         GatherShuffleSeq.insert(I);
7704         CSEBlocks.insert(I->getParent());
7705       }
7706       V = ShuffleBuilder.finalize(V);
7707 
7708       E->VectorizedValue = V;
7709       ++NumVectorInstructions;
7710 
7711       return V;
7712     }
7713     default:
7714     llvm_unreachable("unknown inst");
7715   }
7716   return nullptr;
7717 }
7718 
7719 Value *BoUpSLP::vectorizeTree() {
7720   ExtraValueToDebugLocsMap ExternallyUsedValues;
7721   return vectorizeTree(ExternallyUsedValues);
7722 }
7723 
7724 Value *
7725 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
7726   // All blocks must be scheduled before any instructions are inserted.
7727   for (auto &BSIter : BlocksSchedules) {
7728     scheduleBlock(BSIter.second.get());
7729   }
7730 
7731   Builder.SetInsertPoint(&F->getEntryBlock().front());
7732   auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
7733 
7734   // If the vectorized tree can be rewritten in a smaller type, we truncate the
7735   // vectorized root. InstCombine will then rewrite the entire expression. We
7736   // sign extend the extracted values below.
7737   auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
7738   if (MinBWs.count(ScalarRoot)) {
7739     if (auto *I = dyn_cast<Instruction>(VectorRoot)) {
7740       // If current instr is a phi and not the last phi, insert it after the
7741       // last phi node.
7742       if (isa<PHINode>(I))
7743         Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt());
7744       else
7745         Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
7746     }
7747     auto BundleWidth = VectorizableTree[0]->Scalars.size();
7748     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
7749     auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
7750     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
7751     VectorizableTree[0]->VectorizedValue = Trunc;
7752   }
7753 
7754   LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
7755                     << " values .\n");
7756 
7757   // Extract all of the elements with the external uses.
7758   for (const auto &ExternalUse : ExternalUses) {
7759     Value *Scalar = ExternalUse.Scalar;
7760     llvm::User *User = ExternalUse.User;
7761 
7762     // Skip users that we already RAUW. This happens when one instruction
7763     // has multiple uses of the same value.
7764     if (User && !is_contained(Scalar->users(), User))
7765       continue;
7766     TreeEntry *E = getTreeEntry(Scalar);
7767     assert(E && "Invalid scalar");
7768     assert(E->State != TreeEntry::NeedToGather &&
7769            "Extracting from a gather list");
7770 
7771     Value *Vec = E->VectorizedValue;
7772     assert(Vec && "Can't find vectorizable value");
7773 
7774     Value *Lane = Builder.getInt32(ExternalUse.Lane);
7775     auto ExtractAndExtendIfNeeded = [&](Value *Vec) {
7776       if (Scalar->getType() != Vec->getType()) {
7777         Value *Ex;
7778         // "Reuse" the existing extract to improve final codegen.
7779         if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) {
7780           Ex = Builder.CreateExtractElement(ES->getOperand(0),
7781                                             ES->getOperand(1));
7782         } else {
7783           Ex = Builder.CreateExtractElement(Vec, Lane);
7784         }
7785         // If necessary, sign-extend or zero-extend ScalarRoot
7786         // to the larger type.
7787         if (!MinBWs.count(ScalarRoot))
7788           return Ex;
7789         if (MinBWs[ScalarRoot].second)
7790           return Builder.CreateSExt(Ex, Scalar->getType());
7791         return Builder.CreateZExt(Ex, Scalar->getType());
7792       }
7793       assert(isa<FixedVectorType>(Scalar->getType()) &&
7794              isa<InsertElementInst>(Scalar) &&
7795              "In-tree scalar of vector type is not insertelement?");
7796       return Vec;
7797     };
7798     // If User == nullptr, the Scalar is used as extra arg. Generate
7799     // ExtractElement instruction and update the record for this scalar in
7800     // ExternallyUsedValues.
7801     if (!User) {
7802       assert(ExternallyUsedValues.count(Scalar) &&
7803              "Scalar with nullptr as an external user must be registered in "
7804              "ExternallyUsedValues map");
7805       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7806         Builder.SetInsertPoint(VecI->getParent(),
7807                                std::next(VecI->getIterator()));
7808       } else {
7809         Builder.SetInsertPoint(&F->getEntryBlock().front());
7810       }
7811       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7812       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
7813       auto &NewInstLocs = ExternallyUsedValues[NewInst];
7814       auto It = ExternallyUsedValues.find(Scalar);
7815       assert(It != ExternallyUsedValues.end() &&
7816              "Externally used scalar is not found in ExternallyUsedValues");
7817       NewInstLocs.append(It->second);
7818       ExternallyUsedValues.erase(Scalar);
7819       // Required to update internally referenced instructions.
7820       Scalar->replaceAllUsesWith(NewInst);
7821       continue;
7822     }
7823 
7824     // Generate extracts for out-of-tree users.
7825     // Find the insertion point for the extractelement lane.
7826     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7827       if (PHINode *PH = dyn_cast<PHINode>(User)) {
7828         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
7829           if (PH->getIncomingValue(i) == Scalar) {
7830             Instruction *IncomingTerminator =
7831                 PH->getIncomingBlock(i)->getTerminator();
7832             if (isa<CatchSwitchInst>(IncomingTerminator)) {
7833               Builder.SetInsertPoint(VecI->getParent(),
7834                                      std::next(VecI->getIterator()));
7835             } else {
7836               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
7837             }
7838             Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7839             CSEBlocks.insert(PH->getIncomingBlock(i));
7840             PH->setOperand(i, NewInst);
7841           }
7842         }
7843       } else {
7844         Builder.SetInsertPoint(cast<Instruction>(User));
7845         Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7846         CSEBlocks.insert(cast<Instruction>(User)->getParent());
7847         User->replaceUsesOfWith(Scalar, NewInst);
7848       }
7849     } else {
7850       Builder.SetInsertPoint(&F->getEntryBlock().front());
7851       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7852       CSEBlocks.insert(&F->getEntryBlock());
7853       User->replaceUsesOfWith(Scalar, NewInst);
7854     }
7855 
7856     LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
7857   }
7858 
7859   // For each vectorized value:
7860   for (auto &TEPtr : VectorizableTree) {
7861     TreeEntry *Entry = TEPtr.get();
7862 
7863     // No need to handle users of gathered values.
7864     if (Entry->State == TreeEntry::NeedToGather)
7865       continue;
7866 
7867     assert(Entry->VectorizedValue && "Can't find vectorizable value");
7868 
7869     // For each lane:
7870     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
7871       Value *Scalar = Entry->Scalars[Lane];
7872 
7873 #ifndef NDEBUG
7874       Type *Ty = Scalar->getType();
7875       if (!Ty->isVoidTy()) {
7876         for (User *U : Scalar->users()) {
7877           LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
7878 
7879           // It is legal to delete users in the ignorelist.
7880           assert((getTreeEntry(U) || is_contained(UserIgnoreList, U) ||
7881                   (isa_and_nonnull<Instruction>(U) &&
7882                    isDeleted(cast<Instruction>(U)))) &&
7883                  "Deleting out-of-tree value");
7884         }
7885       }
7886 #endif
7887       LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
7888       eraseInstruction(cast<Instruction>(Scalar));
7889     }
7890   }
7891 
7892   Builder.ClearInsertionPoint();
7893   InstrElementSize.clear();
7894 
7895   return VectorizableTree[0]->VectorizedValue;
7896 }
7897 
7898 void BoUpSLP::optimizeGatherSequence() {
7899   LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleSeq.size()
7900                     << " gather sequences instructions.\n");
7901   // LICM InsertElementInst sequences.
7902   for (Instruction *I : GatherShuffleSeq) {
7903     if (isDeleted(I))
7904       continue;
7905 
7906     // Check if this block is inside a loop.
7907     Loop *L = LI->getLoopFor(I->getParent());
7908     if (!L)
7909       continue;
7910 
7911     // Check if it has a preheader.
7912     BasicBlock *PreHeader = L->getLoopPreheader();
7913     if (!PreHeader)
7914       continue;
7915 
7916     // If the vector or the element that we insert into it are
7917     // instructions that are defined in this basic block then we can't
7918     // hoist this instruction.
7919     if (any_of(I->operands(), [L](Value *V) {
7920           auto *OpI = dyn_cast<Instruction>(V);
7921           return OpI && L->contains(OpI);
7922         }))
7923       continue;
7924 
7925     // We can hoist this instruction. Move it to the pre-header.
7926     I->moveBefore(PreHeader->getTerminator());
7927   }
7928 
7929   // Make a list of all reachable blocks in our CSE queue.
7930   SmallVector<const DomTreeNode *, 8> CSEWorkList;
7931   CSEWorkList.reserve(CSEBlocks.size());
7932   for (BasicBlock *BB : CSEBlocks)
7933     if (DomTreeNode *N = DT->getNode(BB)) {
7934       assert(DT->isReachableFromEntry(N));
7935       CSEWorkList.push_back(N);
7936     }
7937 
7938   // Sort blocks by domination. This ensures we visit a block after all blocks
7939   // dominating it are visited.
7940   llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) {
7941     assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) &&
7942            "Different nodes should have different DFS numbers");
7943     return A->getDFSNumIn() < B->getDFSNumIn();
7944   });
7945 
7946   // Less defined shuffles can be replaced by the more defined copies.
7947   // Between two shuffles one is less defined if it has the same vector operands
7948   // and its mask indeces are the same as in the first one or undefs. E.g.
7949   // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0,
7950   // poison, <0, 0, 0, 0>.
7951   auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2,
7952                                            SmallVectorImpl<int> &NewMask) {
7953     if (I1->getType() != I2->getType())
7954       return false;
7955     auto *SI1 = dyn_cast<ShuffleVectorInst>(I1);
7956     auto *SI2 = dyn_cast<ShuffleVectorInst>(I2);
7957     if (!SI1 || !SI2)
7958       return I1->isIdenticalTo(I2);
7959     if (SI1->isIdenticalTo(SI2))
7960       return true;
7961     for (int I = 0, E = SI1->getNumOperands(); I < E; ++I)
7962       if (SI1->getOperand(I) != SI2->getOperand(I))
7963         return false;
7964     // Check if the second instruction is more defined than the first one.
7965     NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end());
7966     ArrayRef<int> SM1 = SI1->getShuffleMask();
7967     // Count trailing undefs in the mask to check the final number of used
7968     // registers.
7969     unsigned LastUndefsCnt = 0;
7970     for (int I = 0, E = NewMask.size(); I < E; ++I) {
7971       if (SM1[I] == UndefMaskElem)
7972         ++LastUndefsCnt;
7973       else
7974         LastUndefsCnt = 0;
7975       if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem &&
7976           NewMask[I] != SM1[I])
7977         return false;
7978       if (NewMask[I] == UndefMaskElem)
7979         NewMask[I] = SM1[I];
7980     }
7981     // Check if the last undefs actually change the final number of used vector
7982     // registers.
7983     return SM1.size() - LastUndefsCnt > 1 &&
7984            TTI->getNumberOfParts(SI1->getType()) ==
7985                TTI->getNumberOfParts(
7986                    FixedVectorType::get(SI1->getType()->getElementType(),
7987                                         SM1.size() - LastUndefsCnt));
7988   };
7989   // Perform O(N^2) search over the gather/shuffle sequences and merge identical
7990   // instructions. TODO: We can further optimize this scan if we split the
7991   // instructions into different buckets based on the insert lane.
7992   SmallVector<Instruction *, 16> Visited;
7993   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
7994     assert(*I &&
7995            (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
7996            "Worklist not sorted properly!");
7997     BasicBlock *BB = (*I)->getBlock();
7998     // For all instructions in blocks containing gather sequences:
7999     for (Instruction &In : llvm::make_early_inc_range(*BB)) {
8000       if (isDeleted(&In))
8001         continue;
8002       if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) &&
8003           !isa<ShuffleVectorInst>(&In) && !GatherShuffleSeq.contains(&In))
8004         continue;
8005 
8006       // Check if we can replace this instruction with any of the
8007       // visited instructions.
8008       bool Replaced = false;
8009       for (Instruction *&V : Visited) {
8010         SmallVector<int> NewMask;
8011         if (IsIdenticalOrLessDefined(&In, V, NewMask) &&
8012             DT->dominates(V->getParent(), In.getParent())) {
8013           In.replaceAllUsesWith(V);
8014           eraseInstruction(&In);
8015           if (auto *SI = dyn_cast<ShuffleVectorInst>(V))
8016             if (!NewMask.empty())
8017               SI->setShuffleMask(NewMask);
8018           Replaced = true;
8019           break;
8020         }
8021         if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) &&
8022             GatherShuffleSeq.contains(V) &&
8023             IsIdenticalOrLessDefined(V, &In, NewMask) &&
8024             DT->dominates(In.getParent(), V->getParent())) {
8025           In.moveAfter(V);
8026           V->replaceAllUsesWith(&In);
8027           eraseInstruction(V);
8028           if (auto *SI = dyn_cast<ShuffleVectorInst>(&In))
8029             if (!NewMask.empty())
8030               SI->setShuffleMask(NewMask);
8031           V = &In;
8032           Replaced = true;
8033           break;
8034         }
8035       }
8036       if (!Replaced) {
8037         assert(!is_contained(Visited, &In));
8038         Visited.push_back(&In);
8039       }
8040     }
8041   }
8042   CSEBlocks.clear();
8043   GatherShuffleSeq.clear();
8044 }
8045 
8046 BoUpSLP::ScheduleData *
8047 BoUpSLP::BlockScheduling::buildBundle(ArrayRef<Value *> VL) {
8048   ScheduleData *Bundle = nullptr;
8049   ScheduleData *PrevInBundle = nullptr;
8050   for (Value *V : VL) {
8051     if (doesNotNeedToBeScheduled(V))
8052       continue;
8053     ScheduleData *BundleMember = getScheduleData(V);
8054     assert(BundleMember &&
8055            "no ScheduleData for bundle member "
8056            "(maybe not in same basic block)");
8057     assert(BundleMember->isSchedulingEntity() &&
8058            "bundle member already part of other bundle");
8059     if (PrevInBundle) {
8060       PrevInBundle->NextInBundle = BundleMember;
8061     } else {
8062       Bundle = BundleMember;
8063     }
8064 
8065     // Group the instructions to a bundle.
8066     BundleMember->FirstInBundle = Bundle;
8067     PrevInBundle = BundleMember;
8068   }
8069   assert(Bundle && "Failed to find schedule bundle");
8070   return Bundle;
8071 }
8072 
8073 // Groups the instructions to a bundle (which is then a single scheduling entity)
8074 // and schedules instructions until the bundle gets ready.
8075 Optional<BoUpSLP::ScheduleData *>
8076 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
8077                                             const InstructionsState &S) {
8078   // No need to schedule PHIs, insertelement, extractelement and extractvalue
8079   // instructions.
8080   if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue) ||
8081       doesNotNeedToSchedule(VL))
8082     return nullptr;
8083 
8084   // Initialize the instruction bundle.
8085   Instruction *OldScheduleEnd = ScheduleEnd;
8086   LLVM_DEBUG(dbgs() << "SLP:  bundle: " << *S.OpValue << "\n");
8087 
8088   auto TryScheduleBundleImpl = [this, OldScheduleEnd, SLP](bool ReSchedule,
8089                                                          ScheduleData *Bundle) {
8090     // The scheduling region got new instructions at the lower end (or it is a
8091     // new region for the first bundle). This makes it necessary to
8092     // recalculate all dependencies.
8093     // It is seldom that this needs to be done a second time after adding the
8094     // initial bundle to the region.
8095     if (ScheduleEnd != OldScheduleEnd) {
8096       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode())
8097         doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); });
8098       ReSchedule = true;
8099     }
8100     if (Bundle) {
8101       LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle
8102                         << " in block " << BB->getName() << "\n");
8103       calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP);
8104     }
8105 
8106     if (ReSchedule) {
8107       resetSchedule();
8108       initialFillReadyList(ReadyInsts);
8109     }
8110 
8111     // Now try to schedule the new bundle or (if no bundle) just calculate
8112     // dependencies. As soon as the bundle is "ready" it means that there are no
8113     // cyclic dependencies and we can schedule it. Note that's important that we
8114     // don't "schedule" the bundle yet (see cancelScheduling).
8115     while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) &&
8116            !ReadyInsts.empty()) {
8117       ScheduleData *Picked = ReadyInsts.pop_back_val();
8118       assert(Picked->isSchedulingEntity() && Picked->isReady() &&
8119              "must be ready to schedule");
8120       schedule(Picked, ReadyInsts);
8121     }
8122   };
8123 
8124   // Make sure that the scheduling region contains all
8125   // instructions of the bundle.
8126   for (Value *V : VL) {
8127     if (doesNotNeedToBeScheduled(V))
8128       continue;
8129     if (!extendSchedulingRegion(V, S)) {
8130       // If the scheduling region got new instructions at the lower end (or it
8131       // is a new region for the first bundle). This makes it necessary to
8132       // recalculate all dependencies.
8133       // Otherwise the compiler may crash trying to incorrectly calculate
8134       // dependencies and emit instruction in the wrong order at the actual
8135       // scheduling.
8136       TryScheduleBundleImpl(/*ReSchedule=*/false, nullptr);
8137       return None;
8138     }
8139   }
8140 
8141   bool ReSchedule = false;
8142   for (Value *V : VL) {
8143     if (doesNotNeedToBeScheduled(V))
8144       continue;
8145     ScheduleData *BundleMember = getScheduleData(V);
8146     assert(BundleMember &&
8147            "no ScheduleData for bundle member (maybe not in same basic block)");
8148 
8149     // Make sure we don't leave the pieces of the bundle in the ready list when
8150     // whole bundle might not be ready.
8151     ReadyInsts.remove(BundleMember);
8152 
8153     if (!BundleMember->IsScheduled)
8154       continue;
8155     // A bundle member was scheduled as single instruction before and now
8156     // needs to be scheduled as part of the bundle. We just get rid of the
8157     // existing schedule.
8158     LLVM_DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
8159                       << " was already scheduled\n");
8160     ReSchedule = true;
8161   }
8162 
8163   auto *Bundle = buildBundle(VL);
8164   TryScheduleBundleImpl(ReSchedule, Bundle);
8165   if (!Bundle->isReady()) {
8166     cancelScheduling(VL, S.OpValue);
8167     return None;
8168   }
8169   return Bundle;
8170 }
8171 
8172 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
8173                                                 Value *OpValue) {
8174   if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue) ||
8175       doesNotNeedToSchedule(VL))
8176     return;
8177 
8178   if (doesNotNeedToBeScheduled(OpValue))
8179     OpValue = *find_if_not(VL, doesNotNeedToBeScheduled);
8180   ScheduleData *Bundle = getScheduleData(OpValue);
8181   LLVM_DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
8182   assert(!Bundle->IsScheduled &&
8183          "Can't cancel bundle which is already scheduled");
8184   assert(Bundle->isSchedulingEntity() &&
8185          (Bundle->isPartOfBundle() || needToScheduleSingleInstruction(VL)) &&
8186          "tried to unbundle something which is not a bundle");
8187 
8188   // Remove the bundle from the ready list.
8189   if (Bundle->isReady())
8190     ReadyInsts.remove(Bundle);
8191 
8192   // Un-bundle: make single instructions out of the bundle.
8193   ScheduleData *BundleMember = Bundle;
8194   while (BundleMember) {
8195     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
8196     BundleMember->FirstInBundle = BundleMember;
8197     ScheduleData *Next = BundleMember->NextInBundle;
8198     BundleMember->NextInBundle = nullptr;
8199     BundleMember->TE = nullptr;
8200     if (BundleMember->unscheduledDepsInBundle() == 0) {
8201       ReadyInsts.insert(BundleMember);
8202     }
8203     BundleMember = Next;
8204   }
8205 }
8206 
8207 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
8208   // Allocate a new ScheduleData for the instruction.
8209   if (ChunkPos >= ChunkSize) {
8210     ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
8211     ChunkPos = 0;
8212   }
8213   return &(ScheduleDataChunks.back()[ChunkPos++]);
8214 }
8215 
8216 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
8217                                                       const InstructionsState &S) {
8218   if (getScheduleData(V, isOneOf(S, V)))
8219     return true;
8220   Instruction *I = dyn_cast<Instruction>(V);
8221   assert(I && "bundle member must be an instruction");
8222   assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) &&
8223          !doesNotNeedToBeScheduled(I) &&
8224          "phi nodes/insertelements/extractelements/extractvalues don't need to "
8225          "be scheduled");
8226   auto &&CheckScheduleForI = [this, &S](Instruction *I) -> bool {
8227     ScheduleData *ISD = getScheduleData(I);
8228     if (!ISD)
8229       return false;
8230     assert(isInSchedulingRegion(ISD) &&
8231            "ScheduleData not in scheduling region");
8232     ScheduleData *SD = allocateScheduleDataChunks();
8233     SD->Inst = I;
8234     SD->init(SchedulingRegionID, S.OpValue);
8235     ExtraScheduleDataMap[I][S.OpValue] = SD;
8236     return true;
8237   };
8238   if (CheckScheduleForI(I))
8239     return true;
8240   if (!ScheduleStart) {
8241     // It's the first instruction in the new region.
8242     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
8243     ScheduleStart = I;
8244     ScheduleEnd = I->getNextNode();
8245     if (isOneOf(S, I) != I)
8246       CheckScheduleForI(I);
8247     assert(ScheduleEnd && "tried to vectorize a terminator?");
8248     LLVM_DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
8249     return true;
8250   }
8251   // Search up and down at the same time, because we don't know if the new
8252   // instruction is above or below the existing scheduling region.
8253   BasicBlock::reverse_iterator UpIter =
8254       ++ScheduleStart->getIterator().getReverse();
8255   BasicBlock::reverse_iterator UpperEnd = BB->rend();
8256   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
8257   BasicBlock::iterator LowerEnd = BB->end();
8258   while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I &&
8259          &*DownIter != I) {
8260     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
8261       LLVM_DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
8262       return false;
8263     }
8264 
8265     ++UpIter;
8266     ++DownIter;
8267   }
8268   if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) {
8269     assert(I->getParent() == ScheduleStart->getParent() &&
8270            "Instruction is in wrong basic block.");
8271     initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
8272     ScheduleStart = I;
8273     if (isOneOf(S, I) != I)
8274       CheckScheduleForI(I);
8275     LLVM_DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I
8276                       << "\n");
8277     return true;
8278   }
8279   assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) &&
8280          "Expected to reach top of the basic block or instruction down the "
8281          "lower end.");
8282   assert(I->getParent() == ScheduleEnd->getParent() &&
8283          "Instruction is in wrong basic block.");
8284   initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
8285                    nullptr);
8286   ScheduleEnd = I->getNextNode();
8287   if (isOneOf(S, I) != I)
8288     CheckScheduleForI(I);
8289   assert(ScheduleEnd && "tried to vectorize a terminator?");
8290   LLVM_DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
8291   return true;
8292 }
8293 
8294 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
8295                                                 Instruction *ToI,
8296                                                 ScheduleData *PrevLoadStore,
8297                                                 ScheduleData *NextLoadStore) {
8298   ScheduleData *CurrentLoadStore = PrevLoadStore;
8299   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
8300     // No need to allocate data for non-schedulable instructions.
8301     if (doesNotNeedToBeScheduled(I))
8302       continue;
8303     ScheduleData *SD = ScheduleDataMap.lookup(I);
8304     if (!SD) {
8305       SD = allocateScheduleDataChunks();
8306       ScheduleDataMap[I] = SD;
8307       SD->Inst = I;
8308     }
8309     assert(!isInSchedulingRegion(SD) &&
8310            "new ScheduleData already in scheduling region");
8311     SD->init(SchedulingRegionID, I);
8312 
8313     if (I->mayReadOrWriteMemory() &&
8314         (!isa<IntrinsicInst>(I) ||
8315          (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect &&
8316           cast<IntrinsicInst>(I)->getIntrinsicID() !=
8317               Intrinsic::pseudoprobe))) {
8318       // Update the linked list of memory accessing instructions.
8319       if (CurrentLoadStore) {
8320         CurrentLoadStore->NextLoadStore = SD;
8321       } else {
8322         FirstLoadStoreInRegion = SD;
8323       }
8324       CurrentLoadStore = SD;
8325     }
8326 
8327     if (match(I, m_Intrinsic<Intrinsic::stacksave>()) ||
8328         match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8329       RegionHasStackSave = true;
8330   }
8331   if (NextLoadStore) {
8332     if (CurrentLoadStore)
8333       CurrentLoadStore->NextLoadStore = NextLoadStore;
8334   } else {
8335     LastLoadStoreInRegion = CurrentLoadStore;
8336   }
8337 }
8338 
8339 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
8340                                                      bool InsertInReadyList,
8341                                                      BoUpSLP *SLP) {
8342   assert(SD->isSchedulingEntity());
8343 
8344   SmallVector<ScheduleData *, 10> WorkList;
8345   WorkList.push_back(SD);
8346 
8347   while (!WorkList.empty()) {
8348     ScheduleData *SD = WorkList.pop_back_val();
8349     for (ScheduleData *BundleMember = SD; BundleMember;
8350          BundleMember = BundleMember->NextInBundle) {
8351       assert(isInSchedulingRegion(BundleMember));
8352       if (BundleMember->hasValidDependencies())
8353         continue;
8354 
8355       LLVM_DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember
8356                  << "\n");
8357       BundleMember->Dependencies = 0;
8358       BundleMember->resetUnscheduledDeps();
8359 
8360       // Handle def-use chain dependencies.
8361       if (BundleMember->OpValue != BundleMember->Inst) {
8362         if (ScheduleData *UseSD = getScheduleData(BundleMember->Inst)) {
8363           BundleMember->Dependencies++;
8364           ScheduleData *DestBundle = UseSD->FirstInBundle;
8365           if (!DestBundle->IsScheduled)
8366             BundleMember->incrementUnscheduledDeps(1);
8367           if (!DestBundle->hasValidDependencies())
8368             WorkList.push_back(DestBundle);
8369         }
8370       } else {
8371         for (User *U : BundleMember->Inst->users()) {
8372           if (ScheduleData *UseSD = getScheduleData(cast<Instruction>(U))) {
8373             BundleMember->Dependencies++;
8374             ScheduleData *DestBundle = UseSD->FirstInBundle;
8375             if (!DestBundle->IsScheduled)
8376               BundleMember->incrementUnscheduledDeps(1);
8377             if (!DestBundle->hasValidDependencies())
8378               WorkList.push_back(DestBundle);
8379           }
8380         }
8381       }
8382 
8383       auto makeControlDependent = [&](Instruction *I) {
8384         auto *DepDest = getScheduleData(I);
8385         assert(DepDest && "must be in schedule window");
8386         DepDest->ControlDependencies.push_back(BundleMember);
8387         BundleMember->Dependencies++;
8388         ScheduleData *DestBundle = DepDest->FirstInBundle;
8389         if (!DestBundle->IsScheduled)
8390           BundleMember->incrementUnscheduledDeps(1);
8391         if (!DestBundle->hasValidDependencies())
8392           WorkList.push_back(DestBundle);
8393       };
8394 
8395       // Any instruction which isn't safe to speculate at the begining of the
8396       // block is control dependend on any early exit or non-willreturn call
8397       // which proceeds it.
8398       if (!isGuaranteedToTransferExecutionToSuccessor(BundleMember->Inst)) {
8399         for (Instruction *I = BundleMember->Inst->getNextNode();
8400              I != ScheduleEnd; I = I->getNextNode()) {
8401           if (isSafeToSpeculativelyExecute(I, &*BB->begin()))
8402             continue;
8403 
8404           // Add the dependency
8405           makeControlDependent(I);
8406 
8407           if (!isGuaranteedToTransferExecutionToSuccessor(I))
8408             // Everything past here must be control dependent on I.
8409             break;
8410         }
8411       }
8412 
8413       if (RegionHasStackSave) {
8414         // If we have an inalloc alloca instruction, it needs to be scheduled
8415         // after any preceeding stacksave.  We also need to prevent any alloca
8416         // from reordering above a preceeding stackrestore.
8417         if (match(BundleMember->Inst, m_Intrinsic<Intrinsic::stacksave>()) ||
8418             match(BundleMember->Inst, m_Intrinsic<Intrinsic::stackrestore>())) {
8419           for (Instruction *I = BundleMember->Inst->getNextNode();
8420                I != ScheduleEnd; I = I->getNextNode()) {
8421             if (match(I, m_Intrinsic<Intrinsic::stacksave>()) ||
8422                 match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8423               // Any allocas past here must be control dependent on I, and I
8424               // must be memory dependend on BundleMember->Inst.
8425               break;
8426 
8427             if (!isa<AllocaInst>(I))
8428               continue;
8429 
8430             // Add the dependency
8431             makeControlDependent(I);
8432           }
8433         }
8434 
8435         // In addition to the cases handle just above, we need to prevent
8436         // allocas from moving below a stacksave.  The stackrestore case
8437         // is currently thought to be conservatism.
8438         if (isa<AllocaInst>(BundleMember->Inst)) {
8439           for (Instruction *I = BundleMember->Inst->getNextNode();
8440                I != ScheduleEnd; I = I->getNextNode()) {
8441             if (!match(I, m_Intrinsic<Intrinsic::stacksave>()) &&
8442                 !match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8443               continue;
8444 
8445             // Add the dependency
8446             makeControlDependent(I);
8447             break;
8448           }
8449         }
8450       }
8451 
8452       // Handle the memory dependencies (if any).
8453       ScheduleData *DepDest = BundleMember->NextLoadStore;
8454       if (!DepDest)
8455         continue;
8456       Instruction *SrcInst = BundleMember->Inst;
8457       assert(SrcInst->mayReadOrWriteMemory() &&
8458              "NextLoadStore list for non memory effecting bundle?");
8459       MemoryLocation SrcLoc = getLocation(SrcInst);
8460       bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
8461       unsigned numAliased = 0;
8462       unsigned DistToSrc = 1;
8463 
8464       for ( ; DepDest; DepDest = DepDest->NextLoadStore) {
8465         assert(isInSchedulingRegion(DepDest));
8466 
8467         // We have two limits to reduce the complexity:
8468         // 1) AliasedCheckLimit: It's a small limit to reduce calls to
8469         //    SLP->isAliased (which is the expensive part in this loop).
8470         // 2) MaxMemDepDistance: It's for very large blocks and it aborts
8471         //    the whole loop (even if the loop is fast, it's quadratic).
8472         //    It's important for the loop break condition (see below) to
8473         //    check this limit even between two read-only instructions.
8474         if (DistToSrc >= MaxMemDepDistance ||
8475             ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
8476              (numAliased >= AliasedCheckLimit ||
8477               SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
8478 
8479           // We increment the counter only if the locations are aliased
8480           // (instead of counting all alias checks). This gives a better
8481           // balance between reduced runtime and accurate dependencies.
8482           numAliased++;
8483 
8484           DepDest->MemoryDependencies.push_back(BundleMember);
8485           BundleMember->Dependencies++;
8486           ScheduleData *DestBundle = DepDest->FirstInBundle;
8487           if (!DestBundle->IsScheduled) {
8488             BundleMember->incrementUnscheduledDeps(1);
8489           }
8490           if (!DestBundle->hasValidDependencies()) {
8491             WorkList.push_back(DestBundle);
8492           }
8493         }
8494 
8495         // Example, explaining the loop break condition: Let's assume our
8496         // starting instruction is i0 and MaxMemDepDistance = 3.
8497         //
8498         //                      +--------v--v--v
8499         //             i0,i1,i2,i3,i4,i5,i6,i7,i8
8500         //             +--------^--^--^
8501         //
8502         // MaxMemDepDistance let us stop alias-checking at i3 and we add
8503         // dependencies from i0 to i3,i4,.. (even if they are not aliased).
8504         // Previously we already added dependencies from i3 to i6,i7,i8
8505         // (because of MaxMemDepDistance). As we added a dependency from
8506         // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
8507         // and we can abort this loop at i6.
8508         if (DistToSrc >= 2 * MaxMemDepDistance)
8509           break;
8510         DistToSrc++;
8511       }
8512     }
8513     if (InsertInReadyList && SD->isReady()) {
8514       ReadyInsts.insert(SD);
8515       LLVM_DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst
8516                         << "\n");
8517     }
8518   }
8519 }
8520 
8521 void BoUpSLP::BlockScheduling::resetSchedule() {
8522   assert(ScheduleStart &&
8523          "tried to reset schedule on block which has not been scheduled");
8524   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
8525     doForAllOpcodes(I, [&](ScheduleData *SD) {
8526       assert(isInSchedulingRegion(SD) &&
8527              "ScheduleData not in scheduling region");
8528       SD->IsScheduled = false;
8529       SD->resetUnscheduledDeps();
8530     });
8531   }
8532   ReadyInsts.clear();
8533 }
8534 
8535 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
8536   if (!BS->ScheduleStart)
8537     return;
8538 
8539   LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
8540 
8541   // A key point - if we got here, pre-scheduling was able to find a valid
8542   // scheduling of the sub-graph of the scheduling window which consists
8543   // of all vector bundles and their transitive users.  As such, we do not
8544   // need to reschedule anything *outside of* that subgraph.
8545 
8546   BS->resetSchedule();
8547 
8548   // For the real scheduling we use a more sophisticated ready-list: it is
8549   // sorted by the original instruction location. This lets the final schedule
8550   // be as  close as possible to the original instruction order.
8551   // WARNING: If changing this order causes a correctness issue, that means
8552   // there is some missing dependence edge in the schedule data graph.
8553   struct ScheduleDataCompare {
8554     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
8555       return SD2->SchedulingPriority < SD1->SchedulingPriority;
8556     }
8557   };
8558   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
8559 
8560   // Ensure that all dependency data is updated (for nodes in the sub-graph)
8561   // and fill the ready-list with initial instructions.
8562   int Idx = 0;
8563   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
8564        I = I->getNextNode()) {
8565     BS->doForAllOpcodes(I, [this, &Idx, BS](ScheduleData *SD) {
8566       TreeEntry *SDTE = getTreeEntry(SD->Inst);
8567       (void)SDTE;
8568       assert((isVectorLikeInstWithConstOps(SD->Inst) ||
8569               SD->isPartOfBundle() ==
8570                   (SDTE && !doesNotNeedToSchedule(SDTE->Scalars))) &&
8571              "scheduler and vectorizer bundle mismatch");
8572       SD->FirstInBundle->SchedulingPriority = Idx++;
8573 
8574       if (SD->isSchedulingEntity() && SD->isPartOfBundle())
8575         BS->calculateDependencies(SD, false, this);
8576     });
8577   }
8578   BS->initialFillReadyList(ReadyInsts);
8579 
8580   Instruction *LastScheduledInst = BS->ScheduleEnd;
8581 
8582   // Do the "real" scheduling.
8583   while (!ReadyInsts.empty()) {
8584     ScheduleData *picked = *ReadyInsts.begin();
8585     ReadyInsts.erase(ReadyInsts.begin());
8586 
8587     // Move the scheduled instruction(s) to their dedicated places, if not
8588     // there yet.
8589     for (ScheduleData *BundleMember = picked; BundleMember;
8590          BundleMember = BundleMember->NextInBundle) {
8591       Instruction *pickedInst = BundleMember->Inst;
8592       if (pickedInst->getNextNode() != LastScheduledInst)
8593         pickedInst->moveBefore(LastScheduledInst);
8594       LastScheduledInst = pickedInst;
8595     }
8596 
8597     BS->schedule(picked, ReadyInsts);
8598   }
8599 
8600   // Check that we didn't break any of our invariants.
8601 #ifdef EXPENSIVE_CHECKS
8602   BS->verify();
8603 #endif
8604 
8605 #if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS)
8606   // Check that all schedulable entities got scheduled
8607   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; I = I->getNextNode()) {
8608     BS->doForAllOpcodes(I, [&](ScheduleData *SD) {
8609       if (SD->isSchedulingEntity() && SD->hasValidDependencies()) {
8610         assert(SD->IsScheduled && "must be scheduled at this point");
8611       }
8612     });
8613   }
8614 #endif
8615 
8616   // Avoid duplicate scheduling of the block.
8617   BS->ScheduleStart = nullptr;
8618 }
8619 
8620 unsigned BoUpSLP::getVectorElementSize(Value *V) {
8621   // If V is a store, just return the width of the stored value (or value
8622   // truncated just before storing) without traversing the expression tree.
8623   // This is the common case.
8624   if (auto *Store = dyn_cast<StoreInst>(V))
8625     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
8626 
8627   if (auto *IEI = dyn_cast<InsertElementInst>(V))
8628     return getVectorElementSize(IEI->getOperand(1));
8629 
8630   auto E = InstrElementSize.find(V);
8631   if (E != InstrElementSize.end())
8632     return E->second;
8633 
8634   // If V is not a store, we can traverse the expression tree to find loads
8635   // that feed it. The type of the loaded value may indicate a more suitable
8636   // width than V's type. We want to base the vector element size on the width
8637   // of memory operations where possible.
8638   SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist;
8639   SmallPtrSet<Instruction *, 16> Visited;
8640   if (auto *I = dyn_cast<Instruction>(V)) {
8641     Worklist.emplace_back(I, I->getParent());
8642     Visited.insert(I);
8643   }
8644 
8645   // Traverse the expression tree in bottom-up order looking for loads. If we
8646   // encounter an instruction we don't yet handle, we give up.
8647   auto Width = 0u;
8648   while (!Worklist.empty()) {
8649     Instruction *I;
8650     BasicBlock *Parent;
8651     std::tie(I, Parent) = Worklist.pop_back_val();
8652 
8653     // We should only be looking at scalar instructions here. If the current
8654     // instruction has a vector type, skip.
8655     auto *Ty = I->getType();
8656     if (isa<VectorType>(Ty))
8657       continue;
8658 
8659     // If the current instruction is a load, update MaxWidth to reflect the
8660     // width of the loaded value.
8661     if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) ||
8662         isa<ExtractValueInst>(I))
8663       Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty));
8664 
8665     // Otherwise, we need to visit the operands of the instruction. We only
8666     // handle the interesting cases from buildTree here. If an operand is an
8667     // instruction we haven't yet visited and from the same basic block as the
8668     // user or the use is a PHI node, we add it to the worklist.
8669     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
8670              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) ||
8671              isa<UnaryOperator>(I)) {
8672       for (Use &U : I->operands())
8673         if (auto *J = dyn_cast<Instruction>(U.get()))
8674           if (Visited.insert(J).second &&
8675               (isa<PHINode>(I) || J->getParent() == Parent))
8676             Worklist.emplace_back(J, J->getParent());
8677     } else {
8678       break;
8679     }
8680   }
8681 
8682   // If we didn't encounter a memory access in the expression tree, or if we
8683   // gave up for some reason, just return the width of V. Otherwise, return the
8684   // maximum width we found.
8685   if (!Width) {
8686     if (auto *CI = dyn_cast<CmpInst>(V))
8687       V = CI->getOperand(0);
8688     Width = DL->getTypeSizeInBits(V->getType());
8689   }
8690 
8691   for (Instruction *I : Visited)
8692     InstrElementSize[I] = Width;
8693 
8694   return Width;
8695 }
8696 
8697 // Determine if a value V in a vectorizable expression Expr can be demoted to a
8698 // smaller type with a truncation. We collect the values that will be demoted
8699 // in ToDemote and additional roots that require investigating in Roots.
8700 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
8701                                   SmallVectorImpl<Value *> &ToDemote,
8702                                   SmallVectorImpl<Value *> &Roots) {
8703   // We can always demote constants.
8704   if (isa<Constant>(V)) {
8705     ToDemote.push_back(V);
8706     return true;
8707   }
8708 
8709   // If the value is not an instruction in the expression with only one use, it
8710   // cannot be demoted.
8711   auto *I = dyn_cast<Instruction>(V);
8712   if (!I || !I->hasOneUse() || !Expr.count(I))
8713     return false;
8714 
8715   switch (I->getOpcode()) {
8716 
8717   // We can always demote truncations and extensions. Since truncations can
8718   // seed additional demotion, we save the truncated value.
8719   case Instruction::Trunc:
8720     Roots.push_back(I->getOperand(0));
8721     break;
8722   case Instruction::ZExt:
8723   case Instruction::SExt:
8724     if (isa<ExtractElementInst>(I->getOperand(0)) ||
8725         isa<InsertElementInst>(I->getOperand(0)))
8726       return false;
8727     break;
8728 
8729   // We can demote certain binary operations if we can demote both of their
8730   // operands.
8731   case Instruction::Add:
8732   case Instruction::Sub:
8733   case Instruction::Mul:
8734   case Instruction::And:
8735   case Instruction::Or:
8736   case Instruction::Xor:
8737     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
8738         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
8739       return false;
8740     break;
8741 
8742   // We can demote selects if we can demote their true and false values.
8743   case Instruction::Select: {
8744     SelectInst *SI = cast<SelectInst>(I);
8745     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
8746         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
8747       return false;
8748     break;
8749   }
8750 
8751   // We can demote phis if we can demote all their incoming operands. Note that
8752   // we don't need to worry about cycles since we ensure single use above.
8753   case Instruction::PHI: {
8754     PHINode *PN = cast<PHINode>(I);
8755     for (Value *IncValue : PN->incoming_values())
8756       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
8757         return false;
8758     break;
8759   }
8760 
8761   // Otherwise, conservatively give up.
8762   default:
8763     return false;
8764   }
8765 
8766   // Record the value that we can demote.
8767   ToDemote.push_back(V);
8768   return true;
8769 }
8770 
8771 void BoUpSLP::computeMinimumValueSizes() {
8772   // If there are no external uses, the expression tree must be rooted by a
8773   // store. We can't demote in-memory values, so there is nothing to do here.
8774   if (ExternalUses.empty())
8775     return;
8776 
8777   // We only attempt to truncate integer expressions.
8778   auto &TreeRoot = VectorizableTree[0]->Scalars;
8779   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
8780   if (!TreeRootIT)
8781     return;
8782 
8783   // If the expression is not rooted by a store, these roots should have
8784   // external uses. We will rely on InstCombine to rewrite the expression in
8785   // the narrower type. However, InstCombine only rewrites single-use values.
8786   // This means that if a tree entry other than a root is used externally, it
8787   // must have multiple uses and InstCombine will not rewrite it. The code
8788   // below ensures that only the roots are used externally.
8789   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
8790   for (auto &EU : ExternalUses)
8791     if (!Expr.erase(EU.Scalar))
8792       return;
8793   if (!Expr.empty())
8794     return;
8795 
8796   // Collect the scalar values of the vectorizable expression. We will use this
8797   // context to determine which values can be demoted. If we see a truncation,
8798   // we mark it as seeding another demotion.
8799   for (auto &EntryPtr : VectorizableTree)
8800     Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
8801 
8802   // Ensure the roots of the vectorizable tree don't form a cycle. They must
8803   // have a single external user that is not in the vectorizable tree.
8804   for (auto *Root : TreeRoot)
8805     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
8806       return;
8807 
8808   // Conservatively determine if we can actually truncate the roots of the
8809   // expression. Collect the values that can be demoted in ToDemote and
8810   // additional roots that require investigating in Roots.
8811   SmallVector<Value *, 32> ToDemote;
8812   SmallVector<Value *, 4> Roots;
8813   for (auto *Root : TreeRoot)
8814     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
8815       return;
8816 
8817   // The maximum bit width required to represent all the values that can be
8818   // demoted without loss of precision. It would be safe to truncate the roots
8819   // of the expression to this width.
8820   auto MaxBitWidth = 8u;
8821 
8822   // We first check if all the bits of the roots are demanded. If they're not,
8823   // we can truncate the roots to this narrower type.
8824   for (auto *Root : TreeRoot) {
8825     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
8826     MaxBitWidth = std::max<unsigned>(
8827         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
8828   }
8829 
8830   // True if the roots can be zero-extended back to their original type, rather
8831   // than sign-extended. We know that if the leading bits are not demanded, we
8832   // can safely zero-extend. So we initialize IsKnownPositive to True.
8833   bool IsKnownPositive = true;
8834 
8835   // If all the bits of the roots are demanded, we can try a little harder to
8836   // compute a narrower type. This can happen, for example, if the roots are
8837   // getelementptr indices. InstCombine promotes these indices to the pointer
8838   // width. Thus, all their bits are technically demanded even though the
8839   // address computation might be vectorized in a smaller type.
8840   //
8841   // We start by looking at each entry that can be demoted. We compute the
8842   // maximum bit width required to store the scalar by using ValueTracking to
8843   // compute the number of high-order bits we can truncate.
8844   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
8845       llvm::all_of(TreeRoot, [](Value *R) {
8846         assert(R->hasOneUse() && "Root should have only one use!");
8847         return isa<GetElementPtrInst>(R->user_back());
8848       })) {
8849     MaxBitWidth = 8u;
8850 
8851     // Determine if the sign bit of all the roots is known to be zero. If not,
8852     // IsKnownPositive is set to False.
8853     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
8854       KnownBits Known = computeKnownBits(R, *DL);
8855       return Known.isNonNegative();
8856     });
8857 
8858     // Determine the maximum number of bits required to store the scalar
8859     // values.
8860     for (auto *Scalar : ToDemote) {
8861       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
8862       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
8863       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
8864     }
8865 
8866     // If we can't prove that the sign bit is zero, we must add one to the
8867     // maximum bit width to account for the unknown sign bit. This preserves
8868     // the existing sign bit so we can safely sign-extend the root back to the
8869     // original type. Otherwise, if we know the sign bit is zero, we will
8870     // zero-extend the root instead.
8871     //
8872     // FIXME: This is somewhat suboptimal, as there will be cases where adding
8873     //        one to the maximum bit width will yield a larger-than-necessary
8874     //        type. In general, we need to add an extra bit only if we can't
8875     //        prove that the upper bit of the original type is equal to the
8876     //        upper bit of the proposed smaller type. If these two bits are the
8877     //        same (either zero or one) we know that sign-extending from the
8878     //        smaller type will result in the same value. Here, since we can't
8879     //        yet prove this, we are just making the proposed smaller type
8880     //        larger to ensure correctness.
8881     if (!IsKnownPositive)
8882       ++MaxBitWidth;
8883   }
8884 
8885   // Round MaxBitWidth up to the next power-of-two.
8886   if (!isPowerOf2_64(MaxBitWidth))
8887     MaxBitWidth = NextPowerOf2(MaxBitWidth);
8888 
8889   // If the maximum bit width we compute is less than the with of the roots'
8890   // type, we can proceed with the narrowing. Otherwise, do nothing.
8891   if (MaxBitWidth >= TreeRootIT->getBitWidth())
8892     return;
8893 
8894   // If we can truncate the root, we must collect additional values that might
8895   // be demoted as a result. That is, those seeded by truncations we will
8896   // modify.
8897   while (!Roots.empty())
8898     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
8899 
8900   // Finally, map the values we can demote to the maximum bit with we computed.
8901   for (auto *Scalar : ToDemote)
8902     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
8903 }
8904 
8905 namespace {
8906 
8907 /// The SLPVectorizer Pass.
8908 struct SLPVectorizer : public FunctionPass {
8909   SLPVectorizerPass Impl;
8910 
8911   /// Pass identification, replacement for typeid
8912   static char ID;
8913 
8914   explicit SLPVectorizer() : FunctionPass(ID) {
8915     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
8916   }
8917 
8918   bool doInitialization(Module &M) override { return false; }
8919 
8920   bool runOnFunction(Function &F) override {
8921     if (skipFunction(F))
8922       return false;
8923 
8924     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
8925     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
8926     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
8927     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
8928     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
8929     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
8930     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
8931     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
8932     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
8933     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
8934 
8935     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8936   }
8937 
8938   void getAnalysisUsage(AnalysisUsage &AU) const override {
8939     FunctionPass::getAnalysisUsage(AU);
8940     AU.addRequired<AssumptionCacheTracker>();
8941     AU.addRequired<ScalarEvolutionWrapperPass>();
8942     AU.addRequired<AAResultsWrapperPass>();
8943     AU.addRequired<TargetTransformInfoWrapperPass>();
8944     AU.addRequired<LoopInfoWrapperPass>();
8945     AU.addRequired<DominatorTreeWrapperPass>();
8946     AU.addRequired<DemandedBitsWrapperPass>();
8947     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
8948     AU.addRequired<InjectTLIMappingsLegacy>();
8949     AU.addPreserved<LoopInfoWrapperPass>();
8950     AU.addPreserved<DominatorTreeWrapperPass>();
8951     AU.addPreserved<AAResultsWrapperPass>();
8952     AU.addPreserved<GlobalsAAWrapperPass>();
8953     AU.setPreservesCFG();
8954   }
8955 };
8956 
8957 } // end anonymous namespace
8958 
8959 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
8960   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
8961   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
8962   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
8963   auto *AA = &AM.getResult<AAManager>(F);
8964   auto *LI = &AM.getResult<LoopAnalysis>(F);
8965   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
8966   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
8967   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
8968   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
8969 
8970   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8971   if (!Changed)
8972     return PreservedAnalyses::all();
8973 
8974   PreservedAnalyses PA;
8975   PA.preserveSet<CFGAnalyses>();
8976   return PA;
8977 }
8978 
8979 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
8980                                 TargetTransformInfo *TTI_,
8981                                 TargetLibraryInfo *TLI_, AAResults *AA_,
8982                                 LoopInfo *LI_, DominatorTree *DT_,
8983                                 AssumptionCache *AC_, DemandedBits *DB_,
8984                                 OptimizationRemarkEmitter *ORE_) {
8985   if (!RunSLPVectorization)
8986     return false;
8987   SE = SE_;
8988   TTI = TTI_;
8989   TLI = TLI_;
8990   AA = AA_;
8991   LI = LI_;
8992   DT = DT_;
8993   AC = AC_;
8994   DB = DB_;
8995   DL = &F.getParent()->getDataLayout();
8996 
8997   Stores.clear();
8998   GEPs.clear();
8999   bool Changed = false;
9000 
9001   // If the target claims to have no vector registers don't attempt
9002   // vectorization.
9003   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true))) {
9004     LLVM_DEBUG(
9005         dbgs() << "SLP: Didn't find any vector registers for target, abort.\n");
9006     return false;
9007   }
9008 
9009   // Don't vectorize when the attribute NoImplicitFloat is used.
9010   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
9011     return false;
9012 
9013   LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
9014 
9015   // Use the bottom up slp vectorizer to construct chains that start with
9016   // store instructions.
9017   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
9018 
9019   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
9020   // delete instructions.
9021 
9022   // Update DFS numbers now so that we can use them for ordering.
9023   DT->updateDFSNumbers();
9024 
9025   // Scan the blocks in the function in post order.
9026   for (auto BB : post_order(&F.getEntryBlock())) {
9027     // Start new block - clear the list of reduction roots.
9028     R.clearReductionData();
9029     collectSeedInstructions(BB);
9030 
9031     // Vectorize trees that end at stores.
9032     if (!Stores.empty()) {
9033       LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
9034                         << " underlying objects.\n");
9035       Changed |= vectorizeStoreChains(R);
9036     }
9037 
9038     // Vectorize trees that end at reductions.
9039     Changed |= vectorizeChainsInBlock(BB, R);
9040 
9041     // Vectorize the index computations of getelementptr instructions. This
9042     // is primarily intended to catch gather-like idioms ending at
9043     // non-consecutive loads.
9044     if (!GEPs.empty()) {
9045       LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
9046                         << " underlying objects.\n");
9047       Changed |= vectorizeGEPIndices(BB, R);
9048     }
9049   }
9050 
9051   if (Changed) {
9052     R.optimizeGatherSequence();
9053     LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
9054   }
9055   return Changed;
9056 }
9057 
9058 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
9059                                             unsigned Idx, unsigned MinVF) {
9060   LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()
9061                     << "\n");
9062   const unsigned Sz = R.getVectorElementSize(Chain[0]);
9063   unsigned VF = Chain.size();
9064 
9065   if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
9066     return false;
9067 
9068   LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx
9069                     << "\n");
9070 
9071   R.buildTree(Chain);
9072   if (R.isTreeTinyAndNotFullyVectorizable())
9073     return false;
9074   if (R.isLoadCombineCandidate())
9075     return false;
9076   R.reorderTopToBottom();
9077   R.reorderBottomToTop();
9078   R.buildExternalUses();
9079 
9080   R.computeMinimumValueSizes();
9081 
9082   InstructionCost Cost = R.getTreeCost();
9083 
9084   LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n");
9085   if (Cost < -SLPCostThreshold) {
9086     LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n");
9087 
9088     using namespace ore;
9089 
9090     R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
9091                                         cast<StoreInst>(Chain[0]))
9092                      << "Stores SLP vectorized with cost " << NV("Cost", Cost)
9093                      << " and with tree size "
9094                      << NV("TreeSize", R.getTreeSize()));
9095 
9096     R.vectorizeTree();
9097     return true;
9098   }
9099 
9100   return false;
9101 }
9102 
9103 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
9104                                         BoUpSLP &R) {
9105   // We may run into multiple chains that merge into a single chain. We mark the
9106   // stores that we vectorized so that we don't visit the same store twice.
9107   BoUpSLP::ValueSet VectorizedStores;
9108   bool Changed = false;
9109 
9110   int E = Stores.size();
9111   SmallBitVector Tails(E, false);
9112   int MaxIter = MaxStoreLookup.getValue();
9113   SmallVector<std::pair<int, int>, 16> ConsecutiveChain(
9114       E, std::make_pair(E, INT_MAX));
9115   SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false));
9116   int IterCnt;
9117   auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
9118                                   &CheckedPairs,
9119                                   &ConsecutiveChain](int K, int Idx) {
9120     if (IterCnt >= MaxIter)
9121       return true;
9122     if (CheckedPairs[Idx].test(K))
9123       return ConsecutiveChain[K].second == 1 &&
9124              ConsecutiveChain[K].first == Idx;
9125     ++IterCnt;
9126     CheckedPairs[Idx].set(K);
9127     CheckedPairs[K].set(Idx);
9128     Optional<int> Diff = getPointersDiff(
9129         Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(),
9130         Stores[Idx]->getValueOperand()->getType(),
9131         Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true);
9132     if (!Diff || *Diff == 0)
9133       return false;
9134     int Val = *Diff;
9135     if (Val < 0) {
9136       if (ConsecutiveChain[Idx].second > -Val) {
9137         Tails.set(K);
9138         ConsecutiveChain[Idx] = std::make_pair(K, -Val);
9139       }
9140       return false;
9141     }
9142     if (ConsecutiveChain[K].second <= Val)
9143       return false;
9144 
9145     Tails.set(Idx);
9146     ConsecutiveChain[K] = std::make_pair(Idx, Val);
9147     return Val == 1;
9148   };
9149   // Do a quadratic search on all of the given stores in reverse order and find
9150   // all of the pairs of stores that follow each other.
9151   for (int Idx = E - 1; Idx >= 0; --Idx) {
9152     // If a store has multiple consecutive store candidates, search according
9153     // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
9154     // This is because usually pairing with immediate succeeding or preceding
9155     // candidate create the best chance to find slp vectorization opportunity.
9156     const int MaxLookDepth = std::max(E - Idx, Idx + 1);
9157     IterCnt = 0;
9158     for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
9159       if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
9160           (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
9161         break;
9162   }
9163 
9164   // Tracks if we tried to vectorize stores starting from the given tail
9165   // already.
9166   SmallBitVector TriedTails(E, false);
9167   // For stores that start but don't end a link in the chain:
9168   for (int Cnt = E; Cnt > 0; --Cnt) {
9169     int I = Cnt - 1;
9170     if (ConsecutiveChain[I].first == E || Tails.test(I))
9171       continue;
9172     // We found a store instr that starts a chain. Now follow the chain and try
9173     // to vectorize it.
9174     BoUpSLP::ValueList Operands;
9175     // Collect the chain into a list.
9176     while (I != E && !VectorizedStores.count(Stores[I])) {
9177       Operands.push_back(Stores[I]);
9178       Tails.set(I);
9179       if (ConsecutiveChain[I].second != 1) {
9180         // Mark the new end in the chain and go back, if required. It might be
9181         // required if the original stores come in reversed order, for example.
9182         if (ConsecutiveChain[I].first != E &&
9183             Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) &&
9184             !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) {
9185           TriedTails.set(I);
9186           Tails.reset(ConsecutiveChain[I].first);
9187           if (Cnt < ConsecutiveChain[I].first + 2)
9188             Cnt = ConsecutiveChain[I].first + 2;
9189         }
9190         break;
9191       }
9192       // Move to the next value in the chain.
9193       I = ConsecutiveChain[I].first;
9194     }
9195     assert(!Operands.empty() && "Expected non-empty list of stores.");
9196 
9197     unsigned MaxVecRegSize = R.getMaxVecRegSize();
9198     unsigned EltSize = R.getVectorElementSize(Operands[0]);
9199     unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize);
9200 
9201     unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store),
9202                               MaxElts);
9203     auto *Store = cast<StoreInst>(Operands[0]);
9204     Type *StoreTy = Store->getValueOperand()->getType();
9205     Type *ValueTy = StoreTy;
9206     if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand()))
9207       ValueTy = Trunc->getSrcTy();
9208     unsigned MinVF = TTI->getStoreMinimumVF(
9209         R.getMinVF(DL->getTypeSizeInBits(ValueTy)), StoreTy, ValueTy);
9210 
9211     // FIXME: Is division-by-2 the correct step? Should we assert that the
9212     // register size is a power-of-2?
9213     unsigned StartIdx = 0;
9214     for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) {
9215       for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
9216         ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size);
9217         if (!VectorizedStores.count(Slice.front()) &&
9218             !VectorizedStores.count(Slice.back()) &&
9219             vectorizeStoreChain(Slice, R, Cnt, MinVF)) {
9220           // Mark the vectorized stores so that we don't vectorize them again.
9221           VectorizedStores.insert(Slice.begin(), Slice.end());
9222           Changed = true;
9223           // If we vectorized initial block, no need to try to vectorize it
9224           // again.
9225           if (Cnt == StartIdx)
9226             StartIdx += Size;
9227           Cnt += Size;
9228           continue;
9229         }
9230         ++Cnt;
9231       }
9232       // Check if the whole array was vectorized already - exit.
9233       if (StartIdx >= Operands.size())
9234         break;
9235     }
9236   }
9237 
9238   return Changed;
9239 }
9240 
9241 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
9242   // Initialize the collections. We will make a single pass over the block.
9243   Stores.clear();
9244   GEPs.clear();
9245 
9246   // Visit the store and getelementptr instructions in BB and organize them in
9247   // Stores and GEPs according to the underlying objects of their pointer
9248   // operands.
9249   for (Instruction &I : *BB) {
9250     // Ignore store instructions that are volatile or have a pointer operand
9251     // that doesn't point to a scalar type.
9252     if (auto *SI = dyn_cast<StoreInst>(&I)) {
9253       if (!SI->isSimple())
9254         continue;
9255       if (!isValidElementType(SI->getValueOperand()->getType()))
9256         continue;
9257       Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI);
9258     }
9259 
9260     // Ignore getelementptr instructions that have more than one index, a
9261     // constant index, or a pointer operand that doesn't point to a scalar
9262     // type.
9263     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
9264       auto Idx = GEP->idx_begin()->get();
9265       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
9266         continue;
9267       if (!isValidElementType(Idx->getType()))
9268         continue;
9269       if (GEP->getType()->isVectorTy())
9270         continue;
9271       GEPs[GEP->getPointerOperand()].push_back(GEP);
9272     }
9273   }
9274 }
9275 
9276 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
9277   if (!A || !B)
9278     return false;
9279   if (isa<InsertElementInst>(A) || isa<InsertElementInst>(B))
9280     return false;
9281   Value *VL[] = {A, B};
9282   return tryToVectorizeList(VL, R);
9283 }
9284 
9285 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
9286                                            bool LimitForRegisterSize) {
9287   if (VL.size() < 2)
9288     return false;
9289 
9290   LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
9291                     << VL.size() << ".\n");
9292 
9293   // Check that all of the parts are instructions of the same type,
9294   // we permit an alternate opcode via InstructionsState.
9295   InstructionsState S = getSameOpcode(VL);
9296   if (!S.getOpcode())
9297     return false;
9298 
9299   Instruction *I0 = cast<Instruction>(S.OpValue);
9300   // Make sure invalid types (including vector type) are rejected before
9301   // determining vectorization factor for scalar instructions.
9302   for (Value *V : VL) {
9303     Type *Ty = V->getType();
9304     if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) {
9305       // NOTE: the following will give user internal llvm type name, which may
9306       // not be useful.
9307       R.getORE()->emit([&]() {
9308         std::string type_str;
9309         llvm::raw_string_ostream rso(type_str);
9310         Ty->print(rso);
9311         return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
9312                << "Cannot SLP vectorize list: type "
9313                << rso.str() + " is unsupported by vectorizer";
9314       });
9315       return false;
9316     }
9317   }
9318 
9319   unsigned Sz = R.getVectorElementSize(I0);
9320   unsigned MinVF = R.getMinVF(Sz);
9321   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
9322   MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF);
9323   if (MaxVF < 2) {
9324     R.getORE()->emit([&]() {
9325       return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
9326              << "Cannot SLP vectorize list: vectorization factor "
9327              << "less than 2 is not supported";
9328     });
9329     return false;
9330   }
9331 
9332   bool Changed = false;
9333   bool CandidateFound = false;
9334   InstructionCost MinCost = SLPCostThreshold.getValue();
9335   Type *ScalarTy = VL[0]->getType();
9336   if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
9337     ScalarTy = IE->getOperand(1)->getType();
9338 
9339   unsigned NextInst = 0, MaxInst = VL.size();
9340   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
9341     // No actual vectorization should happen, if number of parts is the same as
9342     // provided vectorization factor (i.e. the scalar type is used for vector
9343     // code during codegen).
9344     auto *VecTy = FixedVectorType::get(ScalarTy, VF);
9345     if (TTI->getNumberOfParts(VecTy) == VF)
9346       continue;
9347     for (unsigned I = NextInst; I < MaxInst; ++I) {
9348       unsigned OpsWidth = 0;
9349 
9350       if (I + VF > MaxInst)
9351         OpsWidth = MaxInst - I;
9352       else
9353         OpsWidth = VF;
9354 
9355       if (!isPowerOf2_32(OpsWidth))
9356         continue;
9357 
9358       if ((LimitForRegisterSize && OpsWidth < MaxVF) ||
9359           (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2))
9360         break;
9361 
9362       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
9363       // Check that a previous iteration of this loop did not delete the Value.
9364       if (llvm::any_of(Ops, [&R](Value *V) {
9365             auto *I = dyn_cast<Instruction>(V);
9366             return I && R.isDeleted(I);
9367           }))
9368         continue;
9369 
9370       LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
9371                         << "\n");
9372 
9373       R.buildTree(Ops);
9374       if (R.isTreeTinyAndNotFullyVectorizable())
9375         continue;
9376       R.reorderTopToBottom();
9377       R.reorderBottomToTop(!isa<InsertElementInst>(Ops.front()));
9378       R.buildExternalUses();
9379 
9380       R.computeMinimumValueSizes();
9381       InstructionCost Cost = R.getTreeCost();
9382       CandidateFound = true;
9383       MinCost = std::min(MinCost, Cost);
9384 
9385       if (Cost < -SLPCostThreshold) {
9386         LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
9387         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
9388                                                     cast<Instruction>(Ops[0]))
9389                                  << "SLP vectorized with cost " << ore::NV("Cost", Cost)
9390                                  << " and with tree size "
9391                                  << ore::NV("TreeSize", R.getTreeSize()));
9392 
9393         R.vectorizeTree();
9394         // Move to the next bundle.
9395         I += VF - 1;
9396         NextInst = I + 1;
9397         Changed = true;
9398       }
9399     }
9400   }
9401 
9402   if (!Changed && CandidateFound) {
9403     R.getORE()->emit([&]() {
9404       return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
9405              << "List vectorization was possible but not beneficial with cost "
9406              << ore::NV("Cost", MinCost) << " >= "
9407              << ore::NV("Treshold", -SLPCostThreshold);
9408     });
9409   } else if (!Changed) {
9410     R.getORE()->emit([&]() {
9411       return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
9412              << "Cannot SLP vectorize list: vectorization was impossible"
9413              << " with available vectorization factors";
9414     });
9415   }
9416   return Changed;
9417 }
9418 
9419 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
9420   if (!I)
9421     return false;
9422 
9423   if ((!isa<BinaryOperator>(I) && !isa<CmpInst>(I)) ||
9424       isa<VectorType>(I->getType()))
9425     return false;
9426 
9427   Value *P = I->getParent();
9428 
9429   // Vectorize in current basic block only.
9430   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
9431   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
9432   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
9433     return false;
9434 
9435   // First collect all possible candidates
9436   SmallVector<std::pair<Value *, Value *>, 4> Candidates;
9437   Candidates.emplace_back(Op0, Op1);
9438 
9439   auto *A = dyn_cast<BinaryOperator>(Op0);
9440   auto *B = dyn_cast<BinaryOperator>(Op1);
9441   // Try to skip B.
9442   if (A && B && B->hasOneUse()) {
9443     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
9444     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
9445     if (B0 && B0->getParent() == P)
9446       Candidates.emplace_back(A, B0);
9447     if (B1 && B1->getParent() == P)
9448       Candidates.emplace_back(A, B1);
9449   }
9450   // Try to skip A.
9451   if (B && A && A->hasOneUse()) {
9452     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
9453     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
9454     if (A0 && A0->getParent() == P)
9455       Candidates.emplace_back(A0, B);
9456     if (A1 && A1->getParent() == P)
9457       Candidates.emplace_back(A1, B);
9458   }
9459 
9460   if (Candidates.size() == 1)
9461     return tryToVectorizePair(Op0, Op1, R);
9462 
9463   // We have multiple options. Try to pick the single best.
9464   Optional<int> BestCandidate = R.findBestRootPair(Candidates);
9465   if (!BestCandidate)
9466     return false;
9467   return tryToVectorizePair(Candidates[*BestCandidate].first,
9468                             Candidates[*BestCandidate].second, R);
9469 }
9470 
9471 namespace {
9472 
9473 /// Model horizontal reductions.
9474 ///
9475 /// A horizontal reduction is a tree of reduction instructions that has values
9476 /// that can be put into a vector as its leaves. For example:
9477 ///
9478 /// mul mul mul mul
9479 ///  \  /    \  /
9480 ///   +       +
9481 ///    \     /
9482 ///       +
9483 /// This tree has "mul" as its leaf values and "+" as its reduction
9484 /// instructions. A reduction can feed into a store or a binary operation
9485 /// feeding a phi.
9486 ///    ...
9487 ///    \  /
9488 ///     +
9489 ///     |
9490 ///  phi +=
9491 ///
9492 ///  Or:
9493 ///    ...
9494 ///    \  /
9495 ///     +
9496 ///     |
9497 ///   *p =
9498 ///
9499 class HorizontalReduction {
9500   using ReductionOpsType = SmallVector<Value *, 16>;
9501   using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
9502   ReductionOpsListType ReductionOps;
9503   /// List of possibly reduced values.
9504   SmallVector<SmallVector<Value *>> ReducedVals;
9505   /// Maps reduced value to the corresponding reduction operation.
9506   DenseMap<Value *, SmallVector<Instruction *>> ReducedValsToOps;
9507   // Use map vector to make stable output.
9508   MapVector<Instruction *, Value *> ExtraArgs;
9509   WeakTrackingVH ReductionRoot;
9510   /// The type of reduction operation.
9511   RecurKind RdxKind;
9512 
9513   static bool isCmpSelMinMax(Instruction *I) {
9514     return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) &&
9515            RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I));
9516   }
9517 
9518   // And/or are potentially poison-safe logical patterns like:
9519   // select x, y, false
9520   // select x, true, y
9521   static bool isBoolLogicOp(Instruction *I) {
9522     return match(I, m_LogicalAnd(m_Value(), m_Value())) ||
9523            match(I, m_LogicalOr(m_Value(), m_Value()));
9524   }
9525 
9526   /// Checks if instruction is associative and can be vectorized.
9527   static bool isVectorizable(RecurKind Kind, Instruction *I) {
9528     if (Kind == RecurKind::None)
9529       return false;
9530 
9531     // Integer ops that map to select instructions or intrinsics are fine.
9532     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) ||
9533         isBoolLogicOp(I))
9534       return true;
9535 
9536     if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) {
9537       // FP min/max are associative except for NaN and -0.0. We do not
9538       // have to rule out -0.0 here because the intrinsic semantics do not
9539       // specify a fixed result for it.
9540       return I->getFastMathFlags().noNaNs();
9541     }
9542 
9543     return I->isAssociative();
9544   }
9545 
9546   static Value *getRdxOperand(Instruction *I, unsigned Index) {
9547     // Poison-safe 'or' takes the form: select X, true, Y
9548     // To make that work with the normal operand processing, we skip the
9549     // true value operand.
9550     // TODO: Change the code and data structures to handle this without a hack.
9551     if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1)
9552       return I->getOperand(2);
9553     return I->getOperand(Index);
9554   }
9555 
9556   /// Creates reduction operation with the current opcode.
9557   static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS,
9558                          Value *RHS, const Twine &Name, bool UseSelect) {
9559     unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind);
9560     switch (Kind) {
9561     case RecurKind::Or:
9562       if (UseSelect &&
9563           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9564         return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name);
9565       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9566                                  Name);
9567     case RecurKind::And:
9568       if (UseSelect &&
9569           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9570         return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name);
9571       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9572                                  Name);
9573     case RecurKind::Add:
9574     case RecurKind::Mul:
9575     case RecurKind::Xor:
9576     case RecurKind::FAdd:
9577     case RecurKind::FMul:
9578       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9579                                  Name);
9580     case RecurKind::FMax:
9581       return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS);
9582     case RecurKind::FMin:
9583       return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS);
9584     case RecurKind::SMax:
9585       if (UseSelect) {
9586         Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name);
9587         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9588       }
9589       return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS);
9590     case RecurKind::SMin:
9591       if (UseSelect) {
9592         Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name);
9593         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9594       }
9595       return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS);
9596     case RecurKind::UMax:
9597       if (UseSelect) {
9598         Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name);
9599         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9600       }
9601       return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS);
9602     case RecurKind::UMin:
9603       if (UseSelect) {
9604         Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name);
9605         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9606       }
9607       return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS);
9608     default:
9609       llvm_unreachable("Unknown reduction operation.");
9610     }
9611   }
9612 
9613   /// Creates reduction operation with the current opcode with the IR flags
9614   /// from \p ReductionOps.
9615   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9616                          Value *RHS, const Twine &Name,
9617                          const ReductionOpsListType &ReductionOps) {
9618     bool UseSelect = ReductionOps.size() == 2 ||
9619                      // Logical or/and.
9620                      (ReductionOps.size() == 1 &&
9621                       isa<SelectInst>(ReductionOps.front().front()));
9622     assert((!UseSelect || ReductionOps.size() != 2 ||
9623             isa<SelectInst>(ReductionOps[1][0])) &&
9624            "Expected cmp + select pairs for reduction");
9625     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect);
9626     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9627       if (auto *Sel = dyn_cast<SelectInst>(Op)) {
9628         propagateIRFlags(Sel->getCondition(), ReductionOps[0]);
9629         propagateIRFlags(Op, ReductionOps[1]);
9630         return Op;
9631       }
9632     }
9633     propagateIRFlags(Op, ReductionOps[0]);
9634     return Op;
9635   }
9636 
9637   /// Creates reduction operation with the current opcode with the IR flags
9638   /// from \p I.
9639   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9640                          Value *RHS, const Twine &Name, Value *I) {
9641     auto *SelI = dyn_cast<SelectInst>(I);
9642     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, SelI != nullptr);
9643     if (SelI && RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9644       if (auto *Sel = dyn_cast<SelectInst>(Op))
9645         propagateIRFlags(Sel->getCondition(), SelI->getCondition());
9646     }
9647     propagateIRFlags(Op, I);
9648     return Op;
9649   }
9650 
9651   static RecurKind getRdxKind(Value *V) {
9652     auto *I = dyn_cast<Instruction>(V);
9653     if (!I)
9654       return RecurKind::None;
9655     if (match(I, m_Add(m_Value(), m_Value())))
9656       return RecurKind::Add;
9657     if (match(I, m_Mul(m_Value(), m_Value())))
9658       return RecurKind::Mul;
9659     if (match(I, m_And(m_Value(), m_Value())) ||
9660         match(I, m_LogicalAnd(m_Value(), m_Value())))
9661       return RecurKind::And;
9662     if (match(I, m_Or(m_Value(), m_Value())) ||
9663         match(I, m_LogicalOr(m_Value(), m_Value())))
9664       return RecurKind::Or;
9665     if (match(I, m_Xor(m_Value(), m_Value())))
9666       return RecurKind::Xor;
9667     if (match(I, m_FAdd(m_Value(), m_Value())))
9668       return RecurKind::FAdd;
9669     if (match(I, m_FMul(m_Value(), m_Value())))
9670       return RecurKind::FMul;
9671 
9672     if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value())))
9673       return RecurKind::FMax;
9674     if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value())))
9675       return RecurKind::FMin;
9676 
9677     // This matches either cmp+select or intrinsics. SLP is expected to handle
9678     // either form.
9679     // TODO: If we are canonicalizing to intrinsics, we can remove several
9680     //       special-case paths that deal with selects.
9681     if (match(I, m_SMax(m_Value(), m_Value())))
9682       return RecurKind::SMax;
9683     if (match(I, m_SMin(m_Value(), m_Value())))
9684       return RecurKind::SMin;
9685     if (match(I, m_UMax(m_Value(), m_Value())))
9686       return RecurKind::UMax;
9687     if (match(I, m_UMin(m_Value(), m_Value())))
9688       return RecurKind::UMin;
9689 
9690     if (auto *Select = dyn_cast<SelectInst>(I)) {
9691       // Try harder: look for min/max pattern based on instructions producing
9692       // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
9693       // During the intermediate stages of SLP, it's very common to have
9694       // pattern like this (since optimizeGatherSequence is run only once
9695       // at the end):
9696       // %1 = extractelement <2 x i32> %a, i32 0
9697       // %2 = extractelement <2 x i32> %a, i32 1
9698       // %cond = icmp sgt i32 %1, %2
9699       // %3 = extractelement <2 x i32> %a, i32 0
9700       // %4 = extractelement <2 x i32> %a, i32 1
9701       // %select = select i1 %cond, i32 %3, i32 %4
9702       CmpInst::Predicate Pred;
9703       Instruction *L1;
9704       Instruction *L2;
9705 
9706       Value *LHS = Select->getTrueValue();
9707       Value *RHS = Select->getFalseValue();
9708       Value *Cond = Select->getCondition();
9709 
9710       // TODO: Support inverse predicates.
9711       if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
9712         if (!isa<ExtractElementInst>(RHS) ||
9713             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9714           return RecurKind::None;
9715       } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
9716         if (!isa<ExtractElementInst>(LHS) ||
9717             !L1->isIdenticalTo(cast<Instruction>(LHS)))
9718           return RecurKind::None;
9719       } else {
9720         if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
9721           return RecurKind::None;
9722         if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
9723             !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
9724             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9725           return RecurKind::None;
9726       }
9727 
9728       switch (Pred) {
9729       default:
9730         return RecurKind::None;
9731       case CmpInst::ICMP_SGT:
9732       case CmpInst::ICMP_SGE:
9733         return RecurKind::SMax;
9734       case CmpInst::ICMP_SLT:
9735       case CmpInst::ICMP_SLE:
9736         return RecurKind::SMin;
9737       case CmpInst::ICMP_UGT:
9738       case CmpInst::ICMP_UGE:
9739         return RecurKind::UMax;
9740       case CmpInst::ICMP_ULT:
9741       case CmpInst::ICMP_ULE:
9742         return RecurKind::UMin;
9743       }
9744     }
9745     return RecurKind::None;
9746   }
9747 
9748   /// Get the index of the first operand.
9749   static unsigned getFirstOperandIndex(Instruction *I) {
9750     return isCmpSelMinMax(I) ? 1 : 0;
9751   }
9752 
9753   /// Total number of operands in the reduction operation.
9754   static unsigned getNumberOfOperands(Instruction *I) {
9755     return isCmpSelMinMax(I) ? 3 : 2;
9756   }
9757 
9758   /// Checks if the instruction is in basic block \p BB.
9759   /// For a cmp+sel min/max reduction check that both ops are in \p BB.
9760   static bool hasSameParent(Instruction *I, BasicBlock *BB) {
9761     if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) {
9762       auto *Sel = cast<SelectInst>(I);
9763       auto *Cmp = dyn_cast<Instruction>(Sel->getCondition());
9764       return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB;
9765     }
9766     return I->getParent() == BB;
9767   }
9768 
9769   /// Expected number of uses for reduction operations/reduced values.
9770   static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) {
9771     if (IsCmpSelMinMax) {
9772       // SelectInst must be used twice while the condition op must have single
9773       // use only.
9774       if (auto *Sel = dyn_cast<SelectInst>(I))
9775         return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse();
9776       return I->hasNUses(2);
9777     }
9778 
9779     // Arithmetic reduction operation must be used once only.
9780     return I->hasOneUse();
9781   }
9782 
9783   /// Initializes the list of reduction operations.
9784   void initReductionOps(Instruction *I) {
9785     if (isCmpSelMinMax(I))
9786       ReductionOps.assign(2, ReductionOpsType());
9787     else
9788       ReductionOps.assign(1, ReductionOpsType());
9789   }
9790 
9791   /// Add all reduction operations for the reduction instruction \p I.
9792   void addReductionOps(Instruction *I) {
9793     if (isCmpSelMinMax(I)) {
9794       ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
9795       ReductionOps[1].emplace_back(I);
9796     } else {
9797       ReductionOps[0].emplace_back(I);
9798     }
9799   }
9800 
9801   static Value *getLHS(RecurKind Kind, Instruction *I) {
9802     if (Kind == RecurKind::None)
9803       return nullptr;
9804     return I->getOperand(getFirstOperandIndex(I));
9805   }
9806   static Value *getRHS(RecurKind Kind, Instruction *I) {
9807     if (Kind == RecurKind::None)
9808       return nullptr;
9809     return I->getOperand(getFirstOperandIndex(I) + 1);
9810   }
9811 
9812 public:
9813   HorizontalReduction() = default;
9814 
9815   /// Try to find a reduction tree.
9816   bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst,
9817                                  ScalarEvolution &SE, const DataLayout &DL,
9818                                  const TargetLibraryInfo &TLI) {
9819     assert((!Phi || is_contained(Phi->operands(), Inst)) &&
9820            "Phi needs to use the binary operator");
9821     assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) ||
9822             isa<IntrinsicInst>(Inst)) &&
9823            "Expected binop, select, or intrinsic for reduction matching");
9824     RdxKind = getRdxKind(Inst);
9825 
9826     // We could have a initial reductions that is not an add.
9827     //  r *= v1 + v2 + v3 + v4
9828     // In such a case start looking for a tree rooted in the first '+'.
9829     if (Phi) {
9830       if (getLHS(RdxKind, Inst) == Phi) {
9831         Phi = nullptr;
9832         Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst));
9833         if (!Inst)
9834           return false;
9835         RdxKind = getRdxKind(Inst);
9836       } else if (getRHS(RdxKind, Inst) == Phi) {
9837         Phi = nullptr;
9838         Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst));
9839         if (!Inst)
9840           return false;
9841         RdxKind = getRdxKind(Inst);
9842       }
9843     }
9844 
9845     if (!isVectorizable(RdxKind, Inst))
9846       return false;
9847 
9848     // Analyze "regular" integer/FP types for reductions - no target-specific
9849     // types or pointers.
9850     Type *Ty = Inst->getType();
9851     if (!isValidElementType(Ty) || Ty->isPointerTy())
9852       return false;
9853 
9854     // Though the ultimate reduction may have multiple uses, its condition must
9855     // have only single use.
9856     if (auto *Sel = dyn_cast<SelectInst>(Inst))
9857       if (!Sel->getCondition()->hasOneUse())
9858         return false;
9859 
9860     ReductionRoot = Inst;
9861 
9862     // Iterate through all the operands of the possible reduction tree and
9863     // gather all the reduced values, sorting them by their value id.
9864     BasicBlock *BB = Inst->getParent();
9865     bool IsCmpSelMinMax = isCmpSelMinMax(Inst);
9866     SmallVector<Instruction *> Worklist(1, Inst);
9867     // Checks if the operands of the \p TreeN instruction are also reduction
9868     // operations or should be treated as reduced values or an extra argument,
9869     // which is not part of the reduction.
9870     auto &&CheckOperands = [this, IsCmpSelMinMax,
9871                             BB](Instruction *TreeN,
9872                                 SmallVectorImpl<Value *> &ExtraArgs,
9873                                 SmallVectorImpl<Value *> &PossibleReducedVals,
9874                                 SmallVectorImpl<Instruction *> &ReductionOps) {
9875       for (int I = getFirstOperandIndex(TreeN),
9876                End = getNumberOfOperands(TreeN);
9877            I < End; ++I) {
9878         Value *EdgeVal = getRdxOperand(TreeN, I);
9879         ReducedValsToOps[EdgeVal].push_back(TreeN);
9880         auto *EdgeInst = dyn_cast<Instruction>(EdgeVal);
9881         // Edge has wrong parent - mark as an extra argument.
9882         if (EdgeInst && !isVectorLikeInstWithConstOps(EdgeInst) &&
9883             !hasSameParent(EdgeInst, BB)) {
9884           ExtraArgs.push_back(EdgeVal);
9885           continue;
9886         }
9887         // If the edge is not an instruction, or it is different from the main
9888         // reduction opcode or has too many uses - possible reduced value.
9889         if (!EdgeInst || getRdxKind(EdgeInst) != RdxKind ||
9890             !hasRequiredNumberOfUses(IsCmpSelMinMax, EdgeInst) ||
9891             !isVectorizable(getRdxKind(EdgeInst), EdgeInst)) {
9892           PossibleReducedVals.push_back(EdgeVal);
9893           continue;
9894         }
9895         ReductionOps.push_back(EdgeInst);
9896       }
9897     };
9898     // Try to regroup reduced values so that it gets more profitable to try to
9899     // reduce them. Values are grouped by their value ids, instructions - by
9900     // instruction op id and/or alternate op id, plus do extra analysis for
9901     // loads (grouping them by the distabce between pointers) and cmp
9902     // instructions (grouping them by the predicate).
9903     MapVector<size_t, MapVector<size_t, MapVector<Value *, unsigned>>>
9904         PossibleReducedVals;
9905     initReductionOps(Inst);
9906     while (!Worklist.empty()) {
9907       Instruction *TreeN = Worklist.pop_back_val();
9908       SmallVector<Value *> Args;
9909       SmallVector<Value *> PossibleRedVals;
9910       SmallVector<Instruction *> PossibleReductionOps;
9911       CheckOperands(TreeN, Args, PossibleRedVals, PossibleReductionOps);
9912       // If too many extra args - mark the instruction itself as a reduction
9913       // value, not a reduction operation.
9914       if (Args.size() < 2) {
9915         addReductionOps(TreeN);
9916         // Add extra args.
9917         if (!Args.empty()) {
9918           assert(Args.size() == 1 && "Expected only single argument.");
9919           ExtraArgs[TreeN] = Args.front();
9920         }
9921         // Add reduction values. The values are sorted for better vectorization
9922         // results.
9923         for (Value *V : PossibleRedVals) {
9924           size_t Key, Idx;
9925           std::tie(Key, Idx) = generateKeySubkey(
9926               V, &TLI,
9927               [&PossibleReducedVals, &DL, &SE](size_t Key, LoadInst *LI) {
9928                 for (const auto &LoadData : PossibleReducedVals[Key]) {
9929                   auto *RLI = cast<LoadInst>(LoadData.second.front().first);
9930                   if (getPointersDiff(RLI->getType(), RLI->getPointerOperand(),
9931                                       LI->getType(), LI->getPointerOperand(),
9932                                       DL, SE, /*StrictCheck=*/true))
9933                     return hash_value(RLI->getPointerOperand());
9934                 }
9935                 return hash_value(LI->getPointerOperand());
9936               },
9937               /*AllowAlternate=*/false);
9938           ++PossibleReducedVals[Key][Idx]
9939                 .insert(std::make_pair(V, 0))
9940                 .first->second;
9941         }
9942         Worklist.append(PossibleReductionOps.rbegin(),
9943                         PossibleReductionOps.rend());
9944       } else {
9945         size_t Key, Idx;
9946         std::tie(Key, Idx) = generateKeySubkey(
9947             TreeN, &TLI,
9948             [&PossibleReducedVals, &DL, &SE](size_t Key, LoadInst *LI) {
9949               for (const auto &LoadData : PossibleReducedVals[Key]) {
9950                 auto *RLI = cast<LoadInst>(LoadData.second.front().first);
9951                 if (getPointersDiff(RLI->getType(), RLI->getPointerOperand(),
9952                                     LI->getType(), LI->getPointerOperand(), DL,
9953                                     SE, /*StrictCheck=*/true))
9954                   return hash_value(RLI->getPointerOperand());
9955               }
9956               return hash_value(LI->getPointerOperand());
9957             },
9958             /*AllowAlternate=*/false);
9959         ++PossibleReducedVals[Key][Idx]
9960               .insert(std::make_pair(TreeN, 0))
9961               .first->second;
9962       }
9963     }
9964     auto PossibleReducedValsVect = PossibleReducedVals.takeVector();
9965     // Sort values by the total number of values kinds to start the reduction
9966     // from the longest possible reduced values sequences.
9967     for (auto &PossibleReducedVals : PossibleReducedValsVect) {
9968       auto PossibleRedVals = PossibleReducedVals.second.takeVector();
9969       SmallVector<SmallVector<Value *>> PossibleRedValsVect;
9970       for (auto It = PossibleRedVals.begin(), E = PossibleRedVals.end();
9971            It != E; ++It) {
9972         PossibleRedValsVect.emplace_back();
9973         auto RedValsVect = It->second.takeVector();
9974         stable_sort(RedValsVect, [](const auto &P1, const auto &P2) {
9975           return P1.second < P2.second;
9976         });
9977         for (const std::pair<Value *, unsigned> &Data : RedValsVect)
9978           PossibleRedValsVect.back().append(Data.second, Data.first);
9979       }
9980       stable_sort(PossibleRedValsVect, [](const auto &P1, const auto &P2) {
9981         return P1.size() > P2.size();
9982       });
9983       ReducedVals.emplace_back();
9984       for (ArrayRef<Value *> Data : PossibleRedValsVect)
9985         ReducedVals.back().append(Data.rbegin(), Data.rend());
9986     }
9987     // Sort the reduced values by number of same/alternate opcode and/or pointer
9988     // operand.
9989     stable_sort(ReducedVals, [](ArrayRef<Value *> P1, ArrayRef<Value *> P2) {
9990       return P1.size() > P2.size();
9991     });
9992     return true;
9993   }
9994 
9995   /// Attempt to vectorize the tree found by matchAssociativeReduction.
9996   Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
9997     constexpr int ReductionLimit = 4;
9998     // If there are a sufficient number of reduction values, reduce
9999     // to a nearby power-of-2. We can safely generate oversized
10000     // vectors and rely on the backend to split them to legal sizes.
10001     unsigned NumReducedVals = std::accumulate(
10002         ReducedVals.begin(), ReducedVals.end(), 0,
10003         [](int Num, ArrayRef<Value *> Vals) { return Num + Vals.size(); });
10004     if (NumReducedVals < ReductionLimit)
10005       return nullptr;
10006 
10007     IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
10008 
10009     // Track the reduced values in case if they are replaced by extractelement
10010     // because of the vectorization.
10011     DenseMap<Value *, WeakTrackingVH> TrackedVals;
10012     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
10013     // The same extra argument may be used several times, so log each attempt
10014     // to use it.
10015     for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) {
10016       assert(Pair.first && "DebugLoc must be set.");
10017       ExternallyUsedValues[Pair.second].push_back(Pair.first);
10018       TrackedVals.try_emplace(Pair.second, Pair.second);
10019     }
10020 
10021     // The compare instruction of a min/max is the insertion point for new
10022     // instructions and may be replaced with a new compare instruction.
10023     auto &&GetCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
10024       assert(isa<SelectInst>(RdxRootInst) &&
10025              "Expected min/max reduction to have select root instruction");
10026       Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
10027       assert(isa<Instruction>(ScalarCond) &&
10028              "Expected min/max reduction to have compare condition");
10029       return cast<Instruction>(ScalarCond);
10030     };
10031 
10032     // The reduction root is used as the insertion point for new instructions,
10033     // so set it as externally used to prevent it from being deleted.
10034     ExternallyUsedValues[ReductionRoot];
10035     SmallVector<Value *> IgnoreList;
10036     for (ReductionOpsType &RdxOps : ReductionOps)
10037       for (Value *RdxOp : RdxOps) {
10038         if (!RdxOp)
10039           continue;
10040         IgnoreList.push_back(RdxOp);
10041       }
10042     bool IsCmpSelMinMax = isCmpSelMinMax(cast<Instruction>(ReductionRoot));
10043 
10044     // Need to track reduced vals, they may be changed during vectorization of
10045     // subvectors.
10046     for (ArrayRef<Value *> Candidates : ReducedVals)
10047       for (Value *V : Candidates)
10048         TrackedVals.try_emplace(V, V);
10049 
10050     DenseMap<Value *, unsigned> VectorizedVals;
10051     Value *VectorizedTree = nullptr;
10052     bool CheckForReusedReductionOps = false;
10053     // Try to vectorize elements based on their type.
10054     for (unsigned I = 0, E = ReducedVals.size(); I < E; ++I) {
10055       ArrayRef<Value *> OrigReducedVals = ReducedVals[I];
10056       InstructionsState S = getSameOpcode(OrigReducedVals);
10057       SmallVector<Value *> Candidates;
10058       DenseMap<Value *, Value *> TrackedToOrig;
10059       for (unsigned Cnt = 0, Sz = OrigReducedVals.size(); Cnt < Sz; ++Cnt) {
10060         Value *RdxVal = TrackedVals.find(OrigReducedVals[Cnt])->second;
10061         // Check if the reduction value was not overriden by the extractelement
10062         // instruction because of the vectorization and exclude it, if it is not
10063         // compatible with other values.
10064         if (auto *Inst = dyn_cast<Instruction>(RdxVal))
10065           if (isVectorLikeInstWithConstOps(Inst) &&
10066               (!S.getOpcode() || !S.isOpcodeOrAlt(Inst)))
10067             continue;
10068         Candidates.push_back(RdxVal);
10069         TrackedToOrig.try_emplace(RdxVal, OrigReducedVals[Cnt]);
10070       }
10071       bool ShuffledExtracts = false;
10072       // Try to handle shuffled extractelements.
10073       if (S.getOpcode() == Instruction::ExtractElement && !S.isAltShuffle() &&
10074           I + 1 < E) {
10075         InstructionsState NextS = getSameOpcode(ReducedVals[I + 1]);
10076         if (NextS.getOpcode() == Instruction::ExtractElement &&
10077             !NextS.isAltShuffle()) {
10078           SmallVector<Value *> CommonCandidates(Candidates);
10079           for (Value *RV : ReducedVals[I + 1]) {
10080             Value *RdxVal = TrackedVals.find(RV)->second;
10081             // Check if the reduction value was not overriden by the
10082             // extractelement instruction because of the vectorization and
10083             // exclude it, if it is not compatible with other values.
10084             if (auto *Inst = dyn_cast<Instruction>(RdxVal))
10085               if (!NextS.getOpcode() || !NextS.isOpcodeOrAlt(Inst))
10086                 continue;
10087             CommonCandidates.push_back(RdxVal);
10088             TrackedToOrig.try_emplace(RdxVal, RV);
10089           }
10090           SmallVector<int> Mask;
10091           if (isFixedVectorShuffle(CommonCandidates, Mask)) {
10092             ++I;
10093             Candidates.swap(CommonCandidates);
10094             ShuffledExtracts = true;
10095           }
10096         }
10097       }
10098       unsigned NumReducedVals = Candidates.size();
10099       if (NumReducedVals < ReductionLimit)
10100         continue;
10101 
10102       unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
10103       unsigned Start = 0;
10104       unsigned Pos = Start;
10105       // Restarts vectorization attempt with lower vector factor.
10106       unsigned PrevReduxWidth = ReduxWidth;
10107       bool CheckForReusedReductionOpsLocal = false;
10108       auto &&AdjustReducedVals = [&Pos, &Start, &ReduxWidth, NumReducedVals,
10109                                   &CheckForReusedReductionOpsLocal,
10110                                   &PrevReduxWidth, &V,
10111                                   &IgnoreList](bool IgnoreVL = false) {
10112         bool IsAnyRedOpGathered =
10113             !IgnoreVL && any_of(IgnoreList, [&V](Value *RedOp) {
10114               return V.isGathered(RedOp);
10115             });
10116         if (!CheckForReusedReductionOpsLocal && PrevReduxWidth == ReduxWidth) {
10117           // Check if any of the reduction ops are gathered. If so, worth
10118           // trying again with less number of reduction ops.
10119           CheckForReusedReductionOpsLocal |= IsAnyRedOpGathered;
10120         }
10121         ++Pos;
10122         if (Pos < NumReducedVals - ReduxWidth + 1)
10123           return IsAnyRedOpGathered;
10124         Pos = Start;
10125         ReduxWidth /= 2;
10126         return IsAnyRedOpGathered;
10127       };
10128       while (Pos < NumReducedVals - ReduxWidth + 1 &&
10129              ReduxWidth >= ReductionLimit) {
10130         // Dependency in tree of the reduction ops - drop this attempt, try
10131         // later.
10132         if (CheckForReusedReductionOpsLocal && PrevReduxWidth != ReduxWidth &&
10133             Start == 0) {
10134           CheckForReusedReductionOps = true;
10135           break;
10136         }
10137         PrevReduxWidth = ReduxWidth;
10138         ArrayRef<Value *> VL(std::next(Candidates.begin(), Pos), ReduxWidth);
10139         // Beeing analyzed already - skip.
10140         if (V.areAnalyzedReductionVals(VL)) {
10141           (void)AdjustReducedVals(/*IgnoreVL=*/true);
10142           continue;
10143         }
10144         // Early exit if any of the reduction values were deleted during
10145         // previous vectorization attempts.
10146         if (any_of(VL, [&V](Value *RedVal) {
10147               auto *RedValI = dyn_cast<Instruction>(RedVal);
10148               if (!RedValI)
10149                 return false;
10150               return V.isDeleted(RedValI);
10151             }))
10152           break;
10153         V.buildTree(VL, IgnoreList);
10154         if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true)) {
10155           if (!AdjustReducedVals())
10156             V.analyzedReductionVals(VL);
10157           continue;
10158         }
10159         if (V.isLoadCombineReductionCandidate(RdxKind)) {
10160           if (!AdjustReducedVals())
10161             V.analyzedReductionVals(VL);
10162           continue;
10163         }
10164         V.reorderTopToBottom();
10165         // No need to reorder the root node at all.
10166         V.reorderBottomToTop(/*IgnoreReorder=*/true);
10167         // Keep extracted other reduction values, if they are used in the
10168         // vectorization trees.
10169         BoUpSLP::ExtraValueToDebugLocsMap LocalExternallyUsedValues(
10170             ExternallyUsedValues);
10171         for (unsigned Cnt = 0, Sz = ReducedVals.size(); Cnt < Sz; ++Cnt) {
10172           if (Cnt == I || (ShuffledExtracts && Cnt == I - 1))
10173             continue;
10174           for_each(ReducedVals[Cnt],
10175                    [&LocalExternallyUsedValues, &TrackedVals](Value *V) {
10176                      if (isa<Instruction>(V))
10177                        LocalExternallyUsedValues[TrackedVals[V]];
10178                    });
10179         }
10180         for (unsigned Cnt = 0; Cnt < NumReducedVals; ++Cnt) {
10181           if (Cnt >= Pos && Cnt < Pos + ReduxWidth)
10182             continue;
10183           if (VectorizedVals.count(Candidates[Cnt]))
10184             continue;
10185           LocalExternallyUsedValues[Candidates[Cnt]];
10186         }
10187         V.buildExternalUses(LocalExternallyUsedValues);
10188 
10189         V.computeMinimumValueSizes();
10190 
10191         // Intersect the fast-math-flags from all reduction operations.
10192         FastMathFlags RdxFMF;
10193         RdxFMF.set();
10194         for (Value *U : IgnoreList)
10195           if (auto *FPMO = dyn_cast<FPMathOperator>(U))
10196             RdxFMF &= FPMO->getFastMathFlags();
10197         // Estimate cost.
10198         InstructionCost TreeCost = V.getTreeCost(VL);
10199         InstructionCost ReductionCost =
10200             getReductionCost(TTI, VL[0], ReduxWidth, RdxFMF);
10201         InstructionCost Cost = TreeCost + ReductionCost;
10202         if (!Cost.isValid()) {
10203           LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n");
10204           return nullptr;
10205         }
10206         if (Cost >= -SLPCostThreshold) {
10207           V.getORE()->emit([&]() {
10208             return OptimizationRemarkMissed(
10209                        SV_NAME, "HorSLPNotBeneficial",
10210                        ReducedValsToOps.find(VL[0])->second.front())
10211                    << "Vectorizing horizontal reduction is possible"
10212                    << "but not beneficial with cost " << ore::NV("Cost", Cost)
10213                    << " and threshold "
10214                    << ore::NV("Threshold", -SLPCostThreshold);
10215           });
10216           if (!AdjustReducedVals())
10217             V.analyzedReductionVals(VL);
10218           continue;
10219         }
10220 
10221         LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
10222                           << Cost << ". (HorRdx)\n");
10223         V.getORE()->emit([&]() {
10224           return OptimizationRemark(
10225                      SV_NAME, "VectorizedHorizontalReduction",
10226                      ReducedValsToOps.find(VL[0])->second.front())
10227                  << "Vectorized horizontal reduction with cost "
10228                  << ore::NV("Cost", Cost) << " and with tree size "
10229                  << ore::NV("TreeSize", V.getTreeSize());
10230         });
10231 
10232         Builder.setFastMathFlags(RdxFMF);
10233 
10234         // Vectorize a tree.
10235         Value *VectorizedRoot = V.vectorizeTree(LocalExternallyUsedValues);
10236 
10237         // Emit a reduction. If the root is a select (min/max idiom), the insert
10238         // point is the compare condition of that select.
10239         Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
10240         if (IsCmpSelMinMax)
10241           Builder.SetInsertPoint(GetCmpForMinMaxReduction(RdxRootInst));
10242         else
10243           Builder.SetInsertPoint(RdxRootInst);
10244 
10245         // To prevent poison from leaking across what used to be sequential,
10246         // safe, scalar boolean logic operations, the reduction operand must be
10247         // frozen.
10248         if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst))
10249           VectorizedRoot = Builder.CreateFreeze(VectorizedRoot);
10250 
10251         Value *ReducedSubTree =
10252             emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
10253 
10254         if (!VectorizedTree) {
10255           // Initialize the final value in the reduction.
10256           VectorizedTree = ReducedSubTree;
10257         } else {
10258           // Update the final value in the reduction.
10259           Builder.SetCurrentDebugLocation(
10260               cast<Instruction>(ReductionOps.front().front())->getDebugLoc());
10261           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
10262                                     ReducedSubTree, "op.rdx", ReductionOps);
10263         }
10264         // Count vectorized reduced values to exclude them from final reduction.
10265         for (Value *V : VL)
10266           ++VectorizedVals.try_emplace(TrackedToOrig.find(V)->second, 0)
10267                 .first->getSecond();
10268         Pos += ReduxWidth;
10269         Start = Pos;
10270         ReduxWidth = PowerOf2Floor(NumReducedVals - Pos);
10271       }
10272     }
10273     if (VectorizedTree) {
10274       // Finish the reduction.
10275       // Need to add extra arguments and not vectorized possible reduction
10276       // values.
10277       SmallPtrSet<Value *, 8> Visited;
10278       for (unsigned I = 0, E = ReducedVals.size(); I < E; ++I) {
10279         ArrayRef<Value *> Candidates = ReducedVals[I];
10280         for (Value *RdxVal : Candidates) {
10281           if (!Visited.insert(RdxVal).second)
10282             continue;
10283           Value *StableRdxVal = RdxVal;
10284           auto TVIt = TrackedVals.find(RdxVal);
10285           if (TVIt != TrackedVals.end())
10286             StableRdxVal = TVIt->second;
10287           unsigned NumOps = 0;
10288           auto It = VectorizedVals.find(RdxVal);
10289           if (It != VectorizedVals.end())
10290             NumOps = It->second;
10291           for (Instruction *RedOp :
10292                makeArrayRef(ReducedValsToOps.find(RdxVal)->second)
10293                    .drop_back(NumOps)) {
10294             Builder.SetCurrentDebugLocation(RedOp->getDebugLoc());
10295             ReductionOpsListType Ops;
10296             if (auto *Sel = dyn_cast<SelectInst>(RedOp))
10297               Ops.emplace_back().push_back(Sel->getCondition());
10298             Ops.emplace_back().push_back(RedOp);
10299             VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
10300                                       StableRdxVal, "op.rdx", Ops);
10301           }
10302         }
10303       }
10304       for (auto &Pair : ExternallyUsedValues) {
10305         // Add each externally used value to the final reduction.
10306         for (auto *I : Pair.second) {
10307           Builder.SetCurrentDebugLocation(I->getDebugLoc());
10308           ReductionOpsListType Ops;
10309           if (auto *Sel = dyn_cast<SelectInst>(I))
10310             Ops.emplace_back().push_back(Sel->getCondition());
10311           Ops.emplace_back().push_back(I);
10312           Value *StableRdxVal = Pair.first;
10313           auto TVIt = TrackedVals.find(Pair.first);
10314           if (TVIt != TrackedVals.end())
10315             StableRdxVal = TVIt->second;
10316           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
10317                                     StableRdxVal, "op.rdx", Ops);
10318         }
10319       }
10320 
10321       ReductionRoot->replaceAllUsesWith(VectorizedTree);
10322 
10323       // The original scalar reduction is expected to have no remaining
10324       // uses outside the reduction tree itself.  Assert that we got this
10325       // correct, replace internal uses with undef, and mark for eventual
10326       // deletion.
10327 #ifndef NDEBUG
10328       SmallSet<Value *, 4> IgnoreSet;
10329       for (ArrayRef<Value *> RdxOps : ReductionOps)
10330         IgnoreSet.insert(RdxOps.begin(), RdxOps.end());
10331 #endif
10332       for (ArrayRef<Value *> RdxOps : ReductionOps) {
10333         for (Value *Ignore : RdxOps) {
10334           if (!Ignore)
10335             continue;
10336 #ifndef NDEBUG
10337           for (auto *U : Ignore->users()) {
10338             assert(IgnoreSet.count(U) &&
10339                    "All users must be either in the reduction ops list.");
10340           }
10341 #endif
10342           if (!Ignore->use_empty()) {
10343             Value *Undef = UndefValue::get(Ignore->getType());
10344             Ignore->replaceAllUsesWith(Undef);
10345           }
10346           V.eraseInstruction(cast<Instruction>(Ignore));
10347         }
10348       }
10349     } else if (!CheckForReusedReductionOps) {
10350       for (ReductionOpsType &RdxOps : ReductionOps)
10351         for (Value *RdxOp : RdxOps)
10352           V.analyzedReductionRoot(cast<Instruction>(RdxOp));
10353     }
10354     return VectorizedTree;
10355   }
10356 
10357   unsigned numReductionValues() const { return ReducedVals.size(); }
10358 
10359 private:
10360   /// Calculate the cost of a reduction.
10361   InstructionCost getReductionCost(TargetTransformInfo *TTI,
10362                                    Value *FirstReducedVal, unsigned ReduxWidth,
10363                                    FastMathFlags FMF) {
10364     TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
10365     Type *ScalarTy = FirstReducedVal->getType();
10366     FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth);
10367     InstructionCost VectorCost, ScalarCost;
10368     switch (RdxKind) {
10369     case RecurKind::Add:
10370     case RecurKind::Mul:
10371     case RecurKind::Or:
10372     case RecurKind::And:
10373     case RecurKind::Xor:
10374     case RecurKind::FAdd:
10375     case RecurKind::FMul: {
10376       unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind);
10377       VectorCost =
10378           TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind);
10379       ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind);
10380       break;
10381     }
10382     case RecurKind::FMax:
10383     case RecurKind::FMin: {
10384       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
10385       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
10386       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
10387                                                /*IsUnsigned=*/false, CostKind);
10388       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
10389       ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy,
10390                                            SclCondTy, RdxPred, CostKind) +
10391                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
10392                                            SclCondTy, RdxPred, CostKind);
10393       break;
10394     }
10395     case RecurKind::SMax:
10396     case RecurKind::SMin:
10397     case RecurKind::UMax:
10398     case RecurKind::UMin: {
10399       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
10400       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
10401       bool IsUnsigned =
10402           RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin;
10403       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, IsUnsigned,
10404                                                CostKind);
10405       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
10406       ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
10407                                            SclCondTy, RdxPred, CostKind) +
10408                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
10409                                            SclCondTy, RdxPred, CostKind);
10410       break;
10411     }
10412     default:
10413       llvm_unreachable("Expected arithmetic or min/max reduction operation");
10414     }
10415 
10416     // Scalar cost is repeated for N-1 elements.
10417     ScalarCost *= (ReduxWidth - 1);
10418     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost
10419                       << " for reduction that starts with " << *FirstReducedVal
10420                       << " (It is a splitting reduction)\n");
10421     return VectorCost - ScalarCost;
10422   }
10423 
10424   /// Emit a horizontal reduction of the vectorized value.
10425   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
10426                        unsigned ReduxWidth, const TargetTransformInfo *TTI) {
10427     assert(VectorizedValue && "Need to have a vectorized tree node");
10428     assert(isPowerOf2_32(ReduxWidth) &&
10429            "We only handle power-of-two reductions for now");
10430     assert(RdxKind != RecurKind::FMulAdd &&
10431            "A call to the llvm.fmuladd intrinsic is not handled yet");
10432 
10433     ++NumVectorInstructions;
10434     return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind);
10435   }
10436 };
10437 
10438 } // end anonymous namespace
10439 
10440 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) {
10441   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
10442     return cast<FixedVectorType>(IE->getType())->getNumElements();
10443 
10444   unsigned AggregateSize = 1;
10445   auto *IV = cast<InsertValueInst>(InsertInst);
10446   Type *CurrentType = IV->getType();
10447   do {
10448     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
10449       for (auto *Elt : ST->elements())
10450         if (Elt != ST->getElementType(0)) // check homogeneity
10451           return None;
10452       AggregateSize *= ST->getNumElements();
10453       CurrentType = ST->getElementType(0);
10454     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
10455       AggregateSize *= AT->getNumElements();
10456       CurrentType = AT->getElementType();
10457     } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
10458       AggregateSize *= VT->getNumElements();
10459       return AggregateSize;
10460     } else if (CurrentType->isSingleValueType()) {
10461       return AggregateSize;
10462     } else {
10463       return None;
10464     }
10465   } while (true);
10466 }
10467 
10468 static void findBuildAggregate_rec(Instruction *LastInsertInst,
10469                                    TargetTransformInfo *TTI,
10470                                    SmallVectorImpl<Value *> &BuildVectorOpds,
10471                                    SmallVectorImpl<Value *> &InsertElts,
10472                                    unsigned OperandOffset) {
10473   do {
10474     Value *InsertedOperand = LastInsertInst->getOperand(1);
10475     Optional<unsigned> OperandIndex =
10476         getInsertIndex(LastInsertInst, OperandOffset);
10477     if (!OperandIndex)
10478       return;
10479     if (isa<InsertElementInst>(InsertedOperand) ||
10480         isa<InsertValueInst>(InsertedOperand)) {
10481       findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI,
10482                              BuildVectorOpds, InsertElts, *OperandIndex);
10483 
10484     } else {
10485       BuildVectorOpds[*OperandIndex] = InsertedOperand;
10486       InsertElts[*OperandIndex] = LastInsertInst;
10487     }
10488     LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0));
10489   } while (LastInsertInst != nullptr &&
10490            (isa<InsertValueInst>(LastInsertInst) ||
10491             isa<InsertElementInst>(LastInsertInst)) &&
10492            LastInsertInst->hasOneUse());
10493 }
10494 
10495 /// Recognize construction of vectors like
10496 ///  %ra = insertelement <4 x float> poison, float %s0, i32 0
10497 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
10498 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
10499 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
10500 ///  starting from the last insertelement or insertvalue instruction.
10501 ///
10502 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>},
10503 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
10504 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
10505 ///
10506 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
10507 ///
10508 /// \return true if it matches.
10509 static bool findBuildAggregate(Instruction *LastInsertInst,
10510                                TargetTransformInfo *TTI,
10511                                SmallVectorImpl<Value *> &BuildVectorOpds,
10512                                SmallVectorImpl<Value *> &InsertElts) {
10513 
10514   assert((isa<InsertElementInst>(LastInsertInst) ||
10515           isa<InsertValueInst>(LastInsertInst)) &&
10516          "Expected insertelement or insertvalue instruction!");
10517 
10518   assert((BuildVectorOpds.empty() && InsertElts.empty()) &&
10519          "Expected empty result vectors!");
10520 
10521   Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst);
10522   if (!AggregateSize)
10523     return false;
10524   BuildVectorOpds.resize(*AggregateSize);
10525   InsertElts.resize(*AggregateSize);
10526 
10527   findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts, 0);
10528   llvm::erase_value(BuildVectorOpds, nullptr);
10529   llvm::erase_value(InsertElts, nullptr);
10530   if (BuildVectorOpds.size() >= 2)
10531     return true;
10532 
10533   return false;
10534 }
10535 
10536 /// Try and get a reduction value from a phi node.
10537 ///
10538 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
10539 /// if they come from either \p ParentBB or a containing loop latch.
10540 ///
10541 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
10542 /// if not possible.
10543 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
10544                                 BasicBlock *ParentBB, LoopInfo *LI) {
10545   // There are situations where the reduction value is not dominated by the
10546   // reduction phi. Vectorizing such cases has been reported to cause
10547   // miscompiles. See PR25787.
10548   auto DominatedReduxValue = [&](Value *R) {
10549     return isa<Instruction>(R) &&
10550            DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
10551   };
10552 
10553   Value *Rdx = nullptr;
10554 
10555   // Return the incoming value if it comes from the same BB as the phi node.
10556   if (P->getIncomingBlock(0) == ParentBB) {
10557     Rdx = P->getIncomingValue(0);
10558   } else if (P->getIncomingBlock(1) == ParentBB) {
10559     Rdx = P->getIncomingValue(1);
10560   }
10561 
10562   if (Rdx && DominatedReduxValue(Rdx))
10563     return Rdx;
10564 
10565   // Otherwise, check whether we have a loop latch to look at.
10566   Loop *BBL = LI->getLoopFor(ParentBB);
10567   if (!BBL)
10568     return nullptr;
10569   BasicBlock *BBLatch = BBL->getLoopLatch();
10570   if (!BBLatch)
10571     return nullptr;
10572 
10573   // There is a loop latch, return the incoming value if it comes from
10574   // that. This reduction pattern occasionally turns up.
10575   if (P->getIncomingBlock(0) == BBLatch) {
10576     Rdx = P->getIncomingValue(0);
10577   } else if (P->getIncomingBlock(1) == BBLatch) {
10578     Rdx = P->getIncomingValue(1);
10579   }
10580 
10581   if (Rdx && DominatedReduxValue(Rdx))
10582     return Rdx;
10583 
10584   return nullptr;
10585 }
10586 
10587 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) {
10588   if (match(I, m_BinOp(m_Value(V0), m_Value(V1))))
10589     return true;
10590   if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1))))
10591     return true;
10592   if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1))))
10593     return true;
10594   if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1))))
10595     return true;
10596   if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1))))
10597     return true;
10598   if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1))))
10599     return true;
10600   if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1))))
10601     return true;
10602   return false;
10603 }
10604 
10605 /// Attempt to reduce a horizontal reduction.
10606 /// If it is legal to match a horizontal reduction feeding the phi node \a P
10607 /// with reduction operators \a Root (or one of its operands) in a basic block
10608 /// \a BB, then check if it can be done. If horizontal reduction is not found
10609 /// and root instruction is a binary operation, vectorization of the operands is
10610 /// attempted.
10611 /// \returns true if a horizontal reduction was matched and reduced or operands
10612 /// of one of the binary instruction were vectorized.
10613 /// \returns false if a horizontal reduction was not matched (or not possible)
10614 /// or no vectorization of any binary operation feeding \a Root instruction was
10615 /// performed.
10616 static bool tryToVectorizeHorReductionOrInstOperands(
10617     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
10618     TargetTransformInfo *TTI, ScalarEvolution &SE, const DataLayout &DL,
10619     const TargetLibraryInfo &TLI,
10620     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
10621   if (!ShouldVectorizeHor)
10622     return false;
10623 
10624   if (!Root)
10625     return false;
10626 
10627   if (Root->getParent() != BB || isa<PHINode>(Root))
10628     return false;
10629   // Start analysis starting from Root instruction. If horizontal reduction is
10630   // found, try to vectorize it. If it is not a horizontal reduction or
10631   // vectorization is not possible or not effective, and currently analyzed
10632   // instruction is a binary operation, try to vectorize the operands, using
10633   // pre-order DFS traversal order. If the operands were not vectorized, repeat
10634   // the same procedure considering each operand as a possible root of the
10635   // horizontal reduction.
10636   // Interrupt the process if the Root instruction itself was vectorized or all
10637   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
10638   // Skip the analysis of CmpInsts. Compiler implements postanalysis of the
10639   // CmpInsts so we can skip extra attempts in
10640   // tryToVectorizeHorReductionOrInstOperands and save compile time.
10641   std::queue<std::pair<Instruction *, unsigned>> Stack;
10642   Stack.emplace(Root, 0);
10643   SmallPtrSet<Value *, 8> VisitedInstrs;
10644   SmallVector<WeakTrackingVH> PostponedInsts;
10645   bool Res = false;
10646   auto &&TryToReduce = [TTI, &SE, &DL, &P, &R, &TLI](Instruction *Inst,
10647                                                      Value *&B0,
10648                                                      Value *&B1) -> Value * {
10649     if (R.isAnalizedReductionRoot(Inst))
10650       return nullptr;
10651     bool IsBinop = matchRdxBop(Inst, B0, B1);
10652     bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value()));
10653     if (IsBinop || IsSelect) {
10654       HorizontalReduction HorRdx;
10655       if (HorRdx.matchAssociativeReduction(P, Inst, SE, DL, TLI))
10656         return HorRdx.tryToReduce(R, TTI);
10657     }
10658     return nullptr;
10659   };
10660   while (!Stack.empty()) {
10661     Instruction *Inst;
10662     unsigned Level;
10663     std::tie(Inst, Level) = Stack.front();
10664     Stack.pop();
10665     // Do not try to analyze instruction that has already been vectorized.
10666     // This may happen when we vectorize instruction operands on a previous
10667     // iteration while stack was populated before that happened.
10668     if (R.isDeleted(Inst))
10669       continue;
10670     Value *B0 = nullptr, *B1 = nullptr;
10671     if (Value *V = TryToReduce(Inst, B0, B1)) {
10672       Res = true;
10673       // Set P to nullptr to avoid re-analysis of phi node in
10674       // matchAssociativeReduction function unless this is the root node.
10675       P = nullptr;
10676       if (auto *I = dyn_cast<Instruction>(V)) {
10677         // Try to find another reduction.
10678         Stack.emplace(I, Level);
10679         continue;
10680       }
10681     } else {
10682       bool IsBinop = B0 && B1;
10683       if (P && IsBinop) {
10684         Inst = dyn_cast<Instruction>(B0);
10685         if (Inst == P)
10686           Inst = dyn_cast<Instruction>(B1);
10687         if (!Inst) {
10688           // Set P to nullptr to avoid re-analysis of phi node in
10689           // matchAssociativeReduction function unless this is the root node.
10690           P = nullptr;
10691           continue;
10692         }
10693       }
10694       // Set P to nullptr to avoid re-analysis of phi node in
10695       // matchAssociativeReduction function unless this is the root node.
10696       P = nullptr;
10697       // Do not try to vectorize CmpInst operands, this is done separately.
10698       // Final attempt for binop args vectorization should happen after the loop
10699       // to try to find reductions.
10700       if (!isa<CmpInst, InsertElementInst, InsertValueInst>(Inst))
10701         PostponedInsts.push_back(Inst);
10702     }
10703 
10704     // Try to vectorize operands.
10705     // Continue analysis for the instruction from the same basic block only to
10706     // save compile time.
10707     if (++Level < RecursionMaxDepth)
10708       for (auto *Op : Inst->operand_values())
10709         if (VisitedInstrs.insert(Op).second)
10710           if (auto *I = dyn_cast<Instruction>(Op))
10711             // Do not try to vectorize CmpInst operands,  this is done
10712             // separately.
10713             if (!isa<PHINode, CmpInst, InsertElementInst, InsertValueInst>(I) &&
10714                 !R.isDeleted(I) && I->getParent() == BB)
10715               Stack.emplace(I, Level);
10716   }
10717   // Try to vectorized binops where reductions were not found.
10718   for (Value *V : PostponedInsts)
10719     if (auto *Inst = dyn_cast<Instruction>(V))
10720       if (!R.isDeleted(Inst))
10721         Res |= Vectorize(Inst, R);
10722   return Res;
10723 }
10724 
10725 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
10726                                                  BasicBlock *BB, BoUpSLP &R,
10727                                                  TargetTransformInfo *TTI) {
10728   auto *I = dyn_cast_or_null<Instruction>(V);
10729   if (!I)
10730     return false;
10731 
10732   if (!isa<BinaryOperator>(I))
10733     P = nullptr;
10734   // Try to match and vectorize a horizontal reduction.
10735   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
10736     return tryToVectorize(I, R);
10737   };
10738   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI, *SE, *DL,
10739                                                   *TLI, ExtraVectorization);
10740 }
10741 
10742 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
10743                                                  BasicBlock *BB, BoUpSLP &R) {
10744   const DataLayout &DL = BB->getModule()->getDataLayout();
10745   if (!R.canMapToVector(IVI->getType(), DL))
10746     return false;
10747 
10748   SmallVector<Value *, 16> BuildVectorOpds;
10749   SmallVector<Value *, 16> BuildVectorInsts;
10750   if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts))
10751     return false;
10752 
10753   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
10754   // Aggregate value is unlikely to be processed in vector register.
10755   return tryToVectorizeList(BuildVectorOpds, R);
10756 }
10757 
10758 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
10759                                                    BasicBlock *BB, BoUpSLP &R) {
10760   SmallVector<Value *, 16> BuildVectorInsts;
10761   SmallVector<Value *, 16> BuildVectorOpds;
10762   SmallVector<int> Mask;
10763   if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
10764       (llvm::all_of(
10765            BuildVectorOpds,
10766            [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) &&
10767        isFixedVectorShuffle(BuildVectorOpds, Mask)))
10768     return false;
10769 
10770   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n");
10771   return tryToVectorizeList(BuildVectorInsts, R);
10772 }
10773 
10774 template <typename T>
10775 static bool
10776 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming,
10777                        function_ref<unsigned(T *)> Limit,
10778                        function_ref<bool(T *, T *)> Comparator,
10779                        function_ref<bool(T *, T *)> AreCompatible,
10780                        function_ref<bool(ArrayRef<T *>, bool)> TryToVectorizeHelper,
10781                        bool LimitForRegisterSize) {
10782   bool Changed = false;
10783   // Sort by type, parent, operands.
10784   stable_sort(Incoming, Comparator);
10785 
10786   // Try to vectorize elements base on their type.
10787   SmallVector<T *> Candidates;
10788   for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) {
10789     // Look for the next elements with the same type, parent and operand
10790     // kinds.
10791     auto *SameTypeIt = IncIt;
10792     while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt))
10793       ++SameTypeIt;
10794 
10795     // Try to vectorize them.
10796     unsigned NumElts = (SameTypeIt - IncIt);
10797     LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes ("
10798                       << NumElts << ")\n");
10799     // The vectorization is a 3-state attempt:
10800     // 1. Try to vectorize instructions with the same/alternate opcodes with the
10801     // size of maximal register at first.
10802     // 2. Try to vectorize remaining instructions with the same type, if
10803     // possible. This may result in the better vectorization results rather than
10804     // if we try just to vectorize instructions with the same/alternate opcodes.
10805     // 3. Final attempt to try to vectorize all instructions with the
10806     // same/alternate ops only, this may result in some extra final
10807     // vectorization.
10808     if (NumElts > 1 &&
10809         TryToVectorizeHelper(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) {
10810       // Success start over because instructions might have been changed.
10811       Changed = true;
10812     } else if (NumElts < Limit(*IncIt) &&
10813                (Candidates.empty() ||
10814                 Candidates.front()->getType() == (*IncIt)->getType())) {
10815       Candidates.append(IncIt, std::next(IncIt, NumElts));
10816     }
10817     // Final attempt to vectorize instructions with the same types.
10818     if (Candidates.size() > 1 &&
10819         (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) {
10820       if (TryToVectorizeHelper(Candidates, /*LimitForRegisterSize=*/false)) {
10821         // Success start over because instructions might have been changed.
10822         Changed = true;
10823       } else if (LimitForRegisterSize) {
10824         // Try to vectorize using small vectors.
10825         for (auto *It = Candidates.begin(), *End = Candidates.end();
10826              It != End;) {
10827           auto *SameTypeIt = It;
10828           while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It))
10829             ++SameTypeIt;
10830           unsigned NumElts = (SameTypeIt - It);
10831           if (NumElts > 1 && TryToVectorizeHelper(makeArrayRef(It, NumElts),
10832                                             /*LimitForRegisterSize=*/false))
10833             Changed = true;
10834           It = SameTypeIt;
10835         }
10836       }
10837       Candidates.clear();
10838     }
10839 
10840     // Start over at the next instruction of a different type (or the end).
10841     IncIt = SameTypeIt;
10842   }
10843   return Changed;
10844 }
10845 
10846 /// Compare two cmp instructions. If IsCompatibility is true, function returns
10847 /// true if 2 cmps have same/swapped predicates and mos compatible corresponding
10848 /// operands. If IsCompatibility is false, function implements strict weak
10849 /// ordering relation between two cmp instructions, returning true if the first
10850 /// instruction is "less" than the second, i.e. its predicate is less than the
10851 /// predicate of the second or the operands IDs are less than the operands IDs
10852 /// of the second cmp instruction.
10853 template <bool IsCompatibility>
10854 static bool compareCmp(Value *V, Value *V2,
10855                        function_ref<bool(Instruction *)> IsDeleted) {
10856   auto *CI1 = cast<CmpInst>(V);
10857   auto *CI2 = cast<CmpInst>(V2);
10858   if (IsDeleted(CI2) || !isValidElementType(CI2->getType()))
10859     return false;
10860   if (CI1->getOperand(0)->getType()->getTypeID() <
10861       CI2->getOperand(0)->getType()->getTypeID())
10862     return !IsCompatibility;
10863   if (CI1->getOperand(0)->getType()->getTypeID() >
10864       CI2->getOperand(0)->getType()->getTypeID())
10865     return false;
10866   CmpInst::Predicate Pred1 = CI1->getPredicate();
10867   CmpInst::Predicate Pred2 = CI2->getPredicate();
10868   CmpInst::Predicate SwapPred1 = CmpInst::getSwappedPredicate(Pred1);
10869   CmpInst::Predicate SwapPred2 = CmpInst::getSwappedPredicate(Pred2);
10870   CmpInst::Predicate BasePred1 = std::min(Pred1, SwapPred1);
10871   CmpInst::Predicate BasePred2 = std::min(Pred2, SwapPred2);
10872   if (BasePred1 < BasePred2)
10873     return !IsCompatibility;
10874   if (BasePred1 > BasePred2)
10875     return false;
10876   // Compare operands.
10877   bool LEPreds = Pred1 <= Pred2;
10878   bool GEPreds = Pred1 >= Pred2;
10879   for (int I = 0, E = CI1->getNumOperands(); I < E; ++I) {
10880     auto *Op1 = CI1->getOperand(LEPreds ? I : E - I - 1);
10881     auto *Op2 = CI2->getOperand(GEPreds ? I : E - I - 1);
10882     if (Op1->getValueID() < Op2->getValueID())
10883       return !IsCompatibility;
10884     if (Op1->getValueID() > Op2->getValueID())
10885       return false;
10886     if (auto *I1 = dyn_cast<Instruction>(Op1))
10887       if (auto *I2 = dyn_cast<Instruction>(Op2)) {
10888         if (I1->getParent() != I2->getParent())
10889           return false;
10890         InstructionsState S = getSameOpcode({I1, I2});
10891         if (S.getOpcode())
10892           continue;
10893         return false;
10894       }
10895   }
10896   return IsCompatibility;
10897 }
10898 
10899 bool SLPVectorizerPass::vectorizeSimpleInstructions(
10900     SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R,
10901     bool AtTerminator) {
10902   bool OpsChanged = false;
10903   SmallVector<Instruction *, 4> PostponedCmps;
10904   for (auto *I : reverse(Instructions)) {
10905     if (R.isDeleted(I))
10906       continue;
10907     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I)) {
10908       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
10909     } else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I)) {
10910       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
10911     } else if (isa<CmpInst>(I)) {
10912       PostponedCmps.push_back(I);
10913       continue;
10914     }
10915     // Try to find reductions in buildvector sequnces.
10916     OpsChanged |= vectorizeRootInstruction(nullptr, I, BB, R, TTI);
10917   }
10918   if (AtTerminator) {
10919     // Try to find reductions first.
10920     for (Instruction *I : PostponedCmps) {
10921       if (R.isDeleted(I))
10922         continue;
10923       for (Value *Op : I->operands())
10924         OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI);
10925     }
10926     // Try to vectorize operands as vector bundles.
10927     for (Instruction *I : PostponedCmps) {
10928       if (R.isDeleted(I))
10929         continue;
10930       OpsChanged |= tryToVectorize(I, R);
10931     }
10932     // Try to vectorize list of compares.
10933     // Sort by type, compare predicate, etc.
10934     auto &&CompareSorter = [&R](Value *V, Value *V2) {
10935       return compareCmp<false>(V, V2,
10936                                [&R](Instruction *I) { return R.isDeleted(I); });
10937     };
10938 
10939     auto &&AreCompatibleCompares = [&R](Value *V1, Value *V2) {
10940       if (V1 == V2)
10941         return true;
10942       return compareCmp<true>(V1, V2,
10943                               [&R](Instruction *I) { return R.isDeleted(I); });
10944     };
10945     auto Limit = [&R](Value *V) {
10946       unsigned EltSize = R.getVectorElementSize(V);
10947       return std::max(2U, R.getMaxVecRegSize() / EltSize);
10948     };
10949 
10950     SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end());
10951     OpsChanged |= tryToVectorizeSequence<Value>(
10952         Vals, Limit, CompareSorter, AreCompatibleCompares,
10953         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10954           // Exclude possible reductions from other blocks.
10955           bool ArePossiblyReducedInOtherBlock =
10956               any_of(Candidates, [](Value *V) {
10957                 return any_of(V->users(), [V](User *U) {
10958                   return isa<SelectInst>(U) &&
10959                          cast<SelectInst>(U)->getParent() !=
10960                              cast<Instruction>(V)->getParent();
10961                 });
10962               });
10963           if (ArePossiblyReducedInOtherBlock)
10964             return false;
10965           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10966         },
10967         /*LimitForRegisterSize=*/true);
10968     Instructions.clear();
10969   } else {
10970     // Insert in reverse order since the PostponedCmps vector was filled in
10971     // reverse order.
10972     Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend());
10973   }
10974   return OpsChanged;
10975 }
10976 
10977 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
10978   bool Changed = false;
10979   SmallVector<Value *, 4> Incoming;
10980   SmallPtrSet<Value *, 16> VisitedInstrs;
10981   // Maps phi nodes to the non-phi nodes found in the use tree for each phi
10982   // node. Allows better to identify the chains that can be vectorized in the
10983   // better way.
10984   DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes;
10985   auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) {
10986     assert(isValidElementType(V1->getType()) &&
10987            isValidElementType(V2->getType()) &&
10988            "Expected vectorizable types only.");
10989     // It is fine to compare type IDs here, since we expect only vectorizable
10990     // types, like ints, floats and pointers, we don't care about other type.
10991     if (V1->getType()->getTypeID() < V2->getType()->getTypeID())
10992       return true;
10993     if (V1->getType()->getTypeID() > V2->getType()->getTypeID())
10994       return false;
10995     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10996     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10997     if (Opcodes1.size() < Opcodes2.size())
10998       return true;
10999     if (Opcodes1.size() > Opcodes2.size())
11000       return false;
11001     Optional<bool> ConstOrder;
11002     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
11003       // Undefs are compatible with any other value.
11004       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) {
11005         if (!ConstOrder)
11006           ConstOrder =
11007               !isa<UndefValue>(Opcodes1[I]) && isa<UndefValue>(Opcodes2[I]);
11008         continue;
11009       }
11010       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
11011         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
11012           DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent());
11013           DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent());
11014           if (!NodeI1)
11015             return NodeI2 != nullptr;
11016           if (!NodeI2)
11017             return false;
11018           assert((NodeI1 == NodeI2) ==
11019                      (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
11020                  "Different nodes should have different DFS numbers");
11021           if (NodeI1 != NodeI2)
11022             return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
11023           InstructionsState S = getSameOpcode({I1, I2});
11024           if (S.getOpcode())
11025             continue;
11026           return I1->getOpcode() < I2->getOpcode();
11027         }
11028       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) {
11029         if (!ConstOrder)
11030           ConstOrder = Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID();
11031         continue;
11032       }
11033       if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID())
11034         return true;
11035       if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID())
11036         return false;
11037     }
11038     return ConstOrder && *ConstOrder;
11039   };
11040   auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) {
11041     if (V1 == V2)
11042       return true;
11043     if (V1->getType() != V2->getType())
11044       return false;
11045     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
11046     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
11047     if (Opcodes1.size() != Opcodes2.size())
11048       return false;
11049     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
11050       // Undefs are compatible with any other value.
11051       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
11052         continue;
11053       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
11054         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
11055           if (I1->getParent() != I2->getParent())
11056             return false;
11057           InstructionsState S = getSameOpcode({I1, I2});
11058           if (S.getOpcode())
11059             continue;
11060           return false;
11061         }
11062       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
11063         continue;
11064       if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID())
11065         return false;
11066     }
11067     return true;
11068   };
11069   auto Limit = [&R](Value *V) {
11070     unsigned EltSize = R.getVectorElementSize(V);
11071     return std::max(2U, R.getMaxVecRegSize() / EltSize);
11072   };
11073 
11074   bool HaveVectorizedPhiNodes = false;
11075   do {
11076     // Collect the incoming values from the PHIs.
11077     Incoming.clear();
11078     for (Instruction &I : *BB) {
11079       PHINode *P = dyn_cast<PHINode>(&I);
11080       if (!P)
11081         break;
11082 
11083       // No need to analyze deleted, vectorized and non-vectorizable
11084       // instructions.
11085       if (!VisitedInstrs.count(P) && !R.isDeleted(P) &&
11086           isValidElementType(P->getType()))
11087         Incoming.push_back(P);
11088     }
11089 
11090     // Find the corresponding non-phi nodes for better matching when trying to
11091     // build the tree.
11092     for (Value *V : Incoming) {
11093       SmallVectorImpl<Value *> &Opcodes =
11094           PHIToOpcodes.try_emplace(V).first->getSecond();
11095       if (!Opcodes.empty())
11096         continue;
11097       SmallVector<Value *, 4> Nodes(1, V);
11098       SmallPtrSet<Value *, 4> Visited;
11099       while (!Nodes.empty()) {
11100         auto *PHI = cast<PHINode>(Nodes.pop_back_val());
11101         if (!Visited.insert(PHI).second)
11102           continue;
11103         for (Value *V : PHI->incoming_values()) {
11104           if (auto *PHI1 = dyn_cast<PHINode>((V))) {
11105             Nodes.push_back(PHI1);
11106             continue;
11107           }
11108           Opcodes.emplace_back(V);
11109         }
11110       }
11111     }
11112 
11113     HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>(
11114         Incoming, Limit, PHICompare, AreCompatiblePHIs,
11115         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
11116           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
11117         },
11118         /*LimitForRegisterSize=*/true);
11119     Changed |= HaveVectorizedPhiNodes;
11120     VisitedInstrs.insert(Incoming.begin(), Incoming.end());
11121   } while (HaveVectorizedPhiNodes);
11122 
11123   VisitedInstrs.clear();
11124 
11125   SmallVector<Instruction *, 8> PostProcessInstructions;
11126   SmallDenseSet<Instruction *, 4> KeyNodes;
11127   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
11128     // Skip instructions with scalable type. The num of elements is unknown at
11129     // compile-time for scalable type.
11130     if (isa<ScalableVectorType>(it->getType()))
11131       continue;
11132 
11133     // Skip instructions marked for the deletion.
11134     if (R.isDeleted(&*it))
11135       continue;
11136     // We may go through BB multiple times so skip the one we have checked.
11137     if (!VisitedInstrs.insert(&*it).second) {
11138       if (it->use_empty() && KeyNodes.contains(&*it) &&
11139           vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
11140                                       it->isTerminator())) {
11141         // We would like to start over since some instructions are deleted
11142         // and the iterator may become invalid value.
11143         Changed = true;
11144         it = BB->begin();
11145         e = BB->end();
11146       }
11147       continue;
11148     }
11149 
11150     if (isa<DbgInfoIntrinsic>(it))
11151       continue;
11152 
11153     // Try to vectorize reductions that use PHINodes.
11154     if (PHINode *P = dyn_cast<PHINode>(it)) {
11155       // Check that the PHI is a reduction PHI.
11156       if (P->getNumIncomingValues() == 2) {
11157         // Try to match and vectorize a horizontal reduction.
11158         if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
11159                                      TTI)) {
11160           Changed = true;
11161           it = BB->begin();
11162           e = BB->end();
11163           continue;
11164         }
11165       }
11166       // Try to vectorize the incoming values of the PHI, to catch reductions
11167       // that feed into PHIs.
11168       for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) {
11169         // Skip if the incoming block is the current BB for now. Also, bypass
11170         // unreachable IR for efficiency and to avoid crashing.
11171         // TODO: Collect the skipped incoming values and try to vectorize them
11172         // after processing BB.
11173         if (BB == P->getIncomingBlock(I) ||
11174             !DT->isReachableFromEntry(P->getIncomingBlock(I)))
11175           continue;
11176 
11177         Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I),
11178                                             P->getIncomingBlock(I), R, TTI);
11179       }
11180       continue;
11181     }
11182 
11183     // Ran into an instruction without users, like terminator, or function call
11184     // with ignored return value, store. Ignore unused instructions (basing on
11185     // instruction type, except for CallInst and InvokeInst).
11186     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
11187                             isa<InvokeInst>(it))) {
11188       KeyNodes.insert(&*it);
11189       bool OpsChanged = false;
11190       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
11191         for (auto *V : it->operand_values()) {
11192           // Try to match and vectorize a horizontal reduction.
11193           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
11194         }
11195       }
11196       // Start vectorization of post-process list of instructions from the
11197       // top-tree instructions to try to vectorize as many instructions as
11198       // possible.
11199       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
11200                                                 it->isTerminator());
11201       if (OpsChanged) {
11202         // We would like to start over since some instructions are deleted
11203         // and the iterator may become invalid value.
11204         Changed = true;
11205         it = BB->begin();
11206         e = BB->end();
11207         continue;
11208       }
11209     }
11210 
11211     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
11212         isa<InsertValueInst>(it))
11213       PostProcessInstructions.push_back(&*it);
11214   }
11215 
11216   return Changed;
11217 }
11218 
11219 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
11220   auto Changed = false;
11221   for (auto &Entry : GEPs) {
11222     // If the getelementptr list has fewer than two elements, there's nothing
11223     // to do.
11224     if (Entry.second.size() < 2)
11225       continue;
11226 
11227     LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
11228                       << Entry.second.size() << ".\n");
11229 
11230     // Process the GEP list in chunks suitable for the target's supported
11231     // vector size. If a vector register can't hold 1 element, we are done. We
11232     // are trying to vectorize the index computations, so the maximum number of
11233     // elements is based on the size of the index expression, rather than the
11234     // size of the GEP itself (the target's pointer size).
11235     unsigned MaxVecRegSize = R.getMaxVecRegSize();
11236     unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin());
11237     if (MaxVecRegSize < EltSize)
11238       continue;
11239 
11240     unsigned MaxElts = MaxVecRegSize / EltSize;
11241     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
11242       auto Len = std::min<unsigned>(BE - BI, MaxElts);
11243       ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len);
11244 
11245       // Initialize a set a candidate getelementptrs. Note that we use a
11246       // SetVector here to preserve program order. If the index computations
11247       // are vectorizable and begin with loads, we want to minimize the chance
11248       // of having to reorder them later.
11249       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
11250 
11251       // Some of the candidates may have already been vectorized after we
11252       // initially collected them. If so, they are marked as deleted, so remove
11253       // them from the set of candidates.
11254       Candidates.remove_if(
11255           [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
11256 
11257       // Remove from the set of candidates all pairs of getelementptrs with
11258       // constant differences. Such getelementptrs are likely not good
11259       // candidates for vectorization in a bottom-up phase since one can be
11260       // computed from the other. We also ensure all candidate getelementptr
11261       // indices are unique.
11262       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
11263         auto *GEPI = GEPList[I];
11264         if (!Candidates.count(GEPI))
11265           continue;
11266         auto *SCEVI = SE->getSCEV(GEPList[I]);
11267         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
11268           auto *GEPJ = GEPList[J];
11269           auto *SCEVJ = SE->getSCEV(GEPList[J]);
11270           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
11271             Candidates.remove(GEPI);
11272             Candidates.remove(GEPJ);
11273           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
11274             Candidates.remove(GEPJ);
11275           }
11276         }
11277       }
11278 
11279       // We break out of the above computation as soon as we know there are
11280       // fewer than two candidates remaining.
11281       if (Candidates.size() < 2)
11282         continue;
11283 
11284       // Add the single, non-constant index of each candidate to the bundle. We
11285       // ensured the indices met these constraints when we originally collected
11286       // the getelementptrs.
11287       SmallVector<Value *, 16> Bundle(Candidates.size());
11288       auto BundleIndex = 0u;
11289       for (auto *V : Candidates) {
11290         auto *GEP = cast<GetElementPtrInst>(V);
11291         auto *GEPIdx = GEP->idx_begin()->get();
11292         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
11293         Bundle[BundleIndex++] = GEPIdx;
11294       }
11295 
11296       // Try and vectorize the indices. We are currently only interested in
11297       // gather-like cases of the form:
11298       //
11299       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
11300       //
11301       // where the loads of "a", the loads of "b", and the subtractions can be
11302       // performed in parallel. It's likely that detecting this pattern in a
11303       // bottom-up phase will be simpler and less costly than building a
11304       // full-blown top-down phase beginning at the consecutive loads.
11305       Changed |= tryToVectorizeList(Bundle, R);
11306     }
11307   }
11308   return Changed;
11309 }
11310 
11311 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
11312   bool Changed = false;
11313   // Sort by type, base pointers and values operand. Value operands must be
11314   // compatible (have the same opcode, same parent), otherwise it is
11315   // definitely not profitable to try to vectorize them.
11316   auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) {
11317     if (V->getPointerOperandType()->getTypeID() <
11318         V2->getPointerOperandType()->getTypeID())
11319       return true;
11320     if (V->getPointerOperandType()->getTypeID() >
11321         V2->getPointerOperandType()->getTypeID())
11322       return false;
11323     // UndefValues are compatible with all other values.
11324     if (isa<UndefValue>(V->getValueOperand()) ||
11325         isa<UndefValue>(V2->getValueOperand()))
11326       return false;
11327     if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand()))
11328       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
11329         DomTreeNodeBase<llvm::BasicBlock> *NodeI1 =
11330             DT->getNode(I1->getParent());
11331         DomTreeNodeBase<llvm::BasicBlock> *NodeI2 =
11332             DT->getNode(I2->getParent());
11333         assert(NodeI1 && "Should only process reachable instructions");
11334         assert(NodeI2 && "Should only process reachable instructions");
11335         assert((NodeI1 == NodeI2) ==
11336                    (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
11337                "Different nodes should have different DFS numbers");
11338         if (NodeI1 != NodeI2)
11339           return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
11340         InstructionsState S = getSameOpcode({I1, I2});
11341         if (S.getOpcode())
11342           return false;
11343         return I1->getOpcode() < I2->getOpcode();
11344       }
11345     if (isa<Constant>(V->getValueOperand()) &&
11346         isa<Constant>(V2->getValueOperand()))
11347       return false;
11348     return V->getValueOperand()->getValueID() <
11349            V2->getValueOperand()->getValueID();
11350   };
11351 
11352   auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) {
11353     if (V1 == V2)
11354       return true;
11355     if (V1->getPointerOperandType() != V2->getPointerOperandType())
11356       return false;
11357     // Undefs are compatible with any other value.
11358     if (isa<UndefValue>(V1->getValueOperand()) ||
11359         isa<UndefValue>(V2->getValueOperand()))
11360       return true;
11361     if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand()))
11362       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
11363         if (I1->getParent() != I2->getParent())
11364           return false;
11365         InstructionsState S = getSameOpcode({I1, I2});
11366         return S.getOpcode() > 0;
11367       }
11368     if (isa<Constant>(V1->getValueOperand()) &&
11369         isa<Constant>(V2->getValueOperand()))
11370       return true;
11371     return V1->getValueOperand()->getValueID() ==
11372            V2->getValueOperand()->getValueID();
11373   };
11374   auto Limit = [&R, this](StoreInst *SI) {
11375     unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
11376     return R.getMinVF(EltSize);
11377   };
11378 
11379   // Attempt to sort and vectorize each of the store-groups.
11380   for (auto &Pair : Stores) {
11381     if (Pair.second.size() < 2)
11382       continue;
11383 
11384     LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
11385                       << Pair.second.size() << ".\n");
11386 
11387     if (!isValidElementType(Pair.second.front()->getValueOperand()->getType()))
11388       continue;
11389 
11390     Changed |= tryToVectorizeSequence<StoreInst>(
11391         Pair.second, Limit, StoreSorter, AreCompatibleStores,
11392         [this, &R](ArrayRef<StoreInst *> Candidates, bool) {
11393           return vectorizeStores(Candidates, R);
11394         },
11395         /*LimitForRegisterSize=*/false);
11396   }
11397   return Changed;
11398 }
11399 
11400 char SLPVectorizer::ID = 0;
11401 
11402 static const char lv_name[] = "SLP Vectorizer";
11403 
11404 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
11405 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
11406 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
11407 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
11408 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
11409 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
11410 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
11411 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
11412 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
11413 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
11414 
11415 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
11416