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(const Value *InsertInst,
741                                          unsigned Offset = 0) {
742   int Index = Offset;
743   if (const auto *IE = dyn_cast<InsertElementInst>(InsertInst)) {
744     if (const 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   const auto *IV = cast<InsertValueInst>(InsertInst);
756   Type *CurrentType = IV->getType();
757   for (unsigned I : IV->indices()) {
758     if (const auto *ST = dyn_cast<StructType>(CurrentType)) {
759       Index *= ST->getNumElements();
760       CurrentType = ST->getElementType(I);
761     } else if (const 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                  const SmallDenseSet<Value *> &UserIgnoreLst);
899 
900   /// Construct a vectorizable tree that starts at \p Roots.
901   void buildTree(ArrayRef<Value *> Roots);
902 
903   /// Builds external uses of the vectorized scalars, i.e. the list of
904   /// vectorized scalars to be extracted, their lanes and their scalar users. \p
905   /// ExternallyUsedValues contains additional list of external uses to handle
906   /// vectorization of reductions.
907   void
908   buildExternalUses(const ExtraValueToDebugLocsMap &ExternallyUsedValues = {});
909 
910   /// Clear the internal data structures that are created by 'buildTree'.
911   void deleteTree() {
912     VectorizableTree.clear();
913     ScalarToTreeEntry.clear();
914     MustGather.clear();
915     ExternalUses.clear();
916     for (auto &Iter : BlocksSchedules) {
917       BlockScheduling *BS = Iter.second.get();
918       BS->clear();
919     }
920     MinBWs.clear();
921     InstrElementSize.clear();
922     UserIgnoreList = nullptr;
923   }
924 
925   unsigned getTreeSize() const { return VectorizableTree.size(); }
926 
927   /// Perform LICM and CSE on the newly generated gather sequences.
928   void optimizeGatherSequence();
929 
930   /// Checks if the specified gather tree entry \p TE can be represented as a
931   /// shuffled vector entry + (possibly) permutation with other gathers. It
932   /// implements the checks only for possibly ordered scalars (Loads,
933   /// ExtractElement, ExtractValue), which can be part of the graph.
934   Optional<OrdersType> findReusedOrderedScalars(const TreeEntry &TE);
935 
936   /// Sort loads into increasing pointers offsets to allow greater clustering.
937   Optional<OrdersType> findPartiallyOrderedLoads(const TreeEntry &TE);
938 
939   /// Gets reordering data for the given tree entry. If the entry is vectorized
940   /// - just return ReorderIndices, otherwise check if the scalars can be
941   /// reordered and return the most optimal order.
942   /// \param TopToBottom If true, include the order of vectorized stores and
943   /// insertelement nodes, otherwise skip them.
944   Optional<OrdersType> getReorderingData(const TreeEntry &TE, bool TopToBottom);
945 
946   /// Reorders the current graph to the most profitable order starting from the
947   /// root node to the leaf nodes. The best order is chosen only from the nodes
948   /// of the same size (vectorization factor). Smaller nodes are considered
949   /// parts of subgraph with smaller VF and they are reordered independently. We
950   /// can make it because we still need to extend smaller nodes to the wider VF
951   /// and we can merge reordering shuffles with the widening shuffles.
952   void reorderTopToBottom();
953 
954   /// Reorders the current graph to the most profitable order starting from
955   /// leaves to the root. It allows to rotate small subgraphs and reduce the
956   /// number of reshuffles if the leaf nodes use the same order. In this case we
957   /// can merge the orders and just shuffle user node instead of shuffling its
958   /// operands. Plus, even the leaf nodes have different orders, it allows to
959   /// sink reordering in the graph closer to the root node and merge it later
960   /// during analysis.
961   void reorderBottomToTop(bool IgnoreReorder = false);
962 
963   /// \return The vector element size in bits to use when vectorizing the
964   /// expression tree ending at \p V. If V is a store, the size is the width of
965   /// the stored value. Otherwise, the size is the width of the largest loaded
966   /// value reaching V. This method is used by the vectorizer to calculate
967   /// vectorization factors.
968   unsigned getVectorElementSize(Value *V);
969 
970   /// Compute the minimum type sizes required to represent the entries in a
971   /// vectorizable tree.
972   void computeMinimumValueSizes();
973 
974   // \returns maximum vector register size as set by TTI or overridden by cl::opt.
975   unsigned getMaxVecRegSize() const {
976     return MaxVecRegSize;
977   }
978 
979   // \returns minimum vector register size as set by cl::opt.
980   unsigned getMinVecRegSize() const {
981     return MinVecRegSize;
982   }
983 
984   unsigned getMinVF(unsigned Sz) const {
985     return std::max(2U, getMinVecRegSize() / Sz);
986   }
987 
988   unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const {
989     unsigned MaxVF = MaxVFOption.getNumOccurrences() ?
990       MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode);
991     return MaxVF ? MaxVF : UINT_MAX;
992   }
993 
994   /// Check if homogeneous aggregate is isomorphic to some VectorType.
995   /// Accepts homogeneous multidimensional aggregate of scalars/vectors like
996   /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> },
997   /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on.
998   ///
999   /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
1000   unsigned canMapToVector(Type *T, const DataLayout &DL) const;
1001 
1002   /// \returns True if the VectorizableTree is both tiny and not fully
1003   /// vectorizable. We do not vectorize such trees.
1004   bool isTreeTinyAndNotFullyVectorizable(bool ForReduction = false) const;
1005 
1006   /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values
1007   /// can be load combined in the backend. Load combining may not be allowed in
1008   /// the IR optimizer, so we do not want to alter the pattern. For example,
1009   /// partially transforming a scalar bswap() pattern into vector code is
1010   /// effectively impossible for the backend to undo.
1011   /// TODO: If load combining is allowed in the IR optimizer, this analysis
1012   ///       may not be necessary.
1013   bool isLoadCombineReductionCandidate(RecurKind RdxKind) const;
1014 
1015   /// Assume that a vector of stores of bitwise-or/shifted/zexted loaded values
1016   /// can be load combined in the backend. Load combining may not be allowed in
1017   /// the IR optimizer, so we do not want to alter the pattern. For example,
1018   /// partially transforming a scalar bswap() pattern into vector code is
1019   /// effectively impossible for the backend to undo.
1020   /// TODO: If load combining is allowed in the IR optimizer, this analysis
1021   ///       may not be necessary.
1022   bool isLoadCombineCandidate() const;
1023 
1024   OptimizationRemarkEmitter *getORE() { return ORE; }
1025 
1026   /// This structure holds any data we need about the edges being traversed
1027   /// during buildTree_rec(). We keep track of:
1028   /// (i) the user TreeEntry index, and
1029   /// (ii) the index of the edge.
1030   struct EdgeInfo {
1031     EdgeInfo() = default;
1032     EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx)
1033         : UserTE(UserTE), EdgeIdx(EdgeIdx) {}
1034     /// The user TreeEntry.
1035     TreeEntry *UserTE = nullptr;
1036     /// The operand index of the use.
1037     unsigned EdgeIdx = UINT_MAX;
1038 #ifndef NDEBUG
1039     friend inline raw_ostream &operator<<(raw_ostream &OS,
1040                                           const BoUpSLP::EdgeInfo &EI) {
1041       EI.dump(OS);
1042       return OS;
1043     }
1044     /// Debug print.
1045     void dump(raw_ostream &OS) const {
1046       OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null")
1047          << " EdgeIdx:" << EdgeIdx << "}";
1048     }
1049     LLVM_DUMP_METHOD void dump() const { dump(dbgs()); }
1050 #endif
1051   };
1052 
1053   /// A helper class used for scoring candidates for two consecutive lanes.
1054   class LookAheadHeuristics {
1055     const DataLayout &DL;
1056     ScalarEvolution &SE;
1057     const BoUpSLP &R;
1058     int NumLanes; // Total number of lanes (aka vectorization factor).
1059     int MaxLevel; // The maximum recursion depth for accumulating score.
1060 
1061   public:
1062     LookAheadHeuristics(const DataLayout &DL, ScalarEvolution &SE,
1063                         const BoUpSLP &R, int NumLanes, int MaxLevel)
1064         : DL(DL), SE(SE), R(R), NumLanes(NumLanes), MaxLevel(MaxLevel) {}
1065 
1066     // The hard-coded scores listed here are not very important, though it shall
1067     // be higher for better matches to improve the resulting cost. When
1068     // computing the scores of matching one sub-tree with another, we are
1069     // basically counting the number of values that are matching. So even if all
1070     // scores are set to 1, we would still get a decent matching result.
1071     // However, sometimes we have to break ties. For example we may have to
1072     // choose between matching loads vs matching opcodes. This is what these
1073     // scores are helping us with: they provide the order of preference. Also,
1074     // this is important if the scalar is externally used or used in another
1075     // tree entry node in the different lane.
1076 
1077     /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]).
1078     static const int ScoreConsecutiveLoads = 4;
1079     /// The same load multiple times. This should have a better score than
1080     /// `ScoreSplat` because it in x86 for a 2-lane vector we can represent it
1081     /// with `movddup (%reg), xmm0` which has a throughput of 0.5 versus 0.5 for
1082     /// a vector load and 1.0 for a broadcast.
1083     static const int ScoreSplatLoads = 3;
1084     /// Loads from reversed memory addresses, e.g. load(A[i+1]), load(A[i]).
1085     static const int ScoreReversedLoads = 3;
1086     /// ExtractElementInst from same vector and consecutive indexes.
1087     static const int ScoreConsecutiveExtracts = 4;
1088     /// ExtractElementInst from same vector and reversed indices.
1089     static const int ScoreReversedExtracts = 3;
1090     /// Constants.
1091     static const int ScoreConstants = 2;
1092     /// Instructions with the same opcode.
1093     static const int ScoreSameOpcode = 2;
1094     /// Instructions with alt opcodes (e.g, add + sub).
1095     static const int ScoreAltOpcodes = 1;
1096     /// Identical instructions (a.k.a. splat or broadcast).
1097     static const int ScoreSplat = 1;
1098     /// Matching with an undef is preferable to failing.
1099     static const int ScoreUndef = 1;
1100     /// Score for failing to find a decent match.
1101     static const int ScoreFail = 0;
1102     /// Score if all users are vectorized.
1103     static const int ScoreAllUserVectorized = 1;
1104 
1105     /// \returns the score of placing \p V1 and \p V2 in consecutive lanes.
1106     /// \p U1 and \p U2 are the users of \p V1 and \p V2.
1107     /// Also, checks if \p V1 and \p V2 are compatible with instructions in \p
1108     /// MainAltOps.
1109     int getShallowScore(Value *V1, Value *V2, Instruction *U1, Instruction *U2,
1110                         ArrayRef<Value *> MainAltOps) const {
1111       if (V1 == V2) {
1112         if (isa<LoadInst>(V1)) {
1113           // Retruns true if the users of V1 and V2 won't need to be extracted.
1114           auto AllUsersAreInternal = [U1, U2, this](Value *V1, Value *V2) {
1115             // Bail out if we have too many uses to save compilation time.
1116             static constexpr unsigned Limit = 8;
1117             if (V1->hasNUsesOrMore(Limit) || V2->hasNUsesOrMore(Limit))
1118               return false;
1119 
1120             auto AllUsersVectorized = [U1, U2, this](Value *V) {
1121               return llvm::all_of(V->users(), [U1, U2, this](Value *U) {
1122                 return U == U1 || U == U2 || R.getTreeEntry(U) != nullptr;
1123               });
1124             };
1125             return AllUsersVectorized(V1) && AllUsersVectorized(V2);
1126           };
1127           // A broadcast of a load can be cheaper on some targets.
1128           if (R.TTI->isLegalBroadcastLoad(V1->getType(),
1129                                           ElementCount::getFixed(NumLanes)) &&
1130               ((int)V1->getNumUses() == NumLanes ||
1131                AllUsersAreInternal(V1, V2)))
1132             return LookAheadHeuristics::ScoreSplatLoads;
1133         }
1134         return LookAheadHeuristics::ScoreSplat;
1135       }
1136 
1137       auto *LI1 = dyn_cast<LoadInst>(V1);
1138       auto *LI2 = dyn_cast<LoadInst>(V2);
1139       if (LI1 && LI2) {
1140         if (LI1->getParent() != LI2->getParent())
1141           return LookAheadHeuristics::ScoreFail;
1142 
1143         Optional<int> Dist = getPointersDiff(
1144             LI1->getType(), LI1->getPointerOperand(), LI2->getType(),
1145             LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true);
1146         if (!Dist || *Dist == 0)
1147           return LookAheadHeuristics::ScoreFail;
1148         // The distance is too large - still may be profitable to use masked
1149         // loads/gathers.
1150         if (std::abs(*Dist) > NumLanes / 2)
1151           return LookAheadHeuristics::ScoreAltOpcodes;
1152         // This still will detect consecutive loads, but we might have "holes"
1153         // in some cases. It is ok for non-power-2 vectorization and may produce
1154         // better results. It should not affect current vectorization.
1155         return (*Dist > 0) ? LookAheadHeuristics::ScoreConsecutiveLoads
1156                            : LookAheadHeuristics::ScoreReversedLoads;
1157       }
1158 
1159       auto *C1 = dyn_cast<Constant>(V1);
1160       auto *C2 = dyn_cast<Constant>(V2);
1161       if (C1 && C2)
1162         return LookAheadHeuristics::ScoreConstants;
1163 
1164       // Extracts from consecutive indexes of the same vector better score as
1165       // the extracts could be optimized away.
1166       Value *EV1;
1167       ConstantInt *Ex1Idx;
1168       if (match(V1, m_ExtractElt(m_Value(EV1), m_ConstantInt(Ex1Idx)))) {
1169         // Undefs are always profitable for extractelements.
1170         if (isa<UndefValue>(V2))
1171           return LookAheadHeuristics::ScoreConsecutiveExtracts;
1172         Value *EV2 = nullptr;
1173         ConstantInt *Ex2Idx = nullptr;
1174         if (match(V2,
1175                   m_ExtractElt(m_Value(EV2), m_CombineOr(m_ConstantInt(Ex2Idx),
1176                                                          m_Undef())))) {
1177           // Undefs are always profitable for extractelements.
1178           if (!Ex2Idx)
1179             return LookAheadHeuristics::ScoreConsecutiveExtracts;
1180           if (isUndefVector(EV2) && EV2->getType() == EV1->getType())
1181             return LookAheadHeuristics::ScoreConsecutiveExtracts;
1182           if (EV2 == EV1) {
1183             int Idx1 = Ex1Idx->getZExtValue();
1184             int Idx2 = Ex2Idx->getZExtValue();
1185             int Dist = Idx2 - Idx1;
1186             // The distance is too large - still may be profitable to use
1187             // shuffles.
1188             if (std::abs(Dist) == 0)
1189               return LookAheadHeuristics::ScoreSplat;
1190             if (std::abs(Dist) > NumLanes / 2)
1191               return LookAheadHeuristics::ScoreSameOpcode;
1192             return (Dist > 0) ? LookAheadHeuristics::ScoreConsecutiveExtracts
1193                               : LookAheadHeuristics::ScoreReversedExtracts;
1194           }
1195           return LookAheadHeuristics::ScoreAltOpcodes;
1196         }
1197         return LookAheadHeuristics::ScoreFail;
1198       }
1199 
1200       auto *I1 = dyn_cast<Instruction>(V1);
1201       auto *I2 = dyn_cast<Instruction>(V2);
1202       if (I1 && I2) {
1203         if (I1->getParent() != I2->getParent())
1204           return LookAheadHeuristics::ScoreFail;
1205         SmallVector<Value *, 4> Ops(MainAltOps.begin(), MainAltOps.end());
1206         Ops.push_back(I1);
1207         Ops.push_back(I2);
1208         InstructionsState S = getSameOpcode(Ops);
1209         // Note: Only consider instructions with <= 2 operands to avoid
1210         // complexity explosion.
1211         if (S.getOpcode() &&
1212             (S.MainOp->getNumOperands() <= 2 || !MainAltOps.empty() ||
1213              !S.isAltShuffle()) &&
1214             all_of(Ops, [&S](Value *V) {
1215               return cast<Instruction>(V)->getNumOperands() ==
1216                      S.MainOp->getNumOperands();
1217             }))
1218           return S.isAltShuffle() ? LookAheadHeuristics::ScoreAltOpcodes
1219                                   : LookAheadHeuristics::ScoreSameOpcode;
1220       }
1221 
1222       if (isa<UndefValue>(V2))
1223         return LookAheadHeuristics::ScoreUndef;
1224 
1225       return LookAheadHeuristics::ScoreFail;
1226     }
1227 
1228     /// Go through the operands of \p LHS and \p RHS recursively until
1229     /// MaxLevel, and return the cummulative score. \p U1 and \p U2 are
1230     /// the users of \p LHS and \p RHS (that is \p LHS and \p RHS are operands
1231     /// of \p U1 and \p U2), except at the beginning of the recursion where
1232     /// these are set to nullptr.
1233     ///
1234     /// For example:
1235     /// \verbatim
1236     ///  A[0]  B[0]  A[1]  B[1]  C[0] D[0]  B[1] A[1]
1237     ///     \ /         \ /         \ /        \ /
1238     ///      +           +           +          +
1239     ///     G1          G2          G3         G4
1240     /// \endverbatim
1241     /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at
1242     /// each level recursively, accumulating the score. It starts from matching
1243     /// the additions at level 0, then moves on to the loads (level 1). The
1244     /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and
1245     /// {B[0],B[1]} match with LookAheadHeuristics::ScoreConsecutiveLoads, while
1246     /// {A[0],C[0]} has a score of LookAheadHeuristics::ScoreFail.
1247     /// Please note that the order of the operands does not matter, as we
1248     /// evaluate the score of all profitable combinations of operands. In
1249     /// other words the score of G1 and G4 is the same as G1 and G2. This
1250     /// heuristic is based on ideas described in:
1251     ///   Look-ahead SLP: Auto-vectorization in the presence of commutative
1252     ///   operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha,
1253     ///   Luís F. W. Góes
1254     int getScoreAtLevelRec(Value *LHS, Value *RHS, Instruction *U1,
1255                            Instruction *U2, int CurrLevel,
1256                            ArrayRef<Value *> MainAltOps) const {
1257 
1258       // Get the shallow score of V1 and V2.
1259       int ShallowScoreAtThisLevel =
1260           getShallowScore(LHS, RHS, U1, U2, MainAltOps);
1261 
1262       // If reached MaxLevel,
1263       //  or if V1 and V2 are not instructions,
1264       //  or if they are SPLAT,
1265       //  or if they are not consecutive,
1266       //  or if profitable to vectorize loads or extractelements, early return
1267       //  the current cost.
1268       auto *I1 = dyn_cast<Instruction>(LHS);
1269       auto *I2 = dyn_cast<Instruction>(RHS);
1270       if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 ||
1271           ShallowScoreAtThisLevel == LookAheadHeuristics::ScoreFail ||
1272           (((isa<LoadInst>(I1) && isa<LoadInst>(I2)) ||
1273             (I1->getNumOperands() > 2 && I2->getNumOperands() > 2) ||
1274             (isa<ExtractElementInst>(I1) && isa<ExtractElementInst>(I2))) &&
1275            ShallowScoreAtThisLevel))
1276         return ShallowScoreAtThisLevel;
1277       assert(I1 && I2 && "Should have early exited.");
1278 
1279       // Contains the I2 operand indexes that got matched with I1 operands.
1280       SmallSet<unsigned, 4> Op2Used;
1281 
1282       // Recursion towards the operands of I1 and I2. We are trying all possible
1283       // operand pairs, and keeping track of the best score.
1284       for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands();
1285            OpIdx1 != NumOperands1; ++OpIdx1) {
1286         // Try to pair op1I with the best operand of I2.
1287         int MaxTmpScore = 0;
1288         unsigned MaxOpIdx2 = 0;
1289         bool FoundBest = false;
1290         // If I2 is commutative try all combinations.
1291         unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1;
1292         unsigned ToIdx = isCommutative(I2)
1293                              ? I2->getNumOperands()
1294                              : std::min(I2->getNumOperands(), OpIdx1 + 1);
1295         assert(FromIdx <= ToIdx && "Bad index");
1296         for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) {
1297           // Skip operands already paired with OpIdx1.
1298           if (Op2Used.count(OpIdx2))
1299             continue;
1300           // Recursively calculate the cost at each level
1301           int TmpScore =
1302               getScoreAtLevelRec(I1->getOperand(OpIdx1), I2->getOperand(OpIdx2),
1303                                  I1, I2, CurrLevel + 1, None);
1304           // Look for the best score.
1305           if (TmpScore > LookAheadHeuristics::ScoreFail &&
1306               TmpScore > MaxTmpScore) {
1307             MaxTmpScore = TmpScore;
1308             MaxOpIdx2 = OpIdx2;
1309             FoundBest = true;
1310           }
1311         }
1312         if (FoundBest) {
1313           // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it.
1314           Op2Used.insert(MaxOpIdx2);
1315           ShallowScoreAtThisLevel += MaxTmpScore;
1316         }
1317       }
1318       return ShallowScoreAtThisLevel;
1319     }
1320   };
1321   /// A helper data structure to hold the operands of a vector of instructions.
1322   /// This supports a fixed vector length for all operand vectors.
1323   class VLOperands {
1324     /// For each operand we need (i) the value, and (ii) the opcode that it
1325     /// would be attached to if the expression was in a left-linearized form.
1326     /// This is required to avoid illegal operand reordering.
1327     /// For example:
1328     /// \verbatim
1329     ///                         0 Op1
1330     ///                         |/
1331     /// Op1 Op2   Linearized    + Op2
1332     ///   \ /     ---------->   |/
1333     ///    -                    -
1334     ///
1335     /// Op1 - Op2            (0 + Op1) - Op2
1336     /// \endverbatim
1337     ///
1338     /// Value Op1 is attached to a '+' operation, and Op2 to a '-'.
1339     ///
1340     /// Another way to think of this is to track all the operations across the
1341     /// path from the operand all the way to the root of the tree and to
1342     /// calculate the operation that corresponds to this path. For example, the
1343     /// path from Op2 to the root crosses the RHS of the '-', therefore the
1344     /// corresponding operation is a '-' (which matches the one in the
1345     /// linearized tree, as shown above).
1346     ///
1347     /// For lack of a better term, we refer to this operation as Accumulated
1348     /// Path Operation (APO).
1349     struct OperandData {
1350       OperandData() = default;
1351       OperandData(Value *V, bool APO, bool IsUsed)
1352           : V(V), APO(APO), IsUsed(IsUsed) {}
1353       /// The operand value.
1354       Value *V = nullptr;
1355       /// TreeEntries only allow a single opcode, or an alternate sequence of
1356       /// them (e.g, +, -). Therefore, we can safely use a boolean value for the
1357       /// APO. It is set to 'true' if 'V' is attached to an inverse operation
1358       /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise
1359       /// (e.g., Add/Mul)
1360       bool APO = false;
1361       /// Helper data for the reordering function.
1362       bool IsUsed = false;
1363     };
1364 
1365     /// During operand reordering, we are trying to select the operand at lane
1366     /// that matches best with the operand at the neighboring lane. Our
1367     /// selection is based on the type of value we are looking for. For example,
1368     /// if the neighboring lane has a load, we need to look for a load that is
1369     /// accessing a consecutive address. These strategies are summarized in the
1370     /// 'ReorderingMode' enumerator.
1371     enum class ReorderingMode {
1372       Load,     ///< Matching loads to consecutive memory addresses
1373       Opcode,   ///< Matching instructions based on opcode (same or alternate)
1374       Constant, ///< Matching constants
1375       Splat,    ///< Matching the same instruction multiple times (broadcast)
1376       Failed,   ///< We failed to create a vectorizable group
1377     };
1378 
1379     using OperandDataVec = SmallVector<OperandData, 2>;
1380 
1381     /// A vector of operand vectors.
1382     SmallVector<OperandDataVec, 4> OpsVec;
1383 
1384     const DataLayout &DL;
1385     ScalarEvolution &SE;
1386     const BoUpSLP &R;
1387 
1388     /// \returns the operand data at \p OpIdx and \p Lane.
1389     OperandData &getData(unsigned OpIdx, unsigned Lane) {
1390       return OpsVec[OpIdx][Lane];
1391     }
1392 
1393     /// \returns the operand data at \p OpIdx and \p Lane. Const version.
1394     const OperandData &getData(unsigned OpIdx, unsigned Lane) const {
1395       return OpsVec[OpIdx][Lane];
1396     }
1397 
1398     /// Clears the used flag for all entries.
1399     void clearUsed() {
1400       for (unsigned OpIdx = 0, NumOperands = getNumOperands();
1401            OpIdx != NumOperands; ++OpIdx)
1402         for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
1403              ++Lane)
1404           OpsVec[OpIdx][Lane].IsUsed = false;
1405     }
1406 
1407     /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2.
1408     void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) {
1409       std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]);
1410     }
1411 
1412     /// \param Lane lane of the operands under analysis.
1413     /// \param OpIdx operand index in \p Lane lane we're looking the best
1414     /// candidate for.
1415     /// \param Idx operand index of the current candidate value.
1416     /// \returns The additional score due to possible broadcasting of the
1417     /// elements in the lane. It is more profitable to have power-of-2 unique
1418     /// elements in the lane, it will be vectorized with higher probability
1419     /// after removing duplicates. Currently the SLP vectorizer supports only
1420     /// vectorization of the power-of-2 number of unique scalars.
1421     int getSplatScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1422       Value *IdxLaneV = getData(Idx, Lane).V;
1423       if (!isa<Instruction>(IdxLaneV) || IdxLaneV == getData(OpIdx, Lane).V)
1424         return 0;
1425       SmallPtrSet<Value *, 4> Uniques;
1426       for (unsigned Ln = 0, E = getNumLanes(); Ln < E; ++Ln) {
1427         if (Ln == Lane)
1428           continue;
1429         Value *OpIdxLnV = getData(OpIdx, Ln).V;
1430         if (!isa<Instruction>(OpIdxLnV))
1431           return 0;
1432         Uniques.insert(OpIdxLnV);
1433       }
1434       int UniquesCount = Uniques.size();
1435       int UniquesCntWithIdxLaneV =
1436           Uniques.contains(IdxLaneV) ? UniquesCount : UniquesCount + 1;
1437       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1438       int UniquesCntWithOpIdxLaneV =
1439           Uniques.contains(OpIdxLaneV) ? UniquesCount : UniquesCount + 1;
1440       if (UniquesCntWithIdxLaneV == UniquesCntWithOpIdxLaneV)
1441         return 0;
1442       return (PowerOf2Ceil(UniquesCntWithOpIdxLaneV) -
1443               UniquesCntWithOpIdxLaneV) -
1444              (PowerOf2Ceil(UniquesCntWithIdxLaneV) - UniquesCntWithIdxLaneV);
1445     }
1446 
1447     /// \param Lane lane of the operands under analysis.
1448     /// \param OpIdx operand index in \p Lane lane we're looking the best
1449     /// candidate for.
1450     /// \param Idx operand index of the current candidate value.
1451     /// \returns The additional score for the scalar which users are all
1452     /// vectorized.
1453     int getExternalUseScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1454       Value *IdxLaneV = getData(Idx, Lane).V;
1455       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1456       // Do not care about number of uses for vector-like instructions
1457       // (extractelement/extractvalue with constant indices), they are extracts
1458       // themselves and already externally used. Vectorization of such
1459       // instructions does not add extra extractelement instruction, just may
1460       // remove it.
1461       if (isVectorLikeInstWithConstOps(IdxLaneV) &&
1462           isVectorLikeInstWithConstOps(OpIdxLaneV))
1463         return LookAheadHeuristics::ScoreAllUserVectorized;
1464       auto *IdxLaneI = dyn_cast<Instruction>(IdxLaneV);
1465       if (!IdxLaneI || !isa<Instruction>(OpIdxLaneV))
1466         return 0;
1467       return R.areAllUsersVectorized(IdxLaneI, None)
1468                  ? LookAheadHeuristics::ScoreAllUserVectorized
1469                  : 0;
1470     }
1471 
1472     /// Score scaling factor for fully compatible instructions but with
1473     /// different number of external uses. Allows better selection of the
1474     /// instructions with less external uses.
1475     static const int ScoreScaleFactor = 10;
1476 
1477     /// \Returns the look-ahead score, which tells us how much the sub-trees
1478     /// rooted at \p LHS and \p RHS match, the more they match the higher the
1479     /// score. This helps break ties in an informed way when we cannot decide on
1480     /// the order of the operands by just considering the immediate
1481     /// predecessors.
1482     int getLookAheadScore(Value *LHS, Value *RHS, ArrayRef<Value *> MainAltOps,
1483                           int Lane, unsigned OpIdx, unsigned Idx,
1484                           bool &IsUsed) {
1485       LookAheadHeuristics LookAhead(DL, SE, R, getNumLanes(),
1486                                     LookAheadMaxDepth);
1487       // Keep track of the instruction stack as we recurse into the operands
1488       // during the look-ahead score exploration.
1489       int Score =
1490           LookAhead.getScoreAtLevelRec(LHS, RHS, /*U1=*/nullptr, /*U2=*/nullptr,
1491                                        /*CurrLevel=*/1, MainAltOps);
1492       if (Score) {
1493         int SplatScore = getSplatScore(Lane, OpIdx, Idx);
1494         if (Score <= -SplatScore) {
1495           // Set the minimum score for splat-like sequence to avoid setting
1496           // failed state.
1497           Score = 1;
1498         } else {
1499           Score += SplatScore;
1500           // Scale score to see the difference between different operands
1501           // and similar operands but all vectorized/not all vectorized
1502           // uses. It does not affect actual selection of the best
1503           // compatible operand in general, just allows to select the
1504           // operand with all vectorized uses.
1505           Score *= ScoreScaleFactor;
1506           Score += getExternalUseScore(Lane, OpIdx, Idx);
1507           IsUsed = true;
1508         }
1509       }
1510       return Score;
1511     }
1512 
1513     /// Best defined scores per lanes between the passes. Used to choose the
1514     /// best operand (with the highest score) between the passes.
1515     /// The key - {Operand Index, Lane}.
1516     /// The value - the best score between the passes for the lane and the
1517     /// operand.
1518     SmallDenseMap<std::pair<unsigned, unsigned>, unsigned, 8>
1519         BestScoresPerLanes;
1520 
1521     // Search all operands in Ops[*][Lane] for the one that matches best
1522     // Ops[OpIdx][LastLane] and return its opreand index.
1523     // If no good match can be found, return None.
1524     Optional<unsigned> getBestOperand(unsigned OpIdx, int Lane, int LastLane,
1525                                       ArrayRef<ReorderingMode> ReorderingModes,
1526                                       ArrayRef<Value *> MainAltOps) {
1527       unsigned NumOperands = getNumOperands();
1528 
1529       // The operand of the previous lane at OpIdx.
1530       Value *OpLastLane = getData(OpIdx, LastLane).V;
1531 
1532       // Our strategy mode for OpIdx.
1533       ReorderingMode RMode = ReorderingModes[OpIdx];
1534       if (RMode == ReorderingMode::Failed)
1535         return None;
1536 
1537       // The linearized opcode of the operand at OpIdx, Lane.
1538       bool OpIdxAPO = getData(OpIdx, Lane).APO;
1539 
1540       // The best operand index and its score.
1541       // Sometimes we have more than one option (e.g., Opcode and Undefs), so we
1542       // are using the score to differentiate between the two.
1543       struct BestOpData {
1544         Optional<unsigned> Idx = None;
1545         unsigned Score = 0;
1546       } BestOp;
1547       BestOp.Score =
1548           BestScoresPerLanes.try_emplace(std::make_pair(OpIdx, Lane), 0)
1549               .first->second;
1550 
1551       // Track if the operand must be marked as used. If the operand is set to
1552       // Score 1 explicitly (because of non power-of-2 unique scalars, we may
1553       // want to reestimate the operands again on the following iterations).
1554       bool IsUsed =
1555           RMode == ReorderingMode::Splat || RMode == ReorderingMode::Constant;
1556       // Iterate through all unused operands and look for the best.
1557       for (unsigned Idx = 0; Idx != NumOperands; ++Idx) {
1558         // Get the operand at Idx and Lane.
1559         OperandData &OpData = getData(Idx, Lane);
1560         Value *Op = OpData.V;
1561         bool OpAPO = OpData.APO;
1562 
1563         // Skip already selected operands.
1564         if (OpData.IsUsed)
1565           continue;
1566 
1567         // Skip if we are trying to move the operand to a position with a
1568         // different opcode in the linearized tree form. This would break the
1569         // semantics.
1570         if (OpAPO != OpIdxAPO)
1571           continue;
1572 
1573         // Look for an operand that matches the current mode.
1574         switch (RMode) {
1575         case ReorderingMode::Load:
1576         case ReorderingMode::Constant:
1577         case ReorderingMode::Opcode: {
1578           bool LeftToRight = Lane > LastLane;
1579           Value *OpLeft = (LeftToRight) ? OpLastLane : Op;
1580           Value *OpRight = (LeftToRight) ? Op : OpLastLane;
1581           int Score = getLookAheadScore(OpLeft, OpRight, MainAltOps, Lane,
1582                                         OpIdx, Idx, IsUsed);
1583           if (Score > static_cast<int>(BestOp.Score)) {
1584             BestOp.Idx = Idx;
1585             BestOp.Score = Score;
1586             BestScoresPerLanes[std::make_pair(OpIdx, Lane)] = Score;
1587           }
1588           break;
1589         }
1590         case ReorderingMode::Splat:
1591           if (Op == OpLastLane)
1592             BestOp.Idx = Idx;
1593           break;
1594         case ReorderingMode::Failed:
1595           llvm_unreachable("Not expected Failed reordering mode.");
1596         }
1597       }
1598 
1599       if (BestOp.Idx) {
1600         getData(BestOp.Idx.getValue(), Lane).IsUsed = IsUsed;
1601         return BestOp.Idx;
1602       }
1603       // If we could not find a good match return None.
1604       return None;
1605     }
1606 
1607     /// Helper for reorderOperandVecs.
1608     /// \returns the lane that we should start reordering from. This is the one
1609     /// which has the least number of operands that can freely move about or
1610     /// less profitable because it already has the most optimal set of operands.
1611     unsigned getBestLaneToStartReordering() const {
1612       unsigned Min = UINT_MAX;
1613       unsigned SameOpNumber = 0;
1614       // std::pair<unsigned, unsigned> is used to implement a simple voting
1615       // algorithm and choose the lane with the least number of operands that
1616       // can freely move about or less profitable because it already has the
1617       // most optimal set of operands. The first unsigned is a counter for
1618       // voting, the second unsigned is the counter of lanes with instructions
1619       // with same/alternate opcodes and same parent basic block.
1620       MapVector<unsigned, std::pair<unsigned, unsigned>> HashMap;
1621       // Try to be closer to the original results, if we have multiple lanes
1622       // with same cost. If 2 lanes have the same cost, use the one with the
1623       // lowest index.
1624       for (int I = getNumLanes(); I > 0; --I) {
1625         unsigned Lane = I - 1;
1626         OperandsOrderData NumFreeOpsHash =
1627             getMaxNumOperandsThatCanBeReordered(Lane);
1628         // Compare the number of operands that can move and choose the one with
1629         // the least number.
1630         if (NumFreeOpsHash.NumOfAPOs < Min) {
1631           Min = NumFreeOpsHash.NumOfAPOs;
1632           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1633           HashMap.clear();
1634           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1635         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1636                    NumFreeOpsHash.NumOpsWithSameOpcodeParent < SameOpNumber) {
1637           // Select the most optimal lane in terms of number of operands that
1638           // should be moved around.
1639           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1640           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1641         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1642                    NumFreeOpsHash.NumOpsWithSameOpcodeParent == SameOpNumber) {
1643           auto It = HashMap.find(NumFreeOpsHash.Hash);
1644           if (It == HashMap.end())
1645             HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1646           else
1647             ++It->second.first;
1648         }
1649       }
1650       // Select the lane with the minimum counter.
1651       unsigned BestLane = 0;
1652       unsigned CntMin = UINT_MAX;
1653       for (const auto &Data : reverse(HashMap)) {
1654         if (Data.second.first < CntMin) {
1655           CntMin = Data.second.first;
1656           BestLane = Data.second.second;
1657         }
1658       }
1659       return BestLane;
1660     }
1661 
1662     /// Data structure that helps to reorder operands.
1663     struct OperandsOrderData {
1664       /// The best number of operands with the same APOs, which can be
1665       /// reordered.
1666       unsigned NumOfAPOs = UINT_MAX;
1667       /// Number of operands with the same/alternate instruction opcode and
1668       /// parent.
1669       unsigned NumOpsWithSameOpcodeParent = 0;
1670       /// Hash for the actual operands ordering.
1671       /// Used to count operands, actually their position id and opcode
1672       /// value. It is used in the voting mechanism to find the lane with the
1673       /// least number of operands that can freely move about or less profitable
1674       /// because it already has the most optimal set of operands. Can be
1675       /// replaced with SmallVector<unsigned> instead but hash code is faster
1676       /// and requires less memory.
1677       unsigned Hash = 0;
1678     };
1679     /// \returns the maximum number of operands that are allowed to be reordered
1680     /// for \p Lane and the number of compatible instructions(with the same
1681     /// parent/opcode). This is used as a heuristic for selecting the first lane
1682     /// to start operand reordering.
1683     OperandsOrderData getMaxNumOperandsThatCanBeReordered(unsigned Lane) const {
1684       unsigned CntTrue = 0;
1685       unsigned NumOperands = getNumOperands();
1686       // Operands with the same APO can be reordered. We therefore need to count
1687       // how many of them we have for each APO, like this: Cnt[APO] = x.
1688       // Since we only have two APOs, namely true and false, we can avoid using
1689       // a map. Instead we can simply count the number of operands that
1690       // correspond to one of them (in this case the 'true' APO), and calculate
1691       // the other by subtracting it from the total number of operands.
1692       // Operands with the same instruction opcode and parent are more
1693       // profitable since we don't need to move them in many cases, with a high
1694       // probability such lane already can be vectorized effectively.
1695       bool AllUndefs = true;
1696       unsigned NumOpsWithSameOpcodeParent = 0;
1697       Instruction *OpcodeI = nullptr;
1698       BasicBlock *Parent = nullptr;
1699       unsigned Hash = 0;
1700       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1701         const OperandData &OpData = getData(OpIdx, Lane);
1702         if (OpData.APO)
1703           ++CntTrue;
1704         // Use Boyer-Moore majority voting for finding the majority opcode and
1705         // the number of times it occurs.
1706         if (auto *I = dyn_cast<Instruction>(OpData.V)) {
1707           if (!OpcodeI || !getSameOpcode({OpcodeI, I}).getOpcode() ||
1708               I->getParent() != Parent) {
1709             if (NumOpsWithSameOpcodeParent == 0) {
1710               NumOpsWithSameOpcodeParent = 1;
1711               OpcodeI = I;
1712               Parent = I->getParent();
1713             } else {
1714               --NumOpsWithSameOpcodeParent;
1715             }
1716           } else {
1717             ++NumOpsWithSameOpcodeParent;
1718           }
1719         }
1720         Hash = hash_combine(
1721             Hash, hash_value((OpIdx + 1) * (OpData.V->getValueID() + 1)));
1722         AllUndefs = AllUndefs && isa<UndefValue>(OpData.V);
1723       }
1724       if (AllUndefs)
1725         return {};
1726       OperandsOrderData Data;
1727       Data.NumOfAPOs = std::max(CntTrue, NumOperands - CntTrue);
1728       Data.NumOpsWithSameOpcodeParent = NumOpsWithSameOpcodeParent;
1729       Data.Hash = Hash;
1730       return Data;
1731     }
1732 
1733     /// Go through the instructions in VL and append their operands.
1734     void appendOperandsOfVL(ArrayRef<Value *> VL) {
1735       assert(!VL.empty() && "Bad VL");
1736       assert((empty() || VL.size() == getNumLanes()) &&
1737              "Expected same number of lanes");
1738       assert(isa<Instruction>(VL[0]) && "Expected instruction");
1739       unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands();
1740       OpsVec.resize(NumOperands);
1741       unsigned NumLanes = VL.size();
1742       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1743         OpsVec[OpIdx].resize(NumLanes);
1744         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1745           assert(isa<Instruction>(VL[Lane]) && "Expected instruction");
1746           // Our tree has just 3 nodes: the root and two operands.
1747           // It is therefore trivial to get the APO. We only need to check the
1748           // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or
1749           // RHS operand. The LHS operand of both add and sub is never attached
1750           // to an inversese operation in the linearized form, therefore its APO
1751           // is false. The RHS is true only if VL[Lane] is an inverse operation.
1752 
1753           // Since operand reordering is performed on groups of commutative
1754           // operations or alternating sequences (e.g., +, -), we can safely
1755           // tell the inverse operations by checking commutativity.
1756           bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane]));
1757           bool APO = (OpIdx == 0) ? false : IsInverseOperation;
1758           OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx),
1759                                  APO, false};
1760         }
1761       }
1762     }
1763 
1764     /// \returns the number of operands.
1765     unsigned getNumOperands() const { return OpsVec.size(); }
1766 
1767     /// \returns the number of lanes.
1768     unsigned getNumLanes() const { return OpsVec[0].size(); }
1769 
1770     /// \returns the operand value at \p OpIdx and \p Lane.
1771     Value *getValue(unsigned OpIdx, unsigned Lane) const {
1772       return getData(OpIdx, Lane).V;
1773     }
1774 
1775     /// \returns true if the data structure is empty.
1776     bool empty() const { return OpsVec.empty(); }
1777 
1778     /// Clears the data.
1779     void clear() { OpsVec.clear(); }
1780 
1781     /// \Returns true if there are enough operands identical to \p Op to fill
1782     /// the whole vector.
1783     /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow.
1784     bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) {
1785       bool OpAPO = getData(OpIdx, Lane).APO;
1786       for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) {
1787         if (Ln == Lane)
1788           continue;
1789         // This is set to true if we found a candidate for broadcast at Lane.
1790         bool FoundCandidate = false;
1791         for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) {
1792           OperandData &Data = getData(OpI, Ln);
1793           if (Data.APO != OpAPO || Data.IsUsed)
1794             continue;
1795           if (Data.V == Op) {
1796             FoundCandidate = true;
1797             Data.IsUsed = true;
1798             break;
1799           }
1800         }
1801         if (!FoundCandidate)
1802           return false;
1803       }
1804       return true;
1805     }
1806 
1807   public:
1808     /// Initialize with all the operands of the instruction vector \p RootVL.
1809     VLOperands(ArrayRef<Value *> RootVL, const DataLayout &DL,
1810                ScalarEvolution &SE, const BoUpSLP &R)
1811         : DL(DL), SE(SE), R(R) {
1812       // Append all the operands of RootVL.
1813       appendOperandsOfVL(RootVL);
1814     }
1815 
1816     /// \Returns a value vector with the operands across all lanes for the
1817     /// opearnd at \p OpIdx.
1818     ValueList getVL(unsigned OpIdx) const {
1819       ValueList OpVL(OpsVec[OpIdx].size());
1820       assert(OpsVec[OpIdx].size() == getNumLanes() &&
1821              "Expected same num of lanes across all operands");
1822       for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane)
1823         OpVL[Lane] = OpsVec[OpIdx][Lane].V;
1824       return OpVL;
1825     }
1826 
1827     // Performs operand reordering for 2 or more operands.
1828     // The original operands are in OrigOps[OpIdx][Lane].
1829     // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'.
1830     void reorder() {
1831       unsigned NumOperands = getNumOperands();
1832       unsigned NumLanes = getNumLanes();
1833       // Each operand has its own mode. We are using this mode to help us select
1834       // the instructions for each lane, so that they match best with the ones
1835       // we have selected so far.
1836       SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands);
1837 
1838       // This is a greedy single-pass algorithm. We are going over each lane
1839       // once and deciding on the best order right away with no back-tracking.
1840       // However, in order to increase its effectiveness, we start with the lane
1841       // that has operands that can move the least. For example, given the
1842       // following lanes:
1843       //  Lane 0 : A[0] = B[0] + C[0]   // Visited 3rd
1844       //  Lane 1 : A[1] = C[1] - B[1]   // Visited 1st
1845       //  Lane 2 : A[2] = B[2] + C[2]   // Visited 2nd
1846       //  Lane 3 : A[3] = C[3] - B[3]   // Visited 4th
1847       // we will start at Lane 1, since the operands of the subtraction cannot
1848       // be reordered. Then we will visit the rest of the lanes in a circular
1849       // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3.
1850 
1851       // Find the first lane that we will start our search from.
1852       unsigned FirstLane = getBestLaneToStartReordering();
1853 
1854       // Initialize the modes.
1855       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1856         Value *OpLane0 = getValue(OpIdx, FirstLane);
1857         // Keep track if we have instructions with all the same opcode on one
1858         // side.
1859         if (isa<LoadInst>(OpLane0))
1860           ReorderingModes[OpIdx] = ReorderingMode::Load;
1861         else if (isa<Instruction>(OpLane0)) {
1862           // Check if OpLane0 should be broadcast.
1863           if (shouldBroadcast(OpLane0, OpIdx, FirstLane))
1864             ReorderingModes[OpIdx] = ReorderingMode::Splat;
1865           else
1866             ReorderingModes[OpIdx] = ReorderingMode::Opcode;
1867         }
1868         else if (isa<Constant>(OpLane0))
1869           ReorderingModes[OpIdx] = ReorderingMode::Constant;
1870         else if (isa<Argument>(OpLane0))
1871           // Our best hope is a Splat. It may save some cost in some cases.
1872           ReorderingModes[OpIdx] = ReorderingMode::Splat;
1873         else
1874           // NOTE: This should be unreachable.
1875           ReorderingModes[OpIdx] = ReorderingMode::Failed;
1876       }
1877 
1878       // Check that we don't have same operands. No need to reorder if operands
1879       // are just perfect diamond or shuffled diamond match. Do not do it only
1880       // for possible broadcasts or non-power of 2 number of scalars (just for
1881       // now).
1882       auto &&SkipReordering = [this]() {
1883         SmallPtrSet<Value *, 4> UniqueValues;
1884         ArrayRef<OperandData> Op0 = OpsVec.front();
1885         for (const OperandData &Data : Op0)
1886           UniqueValues.insert(Data.V);
1887         for (ArrayRef<OperandData> Op : drop_begin(OpsVec, 1)) {
1888           if (any_of(Op, [&UniqueValues](const OperandData &Data) {
1889                 return !UniqueValues.contains(Data.V);
1890               }))
1891             return false;
1892         }
1893         // TODO: Check if we can remove a check for non-power-2 number of
1894         // scalars after full support of non-power-2 vectorization.
1895         return UniqueValues.size() != 2 && isPowerOf2_32(UniqueValues.size());
1896       };
1897 
1898       // If the initial strategy fails for any of the operand indexes, then we
1899       // perform reordering again in a second pass. This helps avoid assigning
1900       // high priority to the failed strategy, and should improve reordering for
1901       // the non-failed operand indexes.
1902       for (int Pass = 0; Pass != 2; ++Pass) {
1903         // Check if no need to reorder operands since they're are perfect or
1904         // shuffled diamond match.
1905         // Need to to do it to avoid extra external use cost counting for
1906         // shuffled matches, which may cause regressions.
1907         if (SkipReordering())
1908           break;
1909         // Skip the second pass if the first pass did not fail.
1910         bool StrategyFailed = false;
1911         // Mark all operand data as free to use.
1912         clearUsed();
1913         // We keep the original operand order for the FirstLane, so reorder the
1914         // rest of the lanes. We are visiting the nodes in a circular fashion,
1915         // using FirstLane as the center point and increasing the radius
1916         // distance.
1917         SmallVector<SmallVector<Value *, 2>> MainAltOps(NumOperands);
1918         for (unsigned I = 0; I < NumOperands; ++I)
1919           MainAltOps[I].push_back(getData(I, FirstLane).V);
1920 
1921         for (unsigned Distance = 1; Distance != NumLanes; ++Distance) {
1922           // Visit the lane on the right and then the lane on the left.
1923           for (int Direction : {+1, -1}) {
1924             int Lane = FirstLane + Direction * Distance;
1925             if (Lane < 0 || Lane >= (int)NumLanes)
1926               continue;
1927             int LastLane = Lane - Direction;
1928             assert(LastLane >= 0 && LastLane < (int)NumLanes &&
1929                    "Out of bounds");
1930             // Look for a good match for each operand.
1931             for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1932               // Search for the operand that matches SortedOps[OpIdx][Lane-1].
1933               Optional<unsigned> BestIdx = getBestOperand(
1934                   OpIdx, Lane, LastLane, ReorderingModes, MainAltOps[OpIdx]);
1935               // By not selecting a value, we allow the operands that follow to
1936               // select a better matching value. We will get a non-null value in
1937               // the next run of getBestOperand().
1938               if (BestIdx) {
1939                 // Swap the current operand with the one returned by
1940                 // getBestOperand().
1941                 swap(OpIdx, BestIdx.getValue(), Lane);
1942               } else {
1943                 // We failed to find a best operand, set mode to 'Failed'.
1944                 ReorderingModes[OpIdx] = ReorderingMode::Failed;
1945                 // Enable the second pass.
1946                 StrategyFailed = true;
1947               }
1948               // Try to get the alternate opcode and follow it during analysis.
1949               if (MainAltOps[OpIdx].size() != 2) {
1950                 OperandData &AltOp = getData(OpIdx, Lane);
1951                 InstructionsState OpS =
1952                     getSameOpcode({MainAltOps[OpIdx].front(), AltOp.V});
1953                 if (OpS.getOpcode() && OpS.isAltShuffle())
1954                   MainAltOps[OpIdx].push_back(AltOp.V);
1955               }
1956             }
1957           }
1958         }
1959         // Skip second pass if the strategy did not fail.
1960         if (!StrategyFailed)
1961           break;
1962       }
1963     }
1964 
1965 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1966     LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) {
1967       switch (RMode) {
1968       case ReorderingMode::Load:
1969         return "Load";
1970       case ReorderingMode::Opcode:
1971         return "Opcode";
1972       case ReorderingMode::Constant:
1973         return "Constant";
1974       case ReorderingMode::Splat:
1975         return "Splat";
1976       case ReorderingMode::Failed:
1977         return "Failed";
1978       }
1979       llvm_unreachable("Unimplemented Reordering Type");
1980     }
1981 
1982     LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode,
1983                                                    raw_ostream &OS) {
1984       return OS << getModeStr(RMode);
1985     }
1986 
1987     /// Debug print.
1988     LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) {
1989       printMode(RMode, dbgs());
1990     }
1991 
1992     friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) {
1993       return printMode(RMode, OS);
1994     }
1995 
1996     LLVM_DUMP_METHOD raw_ostream &print(raw_ostream &OS) const {
1997       const unsigned Indent = 2;
1998       unsigned Cnt = 0;
1999       for (const OperandDataVec &OpDataVec : OpsVec) {
2000         OS << "Operand " << Cnt++ << "\n";
2001         for (const OperandData &OpData : OpDataVec) {
2002           OS.indent(Indent) << "{";
2003           if (Value *V = OpData.V)
2004             OS << *V;
2005           else
2006             OS << "null";
2007           OS << ", APO:" << OpData.APO << "}\n";
2008         }
2009         OS << "\n";
2010       }
2011       return OS;
2012     }
2013 
2014     /// Debug print.
2015     LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
2016 #endif
2017   };
2018 
2019   /// Evaluate each pair in \p Candidates and return index into \p Candidates
2020   /// for a pair which have highest score deemed to have best chance to form
2021   /// root of profitable tree to vectorize. Return None if no candidate scored
2022   /// above the LookAheadHeuristics::ScoreFail.
2023   /// \param Limit Lower limit of the cost, considered to be good enough score.
2024   Optional<int>
2025   findBestRootPair(ArrayRef<std::pair<Value *, Value *>> Candidates,
2026                    int Limit = LookAheadHeuristics::ScoreFail) {
2027     LookAheadHeuristics LookAhead(*DL, *SE, *this, /*NumLanes=*/2,
2028                                   RootLookAheadMaxDepth);
2029     int BestScore = Limit;
2030     Optional<int> Index = None;
2031     for (int I : seq<int>(0, Candidates.size())) {
2032       int Score = LookAhead.getScoreAtLevelRec(Candidates[I].first,
2033                                                Candidates[I].second,
2034                                                /*U1=*/nullptr, /*U2=*/nullptr,
2035                                                /*Level=*/1, None);
2036       if (Score > BestScore) {
2037         BestScore = Score;
2038         Index = I;
2039       }
2040     }
2041     return Index;
2042   }
2043 
2044   /// Checks if the instruction is marked for deletion.
2045   bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); }
2046 
2047   /// Removes an instruction from its block and eventually deletes it.
2048   /// It's like Instruction::eraseFromParent() except that the actual deletion
2049   /// is delayed until BoUpSLP is destructed.
2050   void eraseInstruction(Instruction *I) {
2051     DeletedInstructions.insert(I);
2052   }
2053 
2054   /// Checks if the instruction was already analyzed for being possible
2055   /// reduction root.
2056   bool isAnalyzedReductionRoot(Instruction *I) const {
2057     return AnalyzedReductionsRoots.count(I);
2058   }
2059   /// Register given instruction as already analyzed for being possible
2060   /// reduction root.
2061   void analyzedReductionRoot(Instruction *I) {
2062     AnalyzedReductionsRoots.insert(I);
2063   }
2064   /// Checks if the provided list of reduced values was checked already for
2065   /// vectorization.
2066   bool areAnalyzedReductionVals(ArrayRef<Value *> VL) {
2067     return AnalyzedReductionVals.contains(hash_value(VL));
2068   }
2069   /// Adds the list of reduced values to list of already checked values for the
2070   /// vectorization.
2071   void analyzedReductionVals(ArrayRef<Value *> VL) {
2072     AnalyzedReductionVals.insert(hash_value(VL));
2073   }
2074   /// Clear the list of the analyzed reduction root instructions.
2075   void clearReductionData() {
2076     AnalyzedReductionsRoots.clear();
2077     AnalyzedReductionVals.clear();
2078   }
2079   /// Checks if the given value is gathered in one of the nodes.
2080   bool isAnyGathered(const SmallDenseSet<Value *> &Vals) const {
2081     return any_of(MustGather, [&](Value *V) { return Vals.contains(V); });
2082   }
2083 
2084   ~BoUpSLP();
2085 
2086 private:
2087   /// Check if the operands on the edges \p Edges of the \p UserTE allows
2088   /// reordering (i.e. the operands can be reordered because they have only one
2089   /// user and reordarable).
2090   /// \param ReorderableGathers List of all gather nodes that require reordering
2091   /// (e.g., gather of extractlements or partially vectorizable loads).
2092   /// \param GatherOps List of gather operand nodes for \p UserTE that require
2093   /// reordering, subset of \p NonVectorized.
2094   bool
2095   canReorderOperands(TreeEntry *UserTE,
2096                      SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
2097                      ArrayRef<TreeEntry *> ReorderableGathers,
2098                      SmallVectorImpl<TreeEntry *> &GatherOps);
2099 
2100   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
2101   /// if any. If it is not vectorized (gather node), returns nullptr.
2102   TreeEntry *getVectorizedOperand(TreeEntry *UserTE, unsigned OpIdx) {
2103     ArrayRef<Value *> VL = UserTE->getOperand(OpIdx);
2104     TreeEntry *TE = nullptr;
2105     const auto *It = find_if(VL, [this, &TE](Value *V) {
2106       TE = getTreeEntry(V);
2107       return TE;
2108     });
2109     if (It != VL.end() && TE->isSame(VL))
2110       return TE;
2111     return nullptr;
2112   }
2113 
2114   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
2115   /// if any. If it is not vectorized (gather node), returns nullptr.
2116   const TreeEntry *getVectorizedOperand(const TreeEntry *UserTE,
2117                                         unsigned OpIdx) const {
2118     return const_cast<BoUpSLP *>(this)->getVectorizedOperand(
2119         const_cast<TreeEntry *>(UserTE), OpIdx);
2120   }
2121 
2122   /// Checks if all users of \p I are the part of the vectorization tree.
2123   bool areAllUsersVectorized(Instruction *I,
2124                              ArrayRef<Value *> VectorizedVals) const;
2125 
2126   /// \returns the cost of the vectorizable entry.
2127   InstructionCost getEntryCost(const TreeEntry *E,
2128                                ArrayRef<Value *> VectorizedVals);
2129 
2130   /// This is the recursive part of buildTree.
2131   void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth,
2132                      const EdgeInfo &EI);
2133 
2134   /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
2135   /// be vectorized to use the original vector (or aggregate "bitcast" to a
2136   /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
2137   /// returns false, setting \p CurrentOrder to either an empty vector or a
2138   /// non-identity permutation that allows to reuse extract instructions.
2139   bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
2140                        SmallVectorImpl<unsigned> &CurrentOrder) const;
2141 
2142   /// Vectorize a single entry in the tree.
2143   Value *vectorizeTree(TreeEntry *E);
2144 
2145   /// Vectorize a single entry in the tree, starting in \p VL.
2146   Value *vectorizeTree(ArrayRef<Value *> VL);
2147 
2148   /// Create a new vector from a list of scalar values.  Produces a sequence
2149   /// which exploits values reused across lanes, and arranges the inserts
2150   /// for ease of later optimization.
2151   Value *createBuildVector(ArrayRef<Value *> VL);
2152 
2153   /// \returns the scalarization cost for this type. Scalarization in this
2154   /// context means the creation of vectors from a group of scalars. If \p
2155   /// NeedToShuffle is true, need to add a cost of reshuffling some of the
2156   /// vector elements.
2157   InstructionCost getGatherCost(FixedVectorType *Ty,
2158                                 const APInt &ShuffledIndices,
2159                                 bool NeedToShuffle) const;
2160 
2161   /// Checks if the gathered \p VL can be represented as shuffle(s) of previous
2162   /// tree entries.
2163   /// \returns ShuffleKind, if gathered values can be represented as shuffles of
2164   /// previous tree entries. \p Mask is filled with the shuffle mask.
2165   Optional<TargetTransformInfo::ShuffleKind>
2166   isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
2167                         SmallVectorImpl<const TreeEntry *> &Entries);
2168 
2169   /// \returns the scalarization cost for this list of values. Assuming that
2170   /// this subtree gets vectorized, we may need to extract the values from the
2171   /// roots. This method calculates the cost of extracting the values.
2172   InstructionCost getGatherCost(ArrayRef<Value *> VL) const;
2173 
2174   /// Set the Builder insert point to one after the last instruction in
2175   /// the bundle
2176   void setInsertPointAfterBundle(const TreeEntry *E);
2177 
2178   /// \returns a vector from a collection of scalars in \p VL.
2179   Value *gather(ArrayRef<Value *> VL);
2180 
2181   /// \returns whether the VectorizableTree is fully vectorizable and will
2182   /// be beneficial even the tree height is tiny.
2183   bool isFullyVectorizableTinyTree(bool ForReduction) const;
2184 
2185   /// Reorder commutative or alt operands to get better probability of
2186   /// generating vectorized code.
2187   static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
2188                                              SmallVectorImpl<Value *> &Left,
2189                                              SmallVectorImpl<Value *> &Right,
2190                                              const DataLayout &DL,
2191                                              ScalarEvolution &SE,
2192                                              const BoUpSLP &R);
2193 
2194   /// Helper for `findExternalStoreUsersReorderIndices()`. It iterates over the
2195   /// users of \p TE and collects the stores. It returns the map from the store
2196   /// pointers to the collected stores.
2197   DenseMap<Value *, SmallVector<StoreInst *, 4>>
2198   collectUserStores(const BoUpSLP::TreeEntry *TE) const;
2199 
2200   /// Helper for `findExternalStoreUsersReorderIndices()`. It checks if the
2201   /// stores in \p StoresVec can for a vector instruction. If so it returns true
2202   /// and populates \p ReorderIndices with the shuffle indices of the the stores
2203   /// when compared to the sorted vector.
2204   bool CanFormVector(const SmallVector<StoreInst *, 4> &StoresVec,
2205                      OrdersType &ReorderIndices) const;
2206 
2207   /// Iterates through the users of \p TE, looking for scalar stores that can be
2208   /// potentially vectorized in a future SLP-tree. If found, it keeps track of
2209   /// their order and builds an order index vector for each store bundle. It
2210   /// returns all these order vectors found.
2211   /// We run this after the tree has formed, otherwise we may come across user
2212   /// instructions that are not yet in the tree.
2213   SmallVector<OrdersType, 1>
2214   findExternalStoreUsersReorderIndices(TreeEntry *TE) const;
2215 
2216   struct TreeEntry {
2217     using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>;
2218     TreeEntry(VecTreeTy &Container) : Container(Container) {}
2219 
2220     /// \returns true if the scalars in VL are equal to this entry.
2221     bool isSame(ArrayRef<Value *> VL) const {
2222       auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) {
2223         if (Mask.size() != VL.size() && VL.size() == Scalars.size())
2224           return std::equal(VL.begin(), VL.end(), Scalars.begin());
2225         return VL.size() == Mask.size() &&
2226                std::equal(VL.begin(), VL.end(), Mask.begin(),
2227                           [Scalars](Value *V, int Idx) {
2228                             return (isa<UndefValue>(V) &&
2229                                     Idx == UndefMaskElem) ||
2230                                    (Idx != UndefMaskElem && V == Scalars[Idx]);
2231                           });
2232       };
2233       if (!ReorderIndices.empty()) {
2234         // TODO: implement matching if the nodes are just reordered, still can
2235         // treat the vector as the same if the list of scalars matches VL
2236         // directly, without reordering.
2237         SmallVector<int> Mask;
2238         inversePermutation(ReorderIndices, Mask);
2239         if (VL.size() == Scalars.size())
2240           return IsSame(Scalars, Mask);
2241         if (VL.size() == ReuseShuffleIndices.size()) {
2242           ::addMask(Mask, ReuseShuffleIndices);
2243           return IsSame(Scalars, Mask);
2244         }
2245         return false;
2246       }
2247       return IsSame(Scalars, ReuseShuffleIndices);
2248     }
2249 
2250     /// \returns true if current entry has same operands as \p TE.
2251     bool hasEqualOperands(const TreeEntry &TE) const {
2252       if (TE.getNumOperands() != getNumOperands())
2253         return false;
2254       SmallBitVector Used(getNumOperands());
2255       for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
2256         unsigned PrevCount = Used.count();
2257         for (unsigned K = 0; K < E; ++K) {
2258           if (Used.test(K))
2259             continue;
2260           if (getOperand(K) == TE.getOperand(I)) {
2261             Used.set(K);
2262             break;
2263           }
2264         }
2265         // Check if we actually found the matching operand.
2266         if (PrevCount == Used.count())
2267           return false;
2268       }
2269       return true;
2270     }
2271 
2272     /// \return Final vectorization factor for the node. Defined by the total
2273     /// number of vectorized scalars, including those, used several times in the
2274     /// entry and counted in the \a ReuseShuffleIndices, if any.
2275     unsigned getVectorFactor() const {
2276       if (!ReuseShuffleIndices.empty())
2277         return ReuseShuffleIndices.size();
2278       return Scalars.size();
2279     };
2280 
2281     /// A vector of scalars.
2282     ValueList Scalars;
2283 
2284     /// The Scalars are vectorized into this value. It is initialized to Null.
2285     Value *VectorizedValue = nullptr;
2286 
2287     /// Do we need to gather this sequence or vectorize it
2288     /// (either with vector instruction or with scatter/gather
2289     /// intrinsics for store/load)?
2290     enum EntryState { Vectorize, ScatterVectorize, NeedToGather };
2291     EntryState State;
2292 
2293     /// Does this sequence require some shuffling?
2294     SmallVector<int, 4> ReuseShuffleIndices;
2295 
2296     /// Does this entry require reordering?
2297     SmallVector<unsigned, 4> ReorderIndices;
2298 
2299     /// Points back to the VectorizableTree.
2300     ///
2301     /// Only used for Graphviz right now.  Unfortunately GraphTrait::NodeRef has
2302     /// to be a pointer and needs to be able to initialize the child iterator.
2303     /// Thus we need a reference back to the container to translate the indices
2304     /// to entries.
2305     VecTreeTy &Container;
2306 
2307     /// The TreeEntry index containing the user of this entry.  We can actually
2308     /// have multiple users so the data structure is not truly a tree.
2309     SmallVector<EdgeInfo, 1> UserTreeIndices;
2310 
2311     /// The index of this treeEntry in VectorizableTree.
2312     int Idx = -1;
2313 
2314   private:
2315     /// The operands of each instruction in each lane Operands[op_index][lane].
2316     /// Note: This helps avoid the replication of the code that performs the
2317     /// reordering of operands during buildTree_rec() and vectorizeTree().
2318     SmallVector<ValueList, 2> Operands;
2319 
2320     /// The main/alternate instruction.
2321     Instruction *MainOp = nullptr;
2322     Instruction *AltOp = nullptr;
2323 
2324   public:
2325     /// Set this bundle's \p OpIdx'th operand to \p OpVL.
2326     void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) {
2327       if (Operands.size() < OpIdx + 1)
2328         Operands.resize(OpIdx + 1);
2329       assert(Operands[OpIdx].empty() && "Already resized?");
2330       assert(OpVL.size() <= Scalars.size() &&
2331              "Number of operands is greater than the number of scalars.");
2332       Operands[OpIdx].resize(OpVL.size());
2333       copy(OpVL, Operands[OpIdx].begin());
2334     }
2335 
2336     /// Set the operands of this bundle in their original order.
2337     void setOperandsInOrder() {
2338       assert(Operands.empty() && "Already initialized?");
2339       auto *I0 = cast<Instruction>(Scalars[0]);
2340       Operands.resize(I0->getNumOperands());
2341       unsigned NumLanes = Scalars.size();
2342       for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands();
2343            OpIdx != NumOperands; ++OpIdx) {
2344         Operands[OpIdx].resize(NumLanes);
2345         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
2346           auto *I = cast<Instruction>(Scalars[Lane]);
2347           assert(I->getNumOperands() == NumOperands &&
2348                  "Expected same number of operands");
2349           Operands[OpIdx][Lane] = I->getOperand(OpIdx);
2350         }
2351       }
2352     }
2353 
2354     /// Reorders operands of the node to the given mask \p Mask.
2355     void reorderOperands(ArrayRef<int> Mask) {
2356       for (ValueList &Operand : Operands)
2357         reorderScalars(Operand, Mask);
2358     }
2359 
2360     /// \returns the \p OpIdx operand of this TreeEntry.
2361     ValueList &getOperand(unsigned OpIdx) {
2362       assert(OpIdx < Operands.size() && "Off bounds");
2363       return Operands[OpIdx];
2364     }
2365 
2366     /// \returns the \p OpIdx operand of this TreeEntry.
2367     ArrayRef<Value *> getOperand(unsigned OpIdx) const {
2368       assert(OpIdx < Operands.size() && "Off bounds");
2369       return Operands[OpIdx];
2370     }
2371 
2372     /// \returns the number of operands.
2373     unsigned getNumOperands() const { return Operands.size(); }
2374 
2375     /// \return the single \p OpIdx operand.
2376     Value *getSingleOperand(unsigned OpIdx) const {
2377       assert(OpIdx < Operands.size() && "Off bounds");
2378       assert(!Operands[OpIdx].empty() && "No operand available");
2379       return Operands[OpIdx][0];
2380     }
2381 
2382     /// Some of the instructions in the list have alternate opcodes.
2383     bool isAltShuffle() const { return MainOp != AltOp; }
2384 
2385     bool isOpcodeOrAlt(Instruction *I) const {
2386       unsigned CheckedOpcode = I->getOpcode();
2387       return (getOpcode() == CheckedOpcode ||
2388               getAltOpcode() == CheckedOpcode);
2389     }
2390 
2391     /// Chooses the correct key for scheduling data. If \p Op has the same (or
2392     /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is
2393     /// \p OpValue.
2394     Value *isOneOf(Value *Op) const {
2395       auto *I = dyn_cast<Instruction>(Op);
2396       if (I && isOpcodeOrAlt(I))
2397         return Op;
2398       return MainOp;
2399     }
2400 
2401     void setOperations(const InstructionsState &S) {
2402       MainOp = S.MainOp;
2403       AltOp = S.AltOp;
2404     }
2405 
2406     Instruction *getMainOp() const {
2407       return MainOp;
2408     }
2409 
2410     Instruction *getAltOp() const {
2411       return AltOp;
2412     }
2413 
2414     /// The main/alternate opcodes for the list of instructions.
2415     unsigned getOpcode() const {
2416       return MainOp ? MainOp->getOpcode() : 0;
2417     }
2418 
2419     unsigned getAltOpcode() const {
2420       return AltOp ? AltOp->getOpcode() : 0;
2421     }
2422 
2423     /// When ReuseReorderShuffleIndices is empty it just returns position of \p
2424     /// V within vector of Scalars. Otherwise, try to remap on its reuse index.
2425     int findLaneForValue(Value *V) const {
2426       unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V));
2427       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2428       if (!ReorderIndices.empty())
2429         FoundLane = ReorderIndices[FoundLane];
2430       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2431       if (!ReuseShuffleIndices.empty()) {
2432         FoundLane = std::distance(ReuseShuffleIndices.begin(),
2433                                   find(ReuseShuffleIndices, FoundLane));
2434       }
2435       return FoundLane;
2436     }
2437 
2438 #ifndef NDEBUG
2439     /// Debug printer.
2440     LLVM_DUMP_METHOD void dump() const {
2441       dbgs() << Idx << ".\n";
2442       for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) {
2443         dbgs() << "Operand " << OpI << ":\n";
2444         for (const Value *V : Operands[OpI])
2445           dbgs().indent(2) << *V << "\n";
2446       }
2447       dbgs() << "Scalars: \n";
2448       for (Value *V : Scalars)
2449         dbgs().indent(2) << *V << "\n";
2450       dbgs() << "State: ";
2451       switch (State) {
2452       case Vectorize:
2453         dbgs() << "Vectorize\n";
2454         break;
2455       case ScatterVectorize:
2456         dbgs() << "ScatterVectorize\n";
2457         break;
2458       case NeedToGather:
2459         dbgs() << "NeedToGather\n";
2460         break;
2461       }
2462       dbgs() << "MainOp: ";
2463       if (MainOp)
2464         dbgs() << *MainOp << "\n";
2465       else
2466         dbgs() << "NULL\n";
2467       dbgs() << "AltOp: ";
2468       if (AltOp)
2469         dbgs() << *AltOp << "\n";
2470       else
2471         dbgs() << "NULL\n";
2472       dbgs() << "VectorizedValue: ";
2473       if (VectorizedValue)
2474         dbgs() << *VectorizedValue << "\n";
2475       else
2476         dbgs() << "NULL\n";
2477       dbgs() << "ReuseShuffleIndices: ";
2478       if (ReuseShuffleIndices.empty())
2479         dbgs() << "Empty";
2480       else
2481         for (int ReuseIdx : ReuseShuffleIndices)
2482           dbgs() << ReuseIdx << ", ";
2483       dbgs() << "\n";
2484       dbgs() << "ReorderIndices: ";
2485       for (unsigned ReorderIdx : ReorderIndices)
2486         dbgs() << ReorderIdx << ", ";
2487       dbgs() << "\n";
2488       dbgs() << "UserTreeIndices: ";
2489       for (const auto &EInfo : UserTreeIndices)
2490         dbgs() << EInfo << ", ";
2491       dbgs() << "\n";
2492     }
2493 #endif
2494   };
2495 
2496 #ifndef NDEBUG
2497   void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost,
2498                      InstructionCost VecCost,
2499                      InstructionCost ScalarCost) const {
2500     dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump();
2501     dbgs() << "SLP: Costs:\n";
2502     dbgs() << "SLP:     ReuseShuffleCost = " << ReuseShuffleCost << "\n";
2503     dbgs() << "SLP:     VectorCost = " << VecCost << "\n";
2504     dbgs() << "SLP:     ScalarCost = " << ScalarCost << "\n";
2505     dbgs() << "SLP:     ReuseShuffleCost + VecCost - ScalarCost = " <<
2506                ReuseShuffleCost + VecCost - ScalarCost << "\n";
2507   }
2508 #endif
2509 
2510   /// Create a new VectorizableTree entry.
2511   TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle,
2512                           const InstructionsState &S,
2513                           const EdgeInfo &UserTreeIdx,
2514                           ArrayRef<int> ReuseShuffleIndices = None,
2515                           ArrayRef<unsigned> ReorderIndices = None) {
2516     TreeEntry::EntryState EntryState =
2517         Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather;
2518     return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx,
2519                         ReuseShuffleIndices, ReorderIndices);
2520   }
2521 
2522   TreeEntry *newTreeEntry(ArrayRef<Value *> VL,
2523                           TreeEntry::EntryState EntryState,
2524                           Optional<ScheduleData *> Bundle,
2525                           const InstructionsState &S,
2526                           const EdgeInfo &UserTreeIdx,
2527                           ArrayRef<int> ReuseShuffleIndices = None,
2528                           ArrayRef<unsigned> ReorderIndices = None) {
2529     assert(((!Bundle && EntryState == TreeEntry::NeedToGather) ||
2530             (Bundle && EntryState != TreeEntry::NeedToGather)) &&
2531            "Need to vectorize gather entry?");
2532     VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree));
2533     TreeEntry *Last = VectorizableTree.back().get();
2534     Last->Idx = VectorizableTree.size() - 1;
2535     Last->State = EntryState;
2536     Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
2537                                      ReuseShuffleIndices.end());
2538     if (ReorderIndices.empty()) {
2539       Last->Scalars.assign(VL.begin(), VL.end());
2540       Last->setOperations(S);
2541     } else {
2542       // Reorder scalars and build final mask.
2543       Last->Scalars.assign(VL.size(), nullptr);
2544       transform(ReorderIndices, Last->Scalars.begin(),
2545                 [VL](unsigned Idx) -> Value * {
2546                   if (Idx >= VL.size())
2547                     return UndefValue::get(VL.front()->getType());
2548                   return VL[Idx];
2549                 });
2550       InstructionsState S = getSameOpcode(Last->Scalars);
2551       Last->setOperations(S);
2552       Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end());
2553     }
2554     if (Last->State != TreeEntry::NeedToGather) {
2555       for (Value *V : VL) {
2556         assert(!getTreeEntry(V) && "Scalar already in tree!");
2557         ScalarToTreeEntry[V] = Last;
2558       }
2559       // Update the scheduler bundle to point to this TreeEntry.
2560       ScheduleData *BundleMember = Bundle.getValue();
2561       assert((BundleMember || isa<PHINode>(S.MainOp) ||
2562               isVectorLikeInstWithConstOps(S.MainOp) ||
2563               doesNotNeedToSchedule(VL)) &&
2564              "Bundle and VL out of sync");
2565       if (BundleMember) {
2566         for (Value *V : VL) {
2567           if (doesNotNeedToBeScheduled(V))
2568             continue;
2569           assert(BundleMember && "Unexpected end of bundle.");
2570           BundleMember->TE = Last;
2571           BundleMember = BundleMember->NextInBundle;
2572         }
2573       }
2574       assert(!BundleMember && "Bundle and VL out of sync");
2575     } else {
2576       MustGather.insert(VL.begin(), VL.end());
2577     }
2578 
2579     if (UserTreeIdx.UserTE)
2580       Last->UserTreeIndices.push_back(UserTreeIdx);
2581 
2582     return Last;
2583   }
2584 
2585   /// -- Vectorization State --
2586   /// Holds all of the tree entries.
2587   TreeEntry::VecTreeTy VectorizableTree;
2588 
2589 #ifndef NDEBUG
2590   /// Debug printer.
2591   LLVM_DUMP_METHOD void dumpVectorizableTree() const {
2592     for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) {
2593       VectorizableTree[Id]->dump();
2594       dbgs() << "\n";
2595     }
2596   }
2597 #endif
2598 
2599   TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); }
2600 
2601   const TreeEntry *getTreeEntry(Value *V) const {
2602     return ScalarToTreeEntry.lookup(V);
2603   }
2604 
2605   /// Maps a specific scalar to its tree entry.
2606   SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry;
2607 
2608   /// Maps a value to the proposed vectorizable size.
2609   SmallDenseMap<Value *, unsigned> InstrElementSize;
2610 
2611   /// A list of scalars that we found that we need to keep as scalars.
2612   ValueSet MustGather;
2613 
2614   /// This POD struct describes one external user in the vectorized tree.
2615   struct ExternalUser {
2616     ExternalUser(Value *S, llvm::User *U, int L)
2617         : Scalar(S), User(U), Lane(L) {}
2618 
2619     // Which scalar in our function.
2620     Value *Scalar;
2621 
2622     // Which user that uses the scalar.
2623     llvm::User *User;
2624 
2625     // Which lane does the scalar belong to.
2626     int Lane;
2627   };
2628   using UserList = SmallVector<ExternalUser, 16>;
2629 
2630   /// Checks if two instructions may access the same memory.
2631   ///
2632   /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
2633   /// is invariant in the calling loop.
2634   bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
2635                  Instruction *Inst2) {
2636     // First check if the result is already in the cache.
2637     AliasCacheKey key = std::make_pair(Inst1, Inst2);
2638     Optional<bool> &result = AliasCache[key];
2639     if (result.hasValue()) {
2640       return result.getValue();
2641     }
2642     bool aliased = true;
2643     if (Loc1.Ptr && isSimple(Inst1))
2644       aliased = isModOrRefSet(BatchAA.getModRefInfo(Inst2, Loc1));
2645     // Store the result in the cache.
2646     result = aliased;
2647     return aliased;
2648   }
2649 
2650   using AliasCacheKey = std::pair<Instruction *, Instruction *>;
2651 
2652   /// Cache for alias results.
2653   /// TODO: consider moving this to the AliasAnalysis itself.
2654   DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
2655 
2656   // Cache for pointerMayBeCaptured calls inside AA.  This is preserved
2657   // globally through SLP because we don't perform any action which
2658   // invalidates capture results.
2659   BatchAAResults BatchAA;
2660 
2661   /// Temporary store for deleted instructions. Instructions will be deleted
2662   /// eventually when the BoUpSLP is destructed.  The deferral is required to
2663   /// ensure that there are no incorrect collisions in the AliasCache, which
2664   /// can happen if a new instruction is allocated at the same address as a
2665   /// previously deleted instruction.
2666   DenseSet<Instruction *> DeletedInstructions;
2667 
2668   /// Set of the instruction, being analyzed already for reductions.
2669   SmallPtrSet<Instruction *, 16> AnalyzedReductionsRoots;
2670 
2671   /// Set of hashes for the list of reduction values already being analyzed.
2672   DenseSet<size_t> AnalyzedReductionVals;
2673 
2674   /// A list of values that need to extracted out of the tree.
2675   /// This list holds pairs of (Internal Scalar : External User). External User
2676   /// can be nullptr, it means that this Internal Scalar will be used later,
2677   /// after vectorization.
2678   UserList ExternalUses;
2679 
2680   /// Values used only by @llvm.assume calls.
2681   SmallPtrSet<const Value *, 32> EphValues;
2682 
2683   /// Holds all of the instructions that we gathered.
2684   SetVector<Instruction *> GatherShuffleSeq;
2685 
2686   /// A list of blocks that we are going to CSE.
2687   SetVector<BasicBlock *> CSEBlocks;
2688 
2689   /// Contains all scheduling relevant data for an instruction.
2690   /// A ScheduleData either represents a single instruction or a member of an
2691   /// instruction bundle (= a group of instructions which is combined into a
2692   /// vector instruction).
2693   struct ScheduleData {
2694     // The initial value for the dependency counters. It means that the
2695     // dependencies are not calculated yet.
2696     enum { InvalidDeps = -1 };
2697 
2698     ScheduleData() = default;
2699 
2700     void init(int BlockSchedulingRegionID, Value *OpVal) {
2701       FirstInBundle = this;
2702       NextInBundle = nullptr;
2703       NextLoadStore = nullptr;
2704       IsScheduled = false;
2705       SchedulingRegionID = BlockSchedulingRegionID;
2706       clearDependencies();
2707       OpValue = OpVal;
2708       TE = nullptr;
2709     }
2710 
2711     /// Verify basic self consistency properties
2712     void verify() {
2713       if (hasValidDependencies()) {
2714         assert(UnscheduledDeps <= Dependencies && "invariant");
2715       } else {
2716         assert(UnscheduledDeps == Dependencies && "invariant");
2717       }
2718 
2719       if (IsScheduled) {
2720         assert(isSchedulingEntity() &&
2721                 "unexpected scheduled state");
2722         for (const ScheduleData *BundleMember = this; BundleMember;
2723              BundleMember = BundleMember->NextInBundle) {
2724           assert(BundleMember->hasValidDependencies() &&
2725                  BundleMember->UnscheduledDeps == 0 &&
2726                  "unexpected scheduled state");
2727           assert((BundleMember == this || !BundleMember->IsScheduled) &&
2728                  "only bundle is marked scheduled");
2729         }
2730       }
2731 
2732       assert(Inst->getParent() == FirstInBundle->Inst->getParent() &&
2733              "all bundle members must be in same basic block");
2734     }
2735 
2736     /// Returns true if the dependency information has been calculated.
2737     /// Note that depenendency validity can vary between instructions within
2738     /// a single bundle.
2739     bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
2740 
2741     /// Returns true for single instructions and for bundle representatives
2742     /// (= the head of a bundle).
2743     bool isSchedulingEntity() const { return FirstInBundle == this; }
2744 
2745     /// Returns true if it represents an instruction bundle and not only a
2746     /// single instruction.
2747     bool isPartOfBundle() const {
2748       return NextInBundle != nullptr || FirstInBundle != this || TE;
2749     }
2750 
2751     /// Returns true if it is ready for scheduling, i.e. it has no more
2752     /// unscheduled depending instructions/bundles.
2753     bool isReady() const {
2754       assert(isSchedulingEntity() &&
2755              "can't consider non-scheduling entity for ready list");
2756       return unscheduledDepsInBundle() == 0 && !IsScheduled;
2757     }
2758 
2759     /// Modifies the number of unscheduled dependencies for this instruction,
2760     /// and returns the number of remaining dependencies for the containing
2761     /// bundle.
2762     int incrementUnscheduledDeps(int Incr) {
2763       assert(hasValidDependencies() &&
2764              "increment of unscheduled deps would be meaningless");
2765       UnscheduledDeps += Incr;
2766       return FirstInBundle->unscheduledDepsInBundle();
2767     }
2768 
2769     /// Sets the number of unscheduled dependencies to the number of
2770     /// dependencies.
2771     void resetUnscheduledDeps() {
2772       UnscheduledDeps = Dependencies;
2773     }
2774 
2775     /// Clears all dependency information.
2776     void clearDependencies() {
2777       Dependencies = InvalidDeps;
2778       resetUnscheduledDeps();
2779       MemoryDependencies.clear();
2780       ControlDependencies.clear();
2781     }
2782 
2783     int unscheduledDepsInBundle() const {
2784       assert(isSchedulingEntity() && "only meaningful on the bundle");
2785       int Sum = 0;
2786       for (const ScheduleData *BundleMember = this; BundleMember;
2787            BundleMember = BundleMember->NextInBundle) {
2788         if (BundleMember->UnscheduledDeps == InvalidDeps)
2789           return InvalidDeps;
2790         Sum += BundleMember->UnscheduledDeps;
2791       }
2792       return Sum;
2793     }
2794 
2795     void dump(raw_ostream &os) const {
2796       if (!isSchedulingEntity()) {
2797         os << "/ " << *Inst;
2798       } else if (NextInBundle) {
2799         os << '[' << *Inst;
2800         ScheduleData *SD = NextInBundle;
2801         while (SD) {
2802           os << ';' << *SD->Inst;
2803           SD = SD->NextInBundle;
2804         }
2805         os << ']';
2806       } else {
2807         os << *Inst;
2808       }
2809     }
2810 
2811     Instruction *Inst = nullptr;
2812 
2813     /// Opcode of the current instruction in the schedule data.
2814     Value *OpValue = nullptr;
2815 
2816     /// The TreeEntry that this instruction corresponds to.
2817     TreeEntry *TE = nullptr;
2818 
2819     /// Points to the head in an instruction bundle (and always to this for
2820     /// single instructions).
2821     ScheduleData *FirstInBundle = nullptr;
2822 
2823     /// Single linked list of all instructions in a bundle. Null if it is a
2824     /// single instruction.
2825     ScheduleData *NextInBundle = nullptr;
2826 
2827     /// Single linked list of all memory instructions (e.g. load, store, call)
2828     /// in the block - until the end of the scheduling region.
2829     ScheduleData *NextLoadStore = nullptr;
2830 
2831     /// The dependent memory instructions.
2832     /// This list is derived on demand in calculateDependencies().
2833     SmallVector<ScheduleData *, 4> MemoryDependencies;
2834 
2835     /// List of instructions which this instruction could be control dependent
2836     /// on.  Allowing such nodes to be scheduled below this one could introduce
2837     /// a runtime fault which didn't exist in the original program.
2838     /// ex: this is a load or udiv following a readonly call which inf loops
2839     SmallVector<ScheduleData *, 4> ControlDependencies;
2840 
2841     /// This ScheduleData is in the current scheduling region if this matches
2842     /// the current SchedulingRegionID of BlockScheduling.
2843     int SchedulingRegionID = 0;
2844 
2845     /// Used for getting a "good" final ordering of instructions.
2846     int SchedulingPriority = 0;
2847 
2848     /// The number of dependencies. Constitutes of the number of users of the
2849     /// instruction plus the number of dependent memory instructions (if any).
2850     /// This value is calculated on demand.
2851     /// If InvalidDeps, the number of dependencies is not calculated yet.
2852     int Dependencies = InvalidDeps;
2853 
2854     /// The number of dependencies minus the number of dependencies of scheduled
2855     /// instructions. As soon as this is zero, the instruction/bundle gets ready
2856     /// for scheduling.
2857     /// Note that this is negative as long as Dependencies is not calculated.
2858     int UnscheduledDeps = InvalidDeps;
2859 
2860     /// True if this instruction is scheduled (or considered as scheduled in the
2861     /// dry-run).
2862     bool IsScheduled = false;
2863   };
2864 
2865 #ifndef NDEBUG
2866   friend inline raw_ostream &operator<<(raw_ostream &os,
2867                                         const BoUpSLP::ScheduleData &SD) {
2868     SD.dump(os);
2869     return os;
2870   }
2871 #endif
2872 
2873   friend struct GraphTraits<BoUpSLP *>;
2874   friend struct DOTGraphTraits<BoUpSLP *>;
2875 
2876   /// Contains all scheduling data for a basic block.
2877   /// It does not schedules instructions, which are not memory read/write
2878   /// instructions and their operands are either constants, or arguments, or
2879   /// phis, or instructions from others blocks, or their users are phis or from
2880   /// the other blocks. The resulting vector instructions can be placed at the
2881   /// beginning of the basic block without scheduling (if operands does not need
2882   /// to be scheduled) or at the end of the block (if users are outside of the
2883   /// block). It allows to save some compile time and memory used by the
2884   /// compiler.
2885   /// ScheduleData is assigned for each instruction in between the boundaries of
2886   /// the tree entry, even for those, which are not part of the graph. It is
2887   /// required to correctly follow the dependencies between the instructions and
2888   /// their correct scheduling. The ScheduleData is not allocated for the
2889   /// instructions, which do not require scheduling, like phis, nodes with
2890   /// extractelements/insertelements only or nodes with instructions, with
2891   /// uses/operands outside of the block.
2892   struct BlockScheduling {
2893     BlockScheduling(BasicBlock *BB)
2894         : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
2895 
2896     void clear() {
2897       ReadyInsts.clear();
2898       ScheduleStart = nullptr;
2899       ScheduleEnd = nullptr;
2900       FirstLoadStoreInRegion = nullptr;
2901       LastLoadStoreInRegion = nullptr;
2902       RegionHasStackSave = false;
2903 
2904       // Reduce the maximum schedule region size by the size of the
2905       // previous scheduling run.
2906       ScheduleRegionSizeLimit -= ScheduleRegionSize;
2907       if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
2908         ScheduleRegionSizeLimit = MinScheduleRegionSize;
2909       ScheduleRegionSize = 0;
2910 
2911       // Make a new scheduling region, i.e. all existing ScheduleData is not
2912       // in the new region yet.
2913       ++SchedulingRegionID;
2914     }
2915 
2916     ScheduleData *getScheduleData(Instruction *I) {
2917       if (BB != I->getParent())
2918         // Avoid lookup if can't possibly be in map.
2919         return nullptr;
2920       ScheduleData *SD = ScheduleDataMap.lookup(I);
2921       if (SD && isInSchedulingRegion(SD))
2922         return SD;
2923       return nullptr;
2924     }
2925 
2926     ScheduleData *getScheduleData(Value *V) {
2927       if (auto *I = dyn_cast<Instruction>(V))
2928         return getScheduleData(I);
2929       return nullptr;
2930     }
2931 
2932     ScheduleData *getScheduleData(Value *V, Value *Key) {
2933       if (V == Key)
2934         return getScheduleData(V);
2935       auto I = ExtraScheduleDataMap.find(V);
2936       if (I != ExtraScheduleDataMap.end()) {
2937         ScheduleData *SD = I->second.lookup(Key);
2938         if (SD && isInSchedulingRegion(SD))
2939           return SD;
2940       }
2941       return nullptr;
2942     }
2943 
2944     bool isInSchedulingRegion(ScheduleData *SD) const {
2945       return SD->SchedulingRegionID == SchedulingRegionID;
2946     }
2947 
2948     /// Marks an instruction as scheduled and puts all dependent ready
2949     /// instructions into the ready-list.
2950     template <typename ReadyListType>
2951     void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
2952       SD->IsScheduled = true;
2953       LLVM_DEBUG(dbgs() << "SLP:   schedule " << *SD << "\n");
2954 
2955       for (ScheduleData *BundleMember = SD; BundleMember;
2956            BundleMember = BundleMember->NextInBundle) {
2957         if (BundleMember->Inst != BundleMember->OpValue)
2958           continue;
2959 
2960         // Handle the def-use chain dependencies.
2961 
2962         // Decrement the unscheduled counter and insert to ready list if ready.
2963         auto &&DecrUnsched = [this, &ReadyList](Instruction *I) {
2964           doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
2965             if (OpDef && OpDef->hasValidDependencies() &&
2966                 OpDef->incrementUnscheduledDeps(-1) == 0) {
2967               // There are no more unscheduled dependencies after
2968               // decrementing, so we can put the dependent instruction
2969               // into the ready list.
2970               ScheduleData *DepBundle = OpDef->FirstInBundle;
2971               assert(!DepBundle->IsScheduled &&
2972                      "already scheduled bundle gets ready");
2973               ReadyList.insert(DepBundle);
2974               LLVM_DEBUG(dbgs()
2975                          << "SLP:    gets ready (def): " << *DepBundle << "\n");
2976             }
2977           });
2978         };
2979 
2980         // If BundleMember is a vector bundle, its operands may have been
2981         // reordered during buildTree(). We therefore need to get its operands
2982         // through the TreeEntry.
2983         if (TreeEntry *TE = BundleMember->TE) {
2984           // Need to search for the lane since the tree entry can be reordered.
2985           int Lane = std::distance(TE->Scalars.begin(),
2986                                    find(TE->Scalars, BundleMember->Inst));
2987           assert(Lane >= 0 && "Lane not set");
2988 
2989           // Since vectorization tree is being built recursively this assertion
2990           // ensures that the tree entry has all operands set before reaching
2991           // this code. Couple of exceptions known at the moment are extracts
2992           // where their second (immediate) operand is not added. Since
2993           // immediates do not affect scheduler behavior this is considered
2994           // okay.
2995           auto *In = BundleMember->Inst;
2996           assert(In &&
2997                  (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) ||
2998                   In->getNumOperands() == TE->getNumOperands()) &&
2999                  "Missed TreeEntry operands?");
3000           (void)In; // fake use to avoid build failure when assertions disabled
3001 
3002           for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands();
3003                OpIdx != NumOperands; ++OpIdx)
3004             if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane]))
3005               DecrUnsched(I);
3006         } else {
3007           // If BundleMember is a stand-alone instruction, no operand reordering
3008           // has taken place, so we directly access its operands.
3009           for (Use &U : BundleMember->Inst->operands())
3010             if (auto *I = dyn_cast<Instruction>(U.get()))
3011               DecrUnsched(I);
3012         }
3013         // Handle the memory dependencies.
3014         for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
3015           if (MemoryDepSD->hasValidDependencies() &&
3016               MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
3017             // There are no more unscheduled dependencies after decrementing,
3018             // so we can put the dependent instruction into the ready list.
3019             ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
3020             assert(!DepBundle->IsScheduled &&
3021                    "already scheduled bundle gets ready");
3022             ReadyList.insert(DepBundle);
3023             LLVM_DEBUG(dbgs()
3024                        << "SLP:    gets ready (mem): " << *DepBundle << "\n");
3025           }
3026         }
3027         // Handle the control dependencies.
3028         for (ScheduleData *DepSD : BundleMember->ControlDependencies) {
3029           if (DepSD->incrementUnscheduledDeps(-1) == 0) {
3030             // There are no more unscheduled dependencies after decrementing,
3031             // so we can put the dependent instruction into the ready list.
3032             ScheduleData *DepBundle = DepSD->FirstInBundle;
3033             assert(!DepBundle->IsScheduled &&
3034                    "already scheduled bundle gets ready");
3035             ReadyList.insert(DepBundle);
3036             LLVM_DEBUG(dbgs()
3037                        << "SLP:    gets ready (ctl): " << *DepBundle << "\n");
3038           }
3039         }
3040 
3041       }
3042     }
3043 
3044     /// Verify basic self consistency properties of the data structure.
3045     void verify() {
3046       if (!ScheduleStart)
3047         return;
3048 
3049       assert(ScheduleStart->getParent() == ScheduleEnd->getParent() &&
3050              ScheduleStart->comesBefore(ScheduleEnd) &&
3051              "Not a valid scheduling region?");
3052 
3053       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
3054         auto *SD = getScheduleData(I);
3055         if (!SD)
3056           continue;
3057         assert(isInSchedulingRegion(SD) &&
3058                "primary schedule data not in window?");
3059         assert(isInSchedulingRegion(SD->FirstInBundle) &&
3060                "entire bundle in window!");
3061         (void)SD;
3062         doForAllOpcodes(I, [](ScheduleData *SD) { SD->verify(); });
3063       }
3064 
3065       for (auto *SD : ReadyInsts) {
3066         assert(SD->isSchedulingEntity() && SD->isReady() &&
3067                "item in ready list not ready?");
3068         (void)SD;
3069       }
3070     }
3071 
3072     void doForAllOpcodes(Value *V,
3073                          function_ref<void(ScheduleData *SD)> Action) {
3074       if (ScheduleData *SD = getScheduleData(V))
3075         Action(SD);
3076       auto I = ExtraScheduleDataMap.find(V);
3077       if (I != ExtraScheduleDataMap.end())
3078         for (auto &P : I->second)
3079           if (isInSchedulingRegion(P.second))
3080             Action(P.second);
3081     }
3082 
3083     /// Put all instructions into the ReadyList which are ready for scheduling.
3084     template <typename ReadyListType>
3085     void initialFillReadyList(ReadyListType &ReadyList) {
3086       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
3087         doForAllOpcodes(I, [&](ScheduleData *SD) {
3088           if (SD->isSchedulingEntity() && SD->hasValidDependencies() &&
3089               SD->isReady()) {
3090             ReadyList.insert(SD);
3091             LLVM_DEBUG(dbgs()
3092                        << "SLP:    initially in ready list: " << *SD << "\n");
3093           }
3094         });
3095       }
3096     }
3097 
3098     /// Build a bundle from the ScheduleData nodes corresponding to the
3099     /// scalar instruction for each lane.
3100     ScheduleData *buildBundle(ArrayRef<Value *> VL);
3101 
3102     /// Checks if a bundle of instructions can be scheduled, i.e. has no
3103     /// cyclic dependencies. This is only a dry-run, no instructions are
3104     /// actually moved at this stage.
3105     /// \returns the scheduling bundle. The returned Optional value is non-None
3106     /// if \p VL is allowed to be scheduled.
3107     Optional<ScheduleData *>
3108     tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
3109                       const InstructionsState &S);
3110 
3111     /// Un-bundles a group of instructions.
3112     void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
3113 
3114     /// Allocates schedule data chunk.
3115     ScheduleData *allocateScheduleDataChunks();
3116 
3117     /// Extends the scheduling region so that V is inside the region.
3118     /// \returns true if the region size is within the limit.
3119     bool extendSchedulingRegion(Value *V, const InstructionsState &S);
3120 
3121     /// Initialize the ScheduleData structures for new instructions in the
3122     /// scheduling region.
3123     void initScheduleData(Instruction *FromI, Instruction *ToI,
3124                           ScheduleData *PrevLoadStore,
3125                           ScheduleData *NextLoadStore);
3126 
3127     /// Updates the dependency information of a bundle and of all instructions/
3128     /// bundles which depend on the original bundle.
3129     void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
3130                                BoUpSLP *SLP);
3131 
3132     /// Sets all instruction in the scheduling region to un-scheduled.
3133     void resetSchedule();
3134 
3135     BasicBlock *BB;
3136 
3137     /// Simple memory allocation for ScheduleData.
3138     std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
3139 
3140     /// The size of a ScheduleData array in ScheduleDataChunks.
3141     int ChunkSize;
3142 
3143     /// The allocator position in the current chunk, which is the last entry
3144     /// of ScheduleDataChunks.
3145     int ChunkPos;
3146 
3147     /// Attaches ScheduleData to Instruction.
3148     /// Note that the mapping survives during all vectorization iterations, i.e.
3149     /// ScheduleData structures are recycled.
3150     DenseMap<Instruction *, ScheduleData *> ScheduleDataMap;
3151 
3152     /// Attaches ScheduleData to Instruction with the leading key.
3153     DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
3154         ExtraScheduleDataMap;
3155 
3156     /// The ready-list for scheduling (only used for the dry-run).
3157     SetVector<ScheduleData *> ReadyInsts;
3158 
3159     /// The first instruction of the scheduling region.
3160     Instruction *ScheduleStart = nullptr;
3161 
3162     /// The first instruction _after_ the scheduling region.
3163     Instruction *ScheduleEnd = nullptr;
3164 
3165     /// The first memory accessing instruction in the scheduling region
3166     /// (can be null).
3167     ScheduleData *FirstLoadStoreInRegion = nullptr;
3168 
3169     /// The last memory accessing instruction in the scheduling region
3170     /// (can be null).
3171     ScheduleData *LastLoadStoreInRegion = nullptr;
3172 
3173     /// Is there an llvm.stacksave or llvm.stackrestore in the scheduling
3174     /// region?  Used to optimize the dependence calculation for the
3175     /// common case where there isn't.
3176     bool RegionHasStackSave = false;
3177 
3178     /// The current size of the scheduling region.
3179     int ScheduleRegionSize = 0;
3180 
3181     /// The maximum size allowed for the scheduling region.
3182     int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
3183 
3184     /// The ID of the scheduling region. For a new vectorization iteration this
3185     /// is incremented which "removes" all ScheduleData from the region.
3186     /// Make sure that the initial SchedulingRegionID is greater than the
3187     /// initial SchedulingRegionID in ScheduleData (which is 0).
3188     int SchedulingRegionID = 1;
3189   };
3190 
3191   /// Attaches the BlockScheduling structures to basic blocks.
3192   MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
3193 
3194   /// Performs the "real" scheduling. Done before vectorization is actually
3195   /// performed in a basic block.
3196   void scheduleBlock(BlockScheduling *BS);
3197 
3198   /// List of users to ignore during scheduling and that don't need extracting.
3199   const SmallDenseSet<Value *> *UserIgnoreList = nullptr;
3200 
3201   /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
3202   /// sorted SmallVectors of unsigned.
3203   struct OrdersTypeDenseMapInfo {
3204     static OrdersType getEmptyKey() {
3205       OrdersType V;
3206       V.push_back(~1U);
3207       return V;
3208     }
3209 
3210     static OrdersType getTombstoneKey() {
3211       OrdersType V;
3212       V.push_back(~2U);
3213       return V;
3214     }
3215 
3216     static unsigned getHashValue(const OrdersType &V) {
3217       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
3218     }
3219 
3220     static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
3221       return LHS == RHS;
3222     }
3223   };
3224 
3225   // Analysis and block reference.
3226   Function *F;
3227   ScalarEvolution *SE;
3228   TargetTransformInfo *TTI;
3229   TargetLibraryInfo *TLI;
3230   LoopInfo *LI;
3231   DominatorTree *DT;
3232   AssumptionCache *AC;
3233   DemandedBits *DB;
3234   const DataLayout *DL;
3235   OptimizationRemarkEmitter *ORE;
3236 
3237   unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
3238   unsigned MinVecRegSize; // Set by cl::opt (default: 128).
3239 
3240   /// Instruction builder to construct the vectorized tree.
3241   IRBuilder<> Builder;
3242 
3243   /// A map of scalar integer values to the smallest bit width with which they
3244   /// can legally be represented. The values map to (width, signed) pairs,
3245   /// where "width" indicates the minimum bit width and "signed" is True if the
3246   /// value must be signed-extended, rather than zero-extended, back to its
3247   /// original width.
3248   MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
3249 };
3250 
3251 } // end namespace slpvectorizer
3252 
3253 template <> struct GraphTraits<BoUpSLP *> {
3254   using TreeEntry = BoUpSLP::TreeEntry;
3255 
3256   /// NodeRef has to be a pointer per the GraphWriter.
3257   using NodeRef = TreeEntry *;
3258 
3259   using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy;
3260 
3261   /// Add the VectorizableTree to the index iterator to be able to return
3262   /// TreeEntry pointers.
3263   struct ChildIteratorType
3264       : public iterator_adaptor_base<
3265             ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
3266     ContainerTy &VectorizableTree;
3267 
3268     ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W,
3269                       ContainerTy &VT)
3270         : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
3271 
3272     NodeRef operator*() { return I->UserTE; }
3273   };
3274 
3275   static NodeRef getEntryNode(BoUpSLP &R) {
3276     return R.VectorizableTree[0].get();
3277   }
3278 
3279   static ChildIteratorType child_begin(NodeRef N) {
3280     return {N->UserTreeIndices.begin(), N->Container};
3281   }
3282 
3283   static ChildIteratorType child_end(NodeRef N) {
3284     return {N->UserTreeIndices.end(), N->Container};
3285   }
3286 
3287   /// For the node iterator we just need to turn the TreeEntry iterator into a
3288   /// TreeEntry* iterator so that it dereferences to NodeRef.
3289   class nodes_iterator {
3290     using ItTy = ContainerTy::iterator;
3291     ItTy It;
3292 
3293   public:
3294     nodes_iterator(const ItTy &It2) : It(It2) {}
3295     NodeRef operator*() { return It->get(); }
3296     nodes_iterator operator++() {
3297       ++It;
3298       return *this;
3299     }
3300     bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
3301   };
3302 
3303   static nodes_iterator nodes_begin(BoUpSLP *R) {
3304     return nodes_iterator(R->VectorizableTree.begin());
3305   }
3306 
3307   static nodes_iterator nodes_end(BoUpSLP *R) {
3308     return nodes_iterator(R->VectorizableTree.end());
3309   }
3310 
3311   static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
3312 };
3313 
3314 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
3315   using TreeEntry = BoUpSLP::TreeEntry;
3316 
3317   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
3318 
3319   std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
3320     std::string Str;
3321     raw_string_ostream OS(Str);
3322     if (isSplat(Entry->Scalars))
3323       OS << "<splat> ";
3324     for (auto V : Entry->Scalars) {
3325       OS << *V;
3326       if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) {
3327             return EU.Scalar == V;
3328           }))
3329         OS << " <extract>";
3330       OS << "\n";
3331     }
3332     return Str;
3333   }
3334 
3335   static std::string getNodeAttributes(const TreeEntry *Entry,
3336                                        const BoUpSLP *) {
3337     if (Entry->State == TreeEntry::NeedToGather)
3338       return "color=red";
3339     return "";
3340   }
3341 };
3342 
3343 } // end namespace llvm
3344 
3345 BoUpSLP::~BoUpSLP() {
3346   SmallVector<WeakTrackingVH> DeadInsts;
3347   for (auto *I : DeletedInstructions) {
3348     for (Use &U : I->operands()) {
3349       auto *Op = dyn_cast<Instruction>(U.get());
3350       if (Op && !DeletedInstructions.count(Op) && Op->hasOneUser() &&
3351           wouldInstructionBeTriviallyDead(Op, TLI))
3352         DeadInsts.emplace_back(Op);
3353     }
3354     I->dropAllReferences();
3355   }
3356   for (auto *I : DeletedInstructions) {
3357     assert(I->use_empty() &&
3358            "trying to erase instruction with users.");
3359     I->eraseFromParent();
3360   }
3361 
3362   // Cleanup any dead scalar code feeding the vectorized instructions
3363   RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI);
3364 
3365 #ifdef EXPENSIVE_CHECKS
3366   // If we could guarantee that this call is not extremely slow, we could
3367   // remove the ifdef limitation (see PR47712).
3368   assert(!verifyFunction(*F, &dbgs()));
3369 #endif
3370 }
3371 
3372 /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses
3373 /// contains original mask for the scalars reused in the node. Procedure
3374 /// transform this mask in accordance with the given \p Mask.
3375 static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) {
3376   assert(!Mask.empty() && Reuses.size() == Mask.size() &&
3377          "Expected non-empty mask.");
3378   SmallVector<int> Prev(Reuses.begin(), Reuses.end());
3379   Prev.swap(Reuses);
3380   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
3381     if (Mask[I] != UndefMaskElem)
3382       Reuses[Mask[I]] = Prev[I];
3383 }
3384 
3385 /// Reorders the given \p Order according to the given \p Mask. \p Order - is
3386 /// the original order of the scalars. Procedure transforms the provided order
3387 /// in accordance with the given \p Mask. If the resulting \p Order is just an
3388 /// identity order, \p Order is cleared.
3389 static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) {
3390   assert(!Mask.empty() && "Expected non-empty mask.");
3391   SmallVector<int> MaskOrder;
3392   if (Order.empty()) {
3393     MaskOrder.resize(Mask.size());
3394     std::iota(MaskOrder.begin(), MaskOrder.end(), 0);
3395   } else {
3396     inversePermutation(Order, MaskOrder);
3397   }
3398   reorderReuses(MaskOrder, Mask);
3399   if (ShuffleVectorInst::isIdentityMask(MaskOrder)) {
3400     Order.clear();
3401     return;
3402   }
3403   Order.assign(Mask.size(), Mask.size());
3404   for (unsigned I = 0, E = Mask.size(); I < E; ++I)
3405     if (MaskOrder[I] != UndefMaskElem)
3406       Order[MaskOrder[I]] = I;
3407   fixupOrderingIndices(Order);
3408 }
3409 
3410 Optional<BoUpSLP::OrdersType>
3411 BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) {
3412   assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
3413   unsigned NumScalars = TE.Scalars.size();
3414   OrdersType CurrentOrder(NumScalars, NumScalars);
3415   SmallVector<int> Positions;
3416   SmallBitVector UsedPositions(NumScalars);
3417   const TreeEntry *STE = nullptr;
3418   // Try to find all gathered scalars that are gets vectorized in other
3419   // vectorize node. Here we can have only one single tree vector node to
3420   // correctly identify order of the gathered scalars.
3421   for (unsigned I = 0; I < NumScalars; ++I) {
3422     Value *V = TE.Scalars[I];
3423     if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V))
3424       continue;
3425     if (const auto *LocalSTE = getTreeEntry(V)) {
3426       if (!STE)
3427         STE = LocalSTE;
3428       else if (STE != LocalSTE)
3429         // Take the order only from the single vector node.
3430         return None;
3431       unsigned Lane =
3432           std::distance(STE->Scalars.begin(), find(STE->Scalars, V));
3433       if (Lane >= NumScalars)
3434         return None;
3435       if (CurrentOrder[Lane] != NumScalars) {
3436         if (Lane != I)
3437           continue;
3438         UsedPositions.reset(CurrentOrder[Lane]);
3439       }
3440       // The partial identity (where only some elements of the gather node are
3441       // in the identity order) is good.
3442       CurrentOrder[Lane] = I;
3443       UsedPositions.set(I);
3444     }
3445   }
3446   // Need to keep the order if we have a vector entry and at least 2 scalars or
3447   // the vectorized entry has just 2 scalars.
3448   if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) {
3449     auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) {
3450       for (unsigned I = 0; I < NumScalars; ++I)
3451         if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars)
3452           return false;
3453       return true;
3454     };
3455     if (IsIdentityOrder(CurrentOrder)) {
3456       CurrentOrder.clear();
3457       return CurrentOrder;
3458     }
3459     auto *It = CurrentOrder.begin();
3460     for (unsigned I = 0; I < NumScalars;) {
3461       if (UsedPositions.test(I)) {
3462         ++I;
3463         continue;
3464       }
3465       if (*It == NumScalars) {
3466         *It = I;
3467         ++I;
3468       }
3469       ++It;
3470     }
3471     return CurrentOrder;
3472   }
3473   return None;
3474 }
3475 
3476 namespace {
3477 /// Tracks the state we can represent the loads in the given sequence.
3478 enum class LoadsState { Gather, Vectorize, ScatterVectorize };
3479 } // anonymous namespace
3480 
3481 /// Checks if the given array of loads can be represented as a vectorized,
3482 /// scatter or just simple gather.
3483 static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0,
3484                                     const TargetTransformInfo &TTI,
3485                                     const DataLayout &DL, ScalarEvolution &SE,
3486                                     SmallVectorImpl<unsigned> &Order,
3487                                     SmallVectorImpl<Value *> &PointerOps) {
3488   // Check that a vectorized load would load the same memory as a scalar
3489   // load. For example, we don't want to vectorize loads that are smaller
3490   // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
3491   // treats loading/storing it as an i8 struct. If we vectorize loads/stores
3492   // from such a struct, we read/write packed bits disagreeing with the
3493   // unvectorized version.
3494   Type *ScalarTy = VL0->getType();
3495 
3496   if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy))
3497     return LoadsState::Gather;
3498 
3499   // Make sure all loads in the bundle are simple - we can't vectorize
3500   // atomic or volatile loads.
3501   PointerOps.clear();
3502   PointerOps.resize(VL.size());
3503   auto *POIter = PointerOps.begin();
3504   for (Value *V : VL) {
3505     auto *L = cast<LoadInst>(V);
3506     if (!L->isSimple())
3507       return LoadsState::Gather;
3508     *POIter = L->getPointerOperand();
3509     ++POIter;
3510   }
3511 
3512   Order.clear();
3513   // Check the order of pointer operands.
3514   if (llvm::sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order)) {
3515     Value *Ptr0;
3516     Value *PtrN;
3517     if (Order.empty()) {
3518       Ptr0 = PointerOps.front();
3519       PtrN = PointerOps.back();
3520     } else {
3521       Ptr0 = PointerOps[Order.front()];
3522       PtrN = PointerOps[Order.back()];
3523     }
3524     Optional<int> Diff =
3525         getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE);
3526     // Check that the sorted loads are consecutive.
3527     if (static_cast<unsigned>(*Diff) == VL.size() - 1)
3528       return LoadsState::Vectorize;
3529     Align CommonAlignment = cast<LoadInst>(VL0)->getAlign();
3530     for (Value *V : VL)
3531       CommonAlignment =
3532           commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
3533     auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
3534     if (TTI.isLegalMaskedGather(VecTy, CommonAlignment) &&
3535         !TTI.forceScalarizeMaskedGather(VecTy, CommonAlignment))
3536       return LoadsState::ScatterVectorize;
3537   }
3538 
3539   return LoadsState::Gather;
3540 }
3541 
3542 bool clusterSortPtrAccesses(ArrayRef<Value *> VL, Type *ElemTy,
3543                             const DataLayout &DL, ScalarEvolution &SE,
3544                             SmallVectorImpl<unsigned> &SortedIndices) {
3545   assert(llvm::all_of(
3546              VL, [](const Value *V) { return V->getType()->isPointerTy(); }) &&
3547          "Expected list of pointer operands.");
3548   // Map from bases to a vector of (Ptr, Offset, OrigIdx), which we insert each
3549   // Ptr into, sort and return the sorted indices with values next to one
3550   // another.
3551   MapVector<Value *, SmallVector<std::tuple<Value *, int, unsigned>>> Bases;
3552   Bases[VL[0]].push_back(std::make_tuple(VL[0], 0U, 0U));
3553 
3554   unsigned Cnt = 1;
3555   for (Value *Ptr : VL.drop_front()) {
3556     bool Found = any_of(Bases, [&](auto &Base) {
3557       Optional<int> Diff =
3558           getPointersDiff(ElemTy, Base.first, ElemTy, Ptr, DL, SE,
3559                           /*StrictCheck=*/true);
3560       if (!Diff)
3561         return false;
3562 
3563       Base.second.emplace_back(Ptr, *Diff, Cnt++);
3564       return true;
3565     });
3566 
3567     if (!Found) {
3568       // If we haven't found enough to usefully cluster, return early.
3569       if (Bases.size() > VL.size() / 2 - 1)
3570         return false;
3571 
3572       // Not found already - add a new Base
3573       Bases[Ptr].emplace_back(Ptr, 0, Cnt++);
3574     }
3575   }
3576 
3577   // For each of the bases sort the pointers by Offset and check if any of the
3578   // base become consecutively allocated.
3579   bool AnyConsecutive = false;
3580   for (auto &Base : Bases) {
3581     auto &Vec = Base.second;
3582     if (Vec.size() > 1) {
3583       llvm::stable_sort(Vec, [](const std::tuple<Value *, int, unsigned> &X,
3584                                 const std::tuple<Value *, int, unsigned> &Y) {
3585         return std::get<1>(X) < std::get<1>(Y);
3586       });
3587       int InitialOffset = std::get<1>(Vec[0]);
3588       AnyConsecutive |= all_of(enumerate(Vec), [InitialOffset](auto &P) {
3589         return std::get<1>(P.value()) == int(P.index()) + InitialOffset;
3590       });
3591     }
3592   }
3593 
3594   // Fill SortedIndices array only if it looks worth-while to sort the ptrs.
3595   SortedIndices.clear();
3596   if (!AnyConsecutive)
3597     return false;
3598 
3599   for (auto &Base : Bases) {
3600     for (auto &T : Base.second)
3601       SortedIndices.push_back(std::get<2>(T));
3602   }
3603 
3604   assert(SortedIndices.size() == VL.size() &&
3605          "Expected SortedIndices to be the size of VL");
3606   return true;
3607 }
3608 
3609 Optional<BoUpSLP::OrdersType>
3610 BoUpSLP::findPartiallyOrderedLoads(const BoUpSLP::TreeEntry &TE) {
3611   assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
3612   Type *ScalarTy = TE.Scalars[0]->getType();
3613 
3614   SmallVector<Value *> Ptrs;
3615   Ptrs.reserve(TE.Scalars.size());
3616   for (Value *V : TE.Scalars) {
3617     auto *L = dyn_cast<LoadInst>(V);
3618     if (!L || !L->isSimple())
3619       return None;
3620     Ptrs.push_back(L->getPointerOperand());
3621   }
3622 
3623   BoUpSLP::OrdersType Order;
3624   if (clusterSortPtrAccesses(Ptrs, ScalarTy, *DL, *SE, Order))
3625     return Order;
3626   return None;
3627 }
3628 
3629 Optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE,
3630                                                          bool TopToBottom) {
3631   // No need to reorder if need to shuffle reuses, still need to shuffle the
3632   // node.
3633   if (!TE.ReuseShuffleIndices.empty())
3634     return None;
3635   if (TE.State == TreeEntry::Vectorize &&
3636       (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) ||
3637        (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) &&
3638       !TE.isAltShuffle())
3639     return TE.ReorderIndices;
3640   if (TE.State == TreeEntry::NeedToGather) {
3641     // TODO: add analysis of other gather nodes with extractelement
3642     // instructions and other values/instructions, not only undefs.
3643     if (((TE.getOpcode() == Instruction::ExtractElement &&
3644           !TE.isAltShuffle()) ||
3645          (all_of(TE.Scalars,
3646                  [](Value *V) {
3647                    return isa<UndefValue, ExtractElementInst>(V);
3648                  }) &&
3649           any_of(TE.Scalars,
3650                  [](Value *V) { return isa<ExtractElementInst>(V); }))) &&
3651         all_of(TE.Scalars,
3652                [](Value *V) {
3653                  auto *EE = dyn_cast<ExtractElementInst>(V);
3654                  return !EE || isa<FixedVectorType>(EE->getVectorOperandType());
3655                }) &&
3656         allSameType(TE.Scalars)) {
3657       // Check that gather of extractelements can be represented as
3658       // just a shuffle of a single vector.
3659       OrdersType CurrentOrder;
3660       bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder);
3661       if (Reuse || !CurrentOrder.empty()) {
3662         if (!CurrentOrder.empty())
3663           fixupOrderingIndices(CurrentOrder);
3664         return CurrentOrder;
3665       }
3666     }
3667     if (Optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE))
3668       return CurrentOrder;
3669     if (TE.Scalars.size() >= 4)
3670       if (Optional<OrdersType> Order = findPartiallyOrderedLoads(TE))
3671         return Order;
3672   }
3673   return None;
3674 }
3675 
3676 void BoUpSLP::reorderTopToBottom() {
3677   // Maps VF to the graph nodes.
3678   DenseMap<unsigned, SetVector<TreeEntry *>> VFToOrderedEntries;
3679   // ExtractElement gather nodes which can be vectorized and need to handle
3680   // their ordering.
3681   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3682 
3683   // Maps a TreeEntry to the reorder indices of external users.
3684   DenseMap<const TreeEntry *, SmallVector<OrdersType, 1>>
3685       ExternalUserReorderMap;
3686   // Find all reorderable nodes with the given VF.
3687   // Currently the are vectorized stores,loads,extracts + some gathering of
3688   // extracts.
3689   for_each(VectorizableTree, [this, &VFToOrderedEntries, &GathersToOrders,
3690                               &ExternalUserReorderMap](
3691                                  const std::unique_ptr<TreeEntry> &TE) {
3692     // Look for external users that will probably be vectorized.
3693     SmallVector<OrdersType, 1> ExternalUserReorderIndices =
3694         findExternalStoreUsersReorderIndices(TE.get());
3695     if (!ExternalUserReorderIndices.empty()) {
3696       VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
3697       ExternalUserReorderMap.try_emplace(TE.get(),
3698                                          std::move(ExternalUserReorderIndices));
3699     }
3700 
3701     if (Optional<OrdersType> CurrentOrder =
3702             getReorderingData(*TE, /*TopToBottom=*/true)) {
3703       // Do not include ordering for nodes used in the alt opcode vectorization,
3704       // better to reorder them during bottom-to-top stage. If follow the order
3705       // here, it causes reordering of the whole graph though actually it is
3706       // profitable just to reorder the subgraph that starts from the alternate
3707       // opcode vectorization node. Such nodes already end-up with the shuffle
3708       // instruction and it is just enough to change this shuffle rather than
3709       // rotate the scalars for the whole graph.
3710       unsigned Cnt = 0;
3711       const TreeEntry *UserTE = TE.get();
3712       while (UserTE && Cnt < RecursionMaxDepth) {
3713         if (UserTE->UserTreeIndices.size() != 1)
3714           break;
3715         if (all_of(UserTE->UserTreeIndices, [](const EdgeInfo &EI) {
3716               return EI.UserTE->State == TreeEntry::Vectorize &&
3717                      EI.UserTE->isAltShuffle() && EI.UserTE->Idx != 0;
3718             }))
3719           return;
3720         if (UserTE->UserTreeIndices.empty())
3721           UserTE = nullptr;
3722         else
3723           UserTE = UserTE->UserTreeIndices.back().UserTE;
3724         ++Cnt;
3725       }
3726       VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
3727       if (TE->State != TreeEntry::Vectorize)
3728         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3729     }
3730   });
3731 
3732   // Reorder the graph nodes according to their vectorization factor.
3733   for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1;
3734        VF /= 2) {
3735     auto It = VFToOrderedEntries.find(VF);
3736     if (It == VFToOrderedEntries.end())
3737       continue;
3738     // Try to find the most profitable order. We just are looking for the most
3739     // used order and reorder scalar elements in the nodes according to this
3740     // mostly used order.
3741     ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef();
3742     // All operands are reordered and used only in this node - propagate the
3743     // most used order to the user node.
3744     MapVector<OrdersType, unsigned,
3745               DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3746         OrdersUses;
3747     SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3748     for (const TreeEntry *OpTE : OrderedEntries) {
3749       // No need to reorder this nodes, still need to extend and to use shuffle,
3750       // just need to merge reordering shuffle and the reuse shuffle.
3751       if (!OpTE->ReuseShuffleIndices.empty())
3752         continue;
3753       // Count number of orders uses.
3754       const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3755         if (OpTE->State == TreeEntry::NeedToGather) {
3756           auto It = GathersToOrders.find(OpTE);
3757           if (It != GathersToOrders.end())
3758             return It->second;
3759         }
3760         return OpTE->ReorderIndices;
3761       }();
3762       // First consider the order of the external scalar users.
3763       auto It = ExternalUserReorderMap.find(OpTE);
3764       if (It != ExternalUserReorderMap.end()) {
3765         const auto &ExternalUserReorderIndices = It->second;
3766         for (const OrdersType &ExtOrder : ExternalUserReorderIndices)
3767           ++OrdersUses.insert(std::make_pair(ExtOrder, 0)).first->second;
3768         // No other useful reorder data in this entry.
3769         if (Order.empty())
3770           continue;
3771       }
3772       // Stores actually store the mask, not the order, need to invert.
3773       if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3774           OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3775         SmallVector<int> Mask;
3776         inversePermutation(Order, Mask);
3777         unsigned E = Order.size();
3778         OrdersType CurrentOrder(E, E);
3779         transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3780           return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3781         });
3782         fixupOrderingIndices(CurrentOrder);
3783         ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
3784       } else {
3785         ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
3786       }
3787     }
3788     // Set order of the user node.
3789     if (OrdersUses.empty())
3790       continue;
3791     // Choose the most used order.
3792     ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3793     unsigned Cnt = OrdersUses.front().second;
3794     for (const auto &Pair : drop_begin(OrdersUses)) {
3795       if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3796         BestOrder = Pair.first;
3797         Cnt = Pair.second;
3798       }
3799     }
3800     // Set order of the user node.
3801     if (BestOrder.empty())
3802       continue;
3803     SmallVector<int> Mask;
3804     inversePermutation(BestOrder, Mask);
3805     SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3806     unsigned E = BestOrder.size();
3807     transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3808       return I < E ? static_cast<int>(I) : UndefMaskElem;
3809     });
3810     // Do an actual reordering, if profitable.
3811     for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
3812       // Just do the reordering for the nodes with the given VF.
3813       if (TE->Scalars.size() != VF) {
3814         if (TE->ReuseShuffleIndices.size() == VF) {
3815           // Need to reorder the reuses masks of the operands with smaller VF to
3816           // be able to find the match between the graph nodes and scalar
3817           // operands of the given node during vectorization/cost estimation.
3818           assert(all_of(TE->UserTreeIndices,
3819                         [VF, &TE](const EdgeInfo &EI) {
3820                           return EI.UserTE->Scalars.size() == VF ||
3821                                  EI.UserTE->Scalars.size() ==
3822                                      TE->Scalars.size();
3823                         }) &&
3824                  "All users must be of VF size.");
3825           // Update ordering of the operands with the smaller VF than the given
3826           // one.
3827           reorderReuses(TE->ReuseShuffleIndices, Mask);
3828         }
3829         continue;
3830       }
3831       if (TE->State == TreeEntry::Vectorize &&
3832           isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst,
3833               InsertElementInst>(TE->getMainOp()) &&
3834           !TE->isAltShuffle()) {
3835         // Build correct orders for extract{element,value}, loads and
3836         // stores.
3837         reorderOrder(TE->ReorderIndices, Mask);
3838         if (isa<InsertElementInst, StoreInst>(TE->getMainOp()))
3839           TE->reorderOperands(Mask);
3840       } else {
3841         // Reorder the node and its operands.
3842         TE->reorderOperands(Mask);
3843         assert(TE->ReorderIndices.empty() &&
3844                "Expected empty reorder sequence.");
3845         reorderScalars(TE->Scalars, Mask);
3846       }
3847       if (!TE->ReuseShuffleIndices.empty()) {
3848         // Apply reversed order to keep the original ordering of the reused
3849         // elements to avoid extra reorder indices shuffling.
3850         OrdersType CurrentOrder;
3851         reorderOrder(CurrentOrder, MaskOrder);
3852         SmallVector<int> NewReuses;
3853         inversePermutation(CurrentOrder, NewReuses);
3854         addMask(NewReuses, TE->ReuseShuffleIndices);
3855         TE->ReuseShuffleIndices.swap(NewReuses);
3856       }
3857     }
3858   }
3859 }
3860 
3861 bool BoUpSLP::canReorderOperands(
3862     TreeEntry *UserTE, SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
3863     ArrayRef<TreeEntry *> ReorderableGathers,
3864     SmallVectorImpl<TreeEntry *> &GatherOps) {
3865   for (unsigned I = 0, E = UserTE->getNumOperands(); I < E; ++I) {
3866     if (any_of(Edges, [I](const std::pair<unsigned, TreeEntry *> &OpData) {
3867           return OpData.first == I &&
3868                  OpData.second->State == TreeEntry::Vectorize;
3869         }))
3870       continue;
3871     if (TreeEntry *TE = getVectorizedOperand(UserTE, I)) {
3872       // Do not reorder if operand node is used by many user nodes.
3873       if (any_of(TE->UserTreeIndices,
3874                  [UserTE](const EdgeInfo &EI) { return EI.UserTE != UserTE; }))
3875         return false;
3876       // Add the node to the list of the ordered nodes with the identity
3877       // order.
3878       Edges.emplace_back(I, TE);
3879       // Add ScatterVectorize nodes to the list of operands, where just
3880       // reordering of the scalars is required. Similar to the gathers, so
3881       // simply add to the list of gathered ops.
3882       if (TE->State != TreeEntry::Vectorize)
3883         GatherOps.push_back(TE);
3884       continue;
3885     }
3886     ArrayRef<Value *> VL = UserTE->getOperand(I);
3887     TreeEntry *Gather = nullptr;
3888     if (count_if(ReorderableGathers, [VL, &Gather](TreeEntry *TE) {
3889           assert(TE->State != TreeEntry::Vectorize &&
3890                  "Only non-vectorized nodes are expected.");
3891           if (TE->isSame(VL)) {
3892             Gather = TE;
3893             return true;
3894           }
3895           return false;
3896         }) > 1)
3897       return false;
3898     if (Gather)
3899       GatherOps.push_back(Gather);
3900   }
3901   return true;
3902 }
3903 
3904 void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) {
3905   SetVector<TreeEntry *> OrderedEntries;
3906   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3907   // Find all reorderable leaf nodes with the given VF.
3908   // Currently the are vectorized loads,extracts without alternate operands +
3909   // some gathering of extracts.
3910   SmallVector<TreeEntry *> NonVectorized;
3911   for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders,
3912                               &NonVectorized](
3913                                  const std::unique_ptr<TreeEntry> &TE) {
3914     if (TE->State != TreeEntry::Vectorize)
3915       NonVectorized.push_back(TE.get());
3916     if (Optional<OrdersType> CurrentOrder =
3917             getReorderingData(*TE, /*TopToBottom=*/false)) {
3918       OrderedEntries.insert(TE.get());
3919       if (TE->State != TreeEntry::Vectorize)
3920         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3921     }
3922   });
3923 
3924   // 1. Propagate order to the graph nodes, which use only reordered nodes.
3925   // I.e., if the node has operands, that are reordered, try to make at least
3926   // one operand order in the natural order and reorder others + reorder the
3927   // user node itself.
3928   SmallPtrSet<const TreeEntry *, 4> Visited;
3929   while (!OrderedEntries.empty()) {
3930     // 1. Filter out only reordered nodes.
3931     // 2. If the entry has multiple uses - skip it and jump to the next node.
3932     DenseMap<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users;
3933     SmallVector<TreeEntry *> Filtered;
3934     for (TreeEntry *TE : OrderedEntries) {
3935       if (!(TE->State == TreeEntry::Vectorize ||
3936             (TE->State == TreeEntry::NeedToGather &&
3937              GathersToOrders.count(TE))) ||
3938           TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3939           !all_of(drop_begin(TE->UserTreeIndices),
3940                   [TE](const EdgeInfo &EI) {
3941                     return EI.UserTE == TE->UserTreeIndices.front().UserTE;
3942                   }) ||
3943           !Visited.insert(TE).second) {
3944         Filtered.push_back(TE);
3945         continue;
3946       }
3947       // Build a map between user nodes and their operands order to speedup
3948       // search. The graph currently does not provide this dependency directly.
3949       for (EdgeInfo &EI : TE->UserTreeIndices) {
3950         TreeEntry *UserTE = EI.UserTE;
3951         auto It = Users.find(UserTE);
3952         if (It == Users.end())
3953           It = Users.insert({UserTE, {}}).first;
3954         It->second.emplace_back(EI.EdgeIdx, TE);
3955       }
3956     }
3957     // Erase filtered entries.
3958     for_each(Filtered,
3959              [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); });
3960     SmallVector<
3961         std::pair<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>>>
3962         UsersVec(Users.begin(), Users.end());
3963     sort(UsersVec, [](const auto &Data1, const auto &Data2) {
3964       return Data1.first->Idx > Data2.first->Idx;
3965     });
3966     for (auto &Data : UsersVec) {
3967       // Check that operands are used only in the User node.
3968       SmallVector<TreeEntry *> GatherOps;
3969       if (!canReorderOperands(Data.first, Data.second, NonVectorized,
3970                               GatherOps)) {
3971         for_each(Data.second,
3972                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3973                    OrderedEntries.remove(Op.second);
3974                  });
3975         continue;
3976       }
3977       // All operands are reordered and used only in this node - propagate the
3978       // most used order to the user node.
3979       MapVector<OrdersType, unsigned,
3980                 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3981           OrdersUses;
3982       // Do the analysis for each tree entry only once, otherwise the order of
3983       // the same node my be considered several times, though might be not
3984       // profitable.
3985       SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3986       SmallPtrSet<const TreeEntry *, 4> VisitedUsers;
3987       for (const auto &Op : Data.second) {
3988         TreeEntry *OpTE = Op.second;
3989         if (!VisitedOps.insert(OpTE).second)
3990           continue;
3991         if (!OpTE->ReuseShuffleIndices.empty() ||
3992             (IgnoreReorder && OpTE == VectorizableTree.front().get()))
3993           continue;
3994         const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3995           if (OpTE->State == TreeEntry::NeedToGather)
3996             return GathersToOrders.find(OpTE)->second;
3997           return OpTE->ReorderIndices;
3998         }();
3999         unsigned NumOps = count_if(
4000             Data.second, [OpTE](const std::pair<unsigned, TreeEntry *> &P) {
4001               return P.second == OpTE;
4002             });
4003         // Stores actually store the mask, not the order, need to invert.
4004         if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
4005             OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
4006           SmallVector<int> Mask;
4007           inversePermutation(Order, Mask);
4008           unsigned E = Order.size();
4009           OrdersType CurrentOrder(E, E);
4010           transform(Mask, CurrentOrder.begin(), [E](int Idx) {
4011             return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
4012           });
4013           fixupOrderingIndices(CurrentOrder);
4014           OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second +=
4015               NumOps;
4016         } else {
4017           OrdersUses.insert(std::make_pair(Order, 0)).first->second += NumOps;
4018         }
4019         auto Res = OrdersUses.insert(std::make_pair(OrdersType(), 0));
4020         const auto &&AllowsReordering = [IgnoreReorder, &GathersToOrders](
4021                                             const TreeEntry *TE) {
4022           if (!TE->ReorderIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
4023               (TE->State == TreeEntry::Vectorize && TE->isAltShuffle()) ||
4024               (IgnoreReorder && TE->Idx == 0))
4025             return true;
4026           if (TE->State == TreeEntry::NeedToGather) {
4027             auto It = GathersToOrders.find(TE);
4028             if (It != GathersToOrders.end())
4029               return !It->second.empty();
4030             return true;
4031           }
4032           return false;
4033         };
4034         for (const EdgeInfo &EI : OpTE->UserTreeIndices) {
4035           TreeEntry *UserTE = EI.UserTE;
4036           if (!VisitedUsers.insert(UserTE).second)
4037             continue;
4038           // May reorder user node if it requires reordering, has reused
4039           // scalars, is an alternate op vectorize node or its op nodes require
4040           // reordering.
4041           if (AllowsReordering(UserTE))
4042             continue;
4043           // Check if users allow reordering.
4044           // Currently look up just 1 level of operands to avoid increase of
4045           // the compile time.
4046           // Profitable to reorder if definitely more operands allow
4047           // reordering rather than those with natural order.
4048           ArrayRef<std::pair<unsigned, TreeEntry *>> Ops = Users[UserTE];
4049           if (static_cast<unsigned>(count_if(
4050                   Ops, [UserTE, &AllowsReordering](
4051                            const std::pair<unsigned, TreeEntry *> &Op) {
4052                     return AllowsReordering(Op.second) &&
4053                            all_of(Op.second->UserTreeIndices,
4054                                   [UserTE](const EdgeInfo &EI) {
4055                                     return EI.UserTE == UserTE;
4056                                   });
4057                   })) <= Ops.size() / 2)
4058             ++Res.first->second;
4059         }
4060       }
4061       // If no orders - skip current nodes and jump to the next one, if any.
4062       if (OrdersUses.empty()) {
4063         for_each(Data.second,
4064                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
4065                    OrderedEntries.remove(Op.second);
4066                  });
4067         continue;
4068       }
4069       // Choose the best order.
4070       ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
4071       unsigned Cnt = OrdersUses.front().second;
4072       for (const auto &Pair : drop_begin(OrdersUses)) {
4073         if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
4074           BestOrder = Pair.first;
4075           Cnt = Pair.second;
4076         }
4077       }
4078       // Set order of the user node (reordering of operands and user nodes).
4079       if (BestOrder.empty()) {
4080         for_each(Data.second,
4081                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
4082                    OrderedEntries.remove(Op.second);
4083                  });
4084         continue;
4085       }
4086       // Erase operands from OrderedEntries list and adjust their orders.
4087       VisitedOps.clear();
4088       SmallVector<int> Mask;
4089       inversePermutation(BestOrder, Mask);
4090       SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
4091       unsigned E = BestOrder.size();
4092       transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
4093         return I < E ? static_cast<int>(I) : UndefMaskElem;
4094       });
4095       for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) {
4096         TreeEntry *TE = Op.second;
4097         OrderedEntries.remove(TE);
4098         if (!VisitedOps.insert(TE).second)
4099           continue;
4100         if (TE->ReuseShuffleIndices.size() == BestOrder.size()) {
4101           // Just reorder reuses indices.
4102           reorderReuses(TE->ReuseShuffleIndices, Mask);
4103           continue;
4104         }
4105         // Gathers are processed separately.
4106         if (TE->State != TreeEntry::Vectorize)
4107           continue;
4108         assert((BestOrder.size() == TE->ReorderIndices.size() ||
4109                 TE->ReorderIndices.empty()) &&
4110                "Non-matching sizes of user/operand entries.");
4111         reorderOrder(TE->ReorderIndices, Mask);
4112       }
4113       // For gathers just need to reorder its scalars.
4114       for (TreeEntry *Gather : GatherOps) {
4115         assert(Gather->ReorderIndices.empty() &&
4116                "Unexpected reordering of gathers.");
4117         if (!Gather->ReuseShuffleIndices.empty()) {
4118           // Just reorder reuses indices.
4119           reorderReuses(Gather->ReuseShuffleIndices, Mask);
4120           continue;
4121         }
4122         reorderScalars(Gather->Scalars, Mask);
4123         OrderedEntries.remove(Gather);
4124       }
4125       // Reorder operands of the user node and set the ordering for the user
4126       // node itself.
4127       if (Data.first->State != TreeEntry::Vectorize ||
4128           !isa<ExtractElementInst, ExtractValueInst, LoadInst>(
4129               Data.first->getMainOp()) ||
4130           Data.first->isAltShuffle())
4131         Data.first->reorderOperands(Mask);
4132       if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) ||
4133           Data.first->isAltShuffle()) {
4134         reorderScalars(Data.first->Scalars, Mask);
4135         reorderOrder(Data.first->ReorderIndices, MaskOrder);
4136         if (Data.first->ReuseShuffleIndices.empty() &&
4137             !Data.first->ReorderIndices.empty() &&
4138             !Data.first->isAltShuffle()) {
4139           // Insert user node to the list to try to sink reordering deeper in
4140           // the graph.
4141           OrderedEntries.insert(Data.first);
4142         }
4143       } else {
4144         reorderOrder(Data.first->ReorderIndices, Mask);
4145       }
4146     }
4147   }
4148   // If the reordering is unnecessary, just remove the reorder.
4149   if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() &&
4150       VectorizableTree.front()->ReuseShuffleIndices.empty())
4151     VectorizableTree.front()->ReorderIndices.clear();
4152 }
4153 
4154 void BoUpSLP::buildExternalUses(
4155     const ExtraValueToDebugLocsMap &ExternallyUsedValues) {
4156   // Collect the values that we need to extract from the tree.
4157   for (auto &TEPtr : VectorizableTree) {
4158     TreeEntry *Entry = TEPtr.get();
4159 
4160     // No need to handle users of gathered values.
4161     if (Entry->State == TreeEntry::NeedToGather)
4162       continue;
4163 
4164     // For each lane:
4165     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
4166       Value *Scalar = Entry->Scalars[Lane];
4167       int FoundLane = Entry->findLaneForValue(Scalar);
4168 
4169       // Check if the scalar is externally used as an extra arg.
4170       auto ExtI = ExternallyUsedValues.find(Scalar);
4171       if (ExtI != ExternallyUsedValues.end()) {
4172         LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
4173                           << Lane << " from " << *Scalar << ".\n");
4174         ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
4175       }
4176       for (User *U : Scalar->users()) {
4177         LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
4178 
4179         Instruction *UserInst = dyn_cast<Instruction>(U);
4180         if (!UserInst)
4181           continue;
4182 
4183         if (isDeleted(UserInst))
4184           continue;
4185 
4186         // Skip in-tree scalars that become vectors
4187         if (TreeEntry *UseEntry = getTreeEntry(U)) {
4188           Value *UseScalar = UseEntry->Scalars[0];
4189           // Some in-tree scalars will remain as scalar in vectorized
4190           // instructions. If that is the case, the one in Lane 0 will
4191           // be used.
4192           if (UseScalar != U ||
4193               UseEntry->State == TreeEntry::ScatterVectorize ||
4194               !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
4195             LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
4196                               << ".\n");
4197             assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state");
4198             continue;
4199           }
4200         }
4201 
4202         // Ignore users in the user ignore list.
4203         if (UserIgnoreList && UserIgnoreList->contains(UserInst))
4204           continue;
4205 
4206         LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
4207                           << Lane << " from " << *Scalar << ".\n");
4208         ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
4209       }
4210     }
4211   }
4212 }
4213 
4214 DenseMap<Value *, SmallVector<StoreInst *, 4>>
4215 BoUpSLP::collectUserStores(const BoUpSLP::TreeEntry *TE) const {
4216   DenseMap<Value *, SmallVector<StoreInst *, 4>> PtrToStoresMap;
4217   for (unsigned Lane : seq<unsigned>(0, TE->Scalars.size())) {
4218     Value *V = TE->Scalars[Lane];
4219     // To save compilation time we don't visit if we have too many users.
4220     static constexpr unsigned UsersLimit = 4;
4221     if (V->hasNUsesOrMore(UsersLimit))
4222       break;
4223 
4224     // Collect stores per pointer object.
4225     for (User *U : V->users()) {
4226       auto *SI = dyn_cast<StoreInst>(U);
4227       if (SI == nullptr || !SI->isSimple() ||
4228           !isValidElementType(SI->getValueOperand()->getType()))
4229         continue;
4230       // Skip entry if already
4231       if (getTreeEntry(U))
4232         continue;
4233 
4234       Value *Ptr = getUnderlyingObject(SI->getPointerOperand());
4235       auto &StoresVec = PtrToStoresMap[Ptr];
4236       // For now just keep one store per pointer object per lane.
4237       // TODO: Extend this to support multiple stores per pointer per lane
4238       if (StoresVec.size() > Lane)
4239         continue;
4240       // Skip if in different BBs.
4241       if (!StoresVec.empty() &&
4242           SI->getParent() != StoresVec.back()->getParent())
4243         continue;
4244       // Make sure that the stores are of the same type.
4245       if (!StoresVec.empty() &&
4246           SI->getValueOperand()->getType() !=
4247               StoresVec.back()->getValueOperand()->getType())
4248         continue;
4249       StoresVec.push_back(SI);
4250     }
4251   }
4252   return PtrToStoresMap;
4253 }
4254 
4255 bool BoUpSLP::CanFormVector(const SmallVector<StoreInst *, 4> &StoresVec,
4256                             OrdersType &ReorderIndices) const {
4257   // We check whether the stores in StoreVec can form a vector by sorting them
4258   // and checking whether they are consecutive.
4259 
4260   // To avoid calling getPointersDiff() while sorting we create a vector of
4261   // pairs {store, offset from first} and sort this instead.
4262   SmallVector<std::pair<StoreInst *, int>, 4> StoreOffsetVec(StoresVec.size());
4263   StoreInst *S0 = StoresVec[0];
4264   StoreOffsetVec[0] = {S0, 0};
4265   Type *S0Ty = S0->getValueOperand()->getType();
4266   Value *S0Ptr = S0->getPointerOperand();
4267   for (unsigned Idx : seq<unsigned>(1, StoresVec.size())) {
4268     StoreInst *SI = StoresVec[Idx];
4269     Optional<int> Diff =
4270         getPointersDiff(S0Ty, S0Ptr, SI->getValueOperand()->getType(),
4271                         SI->getPointerOperand(), *DL, *SE,
4272                         /*StrictCheck=*/true);
4273     // We failed to compare the pointers so just abandon this StoresVec.
4274     if (!Diff)
4275       return false;
4276     StoreOffsetVec[Idx] = {StoresVec[Idx], *Diff};
4277   }
4278 
4279   // Sort the vector based on the pointers. We create a copy because we may
4280   // need the original later for calculating the reorder (shuffle) indices.
4281   stable_sort(StoreOffsetVec, [](const std::pair<StoreInst *, int> &Pair1,
4282                                  const std::pair<StoreInst *, int> &Pair2) {
4283     int Offset1 = Pair1.second;
4284     int Offset2 = Pair2.second;
4285     return Offset1 < Offset2;
4286   });
4287 
4288   // Check if the stores are consecutive by checking if their difference is 1.
4289   for (unsigned Idx : seq<unsigned>(1, StoreOffsetVec.size()))
4290     if (StoreOffsetVec[Idx].second != StoreOffsetVec[Idx-1].second + 1)
4291       return false;
4292 
4293   // Calculate the shuffle indices according to their offset against the sorted
4294   // StoreOffsetVec.
4295   ReorderIndices.reserve(StoresVec.size());
4296   for (StoreInst *SI : StoresVec) {
4297     unsigned Idx = find_if(StoreOffsetVec,
4298                            [SI](const std::pair<StoreInst *, int> &Pair) {
4299                              return Pair.first == SI;
4300                            }) -
4301                    StoreOffsetVec.begin();
4302     ReorderIndices.push_back(Idx);
4303   }
4304   // Identity order (e.g., {0,1,2,3}) is modeled as an empty OrdersType in
4305   // reorderTopToBottom() and reorderBottomToTop(), so we are following the
4306   // same convention here.
4307   auto IsIdentityOrder = [](const OrdersType &Order) {
4308     for (unsigned Idx : seq<unsigned>(0, Order.size()))
4309       if (Idx != Order[Idx])
4310         return false;
4311     return true;
4312   };
4313   if (IsIdentityOrder(ReorderIndices))
4314     ReorderIndices.clear();
4315 
4316   return true;
4317 }
4318 
4319 #ifndef NDEBUG
4320 LLVM_DUMP_METHOD static void dumpOrder(const BoUpSLP::OrdersType &Order) {
4321   for (unsigned Idx : Order)
4322     dbgs() << Idx << ", ";
4323   dbgs() << "\n";
4324 }
4325 #endif
4326 
4327 SmallVector<BoUpSLP::OrdersType, 1>
4328 BoUpSLP::findExternalStoreUsersReorderIndices(TreeEntry *TE) const {
4329   unsigned NumLanes = TE->Scalars.size();
4330 
4331   DenseMap<Value *, SmallVector<StoreInst *, 4>> PtrToStoresMap =
4332       collectUserStores(TE);
4333 
4334   // Holds the reorder indices for each candidate store vector that is a user of
4335   // the current TreeEntry.
4336   SmallVector<OrdersType, 1> ExternalReorderIndices;
4337 
4338   // Now inspect the stores collected per pointer and look for vectorization
4339   // candidates. For each candidate calculate the reorder index vector and push
4340   // it into `ExternalReorderIndices`
4341   for (const auto &Pair : PtrToStoresMap) {
4342     auto &StoresVec = Pair.second;
4343     // If we have fewer than NumLanes stores, then we can't form a vector.
4344     if (StoresVec.size() != NumLanes)
4345       continue;
4346 
4347     // If the stores are not consecutive then abandon this StoresVec.
4348     OrdersType ReorderIndices;
4349     if (!CanFormVector(StoresVec, ReorderIndices))
4350       continue;
4351 
4352     // We now know that the scalars in StoresVec can form a vector instruction,
4353     // so set the reorder indices.
4354     ExternalReorderIndices.push_back(ReorderIndices);
4355   }
4356   return ExternalReorderIndices;
4357 }
4358 
4359 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
4360                         const SmallDenseSet<Value *> &UserIgnoreLst) {
4361   deleteTree();
4362   UserIgnoreList = &UserIgnoreLst;
4363   if (!allSameType(Roots))
4364     return;
4365   buildTree_rec(Roots, 0, EdgeInfo());
4366 }
4367 
4368 void BoUpSLP::buildTree(ArrayRef<Value *> Roots) {
4369   deleteTree();
4370   if (!allSameType(Roots))
4371     return;
4372   buildTree_rec(Roots, 0, EdgeInfo());
4373 }
4374 
4375 /// \return true if the specified list of values has only one instruction that
4376 /// requires scheduling, false otherwise.
4377 #ifndef NDEBUG
4378 static bool needToScheduleSingleInstruction(ArrayRef<Value *> VL) {
4379   Value *NeedsScheduling = nullptr;
4380   for (Value *V : VL) {
4381     if (doesNotNeedToBeScheduled(V))
4382       continue;
4383     if (!NeedsScheduling) {
4384       NeedsScheduling = V;
4385       continue;
4386     }
4387     return false;
4388   }
4389   return NeedsScheduling;
4390 }
4391 #endif
4392 
4393 /// Generates key/subkey pair for the given value to provide effective sorting
4394 /// of the values and better detection of the vectorizable values sequences. The
4395 /// keys/subkeys can be used for better sorting of the values themselves (keys)
4396 /// and in values subgroups (subkeys).
4397 static std::pair<size_t, size_t> generateKeySubkey(
4398     Value *V, const TargetLibraryInfo *TLI,
4399     function_ref<hash_code(size_t, LoadInst *)> LoadsSubkeyGenerator,
4400     bool AllowAlternate) {
4401   hash_code Key = hash_value(V->getValueID() + 2);
4402   hash_code SubKey = hash_value(0);
4403   // Sort the loads by the distance between the pointers.
4404   if (auto *LI = dyn_cast<LoadInst>(V)) {
4405     Key = hash_combine(hash_value(Instruction::Load), Key);
4406     if (LI->isSimple())
4407       SubKey = hash_value(LoadsSubkeyGenerator(Key, LI));
4408     else
4409       SubKey = hash_value(LI);
4410   } else if (isVectorLikeInstWithConstOps(V)) {
4411     // Sort extracts by the vector operands.
4412     if (isa<ExtractElementInst, UndefValue>(V))
4413       Key = hash_value(Value::UndefValueVal + 1);
4414     if (auto *EI = dyn_cast<ExtractElementInst>(V)) {
4415       if (!isUndefVector(EI->getVectorOperand()) &&
4416           !isa<UndefValue>(EI->getIndexOperand()))
4417         SubKey = hash_value(EI->getVectorOperand());
4418     }
4419   } else if (auto *I = dyn_cast<Instruction>(V)) {
4420     // Sort other instructions just by the opcodes except for CMPInst.
4421     // For CMP also sort by the predicate kind.
4422     if ((isa<BinaryOperator>(I) || isa<CastInst>(I)) &&
4423         isValidForAlternation(I->getOpcode())) {
4424       if (AllowAlternate)
4425         Key = hash_value(isa<BinaryOperator>(I) ? 1 : 0);
4426       else
4427         Key = hash_combine(hash_value(I->getOpcode()), Key);
4428       SubKey = hash_combine(
4429           hash_value(I->getOpcode()), hash_value(I->getType()),
4430           hash_value(isa<BinaryOperator>(I)
4431                          ? I->getType()
4432                          : cast<CastInst>(I)->getOperand(0)->getType()));
4433       // For casts, look through the only operand to improve compile time.
4434       if (isa<CastInst>(I)) {
4435         std::pair<size_t, size_t> OpVals =
4436             generateKeySubkey(I->getOperand(0), TLI, LoadsSubkeyGenerator,
4437                               /*=AllowAlternate*/ true);
4438         Key = hash_combine(OpVals.first, Key);
4439         SubKey = hash_combine(OpVals.first, SubKey);
4440       }
4441     } else if (auto *CI = dyn_cast<CmpInst>(I)) {
4442       CmpInst::Predicate Pred = CI->getPredicate();
4443       if (CI->isCommutative())
4444         Pred = std::min(Pred, CmpInst::getInversePredicate(Pred));
4445       CmpInst::Predicate SwapPred = CmpInst::getSwappedPredicate(Pred);
4446       SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(Pred),
4447                             hash_value(SwapPred),
4448                             hash_value(CI->getOperand(0)->getType()));
4449     } else if (auto *Call = dyn_cast<CallInst>(I)) {
4450       Intrinsic::ID ID = getVectorIntrinsicIDForCall(Call, TLI);
4451       if (isTriviallyVectorizable(ID)) {
4452         SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(ID));
4453       } else if (!VFDatabase(*Call).getMappings(*Call).empty()) {
4454         SubKey = hash_combine(hash_value(I->getOpcode()),
4455                               hash_value(Call->getCalledFunction()));
4456       } else {
4457         Key = hash_combine(hash_value(Call), Key);
4458         SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(Call));
4459       }
4460       for (const CallBase::BundleOpInfo &Op : Call->bundle_op_infos())
4461         SubKey = hash_combine(hash_value(Op.Begin), hash_value(Op.End),
4462                               hash_value(Op.Tag), SubKey);
4463     } else if (auto *Gep = dyn_cast<GetElementPtrInst>(I)) {
4464       if (Gep->getNumOperands() == 2 && isa<ConstantInt>(Gep->getOperand(1)))
4465         SubKey = hash_value(Gep->getPointerOperand());
4466       else
4467         SubKey = hash_value(Gep);
4468     } else if (BinaryOperator::isIntDivRem(I->getOpcode()) &&
4469                !isa<ConstantInt>(I->getOperand(1))) {
4470       // Do not try to vectorize instructions with potentially high cost.
4471       SubKey = hash_value(I);
4472     } else {
4473       SubKey = hash_value(I->getOpcode());
4474     }
4475     Key = hash_combine(hash_value(I->getParent()), Key);
4476   }
4477   return std::make_pair(Key, SubKey);
4478 }
4479 
4480 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
4481                             const EdgeInfo &UserTreeIdx) {
4482   assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
4483 
4484   SmallVector<int> ReuseShuffleIndicies;
4485   SmallVector<Value *> UniqueValues;
4486   auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues,
4487                                 &UserTreeIdx,
4488                                 this](const InstructionsState &S) {
4489     // Check that every instruction appears once in this bundle.
4490     DenseMap<Value *, unsigned> UniquePositions;
4491     for (Value *V : VL) {
4492       if (isConstant(V)) {
4493         ReuseShuffleIndicies.emplace_back(
4494             isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size());
4495         UniqueValues.emplace_back(V);
4496         continue;
4497       }
4498       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
4499       ReuseShuffleIndicies.emplace_back(Res.first->second);
4500       if (Res.second)
4501         UniqueValues.emplace_back(V);
4502     }
4503     size_t NumUniqueScalarValues = UniqueValues.size();
4504     if (NumUniqueScalarValues == VL.size()) {
4505       ReuseShuffleIndicies.clear();
4506     } else {
4507       LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
4508       if (NumUniqueScalarValues <= 1 ||
4509           (UniquePositions.size() == 1 && all_of(UniqueValues,
4510                                                  [](Value *V) {
4511                                                    return isa<UndefValue>(V) ||
4512                                                           !isConstant(V);
4513                                                  })) ||
4514           !llvm::isPowerOf2_32(NumUniqueScalarValues)) {
4515         LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
4516         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4517         return false;
4518       }
4519       VL = UniqueValues;
4520     }
4521     return true;
4522   };
4523 
4524   InstructionsState S = getSameOpcode(VL);
4525   if (Depth == RecursionMaxDepth) {
4526     LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
4527     if (TryToFindDuplicates(S))
4528       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4529                    ReuseShuffleIndicies);
4530     return;
4531   }
4532 
4533   // Don't handle scalable vectors
4534   if (S.getOpcode() == Instruction::ExtractElement &&
4535       isa<ScalableVectorType>(
4536           cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) {
4537     LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n");
4538     if (TryToFindDuplicates(S))
4539       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4540                    ReuseShuffleIndicies);
4541     return;
4542   }
4543 
4544   // Don't handle vectors.
4545   if (S.OpValue->getType()->isVectorTy() &&
4546       !isa<InsertElementInst>(S.OpValue)) {
4547     LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
4548     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4549     return;
4550   }
4551 
4552   if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
4553     if (SI->getValueOperand()->getType()->isVectorTy()) {
4554       LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
4555       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4556       return;
4557     }
4558 
4559   // If all of the operands are identical or constant we have a simple solution.
4560   // If we deal with insert/extract instructions, they all must have constant
4561   // indices, otherwise we should gather them, not try to vectorize.
4562   // If alternate op node with 2 elements with gathered operands - do not
4563   // vectorize.
4564   auto &&NotProfitableForVectorization = [&S, this,
4565                                           Depth](ArrayRef<Value *> VL) {
4566     if (!S.getOpcode() || !S.isAltShuffle() || VL.size() > 2)
4567       return false;
4568     if (VectorizableTree.size() < MinTreeSize)
4569       return false;
4570     if (Depth >= RecursionMaxDepth - 1)
4571       return true;
4572     // Check if all operands are extracts, part of vector node or can build a
4573     // regular vectorize node.
4574     SmallVector<unsigned, 2> InstsCount(VL.size(), 0);
4575     for (Value *V : VL) {
4576       auto *I = cast<Instruction>(V);
4577       InstsCount.push_back(count_if(I->operand_values(), [](Value *Op) {
4578         return isa<Instruction>(Op) || isVectorLikeInstWithConstOps(Op);
4579       }));
4580     }
4581     bool IsCommutative = isCommutative(S.MainOp) || isCommutative(S.AltOp);
4582     if ((IsCommutative &&
4583          std::accumulate(InstsCount.begin(), InstsCount.end(), 0) < 2) ||
4584         (!IsCommutative &&
4585          all_of(InstsCount, [](unsigned ICnt) { return ICnt < 2; })))
4586       return true;
4587     assert(VL.size() == 2 && "Expected only 2 alternate op instructions.");
4588     SmallVector<SmallVector<std::pair<Value *, Value *>>> Candidates;
4589     auto *I1 = cast<Instruction>(VL.front());
4590     auto *I2 = cast<Instruction>(VL.back());
4591     for (int Op = 0, E = S.MainOp->getNumOperands(); Op < E; ++Op)
4592       Candidates.emplace_back().emplace_back(I1->getOperand(Op),
4593                                              I2->getOperand(Op));
4594     if (count_if(
4595             Candidates, [this](ArrayRef<std::pair<Value *, Value *>> Cand) {
4596               return findBestRootPair(Cand, LookAheadHeuristics::ScoreSplat);
4597             }) >= S.MainOp->getNumOperands() / 2)
4598       return false;
4599     if (S.MainOp->getNumOperands() > 2)
4600       return true;
4601     if (IsCommutative) {
4602       // Check permuted operands.
4603       Candidates.clear();
4604       for (int Op = 0, E = S.MainOp->getNumOperands(); Op < E; ++Op)
4605         Candidates.emplace_back().emplace_back(I1->getOperand(Op),
4606                                                I2->getOperand((Op + 1) % E));
4607       if (any_of(
4608               Candidates, [this](ArrayRef<std::pair<Value *, Value *>> Cand) {
4609                 return findBestRootPair(Cand, LookAheadHeuristics::ScoreSplat);
4610               }))
4611         return false;
4612     }
4613     return true;
4614   };
4615   if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode() ||
4616       (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(S.MainOp) &&
4617        !all_of(VL, isVectorLikeInstWithConstOps)) ||
4618       NotProfitableForVectorization(VL)) {
4619     LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O, small shuffle. \n");
4620     if (TryToFindDuplicates(S))
4621       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4622                    ReuseShuffleIndicies);
4623     return;
4624   }
4625 
4626   // We now know that this is a vector of instructions of the same type from
4627   // the same block.
4628 
4629   // Don't vectorize ephemeral values.
4630   if (!EphValues.empty()) {
4631     for (Value *V : VL) {
4632       if (EphValues.count(V)) {
4633         LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
4634                           << ") is ephemeral.\n");
4635         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4636         return;
4637       }
4638     }
4639   }
4640 
4641   // Check if this is a duplicate of another entry.
4642   if (TreeEntry *E = getTreeEntry(S.OpValue)) {
4643     LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n");
4644     if (!E->isSame(VL)) {
4645       LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
4646       if (TryToFindDuplicates(S))
4647         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4648                      ReuseShuffleIndicies);
4649       return;
4650     }
4651     // Record the reuse of the tree node.  FIXME, currently this is only used to
4652     // properly draw the graph rather than for the actual vectorization.
4653     E->UserTreeIndices.push_back(UserTreeIdx);
4654     LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue
4655                       << ".\n");
4656     return;
4657   }
4658 
4659   // Check that none of the instructions in the bundle are already in the tree.
4660   for (Value *V : VL) {
4661     auto *I = dyn_cast<Instruction>(V);
4662     if (!I)
4663       continue;
4664     if (getTreeEntry(I)) {
4665       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
4666                         << ") is already in tree.\n");
4667       if (TryToFindDuplicates(S))
4668         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4669                      ReuseShuffleIndicies);
4670       return;
4671     }
4672   }
4673 
4674   // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
4675   if (UserIgnoreList && !UserIgnoreList->empty()) {
4676     for (Value *V : VL) {
4677       if (UserIgnoreList && UserIgnoreList->contains(V)) {
4678         LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
4679         if (TryToFindDuplicates(S))
4680           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4681                        ReuseShuffleIndicies);
4682         return;
4683       }
4684     }
4685   }
4686 
4687   // Check that all of the users of the scalars that we want to vectorize are
4688   // schedulable.
4689   auto *VL0 = cast<Instruction>(S.OpValue);
4690   BasicBlock *BB = VL0->getParent();
4691 
4692   if (!DT->isReachableFromEntry(BB)) {
4693     // Don't go into unreachable blocks. They may contain instructions with
4694     // dependency cycles which confuse the final scheduling.
4695     LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
4696     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4697     return;
4698   }
4699 
4700   // Check that every instruction appears once in this bundle.
4701   if (!TryToFindDuplicates(S))
4702     return;
4703 
4704   auto &BSRef = BlocksSchedules[BB];
4705   if (!BSRef)
4706     BSRef = std::make_unique<BlockScheduling>(BB);
4707 
4708   BlockScheduling &BS = *BSRef;
4709 
4710   Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S);
4711 #ifdef EXPENSIVE_CHECKS
4712   // Make sure we didn't break any internal invariants
4713   BS.verify();
4714 #endif
4715   if (!Bundle) {
4716     LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
4717     assert((!BS.getScheduleData(VL0) ||
4718             !BS.getScheduleData(VL0)->isPartOfBundle()) &&
4719            "tryScheduleBundle should cancelScheduling on failure");
4720     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4721                  ReuseShuffleIndicies);
4722     return;
4723   }
4724   LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
4725 
4726   unsigned ShuffleOrOp = S.isAltShuffle() ?
4727                 (unsigned) Instruction::ShuffleVector : S.getOpcode();
4728   switch (ShuffleOrOp) {
4729     case Instruction::PHI: {
4730       auto *PH = cast<PHINode>(VL0);
4731 
4732       // Check for terminator values (e.g. invoke).
4733       for (Value *V : VL)
4734         for (Value *Incoming : cast<PHINode>(V)->incoming_values()) {
4735           Instruction *Term = dyn_cast<Instruction>(Incoming);
4736           if (Term && Term->isTerminator()) {
4737             LLVM_DEBUG(dbgs()
4738                        << "SLP: Need to swizzle PHINodes (terminator use).\n");
4739             BS.cancelScheduling(VL, VL0);
4740             newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4741                          ReuseShuffleIndicies);
4742             return;
4743           }
4744         }
4745 
4746       TreeEntry *TE =
4747           newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies);
4748       LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
4749 
4750       // Keeps the reordered operands to avoid code duplication.
4751       SmallVector<ValueList, 2> OperandsVec;
4752       for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
4753         if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) {
4754           ValueList Operands(VL.size(), PoisonValue::get(PH->getType()));
4755           TE->setOperand(I, Operands);
4756           OperandsVec.push_back(Operands);
4757           continue;
4758         }
4759         ValueList Operands;
4760         // Prepare the operand vector.
4761         for (Value *V : VL)
4762           Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(
4763               PH->getIncomingBlock(I)));
4764         TE->setOperand(I, Operands);
4765         OperandsVec.push_back(Operands);
4766       }
4767       for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx)
4768         buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx});
4769       return;
4770     }
4771     case Instruction::ExtractValue:
4772     case Instruction::ExtractElement: {
4773       OrdersType CurrentOrder;
4774       bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
4775       if (Reuse) {
4776         LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
4777         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4778                      ReuseShuffleIndicies);
4779         // This is a special case, as it does not gather, but at the same time
4780         // we are not extending buildTree_rec() towards the operands.
4781         ValueList Op0;
4782         Op0.assign(VL.size(), VL0->getOperand(0));
4783         VectorizableTree.back()->setOperand(0, Op0);
4784         return;
4785       }
4786       if (!CurrentOrder.empty()) {
4787         LLVM_DEBUG({
4788           dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
4789                     "with order";
4790           for (unsigned Idx : CurrentOrder)
4791             dbgs() << " " << Idx;
4792           dbgs() << "\n";
4793         });
4794         fixupOrderingIndices(CurrentOrder);
4795         // Insert new order with initial value 0, if it does not exist,
4796         // otherwise return the iterator to the existing one.
4797         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4798                      ReuseShuffleIndicies, CurrentOrder);
4799         // This is a special case, as it does not gather, but at the same time
4800         // we are not extending buildTree_rec() towards the operands.
4801         ValueList Op0;
4802         Op0.assign(VL.size(), VL0->getOperand(0));
4803         VectorizableTree.back()->setOperand(0, Op0);
4804         return;
4805       }
4806       LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
4807       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4808                    ReuseShuffleIndicies);
4809       BS.cancelScheduling(VL, VL0);
4810       return;
4811     }
4812     case Instruction::InsertElement: {
4813       assert(ReuseShuffleIndicies.empty() && "All inserts should be unique");
4814 
4815       // Check that we have a buildvector and not a shuffle of 2 or more
4816       // different vectors.
4817       ValueSet SourceVectors;
4818       for (Value *V : VL) {
4819         SourceVectors.insert(cast<Instruction>(V)->getOperand(0));
4820         assert(getInsertIndex(V) != None && "Non-constant or undef index?");
4821       }
4822 
4823       if (count_if(VL, [&SourceVectors](Value *V) {
4824             return !SourceVectors.contains(V);
4825           }) >= 2) {
4826         // Found 2nd source vector - cancel.
4827         LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with "
4828                              "different source vectors.\n");
4829         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4830         BS.cancelScheduling(VL, VL0);
4831         return;
4832       }
4833 
4834       auto OrdCompare = [](const std::pair<int, int> &P1,
4835                            const std::pair<int, int> &P2) {
4836         return P1.first > P2.first;
4837       };
4838       PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>,
4839                     decltype(OrdCompare)>
4840           Indices(OrdCompare);
4841       for (int I = 0, E = VL.size(); I < E; ++I) {
4842         unsigned Idx = *getInsertIndex(VL[I]);
4843         Indices.emplace(Idx, I);
4844       }
4845       OrdersType CurrentOrder(VL.size(), VL.size());
4846       bool IsIdentity = true;
4847       for (int I = 0, E = VL.size(); I < E; ++I) {
4848         CurrentOrder[Indices.top().second] = I;
4849         IsIdentity &= Indices.top().second == I;
4850         Indices.pop();
4851       }
4852       if (IsIdentity)
4853         CurrentOrder.clear();
4854       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4855                                    None, CurrentOrder);
4856       LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n");
4857 
4858       constexpr int NumOps = 2;
4859       ValueList VectorOperands[NumOps];
4860       for (int I = 0; I < NumOps; ++I) {
4861         for (Value *V : VL)
4862           VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I));
4863 
4864         TE->setOperand(I, VectorOperands[I]);
4865       }
4866       buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1});
4867       return;
4868     }
4869     case Instruction::Load: {
4870       // Check that a vectorized load would load the same memory as a scalar
4871       // load. For example, we don't want to vectorize loads that are smaller
4872       // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
4873       // treats loading/storing it as an i8 struct. If we vectorize loads/stores
4874       // from such a struct, we read/write packed bits disagreeing with the
4875       // unvectorized version.
4876       SmallVector<Value *> PointerOps;
4877       OrdersType CurrentOrder;
4878       TreeEntry *TE = nullptr;
4879       switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, CurrentOrder,
4880                                 PointerOps)) {
4881       case LoadsState::Vectorize:
4882         if (CurrentOrder.empty()) {
4883           // Original loads are consecutive and does not require reordering.
4884           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4885                             ReuseShuffleIndicies);
4886           LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
4887         } else {
4888           fixupOrderingIndices(CurrentOrder);
4889           // Need to reorder.
4890           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4891                             ReuseShuffleIndicies, CurrentOrder);
4892           LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
4893         }
4894         TE->setOperandsInOrder();
4895         break;
4896       case LoadsState::ScatterVectorize:
4897         // Vectorizing non-consecutive loads with `llvm.masked.gather`.
4898         TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S,
4899                           UserTreeIdx, ReuseShuffleIndicies);
4900         TE->setOperandsInOrder();
4901         buildTree_rec(PointerOps, Depth + 1, {TE, 0});
4902         LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n");
4903         break;
4904       case LoadsState::Gather:
4905         BS.cancelScheduling(VL, VL0);
4906         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4907                      ReuseShuffleIndicies);
4908 #ifndef NDEBUG
4909         Type *ScalarTy = VL0->getType();
4910         if (DL->getTypeSizeInBits(ScalarTy) !=
4911             DL->getTypeAllocSizeInBits(ScalarTy))
4912           LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
4913         else if (any_of(VL, [](Value *V) {
4914                    return !cast<LoadInst>(V)->isSimple();
4915                  }))
4916           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
4917         else
4918           LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
4919 #endif // NDEBUG
4920         break;
4921       }
4922       return;
4923     }
4924     case Instruction::ZExt:
4925     case Instruction::SExt:
4926     case Instruction::FPToUI:
4927     case Instruction::FPToSI:
4928     case Instruction::FPExt:
4929     case Instruction::PtrToInt:
4930     case Instruction::IntToPtr:
4931     case Instruction::SIToFP:
4932     case Instruction::UIToFP:
4933     case Instruction::Trunc:
4934     case Instruction::FPTrunc:
4935     case Instruction::BitCast: {
4936       Type *SrcTy = VL0->getOperand(0)->getType();
4937       for (Value *V : VL) {
4938         Type *Ty = cast<Instruction>(V)->getOperand(0)->getType();
4939         if (Ty != SrcTy || !isValidElementType(Ty)) {
4940           BS.cancelScheduling(VL, VL0);
4941           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4942                        ReuseShuffleIndicies);
4943           LLVM_DEBUG(dbgs()
4944                      << "SLP: Gathering casts with different src types.\n");
4945           return;
4946         }
4947       }
4948       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4949                                    ReuseShuffleIndicies);
4950       LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
4951 
4952       TE->setOperandsInOrder();
4953       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4954         ValueList Operands;
4955         // Prepare the operand vector.
4956         for (Value *V : VL)
4957           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4958 
4959         buildTree_rec(Operands, Depth + 1, {TE, i});
4960       }
4961       return;
4962     }
4963     case Instruction::ICmp:
4964     case Instruction::FCmp: {
4965       // Check that all of the compares have the same predicate.
4966       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
4967       CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0);
4968       Type *ComparedTy = VL0->getOperand(0)->getType();
4969       for (Value *V : VL) {
4970         CmpInst *Cmp = cast<CmpInst>(V);
4971         if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) ||
4972             Cmp->getOperand(0)->getType() != ComparedTy) {
4973           BS.cancelScheduling(VL, VL0);
4974           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4975                        ReuseShuffleIndicies);
4976           LLVM_DEBUG(dbgs()
4977                      << "SLP: Gathering cmp with different predicate.\n");
4978           return;
4979         }
4980       }
4981 
4982       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4983                                    ReuseShuffleIndicies);
4984       LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
4985 
4986       ValueList Left, Right;
4987       if (cast<CmpInst>(VL0)->isCommutative()) {
4988         // Commutative predicate - collect + sort operands of the instructions
4989         // so that each side is more likely to have the same opcode.
4990         assert(P0 == SwapP0 && "Commutative Predicate mismatch");
4991         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4992       } else {
4993         // Collect operands - commute if it uses the swapped predicate.
4994         for (Value *V : VL) {
4995           auto *Cmp = cast<CmpInst>(V);
4996           Value *LHS = Cmp->getOperand(0);
4997           Value *RHS = Cmp->getOperand(1);
4998           if (Cmp->getPredicate() != P0)
4999             std::swap(LHS, RHS);
5000           Left.push_back(LHS);
5001           Right.push_back(RHS);
5002         }
5003       }
5004       TE->setOperand(0, Left);
5005       TE->setOperand(1, Right);
5006       buildTree_rec(Left, Depth + 1, {TE, 0});
5007       buildTree_rec(Right, Depth + 1, {TE, 1});
5008       return;
5009     }
5010     case Instruction::Select:
5011     case Instruction::FNeg:
5012     case Instruction::Add:
5013     case Instruction::FAdd:
5014     case Instruction::Sub:
5015     case Instruction::FSub:
5016     case Instruction::Mul:
5017     case Instruction::FMul:
5018     case Instruction::UDiv:
5019     case Instruction::SDiv:
5020     case Instruction::FDiv:
5021     case Instruction::URem:
5022     case Instruction::SRem:
5023     case Instruction::FRem:
5024     case Instruction::Shl:
5025     case Instruction::LShr:
5026     case Instruction::AShr:
5027     case Instruction::And:
5028     case Instruction::Or:
5029     case Instruction::Xor: {
5030       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
5031                                    ReuseShuffleIndicies);
5032       LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n");
5033 
5034       // Sort operands of the instructions so that each side is more likely to
5035       // have the same opcode.
5036       if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
5037         ValueList Left, Right;
5038         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
5039         TE->setOperand(0, Left);
5040         TE->setOperand(1, Right);
5041         buildTree_rec(Left, Depth + 1, {TE, 0});
5042         buildTree_rec(Right, Depth + 1, {TE, 1});
5043         return;
5044       }
5045 
5046       TE->setOperandsInOrder();
5047       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
5048         ValueList Operands;
5049         // Prepare the operand vector.
5050         for (Value *V : VL)
5051           Operands.push_back(cast<Instruction>(V)->getOperand(i));
5052 
5053         buildTree_rec(Operands, Depth + 1, {TE, i});
5054       }
5055       return;
5056     }
5057     case Instruction::GetElementPtr: {
5058       // We don't combine GEPs with complicated (nested) indexing.
5059       for (Value *V : VL) {
5060         if (cast<Instruction>(V)->getNumOperands() != 2) {
5061           LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
5062           BS.cancelScheduling(VL, VL0);
5063           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5064                        ReuseShuffleIndicies);
5065           return;
5066         }
5067       }
5068 
5069       // We can't combine several GEPs into one vector if they operate on
5070       // different types.
5071       Type *Ty0 = cast<GEPOperator>(VL0)->getSourceElementType();
5072       for (Value *V : VL) {
5073         Type *CurTy = cast<GEPOperator>(V)->getSourceElementType();
5074         if (Ty0 != CurTy) {
5075           LLVM_DEBUG(dbgs()
5076                      << "SLP: not-vectorizable GEP (different types).\n");
5077           BS.cancelScheduling(VL, VL0);
5078           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5079                        ReuseShuffleIndicies);
5080           return;
5081         }
5082       }
5083 
5084       // We don't combine GEPs with non-constant indexes.
5085       Type *Ty1 = VL0->getOperand(1)->getType();
5086       for (Value *V : VL) {
5087         auto Op = cast<Instruction>(V)->getOperand(1);
5088         if (!isa<ConstantInt>(Op) ||
5089             (Op->getType() != Ty1 &&
5090              Op->getType()->getScalarSizeInBits() >
5091                  DL->getIndexSizeInBits(
5092                      V->getType()->getPointerAddressSpace()))) {
5093           LLVM_DEBUG(dbgs()
5094                      << "SLP: not-vectorizable GEP (non-constant indexes).\n");
5095           BS.cancelScheduling(VL, VL0);
5096           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5097                        ReuseShuffleIndicies);
5098           return;
5099         }
5100       }
5101 
5102       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
5103                                    ReuseShuffleIndicies);
5104       LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
5105       SmallVector<ValueList, 2> Operands(2);
5106       // Prepare the operand vector for pointer operands.
5107       for (Value *V : VL)
5108         Operands.front().push_back(
5109             cast<GetElementPtrInst>(V)->getPointerOperand());
5110       TE->setOperand(0, Operands.front());
5111       // Need to cast all indices to the same type before vectorization to
5112       // avoid crash.
5113       // Required to be able to find correct matches between different gather
5114       // nodes and reuse the vectorized values rather than trying to gather them
5115       // again.
5116       int IndexIdx = 1;
5117       Type *VL0Ty = VL0->getOperand(IndexIdx)->getType();
5118       Type *Ty = all_of(VL,
5119                         [VL0Ty, IndexIdx](Value *V) {
5120                           return VL0Ty == cast<GetElementPtrInst>(V)
5121                                               ->getOperand(IndexIdx)
5122                                               ->getType();
5123                         })
5124                      ? VL0Ty
5125                      : DL->getIndexType(cast<GetElementPtrInst>(VL0)
5126                                             ->getPointerOperandType()
5127                                             ->getScalarType());
5128       // Prepare the operand vector.
5129       for (Value *V : VL) {
5130         auto *Op = cast<Instruction>(V)->getOperand(IndexIdx);
5131         auto *CI = cast<ConstantInt>(Op);
5132         Operands.back().push_back(ConstantExpr::getIntegerCast(
5133             CI, Ty, CI->getValue().isSignBitSet()));
5134       }
5135       TE->setOperand(IndexIdx, Operands.back());
5136 
5137       for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I)
5138         buildTree_rec(Operands[I], Depth + 1, {TE, I});
5139       return;
5140     }
5141     case Instruction::Store: {
5142       // Check if the stores are consecutive or if we need to swizzle them.
5143       llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType();
5144       // Avoid types that are padded when being allocated as scalars, while
5145       // being packed together in a vector (such as i1).
5146       if (DL->getTypeSizeInBits(ScalarTy) !=
5147           DL->getTypeAllocSizeInBits(ScalarTy)) {
5148         BS.cancelScheduling(VL, VL0);
5149         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5150                      ReuseShuffleIndicies);
5151         LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n");
5152         return;
5153       }
5154       // Make sure all stores in the bundle are simple - we can't vectorize
5155       // atomic or volatile stores.
5156       SmallVector<Value *, 4> PointerOps(VL.size());
5157       ValueList Operands(VL.size());
5158       auto POIter = PointerOps.begin();
5159       auto OIter = Operands.begin();
5160       for (Value *V : VL) {
5161         auto *SI = cast<StoreInst>(V);
5162         if (!SI->isSimple()) {
5163           BS.cancelScheduling(VL, VL0);
5164           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5165                        ReuseShuffleIndicies);
5166           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n");
5167           return;
5168         }
5169         *POIter = SI->getPointerOperand();
5170         *OIter = SI->getValueOperand();
5171         ++POIter;
5172         ++OIter;
5173       }
5174 
5175       OrdersType CurrentOrder;
5176       // Check the order of pointer operands.
5177       if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) {
5178         Value *Ptr0;
5179         Value *PtrN;
5180         if (CurrentOrder.empty()) {
5181           Ptr0 = PointerOps.front();
5182           PtrN = PointerOps.back();
5183         } else {
5184           Ptr0 = PointerOps[CurrentOrder.front()];
5185           PtrN = PointerOps[CurrentOrder.back()];
5186         }
5187         Optional<int> Dist =
5188             getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE);
5189         // Check that the sorted pointer operands are consecutive.
5190         if (static_cast<unsigned>(*Dist) == VL.size() - 1) {
5191           if (CurrentOrder.empty()) {
5192             // Original stores are consecutive and does not require reordering.
5193             TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
5194                                          UserTreeIdx, ReuseShuffleIndicies);
5195             TE->setOperandsInOrder();
5196             buildTree_rec(Operands, Depth + 1, {TE, 0});
5197             LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
5198           } else {
5199             fixupOrderingIndices(CurrentOrder);
5200             TreeEntry *TE =
5201                 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
5202                              ReuseShuffleIndicies, CurrentOrder);
5203             TE->setOperandsInOrder();
5204             buildTree_rec(Operands, Depth + 1, {TE, 0});
5205             LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n");
5206           }
5207           return;
5208         }
5209       }
5210 
5211       BS.cancelScheduling(VL, VL0);
5212       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5213                    ReuseShuffleIndicies);
5214       LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
5215       return;
5216     }
5217     case Instruction::Call: {
5218       // Check if the calls are all to the same vectorizable intrinsic or
5219       // library function.
5220       CallInst *CI = cast<CallInst>(VL0);
5221       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5222 
5223       VFShape Shape = VFShape::get(
5224           *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())),
5225           false /*HasGlobalPred*/);
5226       Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
5227 
5228       if (!VecFunc && !isTriviallyVectorizable(ID)) {
5229         BS.cancelScheduling(VL, VL0);
5230         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5231                      ReuseShuffleIndicies);
5232         LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
5233         return;
5234       }
5235       Function *F = CI->getCalledFunction();
5236       unsigned NumArgs = CI->arg_size();
5237       SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr);
5238       for (unsigned j = 0; j != NumArgs; ++j)
5239         if (isVectorIntrinsicWithScalarOpAtArg(ID, j))
5240           ScalarArgs[j] = CI->getArgOperand(j);
5241       for (Value *V : VL) {
5242         CallInst *CI2 = dyn_cast<CallInst>(V);
5243         if (!CI2 || CI2->getCalledFunction() != F ||
5244             getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
5245             (VecFunc &&
5246              VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) ||
5247             !CI->hasIdenticalOperandBundleSchema(*CI2)) {
5248           BS.cancelScheduling(VL, VL0);
5249           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5250                        ReuseShuffleIndicies);
5251           LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V
5252                             << "\n");
5253           return;
5254         }
5255         // Some intrinsics have scalar arguments and should be same in order for
5256         // them to be vectorized.
5257         for (unsigned j = 0; j != NumArgs; ++j) {
5258           if (isVectorIntrinsicWithScalarOpAtArg(ID, j)) {
5259             Value *A1J = CI2->getArgOperand(j);
5260             if (ScalarArgs[j] != A1J) {
5261               BS.cancelScheduling(VL, VL0);
5262               newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5263                            ReuseShuffleIndicies);
5264               LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
5265                                 << " argument " << ScalarArgs[j] << "!=" << A1J
5266                                 << "\n");
5267               return;
5268             }
5269           }
5270         }
5271         // Verify that the bundle operands are identical between the two calls.
5272         if (CI->hasOperandBundles() &&
5273             !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
5274                         CI->op_begin() + CI->getBundleOperandsEndIndex(),
5275                         CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
5276           BS.cancelScheduling(VL, VL0);
5277           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5278                        ReuseShuffleIndicies);
5279           LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
5280                             << *CI << "!=" << *V << '\n');
5281           return;
5282         }
5283       }
5284 
5285       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
5286                                    ReuseShuffleIndicies);
5287       TE->setOperandsInOrder();
5288       for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
5289         // For scalar operands no need to to create an entry since no need to
5290         // vectorize it.
5291         if (isVectorIntrinsicWithScalarOpAtArg(ID, i))
5292           continue;
5293         ValueList Operands;
5294         // Prepare the operand vector.
5295         for (Value *V : VL) {
5296           auto *CI2 = cast<CallInst>(V);
5297           Operands.push_back(CI2->getArgOperand(i));
5298         }
5299         buildTree_rec(Operands, Depth + 1, {TE, i});
5300       }
5301       return;
5302     }
5303     case Instruction::ShuffleVector: {
5304       // If this is not an alternate sequence of opcode like add-sub
5305       // then do not vectorize this instruction.
5306       if (!S.isAltShuffle()) {
5307         BS.cancelScheduling(VL, VL0);
5308         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5309                      ReuseShuffleIndicies);
5310         LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
5311         return;
5312       }
5313       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
5314                                    ReuseShuffleIndicies);
5315       LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
5316 
5317       // Reorder operands if reordering would enable vectorization.
5318       auto *CI = dyn_cast<CmpInst>(VL0);
5319       if (isa<BinaryOperator>(VL0) || CI) {
5320         ValueList Left, Right;
5321         if (!CI || all_of(VL, [](Value *V) {
5322               return cast<CmpInst>(V)->isCommutative();
5323             })) {
5324           reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
5325         } else {
5326           CmpInst::Predicate P0 = CI->getPredicate();
5327           CmpInst::Predicate AltP0 = cast<CmpInst>(S.AltOp)->getPredicate();
5328           assert(P0 != AltP0 &&
5329                  "Expected different main/alternate predicates.");
5330           CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
5331           Value *BaseOp0 = VL0->getOperand(0);
5332           Value *BaseOp1 = VL0->getOperand(1);
5333           // Collect operands - commute if it uses the swapped predicate or
5334           // alternate operation.
5335           for (Value *V : VL) {
5336             auto *Cmp = cast<CmpInst>(V);
5337             Value *LHS = Cmp->getOperand(0);
5338             Value *RHS = Cmp->getOperand(1);
5339             CmpInst::Predicate CurrentPred = Cmp->getPredicate();
5340             if (P0 == AltP0Swapped) {
5341               if (CI != Cmp && S.AltOp != Cmp &&
5342                   ((P0 == CurrentPred &&
5343                     !areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)) ||
5344                    (AltP0 == CurrentPred &&
5345                     areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS))))
5346                 std::swap(LHS, RHS);
5347             } else if (P0 != CurrentPred && AltP0 != CurrentPred) {
5348               std::swap(LHS, RHS);
5349             }
5350             Left.push_back(LHS);
5351             Right.push_back(RHS);
5352           }
5353         }
5354         TE->setOperand(0, Left);
5355         TE->setOperand(1, Right);
5356         buildTree_rec(Left, Depth + 1, {TE, 0});
5357         buildTree_rec(Right, Depth + 1, {TE, 1});
5358         return;
5359       }
5360 
5361       TE->setOperandsInOrder();
5362       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
5363         ValueList Operands;
5364         // Prepare the operand vector.
5365         for (Value *V : VL)
5366           Operands.push_back(cast<Instruction>(V)->getOperand(i));
5367 
5368         buildTree_rec(Operands, Depth + 1, {TE, i});
5369       }
5370       return;
5371     }
5372     default:
5373       BS.cancelScheduling(VL, VL0);
5374       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5375                    ReuseShuffleIndicies);
5376       LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
5377       return;
5378   }
5379 }
5380 
5381 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
5382   unsigned N = 1;
5383   Type *EltTy = T;
5384 
5385   while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) ||
5386          isa<VectorType>(EltTy)) {
5387     if (auto *ST = dyn_cast<StructType>(EltTy)) {
5388       // Check that struct is homogeneous.
5389       for (const auto *Ty : ST->elements())
5390         if (Ty != *ST->element_begin())
5391           return 0;
5392       N *= ST->getNumElements();
5393       EltTy = *ST->element_begin();
5394     } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) {
5395       N *= AT->getNumElements();
5396       EltTy = AT->getElementType();
5397     } else {
5398       auto *VT = cast<FixedVectorType>(EltTy);
5399       N *= VT->getNumElements();
5400       EltTy = VT->getElementType();
5401     }
5402   }
5403 
5404   if (!isValidElementType(EltTy))
5405     return 0;
5406   uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N));
5407   if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
5408     return 0;
5409   return N;
5410 }
5411 
5412 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
5413                               SmallVectorImpl<unsigned> &CurrentOrder) const {
5414   const auto *It = find_if(VL, [](Value *V) {
5415     return isa<ExtractElementInst, ExtractValueInst>(V);
5416   });
5417   assert(It != VL.end() && "Expected at least one extract instruction.");
5418   auto *E0 = cast<Instruction>(*It);
5419   assert(all_of(VL,
5420                 [](Value *V) {
5421                   return isa<UndefValue, ExtractElementInst, ExtractValueInst>(
5422                       V);
5423                 }) &&
5424          "Invalid opcode");
5425   // Check if all of the extracts come from the same vector and from the
5426   // correct offset.
5427   Value *Vec = E0->getOperand(0);
5428 
5429   CurrentOrder.clear();
5430 
5431   // We have to extract from a vector/aggregate with the same number of elements.
5432   unsigned NElts;
5433   if (E0->getOpcode() == Instruction::ExtractValue) {
5434     const DataLayout &DL = E0->getModule()->getDataLayout();
5435     NElts = canMapToVector(Vec->getType(), DL);
5436     if (!NElts)
5437       return false;
5438     // Check if load can be rewritten as load of vector.
5439     LoadInst *LI = dyn_cast<LoadInst>(Vec);
5440     if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
5441       return false;
5442   } else {
5443     NElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
5444   }
5445 
5446   if (NElts != VL.size())
5447     return false;
5448 
5449   // Check that all of the indices extract from the correct offset.
5450   bool ShouldKeepOrder = true;
5451   unsigned E = VL.size();
5452   // Assign to all items the initial value E + 1 so we can check if the extract
5453   // instruction index was used already.
5454   // Also, later we can check that all the indices are used and we have a
5455   // consecutive access in the extract instructions, by checking that no
5456   // element of CurrentOrder still has value E + 1.
5457   CurrentOrder.assign(E, E);
5458   unsigned I = 0;
5459   for (; I < E; ++I) {
5460     auto *Inst = dyn_cast<Instruction>(VL[I]);
5461     if (!Inst)
5462       continue;
5463     if (Inst->getOperand(0) != Vec)
5464       break;
5465     if (auto *EE = dyn_cast<ExtractElementInst>(Inst))
5466       if (isa<UndefValue>(EE->getIndexOperand()))
5467         continue;
5468     Optional<unsigned> Idx = getExtractIndex(Inst);
5469     if (!Idx)
5470       break;
5471     const unsigned ExtIdx = *Idx;
5472     if (ExtIdx != I) {
5473       if (ExtIdx >= E || CurrentOrder[ExtIdx] != E)
5474         break;
5475       ShouldKeepOrder = false;
5476       CurrentOrder[ExtIdx] = I;
5477     } else {
5478       if (CurrentOrder[I] != E)
5479         break;
5480       CurrentOrder[I] = I;
5481     }
5482   }
5483   if (I < E) {
5484     CurrentOrder.clear();
5485     return false;
5486   }
5487   if (ShouldKeepOrder)
5488     CurrentOrder.clear();
5489 
5490   return ShouldKeepOrder;
5491 }
5492 
5493 bool BoUpSLP::areAllUsersVectorized(Instruction *I,
5494                                     ArrayRef<Value *> VectorizedVals) const {
5495   return (I->hasOneUse() && is_contained(VectorizedVals, I)) ||
5496          all_of(I->users(), [this](User *U) {
5497            return ScalarToTreeEntry.count(U) > 0 ||
5498                   isVectorLikeInstWithConstOps(U) ||
5499                   (isa<ExtractElementInst>(U) && MustGather.contains(U));
5500          });
5501 }
5502 
5503 static std::pair<InstructionCost, InstructionCost>
5504 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy,
5505                    TargetTransformInfo *TTI, TargetLibraryInfo *TLI) {
5506   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5507 
5508   // Calculate the cost of the scalar and vector calls.
5509   SmallVector<Type *, 4> VecTys;
5510   for (Use &Arg : CI->args())
5511     VecTys.push_back(
5512         FixedVectorType::get(Arg->getType(), VecTy->getNumElements()));
5513   FastMathFlags FMF;
5514   if (auto *FPCI = dyn_cast<FPMathOperator>(CI))
5515     FMF = FPCI->getFastMathFlags();
5516   SmallVector<const Value *> Arguments(CI->args());
5517   IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF,
5518                                     dyn_cast<IntrinsicInst>(CI));
5519   auto IntrinsicCost =
5520     TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput);
5521 
5522   auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
5523                                      VecTy->getNumElements())),
5524                             false /*HasGlobalPred*/);
5525   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
5526   auto LibCost = IntrinsicCost;
5527   if (!CI->isNoBuiltin() && VecFunc) {
5528     // Calculate the cost of the vector library call.
5529     // If the corresponding vector call is cheaper, return its cost.
5530     LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys,
5531                                     TTI::TCK_RecipThroughput);
5532   }
5533   return {IntrinsicCost, LibCost};
5534 }
5535 
5536 /// Compute the cost of creating a vector of type \p VecTy containing the
5537 /// extracted values from \p VL.
5538 static InstructionCost
5539 computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy,
5540                    TargetTransformInfo::ShuffleKind ShuffleKind,
5541                    ArrayRef<int> Mask, TargetTransformInfo &TTI) {
5542   unsigned NumOfParts = TTI.getNumberOfParts(VecTy);
5543 
5544   if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts ||
5545       VecTy->getNumElements() < NumOfParts)
5546     return TTI.getShuffleCost(ShuffleKind, VecTy, Mask);
5547 
5548   bool AllConsecutive = true;
5549   unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts;
5550   unsigned Idx = -1;
5551   InstructionCost Cost = 0;
5552 
5553   // Process extracts in blocks of EltsPerVector to check if the source vector
5554   // operand can be re-used directly. If not, add the cost of creating a shuffle
5555   // to extract the values into a vector register.
5556   SmallVector<int> RegMask(EltsPerVector, UndefMaskElem);
5557   for (auto *V : VL) {
5558     ++Idx;
5559 
5560     // Need to exclude undefs from analysis.
5561     if (isa<UndefValue>(V) || Mask[Idx] == UndefMaskElem)
5562       continue;
5563 
5564     // Reached the start of a new vector registers.
5565     if (Idx % EltsPerVector == 0) {
5566       RegMask.assign(EltsPerVector, UndefMaskElem);
5567       AllConsecutive = true;
5568       continue;
5569     }
5570 
5571     // Check all extracts for a vector register on the target directly
5572     // extract values in order.
5573     unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V));
5574     if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != UndefMaskElem) {
5575       unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1]));
5576       AllConsecutive &= PrevIdx + 1 == CurrentIdx &&
5577                         CurrentIdx % EltsPerVector == Idx % EltsPerVector;
5578       RegMask[Idx % EltsPerVector] = CurrentIdx % EltsPerVector;
5579     }
5580 
5581     if (AllConsecutive)
5582       continue;
5583 
5584     // Skip all indices, except for the last index per vector block.
5585     if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size())
5586       continue;
5587 
5588     // If we have a series of extracts which are not consecutive and hence
5589     // cannot re-use the source vector register directly, compute the shuffle
5590     // cost to extract the vector with EltsPerVector elements.
5591     Cost += TTI.getShuffleCost(
5592         TargetTransformInfo::SK_PermuteSingleSrc,
5593         FixedVectorType::get(VecTy->getElementType(), EltsPerVector), RegMask);
5594   }
5595   return Cost;
5596 }
5597 
5598 /// Build shuffle mask for shuffle graph entries and lists of main and alternate
5599 /// operations operands.
5600 static void
5601 buildShuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices,
5602                       ArrayRef<int> ReusesIndices,
5603                       const function_ref<bool(Instruction *)> IsAltOp,
5604                       SmallVectorImpl<int> &Mask,
5605                       SmallVectorImpl<Value *> *OpScalars = nullptr,
5606                       SmallVectorImpl<Value *> *AltScalars = nullptr) {
5607   unsigned Sz = VL.size();
5608   Mask.assign(Sz, UndefMaskElem);
5609   SmallVector<int> OrderMask;
5610   if (!ReorderIndices.empty())
5611     inversePermutation(ReorderIndices, OrderMask);
5612   for (unsigned I = 0; I < Sz; ++I) {
5613     unsigned Idx = I;
5614     if (!ReorderIndices.empty())
5615       Idx = OrderMask[I];
5616     auto *OpInst = cast<Instruction>(VL[Idx]);
5617     if (IsAltOp(OpInst)) {
5618       Mask[I] = Sz + Idx;
5619       if (AltScalars)
5620         AltScalars->push_back(OpInst);
5621     } else {
5622       Mask[I] = Idx;
5623       if (OpScalars)
5624         OpScalars->push_back(OpInst);
5625     }
5626   }
5627   if (!ReusesIndices.empty()) {
5628     SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem);
5629     transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) {
5630       return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem;
5631     });
5632     Mask.swap(NewMask);
5633   }
5634 }
5635 
5636 /// Checks if the specified instruction \p I is an alternate operation for the
5637 /// given \p MainOp and \p AltOp instructions.
5638 static bool isAlternateInstruction(const Instruction *I,
5639                                    const Instruction *MainOp,
5640                                    const Instruction *AltOp) {
5641   if (auto *CI0 = dyn_cast<CmpInst>(MainOp)) {
5642     auto *AltCI0 = cast<CmpInst>(AltOp);
5643     auto *CI = cast<CmpInst>(I);
5644     CmpInst::Predicate P0 = CI0->getPredicate();
5645     CmpInst::Predicate AltP0 = AltCI0->getPredicate();
5646     assert(P0 != AltP0 && "Expected different main/alternate predicates.");
5647     CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
5648     CmpInst::Predicate CurrentPred = CI->getPredicate();
5649     if (P0 == AltP0Swapped)
5650       return I == AltCI0 ||
5651              (I != MainOp &&
5652               !areCompatibleCmpOps(CI0->getOperand(0), CI0->getOperand(1),
5653                                    CI->getOperand(0), CI->getOperand(1)));
5654     return AltP0 == CurrentPred || AltP0Swapped == CurrentPred;
5655   }
5656   return I->getOpcode() == AltOp->getOpcode();
5657 }
5658 
5659 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E,
5660                                       ArrayRef<Value *> VectorizedVals) {
5661   ArrayRef<Value*> VL = E->Scalars;
5662 
5663   Type *ScalarTy = VL[0]->getType();
5664   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
5665     ScalarTy = SI->getValueOperand()->getType();
5666   else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
5667     ScalarTy = CI->getOperand(0)->getType();
5668   else if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
5669     ScalarTy = IE->getOperand(1)->getType();
5670   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
5671   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
5672 
5673   // If we have computed a smaller type for the expression, update VecTy so
5674   // that the costs will be accurate.
5675   if (MinBWs.count(VL[0]))
5676     VecTy = FixedVectorType::get(
5677         IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
5678   unsigned EntryVF = E->getVectorFactor();
5679   auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF);
5680 
5681   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
5682   // FIXME: it tries to fix a problem with MSVC buildbots.
5683   TargetTransformInfo &TTIRef = *TTI;
5684   auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy,
5685                                VectorizedVals, E](InstructionCost &Cost) {
5686     DenseMap<Value *, int> ExtractVectorsTys;
5687     SmallPtrSet<Value *, 4> CheckedExtracts;
5688     for (auto *V : VL) {
5689       if (isa<UndefValue>(V))
5690         continue;
5691       // If all users of instruction are going to be vectorized and this
5692       // instruction itself is not going to be vectorized, consider this
5693       // instruction as dead and remove its cost from the final cost of the
5694       // vectorized tree.
5695       // Also, avoid adjusting the cost for extractelements with multiple uses
5696       // in different graph entries.
5697       const TreeEntry *VE = getTreeEntry(V);
5698       if (!CheckedExtracts.insert(V).second ||
5699           !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) ||
5700           (VE && VE != E))
5701         continue;
5702       auto *EE = cast<ExtractElementInst>(V);
5703       Optional<unsigned> EEIdx = getExtractIndex(EE);
5704       if (!EEIdx)
5705         continue;
5706       unsigned Idx = *EEIdx;
5707       if (TTIRef.getNumberOfParts(VecTy) !=
5708           TTIRef.getNumberOfParts(EE->getVectorOperandType())) {
5709         auto It =
5710             ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first;
5711         It->getSecond() = std::min<int>(It->second, Idx);
5712       }
5713       // Take credit for instruction that will become dead.
5714       if (EE->hasOneUse()) {
5715         Instruction *Ext = EE->user_back();
5716         if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5717             all_of(Ext->users(),
5718                    [](User *U) { return isa<GetElementPtrInst>(U); })) {
5719           // Use getExtractWithExtendCost() to calculate the cost of
5720           // extractelement/ext pair.
5721           Cost -=
5722               TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(),
5723                                               EE->getVectorOperandType(), Idx);
5724           // Add back the cost of s|zext which is subtracted separately.
5725           Cost += TTIRef.getCastInstrCost(
5726               Ext->getOpcode(), Ext->getType(), EE->getType(),
5727               TTI::getCastContextHint(Ext), CostKind, Ext);
5728           continue;
5729         }
5730       }
5731       Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement,
5732                                         EE->getVectorOperandType(), Idx);
5733     }
5734     // Add a cost for subvector extracts/inserts if required.
5735     for (const auto &Data : ExtractVectorsTys) {
5736       auto *EEVTy = cast<FixedVectorType>(Data.first->getType());
5737       unsigned NumElts = VecTy->getNumElements();
5738       if (Data.second % NumElts == 0)
5739         continue;
5740       if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) {
5741         unsigned Idx = (Data.second / NumElts) * NumElts;
5742         unsigned EENumElts = EEVTy->getNumElements();
5743         if (Idx + NumElts <= EENumElts) {
5744           Cost +=
5745               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5746                                     EEVTy, None, Idx, VecTy);
5747         } else {
5748           // Need to round up the subvector type vectorization factor to avoid a
5749           // crash in cost model functions. Make SubVT so that Idx + VF of SubVT
5750           // <= EENumElts.
5751           auto *SubVT =
5752               FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx);
5753           Cost +=
5754               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5755                                     EEVTy, None, Idx, SubVT);
5756         }
5757       } else {
5758         Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector,
5759                                       VecTy, None, 0, EEVTy);
5760       }
5761     }
5762   };
5763   if (E->State == TreeEntry::NeedToGather) {
5764     if (allConstant(VL))
5765       return 0;
5766     if (isa<InsertElementInst>(VL[0]))
5767       return InstructionCost::getInvalid();
5768     SmallVector<int> Mask;
5769     SmallVector<const TreeEntry *> Entries;
5770     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
5771         isGatherShuffledEntry(E, Mask, Entries);
5772     if (Shuffle.hasValue()) {
5773       InstructionCost GatherCost = 0;
5774       if (ShuffleVectorInst::isIdentityMask(Mask)) {
5775         // Perfect match in the graph, will reuse the previously vectorized
5776         // node. Cost is 0.
5777         LLVM_DEBUG(
5778             dbgs()
5779             << "SLP: perfect diamond match for gather bundle that starts with "
5780             << *VL.front() << ".\n");
5781         if (NeedToShuffleReuses)
5782           GatherCost =
5783               TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5784                                   FinalVecTy, E->ReuseShuffleIndices);
5785       } else {
5786         LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size()
5787                           << " entries for bundle that starts with "
5788                           << *VL.front() << ".\n");
5789         // Detected that instead of gather we can emit a shuffle of single/two
5790         // previously vectorized nodes. Add the cost of the permutation rather
5791         // than gather.
5792         ::addMask(Mask, E->ReuseShuffleIndices);
5793         GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask);
5794       }
5795       return GatherCost;
5796     }
5797     if ((E->getOpcode() == Instruction::ExtractElement ||
5798          all_of(E->Scalars,
5799                 [](Value *V) {
5800                   return isa<ExtractElementInst, UndefValue>(V);
5801                 })) &&
5802         allSameType(VL)) {
5803       // Check that gather of extractelements can be represented as just a
5804       // shuffle of a single/two vectors the scalars are extracted from.
5805       SmallVector<int> Mask;
5806       Optional<TargetTransformInfo::ShuffleKind> ShuffleKind =
5807           isFixedVectorShuffle(VL, Mask);
5808       if (ShuffleKind.hasValue()) {
5809         // Found the bunch of extractelement instructions that must be gathered
5810         // into a vector and can be represented as a permutation elements in a
5811         // single input vector or of 2 input vectors.
5812         InstructionCost Cost =
5813             computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI);
5814         AdjustExtractsCost(Cost);
5815         if (NeedToShuffleReuses)
5816           Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5817                                       FinalVecTy, E->ReuseShuffleIndices);
5818         return Cost;
5819       }
5820     }
5821     if (isSplat(VL)) {
5822       // Found the broadcasting of the single scalar, calculate the cost as the
5823       // broadcast.
5824       assert(VecTy == FinalVecTy &&
5825              "No reused scalars expected for broadcast.");
5826       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy,
5827                                  /*Mask=*/None, /*Index=*/0,
5828                                  /*SubTp=*/nullptr, /*Args=*/VL[0]);
5829     }
5830     InstructionCost ReuseShuffleCost = 0;
5831     if (NeedToShuffleReuses)
5832       ReuseShuffleCost = TTI->getShuffleCost(
5833           TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices);
5834     // Improve gather cost for gather of loads, if we can group some of the
5835     // loads into vector loads.
5836     if (VL.size() > 2 && E->getOpcode() == Instruction::Load &&
5837         !E->isAltShuffle()) {
5838       BoUpSLP::ValueSet VectorizedLoads;
5839       unsigned StartIdx = 0;
5840       unsigned VF = VL.size() / 2;
5841       unsigned VectorizedCnt = 0;
5842       unsigned ScatterVectorizeCnt = 0;
5843       const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType());
5844       for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) {
5845         for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End;
5846              Cnt += VF) {
5847           ArrayRef<Value *> Slice = VL.slice(Cnt, VF);
5848           if (!VectorizedLoads.count(Slice.front()) &&
5849               !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) {
5850             SmallVector<Value *> PointerOps;
5851             OrdersType CurrentOrder;
5852             LoadsState LS = canVectorizeLoads(Slice, Slice.front(), *TTI, *DL,
5853                                               *SE, CurrentOrder, PointerOps);
5854             switch (LS) {
5855             case LoadsState::Vectorize:
5856             case LoadsState::ScatterVectorize:
5857               // Mark the vectorized loads so that we don't vectorize them
5858               // again.
5859               if (LS == LoadsState::Vectorize)
5860                 ++VectorizedCnt;
5861               else
5862                 ++ScatterVectorizeCnt;
5863               VectorizedLoads.insert(Slice.begin(), Slice.end());
5864               // If we vectorized initial block, no need to try to vectorize it
5865               // again.
5866               if (Cnt == StartIdx)
5867                 StartIdx += VF;
5868               break;
5869             case LoadsState::Gather:
5870               break;
5871             }
5872           }
5873         }
5874         // Check if the whole array was vectorized already - exit.
5875         if (StartIdx >= VL.size())
5876           break;
5877         // Found vectorizable parts - exit.
5878         if (!VectorizedLoads.empty())
5879           break;
5880       }
5881       if (!VectorizedLoads.empty()) {
5882         InstructionCost GatherCost = 0;
5883         unsigned NumParts = TTI->getNumberOfParts(VecTy);
5884         bool NeedInsertSubvectorAnalysis =
5885             !NumParts || (VL.size() / VF) > NumParts;
5886         // Get the cost for gathered loads.
5887         for (unsigned I = 0, End = VL.size(); I < End; I += VF) {
5888           if (VectorizedLoads.contains(VL[I]))
5889             continue;
5890           GatherCost += getGatherCost(VL.slice(I, VF));
5891         }
5892         // The cost for vectorized loads.
5893         InstructionCost ScalarsCost = 0;
5894         for (Value *V : VectorizedLoads) {
5895           auto *LI = cast<LoadInst>(V);
5896           ScalarsCost += TTI->getMemoryOpCost(
5897               Instruction::Load, LI->getType(), LI->getAlign(),
5898               LI->getPointerAddressSpace(), CostKind, LI);
5899         }
5900         auto *LI = cast<LoadInst>(E->getMainOp());
5901         auto *LoadTy = FixedVectorType::get(LI->getType(), VF);
5902         Align Alignment = LI->getAlign();
5903         GatherCost +=
5904             VectorizedCnt *
5905             TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment,
5906                                  LI->getPointerAddressSpace(), CostKind, LI);
5907         GatherCost += ScatterVectorizeCnt *
5908                       TTI->getGatherScatterOpCost(
5909                           Instruction::Load, LoadTy, LI->getPointerOperand(),
5910                           /*VariableMask=*/false, Alignment, CostKind, LI);
5911         if (NeedInsertSubvectorAnalysis) {
5912           // Add the cost for the subvectors insert.
5913           for (int I = VF, E = VL.size(); I < E; I += VF)
5914             GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy,
5915                                               None, I, LoadTy);
5916         }
5917         return ReuseShuffleCost + GatherCost - ScalarsCost;
5918       }
5919     }
5920     return ReuseShuffleCost + getGatherCost(VL);
5921   }
5922   InstructionCost CommonCost = 0;
5923   SmallVector<int> Mask;
5924   if (!E->ReorderIndices.empty()) {
5925     SmallVector<int> NewMask;
5926     if (E->getOpcode() == Instruction::Store) {
5927       // For stores the order is actually a mask.
5928       NewMask.resize(E->ReorderIndices.size());
5929       copy(E->ReorderIndices, NewMask.begin());
5930     } else {
5931       inversePermutation(E->ReorderIndices, NewMask);
5932     }
5933     ::addMask(Mask, NewMask);
5934   }
5935   if (NeedToShuffleReuses)
5936     ::addMask(Mask, E->ReuseShuffleIndices);
5937   if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask))
5938     CommonCost =
5939         TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask);
5940   assert((E->State == TreeEntry::Vectorize ||
5941           E->State == TreeEntry::ScatterVectorize) &&
5942          "Unhandled state");
5943   assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
5944   Instruction *VL0 = E->getMainOp();
5945   unsigned ShuffleOrOp =
5946       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
5947   switch (ShuffleOrOp) {
5948     case Instruction::PHI:
5949       return 0;
5950 
5951     case Instruction::ExtractValue:
5952     case Instruction::ExtractElement: {
5953       // The common cost of removal ExtractElement/ExtractValue instructions +
5954       // the cost of shuffles, if required to resuffle the original vector.
5955       if (NeedToShuffleReuses) {
5956         unsigned Idx = 0;
5957         for (unsigned I : E->ReuseShuffleIndices) {
5958           if (ShuffleOrOp == Instruction::ExtractElement) {
5959             auto *EE = cast<ExtractElementInst>(VL[I]);
5960             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5961                                                   EE->getVectorOperandType(),
5962                                                   *getExtractIndex(EE));
5963           } else {
5964             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5965                                                   VecTy, Idx);
5966             ++Idx;
5967           }
5968         }
5969         Idx = EntryVF;
5970         for (Value *V : VL) {
5971           if (ShuffleOrOp == Instruction::ExtractElement) {
5972             auto *EE = cast<ExtractElementInst>(V);
5973             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5974                                                   EE->getVectorOperandType(),
5975                                                   *getExtractIndex(EE));
5976           } else {
5977             --Idx;
5978             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5979                                                   VecTy, Idx);
5980           }
5981         }
5982       }
5983       if (ShuffleOrOp == Instruction::ExtractValue) {
5984         for (unsigned I = 0, E = VL.size(); I < E; ++I) {
5985           auto *EI = cast<Instruction>(VL[I]);
5986           // Take credit for instruction that will become dead.
5987           if (EI->hasOneUse()) {
5988             Instruction *Ext = EI->user_back();
5989             if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5990                 all_of(Ext->users(),
5991                        [](User *U) { return isa<GetElementPtrInst>(U); })) {
5992               // Use getExtractWithExtendCost() to calculate the cost of
5993               // extractelement/ext pair.
5994               CommonCost -= TTI->getExtractWithExtendCost(
5995                   Ext->getOpcode(), Ext->getType(), VecTy, I);
5996               // Add back the cost of s|zext which is subtracted separately.
5997               CommonCost += TTI->getCastInstrCost(
5998                   Ext->getOpcode(), Ext->getType(), EI->getType(),
5999                   TTI::getCastContextHint(Ext), CostKind, Ext);
6000               continue;
6001             }
6002           }
6003           CommonCost -=
6004               TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I);
6005         }
6006       } else {
6007         AdjustExtractsCost(CommonCost);
6008       }
6009       return CommonCost;
6010     }
6011     case Instruction::InsertElement: {
6012       assert(E->ReuseShuffleIndices.empty() &&
6013              "Unique insertelements only are expected.");
6014       auto *SrcVecTy = cast<FixedVectorType>(VL0->getType());
6015 
6016       unsigned const NumElts = SrcVecTy->getNumElements();
6017       unsigned const NumScalars = VL.size();
6018       APInt DemandedElts = APInt::getZero(NumElts);
6019       // TODO: Add support for Instruction::InsertValue.
6020       SmallVector<int> Mask;
6021       if (!E->ReorderIndices.empty()) {
6022         inversePermutation(E->ReorderIndices, Mask);
6023         Mask.append(NumElts - NumScalars, UndefMaskElem);
6024       } else {
6025         Mask.assign(NumElts, UndefMaskElem);
6026         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
6027       }
6028       unsigned Offset = *getInsertIndex(VL0);
6029       bool IsIdentity = true;
6030       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
6031       Mask.swap(PrevMask);
6032       for (unsigned I = 0; I < NumScalars; ++I) {
6033         unsigned InsertIdx = *getInsertIndex(VL[PrevMask[I]]);
6034         DemandedElts.setBit(InsertIdx);
6035         IsIdentity &= InsertIdx - Offset == I;
6036         Mask[InsertIdx - Offset] = I;
6037       }
6038       assert(Offset < NumElts && "Failed to find vector index offset");
6039 
6040       InstructionCost Cost = 0;
6041       Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts,
6042                                             /*Insert*/ true, /*Extract*/ false);
6043 
6044       if (IsIdentity && NumElts != NumScalars && Offset % NumScalars != 0) {
6045         // FIXME: Replace with SK_InsertSubvector once it is properly supported.
6046         unsigned Sz = PowerOf2Ceil(Offset + NumScalars);
6047         Cost += TTI->getShuffleCost(
6048             TargetTransformInfo::SK_PermuteSingleSrc,
6049             FixedVectorType::get(SrcVecTy->getElementType(), Sz));
6050       } else if (!IsIdentity) {
6051         auto *FirstInsert =
6052             cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
6053               return !is_contained(E->Scalars,
6054                                    cast<Instruction>(V)->getOperand(0));
6055             }));
6056         if (isUndefVector(FirstInsert->getOperand(0))) {
6057           Cost += TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, SrcVecTy, Mask);
6058         } else {
6059           SmallVector<int> InsertMask(NumElts);
6060           std::iota(InsertMask.begin(), InsertMask.end(), 0);
6061           for (unsigned I = 0; I < NumElts; I++) {
6062             if (Mask[I] != UndefMaskElem)
6063               InsertMask[Offset + I] = NumElts + I;
6064           }
6065           Cost +=
6066               TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVecTy, InsertMask);
6067         }
6068       }
6069 
6070       return Cost;
6071     }
6072     case Instruction::ZExt:
6073     case Instruction::SExt:
6074     case Instruction::FPToUI:
6075     case Instruction::FPToSI:
6076     case Instruction::FPExt:
6077     case Instruction::PtrToInt:
6078     case Instruction::IntToPtr:
6079     case Instruction::SIToFP:
6080     case Instruction::UIToFP:
6081     case Instruction::Trunc:
6082     case Instruction::FPTrunc:
6083     case Instruction::BitCast: {
6084       Type *SrcTy = VL0->getOperand(0)->getType();
6085       InstructionCost ScalarEltCost =
6086           TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy,
6087                                 TTI::getCastContextHint(VL0), CostKind, VL0);
6088       if (NeedToShuffleReuses) {
6089         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
6090       }
6091 
6092       // Calculate the cost of this instruction.
6093       InstructionCost ScalarCost = VL.size() * ScalarEltCost;
6094 
6095       auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size());
6096       InstructionCost VecCost = 0;
6097       // Check if the values are candidates to demote.
6098       if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
6099         VecCost = CommonCost + TTI->getCastInstrCost(
6100                                    E->getOpcode(), VecTy, SrcVecTy,
6101                                    TTI::getCastContextHint(VL0), CostKind, VL0);
6102       }
6103       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
6104       return VecCost - ScalarCost;
6105     }
6106     case Instruction::FCmp:
6107     case Instruction::ICmp:
6108     case Instruction::Select: {
6109       // Calculate the cost of this instruction.
6110       InstructionCost ScalarEltCost =
6111           TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
6112                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0);
6113       if (NeedToShuffleReuses) {
6114         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
6115       }
6116       auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size());
6117       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
6118 
6119       // Check if all entries in VL are either compares or selects with compares
6120       // as condition that have the same predicates.
6121       CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE;
6122       bool First = true;
6123       for (auto *V : VL) {
6124         CmpInst::Predicate CurrentPred;
6125         auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value());
6126         if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) &&
6127              !match(V, MatchCmp)) ||
6128             (!First && VecPred != CurrentPred)) {
6129           VecPred = CmpInst::BAD_ICMP_PREDICATE;
6130           break;
6131         }
6132         First = false;
6133         VecPred = CurrentPred;
6134       }
6135 
6136       InstructionCost VecCost = TTI->getCmpSelInstrCost(
6137           E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0);
6138       // Check if it is possible and profitable to use min/max for selects in
6139       // VL.
6140       //
6141       auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL);
6142       if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) {
6143         IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy,
6144                                           {VecTy, VecTy});
6145         InstructionCost IntrinsicCost =
6146             TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
6147         // If the selects are the only uses of the compares, they will be dead
6148         // and we can adjust the cost by removing their cost.
6149         if (IntrinsicAndUse.second)
6150           IntrinsicCost -= TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy,
6151                                                    MaskTy, VecPred, CostKind);
6152         VecCost = std::min(VecCost, IntrinsicCost);
6153       }
6154       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
6155       return CommonCost + VecCost - ScalarCost;
6156     }
6157     case Instruction::FNeg:
6158     case Instruction::Add:
6159     case Instruction::FAdd:
6160     case Instruction::Sub:
6161     case Instruction::FSub:
6162     case Instruction::Mul:
6163     case Instruction::FMul:
6164     case Instruction::UDiv:
6165     case Instruction::SDiv:
6166     case Instruction::FDiv:
6167     case Instruction::URem:
6168     case Instruction::SRem:
6169     case Instruction::FRem:
6170     case Instruction::Shl:
6171     case Instruction::LShr:
6172     case Instruction::AShr:
6173     case Instruction::And:
6174     case Instruction::Or:
6175     case Instruction::Xor: {
6176       // Certain instructions can be cheaper to vectorize if they have a
6177       // constant second vector operand.
6178       TargetTransformInfo::OperandValueKind Op1VK =
6179           TargetTransformInfo::OK_AnyValue;
6180       TargetTransformInfo::OperandValueKind Op2VK =
6181           TargetTransformInfo::OK_UniformConstantValue;
6182       TargetTransformInfo::OperandValueProperties Op1VP =
6183           TargetTransformInfo::OP_None;
6184       TargetTransformInfo::OperandValueProperties Op2VP =
6185           TargetTransformInfo::OP_PowerOf2;
6186 
6187       // If all operands are exactly the same ConstantInt then set the
6188       // operand kind to OK_UniformConstantValue.
6189       // If instead not all operands are constants, then set the operand kind
6190       // to OK_AnyValue. If all operands are constants but not the same,
6191       // then set the operand kind to OK_NonUniformConstantValue.
6192       ConstantInt *CInt0 = nullptr;
6193       for (unsigned i = 0, e = VL.size(); i < e; ++i) {
6194         const Instruction *I = cast<Instruction>(VL[i]);
6195         unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0;
6196         ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx));
6197         if (!CInt) {
6198           Op2VK = TargetTransformInfo::OK_AnyValue;
6199           Op2VP = TargetTransformInfo::OP_None;
6200           break;
6201         }
6202         if (Op2VP == TargetTransformInfo::OP_PowerOf2 &&
6203             !CInt->getValue().isPowerOf2())
6204           Op2VP = TargetTransformInfo::OP_None;
6205         if (i == 0) {
6206           CInt0 = CInt;
6207           continue;
6208         }
6209         if (CInt0 != CInt)
6210           Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
6211       }
6212 
6213       SmallVector<const Value *, 4> Operands(VL0->operand_values());
6214       InstructionCost ScalarEltCost =
6215           TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK,
6216                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
6217       if (NeedToShuffleReuses) {
6218         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
6219       }
6220       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
6221       InstructionCost VecCost =
6222           TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK,
6223                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
6224       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
6225       return CommonCost + VecCost - ScalarCost;
6226     }
6227     case Instruction::GetElementPtr: {
6228       TargetTransformInfo::OperandValueKind Op1VK =
6229           TargetTransformInfo::OK_AnyValue;
6230       TargetTransformInfo::OperandValueKind Op2VK =
6231           TargetTransformInfo::OK_UniformConstantValue;
6232 
6233       InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost(
6234           Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK);
6235       if (NeedToShuffleReuses) {
6236         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
6237       }
6238       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
6239       InstructionCost VecCost = TTI->getArithmeticInstrCost(
6240           Instruction::Add, VecTy, CostKind, Op1VK, Op2VK);
6241       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
6242       return CommonCost + VecCost - ScalarCost;
6243     }
6244     case Instruction::Load: {
6245       // Cost of wide load - cost of scalar loads.
6246       Align Alignment = cast<LoadInst>(VL0)->getAlign();
6247       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
6248           Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0);
6249       if (NeedToShuffleReuses) {
6250         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
6251       }
6252       InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost;
6253       InstructionCost VecLdCost;
6254       if (E->State == TreeEntry::Vectorize) {
6255         VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0,
6256                                          CostKind, VL0);
6257       } else {
6258         assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState");
6259         Align CommonAlignment = Alignment;
6260         for (Value *V : VL)
6261           CommonAlignment =
6262               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
6263         VecLdCost = TTI->getGatherScatterOpCost(
6264             Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(),
6265             /*VariableMask=*/false, CommonAlignment, CostKind, VL0);
6266       }
6267       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost));
6268       return CommonCost + VecLdCost - ScalarLdCost;
6269     }
6270     case Instruction::Store: {
6271       // We know that we can merge the stores. Calculate the cost.
6272       bool IsReorder = !E->ReorderIndices.empty();
6273       auto *SI =
6274           cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0);
6275       Align Alignment = SI->getAlign();
6276       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
6277           Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0);
6278       InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost;
6279       InstructionCost VecStCost = TTI->getMemoryOpCost(
6280           Instruction::Store, VecTy, Alignment, 0, CostKind, VL0);
6281       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost));
6282       return CommonCost + VecStCost - ScalarStCost;
6283     }
6284     case Instruction::Call: {
6285       CallInst *CI = cast<CallInst>(VL0);
6286       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
6287 
6288       // Calculate the cost of the scalar and vector calls.
6289       IntrinsicCostAttributes CostAttrs(ID, *CI, 1);
6290       InstructionCost ScalarEltCost =
6291           TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
6292       if (NeedToShuffleReuses) {
6293         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
6294       }
6295       InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
6296 
6297       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
6298       InstructionCost VecCallCost =
6299           std::min(VecCallCosts.first, VecCallCosts.second);
6300 
6301       LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
6302                         << " (" << VecCallCost << "-" << ScalarCallCost << ")"
6303                         << " for " << *CI << "\n");
6304 
6305       return CommonCost + VecCallCost - ScalarCallCost;
6306     }
6307     case Instruction::ShuffleVector: {
6308       assert(E->isAltShuffle() &&
6309              ((Instruction::isBinaryOp(E->getOpcode()) &&
6310                Instruction::isBinaryOp(E->getAltOpcode())) ||
6311               (Instruction::isCast(E->getOpcode()) &&
6312                Instruction::isCast(E->getAltOpcode())) ||
6313               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
6314              "Invalid Shuffle Vector Operand");
6315       InstructionCost ScalarCost = 0;
6316       if (NeedToShuffleReuses) {
6317         for (unsigned Idx : E->ReuseShuffleIndices) {
6318           Instruction *I = cast<Instruction>(VL[Idx]);
6319           CommonCost -= TTI->getInstructionCost(I, CostKind);
6320         }
6321         for (Value *V : VL) {
6322           Instruction *I = cast<Instruction>(V);
6323           CommonCost += TTI->getInstructionCost(I, CostKind);
6324         }
6325       }
6326       for (Value *V : VL) {
6327         Instruction *I = cast<Instruction>(V);
6328         assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
6329         ScalarCost += TTI->getInstructionCost(I, CostKind);
6330       }
6331       // VecCost is equal to sum of the cost of creating 2 vectors
6332       // and the cost of creating shuffle.
6333       InstructionCost VecCost = 0;
6334       // Try to find the previous shuffle node with the same operands and same
6335       // main/alternate ops.
6336       auto &&TryFindNodeWithEqualOperands = [this, E]() {
6337         for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
6338           if (TE.get() == E)
6339             break;
6340           if (TE->isAltShuffle() &&
6341               ((TE->getOpcode() == E->getOpcode() &&
6342                 TE->getAltOpcode() == E->getAltOpcode()) ||
6343                (TE->getOpcode() == E->getAltOpcode() &&
6344                 TE->getAltOpcode() == E->getOpcode())) &&
6345               TE->hasEqualOperands(*E))
6346             return true;
6347         }
6348         return false;
6349       };
6350       if (TryFindNodeWithEqualOperands()) {
6351         LLVM_DEBUG({
6352           dbgs() << "SLP: diamond match for alternate node found.\n";
6353           E->dump();
6354         });
6355         // No need to add new vector costs here since we're going to reuse
6356         // same main/alternate vector ops, just do different shuffling.
6357       } else if (Instruction::isBinaryOp(E->getOpcode())) {
6358         VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind);
6359         VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy,
6360                                                CostKind);
6361       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
6362         VecCost = TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy,
6363                                           Builder.getInt1Ty(),
6364                                           CI0->getPredicate(), CostKind, VL0);
6365         VecCost += TTI->getCmpSelInstrCost(
6366             E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
6367             cast<CmpInst>(E->getAltOp())->getPredicate(), CostKind,
6368             E->getAltOp());
6369       } else {
6370         Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
6371         Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
6372         auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size());
6373         auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size());
6374         VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty,
6375                                         TTI::CastContextHint::None, CostKind);
6376         VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty,
6377                                          TTI::CastContextHint::None, CostKind);
6378       }
6379 
6380       if (E->ReuseShuffleIndices.empty()) {
6381         CommonCost =
6382             TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy);
6383       } else {
6384         SmallVector<int> Mask;
6385         buildShuffleEntryMask(
6386             E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
6387             [E](Instruction *I) {
6388               assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
6389               return I->getOpcode() == E->getAltOpcode();
6390             },
6391             Mask);
6392         CommonCost = TTI->getShuffleCost(TargetTransformInfo::SK_PermuteTwoSrc,
6393                                          FinalVecTy, Mask);
6394       }
6395       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
6396       return CommonCost + VecCost - ScalarCost;
6397     }
6398     default:
6399       llvm_unreachable("Unknown instruction");
6400   }
6401 }
6402 
6403 bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const {
6404   LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
6405                     << VectorizableTree.size() << " is fully vectorizable .\n");
6406 
6407   auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) {
6408     SmallVector<int> Mask;
6409     return TE->State == TreeEntry::NeedToGather &&
6410            !any_of(TE->Scalars,
6411                    [this](Value *V) { return EphValues.contains(V); }) &&
6412            (allConstant(TE->Scalars) || isSplat(TE->Scalars) ||
6413             TE->Scalars.size() < Limit ||
6414             ((TE->getOpcode() == Instruction::ExtractElement ||
6415               all_of(TE->Scalars,
6416                      [](Value *V) {
6417                        return isa<ExtractElementInst, UndefValue>(V);
6418                      })) &&
6419              isFixedVectorShuffle(TE->Scalars, Mask)) ||
6420             (TE->State == TreeEntry::NeedToGather &&
6421              TE->getOpcode() == Instruction::Load && !TE->isAltShuffle()));
6422   };
6423 
6424   // We only handle trees of heights 1 and 2.
6425   if (VectorizableTree.size() == 1 &&
6426       (VectorizableTree[0]->State == TreeEntry::Vectorize ||
6427        (ForReduction &&
6428         AreVectorizableGathers(VectorizableTree[0].get(),
6429                                VectorizableTree[0]->Scalars.size()) &&
6430         VectorizableTree[0]->getVectorFactor() > 2)))
6431     return true;
6432 
6433   if (VectorizableTree.size() != 2)
6434     return false;
6435 
6436   // Handle splat and all-constants stores. Also try to vectorize tiny trees
6437   // with the second gather nodes if they have less scalar operands rather than
6438   // the initial tree element (may be profitable to shuffle the second gather)
6439   // or they are extractelements, which form shuffle.
6440   SmallVector<int> Mask;
6441   if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
6442       AreVectorizableGathers(VectorizableTree[1].get(),
6443                              VectorizableTree[0]->Scalars.size()))
6444     return true;
6445 
6446   // Gathering cost would be too much for tiny trees.
6447   if (VectorizableTree[0]->State == TreeEntry::NeedToGather ||
6448       (VectorizableTree[1]->State == TreeEntry::NeedToGather &&
6449        VectorizableTree[0]->State != TreeEntry::ScatterVectorize))
6450     return false;
6451 
6452   return true;
6453 }
6454 
6455 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts,
6456                                        TargetTransformInfo *TTI,
6457                                        bool MustMatchOrInst) {
6458   // Look past the root to find a source value. Arbitrarily follow the
6459   // path through operand 0 of any 'or'. Also, peek through optional
6460   // shift-left-by-multiple-of-8-bits.
6461   Value *ZextLoad = Root;
6462   const APInt *ShAmtC;
6463   bool FoundOr = false;
6464   while (!isa<ConstantExpr>(ZextLoad) &&
6465          (match(ZextLoad, m_Or(m_Value(), m_Value())) ||
6466           (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) &&
6467            ShAmtC->urem(8) == 0))) {
6468     auto *BinOp = cast<BinaryOperator>(ZextLoad);
6469     ZextLoad = BinOp->getOperand(0);
6470     if (BinOp->getOpcode() == Instruction::Or)
6471       FoundOr = true;
6472   }
6473   // Check if the input is an extended load of the required or/shift expression.
6474   Value *Load;
6475   if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root ||
6476       !match(ZextLoad, m_ZExt(m_Value(Load))) || !isa<LoadInst>(Load))
6477     return false;
6478 
6479   // Require that the total load bit width is a legal integer type.
6480   // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
6481   // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
6482   Type *SrcTy = Load->getType();
6483   unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts;
6484   if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth)))
6485     return false;
6486 
6487   // Everything matched - assume that we can fold the whole sequence using
6488   // load combining.
6489   LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "
6490              << *(cast<Instruction>(Root)) << "\n");
6491 
6492   return true;
6493 }
6494 
6495 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const {
6496   if (RdxKind != RecurKind::Or)
6497     return false;
6498 
6499   unsigned NumElts = VectorizableTree[0]->Scalars.size();
6500   Value *FirstReduced = VectorizableTree[0]->Scalars[0];
6501   return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI,
6502                                     /* MatchOr */ false);
6503 }
6504 
6505 bool BoUpSLP::isLoadCombineCandidate() const {
6506   // Peek through a final sequence of stores and check if all operations are
6507   // likely to be load-combined.
6508   unsigned NumElts = VectorizableTree[0]->Scalars.size();
6509   for (Value *Scalar : VectorizableTree[0]->Scalars) {
6510     Value *X;
6511     if (!match(Scalar, m_Store(m_Value(X), m_Value())) ||
6512         !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true))
6513       return false;
6514   }
6515   return true;
6516 }
6517 
6518 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const {
6519   // No need to vectorize inserts of gathered values.
6520   if (VectorizableTree.size() == 2 &&
6521       isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) &&
6522       VectorizableTree[1]->State == TreeEntry::NeedToGather)
6523     return true;
6524 
6525   // We can vectorize the tree if its size is greater than or equal to the
6526   // minimum size specified by the MinTreeSize command line option.
6527   if (VectorizableTree.size() >= MinTreeSize)
6528     return false;
6529 
6530   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
6531   // can vectorize it if we can prove it fully vectorizable.
6532   if (isFullyVectorizableTinyTree(ForReduction))
6533     return false;
6534 
6535   assert(VectorizableTree.empty()
6536              ? ExternalUses.empty()
6537              : true && "We shouldn't have any external users");
6538 
6539   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
6540   // vectorizable.
6541   return true;
6542 }
6543 
6544 InstructionCost BoUpSLP::getSpillCost() const {
6545   // Walk from the bottom of the tree to the top, tracking which values are
6546   // live. When we see a call instruction that is not part of our tree,
6547   // query TTI to see if there is a cost to keeping values live over it
6548   // (for example, if spills and fills are required).
6549   unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
6550   InstructionCost Cost = 0;
6551 
6552   SmallPtrSet<Instruction*, 4> LiveValues;
6553   Instruction *PrevInst = nullptr;
6554 
6555   // The entries in VectorizableTree are not necessarily ordered by their
6556   // position in basic blocks. Collect them and order them by dominance so later
6557   // instructions are guaranteed to be visited first. For instructions in
6558   // different basic blocks, we only scan to the beginning of the block, so
6559   // their order does not matter, as long as all instructions in a basic block
6560   // are grouped together. Using dominance ensures a deterministic order.
6561   SmallVector<Instruction *, 16> OrderedScalars;
6562   for (const auto &TEPtr : VectorizableTree) {
6563     Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
6564     if (!Inst)
6565       continue;
6566     OrderedScalars.push_back(Inst);
6567   }
6568   llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) {
6569     auto *NodeA = DT->getNode(A->getParent());
6570     auto *NodeB = DT->getNode(B->getParent());
6571     assert(NodeA && "Should only process reachable instructions");
6572     assert(NodeB && "Should only process reachable instructions");
6573     assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
6574            "Different nodes should have different DFS numbers");
6575     if (NodeA != NodeB)
6576       return NodeA->getDFSNumIn() < NodeB->getDFSNumIn();
6577     return B->comesBefore(A);
6578   });
6579 
6580   for (Instruction *Inst : OrderedScalars) {
6581     if (!PrevInst) {
6582       PrevInst = Inst;
6583       continue;
6584     }
6585 
6586     // Update LiveValues.
6587     LiveValues.erase(PrevInst);
6588     for (auto &J : PrevInst->operands()) {
6589       if (isa<Instruction>(&*J) && getTreeEntry(&*J))
6590         LiveValues.insert(cast<Instruction>(&*J));
6591     }
6592 
6593     LLVM_DEBUG({
6594       dbgs() << "SLP: #LV: " << LiveValues.size();
6595       for (auto *X : LiveValues)
6596         dbgs() << " " << X->getName();
6597       dbgs() << ", Looking at ";
6598       Inst->dump();
6599     });
6600 
6601     // Now find the sequence of instructions between PrevInst and Inst.
6602     unsigned NumCalls = 0;
6603     BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
6604                                  PrevInstIt =
6605                                      PrevInst->getIterator().getReverse();
6606     while (InstIt != PrevInstIt) {
6607       if (PrevInstIt == PrevInst->getParent()->rend()) {
6608         PrevInstIt = Inst->getParent()->rbegin();
6609         continue;
6610       }
6611 
6612       // Debug information does not impact spill cost.
6613       if ((isa<CallInst>(&*PrevInstIt) &&
6614            !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
6615           &*PrevInstIt != PrevInst)
6616         NumCalls++;
6617 
6618       ++PrevInstIt;
6619     }
6620 
6621     if (NumCalls) {
6622       SmallVector<Type*, 4> V;
6623       for (auto *II : LiveValues) {
6624         auto *ScalarTy = II->getType();
6625         if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy))
6626           ScalarTy = VectorTy->getElementType();
6627         V.push_back(FixedVectorType::get(ScalarTy, BundleWidth));
6628       }
6629       Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
6630     }
6631 
6632     PrevInst = Inst;
6633   }
6634 
6635   return Cost;
6636 }
6637 
6638 /// Check if two insertelement instructions are from the same buildvector.
6639 static bool areTwoInsertFromSameBuildVector(InsertElementInst *VU,
6640                                             InsertElementInst *V) {
6641   // Instructions must be from the same basic blocks.
6642   if (VU->getParent() != V->getParent())
6643     return false;
6644   // Checks if 2 insertelements are from the same buildvector.
6645   if (VU->getType() != V->getType())
6646     return false;
6647   // Multiple used inserts are separate nodes.
6648   if (!VU->hasOneUse() && !V->hasOneUse())
6649     return false;
6650   auto *IE1 = VU;
6651   auto *IE2 = V;
6652   unsigned Idx1 = *getInsertIndex(IE1);
6653   unsigned Idx2 = *getInsertIndex(IE2);
6654   // Go through the vector operand of insertelement instructions trying to find
6655   // either VU as the original vector for IE2 or V as the original vector for
6656   // IE1.
6657   do {
6658     if (IE2 == VU)
6659       return VU->hasOneUse();
6660     if (IE1 == V)
6661       return V->hasOneUse();
6662     if (IE1) {
6663       if ((IE1 != VU && !IE1->hasOneUse()) ||
6664           getInsertIndex(IE1).getValueOr(Idx2) == Idx2)
6665         IE1 = nullptr;
6666       else
6667         IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0));
6668     }
6669     if (IE2) {
6670       if ((IE2 != V && !IE2->hasOneUse()) ||
6671           getInsertIndex(IE2).getValueOr(Idx1) == Idx1)
6672         IE2 = nullptr;
6673       else
6674         IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0));
6675     }
6676   } while (IE1 || IE2);
6677   return false;
6678 }
6679 
6680 /// Checks if the \p IE1 instructions is followed by \p IE2 instruction in the
6681 /// buildvector sequence.
6682 static bool isFirstInsertElement(const InsertElementInst *IE1,
6683                                  const InsertElementInst *IE2) {
6684   if (IE1 == IE2)
6685     return false;
6686   const auto *I1 = IE1;
6687   const auto *I2 = IE2;
6688   const InsertElementInst *PrevI1;
6689   const InsertElementInst *PrevI2;
6690   unsigned Idx1 = *getInsertIndex(IE1);
6691   unsigned Idx2 = *getInsertIndex(IE2);
6692   do {
6693     if (I2 == IE1)
6694       return true;
6695     if (I1 == IE2)
6696       return false;
6697     PrevI1 = I1;
6698     PrevI2 = I2;
6699     if (I1 && (I1 == IE1 || I1->hasOneUse()) &&
6700         getInsertIndex(I1).getValueOr(Idx2) != Idx2)
6701       I1 = dyn_cast<InsertElementInst>(I1->getOperand(0));
6702     if (I2 && ((I2 == IE2 || I2->hasOneUse())) &&
6703         getInsertIndex(I2).getValueOr(Idx1) != Idx1)
6704       I2 = dyn_cast<InsertElementInst>(I2->getOperand(0));
6705   } while ((I1 && PrevI1 != I1) || (I2 && PrevI2 != I2));
6706   llvm_unreachable("Two different buildvectors not expected.");
6707 }
6708 
6709 namespace {
6710 /// Returns incoming Value *, if the requested type is Value * too, or a default
6711 /// value, otherwise.
6712 struct ValueSelect {
6713   template <typename U>
6714   static typename std::enable_if<std::is_same<Value *, U>::value, Value *>::type
6715   get(Value *V) {
6716     return V;
6717   }
6718   template <typename U>
6719   static typename std::enable_if<!std::is_same<Value *, U>::value, U>::type
6720   get(Value *) {
6721     return U();
6722   }
6723 };
6724 } // namespace
6725 
6726 /// Does the analysis of the provided shuffle masks and performs the requested
6727 /// actions on the vectors with the given shuffle masks. It tries to do it in
6728 /// several steps.
6729 /// 1. If the Base vector is not undef vector, resizing the very first mask to
6730 /// have common VF and perform action for 2 input vectors (including non-undef
6731 /// Base). Other shuffle masks are combined with the resulting after the 1 stage
6732 /// and processed as a shuffle of 2 elements.
6733 /// 2. If the Base is undef vector and have only 1 shuffle mask, perform the
6734 /// action only for 1 vector with the given mask, if it is not the identity
6735 /// mask.
6736 /// 3. If > 2 masks are used, perform the remaining shuffle actions for 2
6737 /// vectors, combing the masks properly between the steps.
6738 template <typename T>
6739 static T *performExtractsShuffleAction(
6740     MutableArrayRef<std::pair<T *, SmallVector<int>>> ShuffleMask, Value *Base,
6741     function_ref<unsigned(T *)> GetVF,
6742     function_ref<std::pair<T *, bool>(T *, ArrayRef<int>)> ResizeAction,
6743     function_ref<T *(ArrayRef<int>, ArrayRef<T *>)> Action) {
6744   assert(!ShuffleMask.empty() && "Empty list of shuffles for inserts.");
6745   SmallVector<int> Mask(ShuffleMask.begin()->second);
6746   auto VMIt = std::next(ShuffleMask.begin());
6747   T *Prev = nullptr;
6748   bool IsBaseNotUndef = !isUndefVector(Base);
6749   if (IsBaseNotUndef) {
6750     // Base is not undef, need to combine it with the next subvectors.
6751     std::pair<T *, bool> Res = ResizeAction(ShuffleMask.begin()->first, Mask);
6752     for (unsigned Idx = 0, VF = Mask.size(); Idx < VF; ++Idx) {
6753       if (Mask[Idx] == UndefMaskElem)
6754         Mask[Idx] = Idx;
6755       else
6756         Mask[Idx] = (Res.second ? Idx : Mask[Idx]) + VF;
6757     }
6758     auto *V = ValueSelect::get<T *>(Base);
6759     (void)V;
6760     assert((!V || GetVF(V) == Mask.size()) &&
6761            "Expected base vector of VF number of elements.");
6762     Prev = Action(Mask, {nullptr, Res.first});
6763   } else if (ShuffleMask.size() == 1) {
6764     // Base is undef and only 1 vector is shuffled - perform the action only for
6765     // single vector, if the mask is not the identity mask.
6766     std::pair<T *, bool> Res = ResizeAction(ShuffleMask.begin()->first, Mask);
6767     if (Res.second)
6768       // Identity mask is found.
6769       Prev = Res.first;
6770     else
6771       Prev = Action(Mask, {ShuffleMask.begin()->first});
6772   } else {
6773     // Base is undef and at least 2 input vectors shuffled - perform 2 vectors
6774     // shuffles step by step, combining shuffle between the steps.
6775     unsigned Vec1VF = GetVF(ShuffleMask.begin()->first);
6776     unsigned Vec2VF = GetVF(VMIt->first);
6777     if (Vec1VF == Vec2VF) {
6778       // No need to resize the input vectors since they are of the same size, we
6779       // can shuffle them directly.
6780       ArrayRef<int> SecMask = VMIt->second;
6781       for (unsigned I = 0, VF = Mask.size(); I < VF; ++I) {
6782         if (SecMask[I] != UndefMaskElem) {
6783           assert(Mask[I] == UndefMaskElem && "Multiple uses of scalars.");
6784           Mask[I] = SecMask[I] + Vec1VF;
6785         }
6786       }
6787       Prev = Action(Mask, {ShuffleMask.begin()->first, VMIt->first});
6788     } else {
6789       // Vectors of different sizes - resize and reshuffle.
6790       std::pair<T *, bool> Res1 =
6791           ResizeAction(ShuffleMask.begin()->first, Mask);
6792       std::pair<T *, bool> Res2 = ResizeAction(VMIt->first, VMIt->second);
6793       ArrayRef<int> SecMask = VMIt->second;
6794       for (unsigned I = 0, VF = Mask.size(); I < VF; ++I) {
6795         if (Mask[I] != UndefMaskElem) {
6796           assert(SecMask[I] == UndefMaskElem && "Multiple uses of scalars.");
6797           if (Res1.second)
6798             Mask[I] = I;
6799         } else if (SecMask[I] != UndefMaskElem) {
6800           assert(Mask[I] == UndefMaskElem && "Multiple uses of scalars.");
6801           Mask[I] = (Res2.second ? I : SecMask[I]) + VF;
6802         }
6803       }
6804       Prev = Action(Mask, {Res1.first, Res2.first});
6805     }
6806     VMIt = std::next(VMIt);
6807   }
6808   // Perform requested actions for the remaining masks/vectors.
6809   for (auto E = ShuffleMask.end(); VMIt != E; ++VMIt) {
6810     // Shuffle other input vectors, if any.
6811     std::pair<T *, bool> Res = ResizeAction(VMIt->first, VMIt->second);
6812     ArrayRef<int> SecMask = VMIt->second;
6813     for (unsigned I = 0, VF = Mask.size(); I < VF; ++I) {
6814       if (SecMask[I] != UndefMaskElem) {
6815         assert((Mask[I] == UndefMaskElem || IsBaseNotUndef) &&
6816                "Multiple uses of scalars.");
6817         Mask[I] = (Res.second ? I : SecMask[I]) + VF;
6818       } else if (Mask[I] != UndefMaskElem) {
6819         Mask[I] = I;
6820       }
6821     }
6822     Prev = Action(Mask, {Prev, Res.first});
6823   }
6824   return Prev;
6825 }
6826 
6827 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) {
6828   InstructionCost Cost = 0;
6829   LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
6830                     << VectorizableTree.size() << ".\n");
6831 
6832   unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
6833 
6834   for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
6835     TreeEntry &TE = *VectorizableTree[I];
6836 
6837     InstructionCost C = getEntryCost(&TE, VectorizedVals);
6838     Cost += C;
6839     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6840                       << " for bundle that starts with " << *TE.Scalars[0]
6841                       << ".\n"
6842                       << "SLP: Current total cost = " << Cost << "\n");
6843   }
6844 
6845   SmallPtrSet<Value *, 16> ExtractCostCalculated;
6846   InstructionCost ExtractCost = 0;
6847   SmallVector<MapVector<const TreeEntry *, SmallVector<int>>> ShuffleMasks;
6848   SmallVector<std::pair<Value *, const TreeEntry *>> FirstUsers;
6849   SmallVector<APInt> DemandedElts;
6850   for (ExternalUser &EU : ExternalUses) {
6851     // We only add extract cost once for the same scalar.
6852     if (!isa_and_nonnull<InsertElementInst>(EU.User) &&
6853         !ExtractCostCalculated.insert(EU.Scalar).second)
6854       continue;
6855 
6856     // Uses by ephemeral values are free (because the ephemeral value will be
6857     // removed prior to code generation, and so the extraction will be
6858     // removed as well).
6859     if (EphValues.count(EU.User))
6860       continue;
6861 
6862     // No extract cost for vector "scalar"
6863     if (isa<FixedVectorType>(EU.Scalar->getType()))
6864       continue;
6865 
6866     // Already counted the cost for external uses when tried to adjust the cost
6867     // for extractelements, no need to add it again.
6868     if (isa<ExtractElementInst>(EU.Scalar))
6869       continue;
6870 
6871     // If found user is an insertelement, do not calculate extract cost but try
6872     // to detect it as a final shuffled/identity match.
6873     if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) {
6874       if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) {
6875         Optional<unsigned> InsertIdx = getInsertIndex(VU);
6876         if (InsertIdx) {
6877           const TreeEntry *ScalarTE = getTreeEntry(EU.Scalar);
6878           auto *It =
6879               find_if(FirstUsers,
6880                       [VU](const std::pair<Value *, const TreeEntry *> &Pair) {
6881                         return areTwoInsertFromSameBuildVector(
6882                             VU, cast<InsertElementInst>(Pair.first));
6883                       });
6884           int VecId = -1;
6885           if (It == FirstUsers.end()) {
6886             (void)ShuffleMasks.emplace_back();
6887             SmallVectorImpl<int> &Mask = ShuffleMasks.back()[ScalarTE];
6888             if (Mask.empty())
6889               Mask.assign(FTy->getNumElements(), UndefMaskElem);
6890             // Find the insertvector, vectorized in tree, if any.
6891             Value *Base = VU;
6892             while (auto *IEBase = dyn_cast<InsertElementInst>(Base)) {
6893               if (IEBase != EU.User &&
6894                   (!IEBase->hasOneUse() ||
6895                    getInsertIndex(IEBase).getValueOr(*InsertIdx) == *InsertIdx))
6896                 break;
6897               // Build the mask for the vectorized insertelement instructions.
6898               if (const TreeEntry *E = getTreeEntry(IEBase)) {
6899                 VU = IEBase;
6900                 do {
6901                   IEBase = cast<InsertElementInst>(Base);
6902                   int Idx = *getInsertIndex(IEBase);
6903                   assert(Mask[Idx] == UndefMaskElem &&
6904                          "InsertElementInstruction used already.");
6905                   Mask[Idx] = Idx;
6906                   Base = IEBase->getOperand(0);
6907                 } while (E == getTreeEntry(Base));
6908                 break;
6909               }
6910               Base = cast<InsertElementInst>(Base)->getOperand(0);
6911             }
6912             FirstUsers.emplace_back(VU, ScalarTE);
6913             DemandedElts.push_back(APInt::getZero(FTy->getNumElements()));
6914             VecId = FirstUsers.size() - 1;
6915           } else {
6916             if (isFirstInsertElement(VU, cast<InsertElementInst>(It->first)))
6917               It->first = VU;
6918             VecId = std::distance(FirstUsers.begin(), It);
6919           }
6920           int InIdx = *InsertIdx;
6921           SmallVectorImpl<int> &Mask = ShuffleMasks[VecId][ScalarTE];
6922           if (Mask.empty())
6923             Mask.assign(FTy->getNumElements(), UndefMaskElem);
6924           Mask[InIdx] = EU.Lane;
6925           DemandedElts[VecId].setBit(InIdx);
6926           continue;
6927         }
6928       }
6929     }
6930 
6931     // If we plan to rewrite the tree in a smaller type, we will need to sign
6932     // extend the extracted value back to the original type. Here, we account
6933     // for the extract and the added cost of the sign extend if needed.
6934     auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth);
6935     auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
6936     if (MinBWs.count(ScalarRoot)) {
6937       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
6938       auto Extend =
6939           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
6940       VecTy = FixedVectorType::get(MinTy, BundleWidth);
6941       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
6942                                                    VecTy, EU.Lane);
6943     } else {
6944       ExtractCost +=
6945           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
6946     }
6947   }
6948 
6949   InstructionCost SpillCost = getSpillCost();
6950   Cost += SpillCost + ExtractCost;
6951   auto &&ResizeToVF = [this, &Cost](const TreeEntry *TE, ArrayRef<int> Mask) {
6952     InstructionCost C = 0;
6953     unsigned VF = Mask.size();
6954     unsigned VecVF = TE->getVectorFactor();
6955     if (VF != VecVF &&
6956         (any_of(Mask, [VF](int Idx) { return Idx >= static_cast<int>(VF); }) ||
6957          (all_of(Mask,
6958                  [VF](int Idx) { return Idx < 2 * static_cast<int>(VF); }) &&
6959           !ShuffleVectorInst::isIdentityMask(Mask)))) {
6960       SmallVector<int> OrigMask(VecVF, UndefMaskElem);
6961       std::copy(Mask.begin(), std::next(Mask.begin(), std::min(VF, VecVF)),
6962                 OrigMask.begin());
6963       C = TTI->getShuffleCost(
6964           TTI::SK_PermuteSingleSrc,
6965           FixedVectorType::get(TE->getMainOp()->getType(), VecVF), OrigMask);
6966       LLVM_DEBUG(
6967           dbgs() << "SLP: Adding cost " << C
6968                  << " for final shuffle of insertelement external users.\n";
6969           TE->dump(); dbgs() << "SLP: Current total cost = " << Cost << "\n");
6970       Cost += C;
6971       return std::make_pair(TE, true);
6972     }
6973     return std::make_pair(TE, false);
6974   };
6975   // Calculate the cost of the reshuffled vectors, if any.
6976   for (int I = 0, E = FirstUsers.size(); I < E; ++I) {
6977     Value *Base = cast<Instruction>(FirstUsers[I].first)->getOperand(0);
6978     unsigned VF = ShuffleMasks[I].begin()->second.size();
6979     auto *FTy = FixedVectorType::get(
6980         cast<VectorType>(FirstUsers[I].first->getType())->getElementType(), VF);
6981     auto Vector = ShuffleMasks[I].takeVector();
6982     auto &&EstimateShufflesCost = [this, FTy,
6983                                    &Cost](ArrayRef<int> Mask,
6984                                           ArrayRef<const TreeEntry *> TEs) {
6985       assert((TEs.size() == 1 || TEs.size() == 2) &&
6986              "Expected exactly 1 or 2 tree entries.");
6987       if (TEs.size() == 1) {
6988         int Limit = 2 * Mask.size();
6989         if (!all_of(Mask, [Limit](int Idx) { return Idx < Limit; }) ||
6990             !ShuffleVectorInst::isIdentityMask(Mask)) {
6991           InstructionCost C =
6992               TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FTy, Mask);
6993           LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6994                             << " for final shuffle of insertelement "
6995                                "external users.\n";
6996                      TEs.front()->dump();
6997                      dbgs() << "SLP: Current total cost = " << Cost << "\n");
6998           Cost += C;
6999         }
7000       } else {
7001         InstructionCost C =
7002             TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, FTy, Mask);
7003         LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
7004                           << " for final shuffle of vector node and external "
7005                              "insertelement users.\n";
7006                    if (TEs.front()) { TEs.front()->dump(); } TEs.back()->dump();
7007                    dbgs() << "SLP: Current total cost = " << Cost << "\n");
7008         Cost += C;
7009       }
7010       return TEs.back();
7011     };
7012     (void)performExtractsShuffleAction<const TreeEntry>(
7013         makeMutableArrayRef(Vector.data(), Vector.size()), Base,
7014         [](const TreeEntry *E) { return E->getVectorFactor(); }, ResizeToVF,
7015         EstimateShufflesCost);
7016     InstructionCost InsertCost = TTI->getScalarizationOverhead(
7017         cast<FixedVectorType>(FirstUsers[I].first->getType()), DemandedElts[I],
7018         /*Insert*/ true, /*Extract*/ false);
7019     Cost -= InsertCost;
7020   }
7021 
7022 #ifndef NDEBUG
7023   SmallString<256> Str;
7024   {
7025     raw_svector_ostream OS(Str);
7026     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
7027        << "SLP: Extract Cost = " << ExtractCost << ".\n"
7028        << "SLP: Total Cost = " << Cost << ".\n";
7029   }
7030   LLVM_DEBUG(dbgs() << Str);
7031   if (ViewSLPTree)
7032     ViewGraph(this, "SLP" + F->getName(), false, Str);
7033 #endif
7034 
7035   return Cost;
7036 }
7037 
7038 Optional<TargetTransformInfo::ShuffleKind>
7039 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
7040                                SmallVectorImpl<const TreeEntry *> &Entries) {
7041   // TODO: currently checking only for Scalars in the tree entry, need to count
7042   // reused elements too for better cost estimation.
7043   Mask.assign(TE->Scalars.size(), UndefMaskElem);
7044   Entries.clear();
7045   // Build a lists of values to tree entries.
7046   DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs;
7047   for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) {
7048     if (EntryPtr.get() == TE)
7049       break;
7050     if (EntryPtr->State != TreeEntry::NeedToGather)
7051       continue;
7052     for (Value *V : EntryPtr->Scalars)
7053       ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get());
7054   }
7055   // Find all tree entries used by the gathered values. If no common entries
7056   // found - not a shuffle.
7057   // Here we build a set of tree nodes for each gathered value and trying to
7058   // find the intersection between these sets. If we have at least one common
7059   // tree node for each gathered value - we have just a permutation of the
7060   // single vector. If we have 2 different sets, we're in situation where we
7061   // have a permutation of 2 input vectors.
7062   SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs;
7063   DenseMap<Value *, int> UsedValuesEntry;
7064   for (Value *V : TE->Scalars) {
7065     if (isa<UndefValue>(V))
7066       continue;
7067     // Build a list of tree entries where V is used.
7068     SmallPtrSet<const TreeEntry *, 4> VToTEs;
7069     auto It = ValueToTEs.find(V);
7070     if (It != ValueToTEs.end())
7071       VToTEs = It->second;
7072     if (const TreeEntry *VTE = getTreeEntry(V))
7073       VToTEs.insert(VTE);
7074     if (VToTEs.empty())
7075       return None;
7076     if (UsedTEs.empty()) {
7077       // The first iteration, just insert the list of nodes to vector.
7078       UsedTEs.push_back(VToTEs);
7079     } else {
7080       // Need to check if there are any previously used tree nodes which use V.
7081       // If there are no such nodes, consider that we have another one input
7082       // vector.
7083       SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs);
7084       unsigned Idx = 0;
7085       for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) {
7086         // Do we have a non-empty intersection of previously listed tree entries
7087         // and tree entries using current V?
7088         set_intersect(VToTEs, Set);
7089         if (!VToTEs.empty()) {
7090           // Yes, write the new subset and continue analysis for the next
7091           // scalar.
7092           Set.swap(VToTEs);
7093           break;
7094         }
7095         VToTEs = SavedVToTEs;
7096         ++Idx;
7097       }
7098       // No non-empty intersection found - need to add a second set of possible
7099       // source vectors.
7100       if (Idx == UsedTEs.size()) {
7101         // If the number of input vectors is greater than 2 - not a permutation,
7102         // fallback to the regular gather.
7103         if (UsedTEs.size() == 2)
7104           return None;
7105         UsedTEs.push_back(SavedVToTEs);
7106         Idx = UsedTEs.size() - 1;
7107       }
7108       UsedValuesEntry.try_emplace(V, Idx);
7109     }
7110   }
7111 
7112   if (UsedTEs.empty()) {
7113     assert(all_of(TE->Scalars, UndefValue::classof) &&
7114            "Expected vector of undefs only.");
7115     return None;
7116   }
7117 
7118   unsigned VF = 0;
7119   if (UsedTEs.size() == 1) {
7120     // Try to find the perfect match in another gather node at first.
7121     auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) {
7122       return EntryPtr->isSame(TE->Scalars);
7123     });
7124     if (It != UsedTEs.front().end()) {
7125       Entries.push_back(*It);
7126       std::iota(Mask.begin(), Mask.end(), 0);
7127       return TargetTransformInfo::SK_PermuteSingleSrc;
7128     }
7129     // No perfect match, just shuffle, so choose the first tree node.
7130     Entries.push_back(*UsedTEs.front().begin());
7131   } else {
7132     // Try to find nodes with the same vector factor.
7133     assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries.");
7134     DenseMap<int, const TreeEntry *> VFToTE;
7135     for (const TreeEntry *TE : UsedTEs.front())
7136       VFToTE.try_emplace(TE->getVectorFactor(), TE);
7137     for (const TreeEntry *TE : UsedTEs.back()) {
7138       auto It = VFToTE.find(TE->getVectorFactor());
7139       if (It != VFToTE.end()) {
7140         VF = It->first;
7141         Entries.push_back(It->second);
7142         Entries.push_back(TE);
7143         break;
7144       }
7145     }
7146     // No 2 source vectors with the same vector factor - give up and do regular
7147     // gather.
7148     if (Entries.empty())
7149       return None;
7150   }
7151 
7152   // Build a shuffle mask for better cost estimation and vector emission.
7153   for (int I = 0, E = TE->Scalars.size(); I < E; ++I) {
7154     Value *V = TE->Scalars[I];
7155     if (isa<UndefValue>(V))
7156       continue;
7157     unsigned Idx = UsedValuesEntry.lookup(V);
7158     const TreeEntry *VTE = Entries[Idx];
7159     int FoundLane = VTE->findLaneForValue(V);
7160     Mask[I] = Idx * VF + FoundLane;
7161     // Extra check required by isSingleSourceMaskImpl function (called by
7162     // ShuffleVectorInst::isSingleSourceMask).
7163     if (Mask[I] >= 2 * E)
7164       return None;
7165   }
7166   switch (Entries.size()) {
7167   case 1:
7168     return TargetTransformInfo::SK_PermuteSingleSrc;
7169   case 2:
7170     return TargetTransformInfo::SK_PermuteTwoSrc;
7171   default:
7172     break;
7173   }
7174   return None;
7175 }
7176 
7177 InstructionCost BoUpSLP::getGatherCost(FixedVectorType *Ty,
7178                                        const APInt &ShuffledIndices,
7179                                        bool NeedToShuffle) const {
7180   InstructionCost Cost =
7181       TTI->getScalarizationOverhead(Ty, ~ShuffledIndices, /*Insert*/ true,
7182                                     /*Extract*/ false);
7183   if (NeedToShuffle)
7184     Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
7185   return Cost;
7186 }
7187 
7188 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
7189   // Find the type of the operands in VL.
7190   Type *ScalarTy = VL[0]->getType();
7191   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
7192     ScalarTy = SI->getValueOperand()->getType();
7193   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
7194   bool DuplicateNonConst = false;
7195   // Find the cost of inserting/extracting values from the vector.
7196   // Check if the same elements are inserted several times and count them as
7197   // shuffle candidates.
7198   APInt ShuffledElements = APInt::getZero(VL.size());
7199   DenseSet<Value *> UniqueElements;
7200   // Iterate in reverse order to consider insert elements with the high cost.
7201   for (unsigned I = VL.size(); I > 0; --I) {
7202     unsigned Idx = I - 1;
7203     // No need to shuffle duplicates for constants.
7204     if (isConstant(VL[Idx])) {
7205       ShuffledElements.setBit(Idx);
7206       continue;
7207     }
7208     if (!UniqueElements.insert(VL[Idx]).second) {
7209       DuplicateNonConst = true;
7210       ShuffledElements.setBit(Idx);
7211     }
7212   }
7213   return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst);
7214 }
7215 
7216 // Perform operand reordering on the instructions in VL and return the reordered
7217 // operands in Left and Right.
7218 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
7219                                              SmallVectorImpl<Value *> &Left,
7220                                              SmallVectorImpl<Value *> &Right,
7221                                              const DataLayout &DL,
7222                                              ScalarEvolution &SE,
7223                                              const BoUpSLP &R) {
7224   if (VL.empty())
7225     return;
7226   VLOperands Ops(VL, DL, SE, R);
7227   // Reorder the operands in place.
7228   Ops.reorder();
7229   Left = Ops.getVL(0);
7230   Right = Ops.getVL(1);
7231 }
7232 
7233 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) {
7234   // Get the basic block this bundle is in. All instructions in the bundle
7235   // should be in this block.
7236   auto *Front = E->getMainOp();
7237   auto *BB = Front->getParent();
7238   assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool {
7239     auto *I = cast<Instruction>(V);
7240     return !E->isOpcodeOrAlt(I) || I->getParent() == BB;
7241   }));
7242 
7243   auto &&FindLastInst = [E, Front]() {
7244     Instruction *LastInst = Front;
7245     for (Value *V : E->Scalars) {
7246       auto *I = dyn_cast<Instruction>(V);
7247       if (!I)
7248         continue;
7249       if (LastInst->comesBefore(I))
7250         LastInst = I;
7251     }
7252     return LastInst;
7253   };
7254 
7255   auto &&FindFirstInst = [E, Front]() {
7256     Instruction *FirstInst = Front;
7257     for (Value *V : E->Scalars) {
7258       auto *I = dyn_cast<Instruction>(V);
7259       if (!I)
7260         continue;
7261       if (I->comesBefore(FirstInst))
7262         FirstInst = I;
7263     }
7264     return FirstInst;
7265   };
7266 
7267   // Set the insert point to the beginning of the basic block if the entry
7268   // should not be scheduled.
7269   if (E->State != TreeEntry::NeedToGather &&
7270       doesNotNeedToSchedule(E->Scalars)) {
7271     Instruction *InsertInst;
7272     if (all_of(E->Scalars, isUsedOutsideBlock))
7273       InsertInst = FindLastInst();
7274     else
7275       InsertInst = FindFirstInst();
7276     // If the instruction is PHI, set the insert point after all the PHIs.
7277     if (isa<PHINode>(InsertInst))
7278       InsertInst = BB->getFirstNonPHI();
7279     BasicBlock::iterator InsertPt = InsertInst->getIterator();
7280     Builder.SetInsertPoint(BB, InsertPt);
7281     Builder.SetCurrentDebugLocation(Front->getDebugLoc());
7282     return;
7283   }
7284 
7285   // The last instruction in the bundle in program order.
7286   Instruction *LastInst = nullptr;
7287 
7288   // Find the last instruction. The common case should be that BB has been
7289   // scheduled, and the last instruction is VL.back(). So we start with
7290   // VL.back() and iterate over schedule data until we reach the end of the
7291   // bundle. The end of the bundle is marked by null ScheduleData.
7292   if (BlocksSchedules.count(BB)) {
7293     Value *V = E->isOneOf(E->Scalars.back());
7294     if (doesNotNeedToBeScheduled(V))
7295       V = *find_if_not(E->Scalars, doesNotNeedToBeScheduled);
7296     auto *Bundle = BlocksSchedules[BB]->getScheduleData(V);
7297     if (Bundle && Bundle->isPartOfBundle())
7298       for (; Bundle; Bundle = Bundle->NextInBundle)
7299         if (Bundle->OpValue == Bundle->Inst)
7300           LastInst = Bundle->Inst;
7301   }
7302 
7303   // LastInst can still be null at this point if there's either not an entry
7304   // for BB in BlocksSchedules or there's no ScheduleData available for
7305   // VL.back(). This can be the case if buildTree_rec aborts for various
7306   // reasons (e.g., the maximum recursion depth is reached, the maximum region
7307   // size is reached, etc.). ScheduleData is initialized in the scheduling
7308   // "dry-run".
7309   //
7310   // If this happens, we can still find the last instruction by brute force. We
7311   // iterate forwards from Front (inclusive) until we either see all
7312   // instructions in the bundle or reach the end of the block. If Front is the
7313   // last instruction in program order, LastInst will be set to Front, and we
7314   // will visit all the remaining instructions in the block.
7315   //
7316   // One of the reasons we exit early from buildTree_rec is to place an upper
7317   // bound on compile-time. Thus, taking an additional compile-time hit here is
7318   // not ideal. However, this should be exceedingly rare since it requires that
7319   // we both exit early from buildTree_rec and that the bundle be out-of-order
7320   // (causing us to iterate all the way to the end of the block).
7321   if (!LastInst) {
7322     LastInst = FindLastInst();
7323     // If the instruction is PHI, set the insert point after all the PHIs.
7324     if (isa<PHINode>(LastInst))
7325       LastInst = BB->getFirstNonPHI()->getPrevNode();
7326   }
7327   assert(LastInst && "Failed to find last instruction in bundle");
7328 
7329   // Set the insertion point after the last instruction in the bundle. Set the
7330   // debug location to Front.
7331   Builder.SetInsertPoint(BB, std::next(LastInst->getIterator()));
7332   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
7333 }
7334 
7335 Value *BoUpSLP::gather(ArrayRef<Value *> VL) {
7336   // List of instructions/lanes from current block and/or the blocks which are
7337   // part of the current loop. These instructions will be inserted at the end to
7338   // make it possible to optimize loops and hoist invariant instructions out of
7339   // the loops body with better chances for success.
7340   SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts;
7341   SmallSet<int, 4> PostponedIndices;
7342   Loop *L = LI->getLoopFor(Builder.GetInsertBlock());
7343   auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) {
7344     SmallPtrSet<BasicBlock *, 4> Visited;
7345     while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second)
7346       InsertBB = InsertBB->getSinglePredecessor();
7347     return InsertBB && InsertBB == InstBB;
7348   };
7349   for (int I = 0, E = VL.size(); I < E; ++I) {
7350     if (auto *Inst = dyn_cast<Instruction>(VL[I]))
7351       if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) ||
7352            getTreeEntry(Inst) || (L && (L->contains(Inst)))) &&
7353           PostponedIndices.insert(I).second)
7354         PostponedInsts.emplace_back(Inst, I);
7355   }
7356 
7357   auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) {
7358     Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos));
7359     auto *InsElt = dyn_cast<InsertElementInst>(Vec);
7360     if (!InsElt)
7361       return Vec;
7362     GatherShuffleSeq.insert(InsElt);
7363     CSEBlocks.insert(InsElt->getParent());
7364     // Add to our 'need-to-extract' list.
7365     if (TreeEntry *Entry = getTreeEntry(V)) {
7366       // Find which lane we need to extract.
7367       unsigned FoundLane = Entry->findLaneForValue(V);
7368       ExternalUses.emplace_back(V, InsElt, FoundLane);
7369     }
7370     return Vec;
7371   };
7372   Value *Val0 =
7373       isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0];
7374   FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size());
7375   Value *Vec = PoisonValue::get(VecTy);
7376   SmallVector<int> NonConsts;
7377   // Insert constant values at first.
7378   for (int I = 0, E = VL.size(); I < E; ++I) {
7379     if (PostponedIndices.contains(I))
7380       continue;
7381     if (!isConstant(VL[I])) {
7382       NonConsts.push_back(I);
7383       continue;
7384     }
7385     Vec = CreateInsertElement(Vec, VL[I], I);
7386   }
7387   // Insert non-constant values.
7388   for (int I : NonConsts)
7389     Vec = CreateInsertElement(Vec, VL[I], I);
7390   // Append instructions, which are/may be part of the loop, in the end to make
7391   // it possible to hoist non-loop-based instructions.
7392   for (const std::pair<Value *, unsigned> &Pair : PostponedInsts)
7393     Vec = CreateInsertElement(Vec, Pair.first, Pair.second);
7394 
7395   return Vec;
7396 }
7397 
7398 namespace {
7399 /// Merges shuffle masks and emits final shuffle instruction, if required.
7400 class ShuffleInstructionBuilder {
7401   IRBuilderBase &Builder;
7402   const unsigned VF = 0;
7403   bool IsFinalized = false;
7404   SmallVector<int, 4> Mask;
7405   /// Holds all of the instructions that we gathered.
7406   SetVector<Instruction *> &GatherShuffleSeq;
7407   /// A list of blocks that we are going to CSE.
7408   SetVector<BasicBlock *> &CSEBlocks;
7409 
7410 public:
7411   ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF,
7412                             SetVector<Instruction *> &GatherShuffleSeq,
7413                             SetVector<BasicBlock *> &CSEBlocks)
7414       : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq),
7415         CSEBlocks(CSEBlocks) {}
7416 
7417   /// Adds a mask, inverting it before applying.
7418   void addInversedMask(ArrayRef<unsigned> SubMask) {
7419     if (SubMask.empty())
7420       return;
7421     SmallVector<int, 4> NewMask;
7422     inversePermutation(SubMask, NewMask);
7423     addMask(NewMask);
7424   }
7425 
7426   /// Functions adds masks, merging them into  single one.
7427   void addMask(ArrayRef<unsigned> SubMask) {
7428     SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end());
7429     addMask(NewMask);
7430   }
7431 
7432   void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); }
7433 
7434   Value *finalize(Value *V) {
7435     IsFinalized = true;
7436     unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements();
7437     if (VF == ValueVF && Mask.empty())
7438       return V;
7439     SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem);
7440     std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0);
7441     addMask(NormalizedMask);
7442 
7443     if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask))
7444       return V;
7445     Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle");
7446     if (auto *I = dyn_cast<Instruction>(Vec)) {
7447       GatherShuffleSeq.insert(I);
7448       CSEBlocks.insert(I->getParent());
7449     }
7450     return Vec;
7451   }
7452 
7453   ~ShuffleInstructionBuilder() {
7454     assert((IsFinalized || Mask.empty()) &&
7455            "Shuffle construction must be finalized.");
7456   }
7457 };
7458 } // namespace
7459 
7460 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
7461   const unsigned VF = VL.size();
7462   InstructionsState S = getSameOpcode(VL);
7463   if (S.getOpcode()) {
7464     if (TreeEntry *E = getTreeEntry(S.OpValue))
7465       if (E->isSame(VL)) {
7466         Value *V = vectorizeTree(E);
7467         if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) {
7468           if (!E->ReuseShuffleIndices.empty()) {
7469             // Reshuffle to get only unique values.
7470             // If some of the scalars are duplicated in the vectorization tree
7471             // entry, we do not vectorize them but instead generate a mask for
7472             // the reuses. But if there are several users of the same entry,
7473             // they may have different vectorization factors. This is especially
7474             // important for PHI nodes. In this case, we need to adapt the
7475             // resulting instruction for the user vectorization factor and have
7476             // to reshuffle it again to take only unique elements of the vector.
7477             // Without this code the function incorrectly returns reduced vector
7478             // instruction with the same elements, not with the unique ones.
7479 
7480             // block:
7481             // %phi = phi <2 x > { .., %entry} {%shuffle, %block}
7482             // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0>
7483             // ... (use %2)
7484             // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0}
7485             // br %block
7486             SmallVector<int> UniqueIdxs(VF, UndefMaskElem);
7487             SmallSet<int, 4> UsedIdxs;
7488             int Pos = 0;
7489             int Sz = VL.size();
7490             for (int Idx : E->ReuseShuffleIndices) {
7491               if (Idx != Sz && Idx != UndefMaskElem &&
7492                   UsedIdxs.insert(Idx).second)
7493                 UniqueIdxs[Idx] = Pos;
7494               ++Pos;
7495             }
7496             assert(VF >= UsedIdxs.size() && "Expected vectorization factor "
7497                                             "less than original vector size.");
7498             UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem);
7499             V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle");
7500           } else {
7501             assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() &&
7502                    "Expected vectorization factor less "
7503                    "than original vector size.");
7504             SmallVector<int> UniformMask(VF, 0);
7505             std::iota(UniformMask.begin(), UniformMask.end(), 0);
7506             V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle");
7507           }
7508           if (auto *I = dyn_cast<Instruction>(V)) {
7509             GatherShuffleSeq.insert(I);
7510             CSEBlocks.insert(I->getParent());
7511           }
7512         }
7513         return V;
7514       }
7515   }
7516 
7517   // Can't vectorize this, so simply build a new vector with each lane
7518   // corresponding to the requested value.
7519   return createBuildVector(VL);
7520 }
7521 Value *BoUpSLP::createBuildVector(ArrayRef<Value *> VL) {
7522   unsigned VF = VL.size();
7523   // Exploit possible reuse of values across lanes.
7524   SmallVector<int> ReuseShuffleIndicies;
7525   SmallVector<Value *> UniqueValues;
7526   if (VL.size() > 2) {
7527     DenseMap<Value *, unsigned> UniquePositions;
7528     unsigned NumValues =
7529         std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) {
7530                                     return !isa<UndefValue>(V);
7531                                   }).base());
7532     VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues));
7533     int UniqueVals = 0;
7534     for (Value *V : VL.drop_back(VL.size() - VF)) {
7535       if (isa<UndefValue>(V)) {
7536         ReuseShuffleIndicies.emplace_back(UndefMaskElem);
7537         continue;
7538       }
7539       if (isConstant(V)) {
7540         ReuseShuffleIndicies.emplace_back(UniqueValues.size());
7541         UniqueValues.emplace_back(V);
7542         continue;
7543       }
7544       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
7545       ReuseShuffleIndicies.emplace_back(Res.first->second);
7546       if (Res.second) {
7547         UniqueValues.emplace_back(V);
7548         ++UniqueVals;
7549       }
7550     }
7551     if (UniqueVals == 1 && UniqueValues.size() == 1) {
7552       // Emit pure splat vector.
7553       ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(),
7554                                   UndefMaskElem);
7555     } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) {
7556       if (UniqueValues.empty()) {
7557         assert(all_of(VL, UndefValue::classof) && "Expected list of undefs.");
7558         NumValues = VF;
7559       }
7560       ReuseShuffleIndicies.clear();
7561       UniqueValues.clear();
7562       UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues));
7563     }
7564     UniqueValues.append(VF - UniqueValues.size(),
7565                         PoisonValue::get(VL[0]->getType()));
7566     VL = UniqueValues;
7567   }
7568 
7569   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
7570                                            CSEBlocks);
7571   Value *Vec = gather(VL);
7572   if (!ReuseShuffleIndicies.empty()) {
7573     ShuffleBuilder.addMask(ReuseShuffleIndicies);
7574     Vec = ShuffleBuilder.finalize(Vec);
7575   }
7576   return Vec;
7577 }
7578 
7579 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
7580   IRBuilder<>::InsertPointGuard Guard(Builder);
7581 
7582   if (E->VectorizedValue) {
7583     LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
7584     return E->VectorizedValue;
7585   }
7586 
7587   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
7588   unsigned VF = E->getVectorFactor();
7589   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
7590                                            CSEBlocks);
7591   if (E->State == TreeEntry::NeedToGather) {
7592     if (E->getMainOp())
7593       setInsertPointAfterBundle(E);
7594     Value *Vec;
7595     SmallVector<int> Mask;
7596     SmallVector<const TreeEntry *> Entries;
7597     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
7598         isGatherShuffledEntry(E, Mask, Entries);
7599     if (Shuffle.hasValue()) {
7600       assert((Entries.size() == 1 || Entries.size() == 2) &&
7601              "Expected shuffle of 1 or 2 entries.");
7602       Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue,
7603                                         Entries.back()->VectorizedValue, Mask);
7604       if (auto *I = dyn_cast<Instruction>(Vec)) {
7605         GatherShuffleSeq.insert(I);
7606         CSEBlocks.insert(I->getParent());
7607       }
7608     } else {
7609       Vec = gather(E->Scalars);
7610     }
7611     if (NeedToShuffleReuses) {
7612       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7613       Vec = ShuffleBuilder.finalize(Vec);
7614     }
7615     E->VectorizedValue = Vec;
7616     return Vec;
7617   }
7618 
7619   assert((E->State == TreeEntry::Vectorize ||
7620           E->State == TreeEntry::ScatterVectorize) &&
7621          "Unhandled state");
7622   unsigned ShuffleOrOp =
7623       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
7624   Instruction *VL0 = E->getMainOp();
7625   Type *ScalarTy = VL0->getType();
7626   if (auto *Store = dyn_cast<StoreInst>(VL0))
7627     ScalarTy = Store->getValueOperand()->getType();
7628   else if (auto *IE = dyn_cast<InsertElementInst>(VL0))
7629     ScalarTy = IE->getOperand(1)->getType();
7630   auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
7631   switch (ShuffleOrOp) {
7632     case Instruction::PHI: {
7633       assert(
7634           (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) &&
7635           "PHI reordering is free.");
7636       auto *PH = cast<PHINode>(VL0);
7637       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
7638       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
7639       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
7640       Value *V = NewPhi;
7641 
7642       // Adjust insertion point once all PHI's have been generated.
7643       Builder.SetInsertPoint(&*PH->getParent()->getFirstInsertionPt());
7644       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
7645 
7646       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7647       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7648       V = ShuffleBuilder.finalize(V);
7649 
7650       E->VectorizedValue = V;
7651 
7652       // PHINodes may have multiple entries from the same block. We want to
7653       // visit every block once.
7654       SmallPtrSet<BasicBlock*, 4> VisitedBBs;
7655 
7656       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
7657         ValueList Operands;
7658         BasicBlock *IBB = PH->getIncomingBlock(i);
7659 
7660         if (!VisitedBBs.insert(IBB).second) {
7661           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
7662           continue;
7663         }
7664 
7665         Builder.SetInsertPoint(IBB->getTerminator());
7666         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
7667         Value *Vec = vectorizeTree(E->getOperand(i));
7668         NewPhi->addIncoming(Vec, IBB);
7669       }
7670 
7671       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
7672              "Invalid number of incoming values");
7673       return V;
7674     }
7675 
7676     case Instruction::ExtractElement: {
7677       Value *V = E->getSingleOperand(0);
7678       Builder.SetInsertPoint(VL0);
7679       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7680       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7681       V = ShuffleBuilder.finalize(V);
7682       E->VectorizedValue = V;
7683       return V;
7684     }
7685     case Instruction::ExtractValue: {
7686       auto *LI = cast<LoadInst>(E->getSingleOperand(0));
7687       Builder.SetInsertPoint(LI);
7688       auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
7689       Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
7690       LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
7691       Value *NewV = propagateMetadata(V, E->Scalars);
7692       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7693       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7694       NewV = ShuffleBuilder.finalize(NewV);
7695       E->VectorizedValue = NewV;
7696       return NewV;
7697     }
7698     case Instruction::InsertElement: {
7699       assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique");
7700       Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back()));
7701       Value *V = vectorizeTree(E->getOperand(1));
7702 
7703       // Create InsertVector shuffle if necessary
7704       auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
7705         return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0));
7706       }));
7707       const unsigned NumElts =
7708           cast<FixedVectorType>(FirstInsert->getType())->getNumElements();
7709       const unsigned NumScalars = E->Scalars.size();
7710 
7711       unsigned Offset = *getInsertIndex(VL0);
7712       assert(Offset < NumElts && "Failed to find vector index offset");
7713 
7714       // Create shuffle to resize vector
7715       SmallVector<int> Mask;
7716       if (!E->ReorderIndices.empty()) {
7717         inversePermutation(E->ReorderIndices, Mask);
7718         Mask.append(NumElts - NumScalars, UndefMaskElem);
7719       } else {
7720         Mask.assign(NumElts, UndefMaskElem);
7721         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
7722       }
7723       // Create InsertVector shuffle if necessary
7724       bool IsIdentity = true;
7725       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
7726       Mask.swap(PrevMask);
7727       for (unsigned I = 0; I < NumScalars; ++I) {
7728         Value *Scalar = E->Scalars[PrevMask[I]];
7729         unsigned InsertIdx = *getInsertIndex(Scalar);
7730         IsIdentity &= InsertIdx - Offset == I;
7731         Mask[InsertIdx - Offset] = I;
7732       }
7733       if (!IsIdentity || NumElts != NumScalars) {
7734         V = Builder.CreateShuffleVector(V, Mask);
7735         if (auto *I = dyn_cast<Instruction>(V)) {
7736           GatherShuffleSeq.insert(I);
7737           CSEBlocks.insert(I->getParent());
7738         }
7739       }
7740 
7741       if ((!IsIdentity || Offset != 0 ||
7742            !isUndefVector(FirstInsert->getOperand(0))) &&
7743           NumElts != NumScalars) {
7744         SmallVector<int> InsertMask(NumElts);
7745         std::iota(InsertMask.begin(), InsertMask.end(), 0);
7746         for (unsigned I = 0; I < NumElts; I++) {
7747           if (Mask[I] != UndefMaskElem)
7748             InsertMask[Offset + I] = NumElts + I;
7749         }
7750 
7751         V = Builder.CreateShuffleVector(
7752             FirstInsert->getOperand(0), V, InsertMask,
7753             cast<Instruction>(E->Scalars.back())->getName());
7754         if (auto *I = dyn_cast<Instruction>(V)) {
7755           GatherShuffleSeq.insert(I);
7756           CSEBlocks.insert(I->getParent());
7757         }
7758       }
7759 
7760       ++NumVectorInstructions;
7761       E->VectorizedValue = V;
7762       return V;
7763     }
7764     case Instruction::ZExt:
7765     case Instruction::SExt:
7766     case Instruction::FPToUI:
7767     case Instruction::FPToSI:
7768     case Instruction::FPExt:
7769     case Instruction::PtrToInt:
7770     case Instruction::IntToPtr:
7771     case Instruction::SIToFP:
7772     case Instruction::UIToFP:
7773     case Instruction::Trunc:
7774     case Instruction::FPTrunc:
7775     case Instruction::BitCast: {
7776       setInsertPointAfterBundle(E);
7777 
7778       Value *InVec = vectorizeTree(E->getOperand(0));
7779 
7780       if (E->VectorizedValue) {
7781         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7782         return E->VectorizedValue;
7783       }
7784 
7785       auto *CI = cast<CastInst>(VL0);
7786       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
7787       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7788       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7789       V = ShuffleBuilder.finalize(V);
7790 
7791       E->VectorizedValue = V;
7792       ++NumVectorInstructions;
7793       return V;
7794     }
7795     case Instruction::FCmp:
7796     case Instruction::ICmp: {
7797       setInsertPointAfterBundle(E);
7798 
7799       Value *L = vectorizeTree(E->getOperand(0));
7800       Value *R = vectorizeTree(E->getOperand(1));
7801 
7802       if (E->VectorizedValue) {
7803         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7804         return E->VectorizedValue;
7805       }
7806 
7807       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
7808       Value *V = Builder.CreateCmp(P0, L, R);
7809       propagateIRFlags(V, E->Scalars, VL0);
7810       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7811       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7812       V = ShuffleBuilder.finalize(V);
7813 
7814       E->VectorizedValue = V;
7815       ++NumVectorInstructions;
7816       return V;
7817     }
7818     case Instruction::Select: {
7819       setInsertPointAfterBundle(E);
7820 
7821       Value *Cond = vectorizeTree(E->getOperand(0));
7822       Value *True = vectorizeTree(E->getOperand(1));
7823       Value *False = vectorizeTree(E->getOperand(2));
7824 
7825       if (E->VectorizedValue) {
7826         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7827         return E->VectorizedValue;
7828       }
7829 
7830       Value *V = Builder.CreateSelect(Cond, True, False);
7831       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7832       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7833       V = ShuffleBuilder.finalize(V);
7834 
7835       E->VectorizedValue = V;
7836       ++NumVectorInstructions;
7837       return V;
7838     }
7839     case Instruction::FNeg: {
7840       setInsertPointAfterBundle(E);
7841 
7842       Value *Op = vectorizeTree(E->getOperand(0));
7843 
7844       if (E->VectorizedValue) {
7845         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7846         return E->VectorizedValue;
7847       }
7848 
7849       Value *V = Builder.CreateUnOp(
7850           static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
7851       propagateIRFlags(V, E->Scalars, VL0);
7852       if (auto *I = dyn_cast<Instruction>(V))
7853         V = propagateMetadata(I, E->Scalars);
7854 
7855       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7856       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7857       V = ShuffleBuilder.finalize(V);
7858 
7859       E->VectorizedValue = V;
7860       ++NumVectorInstructions;
7861 
7862       return V;
7863     }
7864     case Instruction::Add:
7865     case Instruction::FAdd:
7866     case Instruction::Sub:
7867     case Instruction::FSub:
7868     case Instruction::Mul:
7869     case Instruction::FMul:
7870     case Instruction::UDiv:
7871     case Instruction::SDiv:
7872     case Instruction::FDiv:
7873     case Instruction::URem:
7874     case Instruction::SRem:
7875     case Instruction::FRem:
7876     case Instruction::Shl:
7877     case Instruction::LShr:
7878     case Instruction::AShr:
7879     case Instruction::And:
7880     case Instruction::Or:
7881     case Instruction::Xor: {
7882       setInsertPointAfterBundle(E);
7883 
7884       Value *LHS = vectorizeTree(E->getOperand(0));
7885       Value *RHS = vectorizeTree(E->getOperand(1));
7886 
7887       if (E->VectorizedValue) {
7888         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7889         return E->VectorizedValue;
7890       }
7891 
7892       Value *V = Builder.CreateBinOp(
7893           static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
7894           RHS);
7895       propagateIRFlags(V, E->Scalars, VL0);
7896       if (auto *I = dyn_cast<Instruction>(V))
7897         V = propagateMetadata(I, E->Scalars);
7898 
7899       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7900       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7901       V = ShuffleBuilder.finalize(V);
7902 
7903       E->VectorizedValue = V;
7904       ++NumVectorInstructions;
7905 
7906       return V;
7907     }
7908     case Instruction::Load: {
7909       // Loads are inserted at the head of the tree because we don't want to
7910       // sink them all the way down past store instructions.
7911       setInsertPointAfterBundle(E);
7912 
7913       LoadInst *LI = cast<LoadInst>(VL0);
7914       Instruction *NewLI;
7915       unsigned AS = LI->getPointerAddressSpace();
7916       Value *PO = LI->getPointerOperand();
7917       if (E->State == TreeEntry::Vectorize) {
7918         Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS));
7919         NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
7920 
7921         // The pointer operand uses an in-tree scalar so we add the new BitCast
7922         // or LoadInst to ExternalUses list to make sure that an extract will
7923         // be generated in the future.
7924         if (TreeEntry *Entry = getTreeEntry(PO)) {
7925           // Find which lane we need to extract.
7926           unsigned FoundLane = Entry->findLaneForValue(PO);
7927           ExternalUses.emplace_back(
7928               PO, PO != VecPtr ? cast<User>(VecPtr) : NewLI, FoundLane);
7929         }
7930       } else {
7931         assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state");
7932         Value *VecPtr = vectorizeTree(E->getOperand(0));
7933         // Use the minimum alignment of the gathered loads.
7934         Align CommonAlignment = LI->getAlign();
7935         for (Value *V : E->Scalars)
7936           CommonAlignment =
7937               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
7938         NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment);
7939       }
7940       Value *V = propagateMetadata(NewLI, E->Scalars);
7941 
7942       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7943       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7944       V = ShuffleBuilder.finalize(V);
7945       E->VectorizedValue = V;
7946       ++NumVectorInstructions;
7947       return V;
7948     }
7949     case Instruction::Store: {
7950       auto *SI = cast<StoreInst>(VL0);
7951       unsigned AS = SI->getPointerAddressSpace();
7952 
7953       setInsertPointAfterBundle(E);
7954 
7955       Value *VecValue = vectorizeTree(E->getOperand(0));
7956       ShuffleBuilder.addMask(E->ReorderIndices);
7957       VecValue = ShuffleBuilder.finalize(VecValue);
7958 
7959       Value *ScalarPtr = SI->getPointerOperand();
7960       Value *VecPtr = Builder.CreateBitCast(
7961           ScalarPtr, VecValue->getType()->getPointerTo(AS));
7962       StoreInst *ST =
7963           Builder.CreateAlignedStore(VecValue, VecPtr, SI->getAlign());
7964 
7965       // The pointer operand uses an in-tree scalar, so add the new BitCast or
7966       // StoreInst to ExternalUses to make sure that an extract will be
7967       // generated in the future.
7968       if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) {
7969         // Find which lane we need to extract.
7970         unsigned FoundLane = Entry->findLaneForValue(ScalarPtr);
7971         ExternalUses.push_back(ExternalUser(
7972             ScalarPtr, ScalarPtr != VecPtr ? cast<User>(VecPtr) : ST,
7973             FoundLane));
7974       }
7975 
7976       Value *V = propagateMetadata(ST, E->Scalars);
7977 
7978       E->VectorizedValue = V;
7979       ++NumVectorInstructions;
7980       return V;
7981     }
7982     case Instruction::GetElementPtr: {
7983       auto *GEP0 = cast<GetElementPtrInst>(VL0);
7984       setInsertPointAfterBundle(E);
7985 
7986       Value *Op0 = vectorizeTree(E->getOperand(0));
7987 
7988       SmallVector<Value *> OpVecs;
7989       for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) {
7990         Value *OpVec = vectorizeTree(E->getOperand(J));
7991         OpVecs.push_back(OpVec);
7992       }
7993 
7994       Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs);
7995       if (Instruction *I = dyn_cast<Instruction>(V))
7996         V = propagateMetadata(I, E->Scalars);
7997 
7998       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7999       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
8000       V = ShuffleBuilder.finalize(V);
8001 
8002       E->VectorizedValue = V;
8003       ++NumVectorInstructions;
8004 
8005       return V;
8006     }
8007     case Instruction::Call: {
8008       CallInst *CI = cast<CallInst>(VL0);
8009       setInsertPointAfterBundle(E);
8010 
8011       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
8012       if (Function *FI = CI->getCalledFunction())
8013         IID = FI->getIntrinsicID();
8014 
8015       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
8016 
8017       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
8018       bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
8019                           VecCallCosts.first <= VecCallCosts.second;
8020 
8021       Value *ScalarArg = nullptr;
8022       std::vector<Value *> OpVecs;
8023       SmallVector<Type *, 2> TysForDecl =
8024           {FixedVectorType::get(CI->getType(), E->Scalars.size())};
8025       for (int j = 0, e = CI->arg_size(); j < e; ++j) {
8026         ValueList OpVL;
8027         // Some intrinsics have scalar arguments. This argument should not be
8028         // vectorized.
8029         if (UseIntrinsic && isVectorIntrinsicWithScalarOpAtArg(IID, j)) {
8030           CallInst *CEI = cast<CallInst>(VL0);
8031           ScalarArg = CEI->getArgOperand(j);
8032           OpVecs.push_back(CEI->getArgOperand(j));
8033           if (isVectorIntrinsicWithOverloadTypeAtArg(IID, j))
8034             TysForDecl.push_back(ScalarArg->getType());
8035           continue;
8036         }
8037 
8038         Value *OpVec = vectorizeTree(E->getOperand(j));
8039         LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
8040         OpVecs.push_back(OpVec);
8041         if (isVectorIntrinsicWithOverloadTypeAtArg(IID, j))
8042           TysForDecl.push_back(OpVec->getType());
8043       }
8044 
8045       Function *CF;
8046       if (!UseIntrinsic) {
8047         VFShape Shape =
8048             VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
8049                                   VecTy->getNumElements())),
8050                          false /*HasGlobalPred*/);
8051         CF = VFDatabase(*CI).getVectorizedFunction(Shape);
8052       } else {
8053         CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl);
8054       }
8055 
8056       SmallVector<OperandBundleDef, 1> OpBundles;
8057       CI->getOperandBundlesAsDefs(OpBundles);
8058       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
8059 
8060       // The scalar argument uses an in-tree scalar so we add the new vectorized
8061       // call to ExternalUses list to make sure that an extract will be
8062       // generated in the future.
8063       if (ScalarArg) {
8064         if (TreeEntry *Entry = getTreeEntry(ScalarArg)) {
8065           // Find which lane we need to extract.
8066           unsigned FoundLane = Entry->findLaneForValue(ScalarArg);
8067           ExternalUses.push_back(
8068               ExternalUser(ScalarArg, cast<User>(V), FoundLane));
8069         }
8070       }
8071 
8072       propagateIRFlags(V, E->Scalars, VL0);
8073       ShuffleBuilder.addInversedMask(E->ReorderIndices);
8074       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
8075       V = ShuffleBuilder.finalize(V);
8076 
8077       E->VectorizedValue = V;
8078       ++NumVectorInstructions;
8079       return V;
8080     }
8081     case Instruction::ShuffleVector: {
8082       assert(E->isAltShuffle() &&
8083              ((Instruction::isBinaryOp(E->getOpcode()) &&
8084                Instruction::isBinaryOp(E->getAltOpcode())) ||
8085               (Instruction::isCast(E->getOpcode()) &&
8086                Instruction::isCast(E->getAltOpcode())) ||
8087               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
8088              "Invalid Shuffle Vector Operand");
8089 
8090       Value *LHS = nullptr, *RHS = nullptr;
8091       if (Instruction::isBinaryOp(E->getOpcode()) || isa<CmpInst>(VL0)) {
8092         setInsertPointAfterBundle(E);
8093         LHS = vectorizeTree(E->getOperand(0));
8094         RHS = vectorizeTree(E->getOperand(1));
8095       } else {
8096         setInsertPointAfterBundle(E);
8097         LHS = vectorizeTree(E->getOperand(0));
8098       }
8099 
8100       if (E->VectorizedValue) {
8101         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
8102         return E->VectorizedValue;
8103       }
8104 
8105       Value *V0, *V1;
8106       if (Instruction::isBinaryOp(E->getOpcode())) {
8107         V0 = Builder.CreateBinOp(
8108             static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
8109         V1 = Builder.CreateBinOp(
8110             static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
8111       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
8112         V0 = Builder.CreateCmp(CI0->getPredicate(), LHS, RHS);
8113         auto *AltCI = cast<CmpInst>(E->getAltOp());
8114         CmpInst::Predicate AltPred = AltCI->getPredicate();
8115         V1 = Builder.CreateCmp(AltPred, LHS, RHS);
8116       } else {
8117         V0 = Builder.CreateCast(
8118             static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
8119         V1 = Builder.CreateCast(
8120             static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
8121       }
8122       // Add V0 and V1 to later analysis to try to find and remove matching
8123       // instruction, if any.
8124       for (Value *V : {V0, V1}) {
8125         if (auto *I = dyn_cast<Instruction>(V)) {
8126           GatherShuffleSeq.insert(I);
8127           CSEBlocks.insert(I->getParent());
8128         }
8129       }
8130 
8131       // Create shuffle to take alternate operations from the vector.
8132       // Also, gather up main and alt scalar ops to propagate IR flags to
8133       // each vector operation.
8134       ValueList OpScalars, AltScalars;
8135       SmallVector<int> Mask;
8136       buildShuffleEntryMask(
8137           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
8138           [E](Instruction *I) {
8139             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
8140             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
8141           },
8142           Mask, &OpScalars, &AltScalars);
8143 
8144       propagateIRFlags(V0, OpScalars);
8145       propagateIRFlags(V1, AltScalars);
8146 
8147       Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
8148       if (auto *I = dyn_cast<Instruction>(V)) {
8149         V = propagateMetadata(I, E->Scalars);
8150         GatherShuffleSeq.insert(I);
8151         CSEBlocks.insert(I->getParent());
8152       }
8153       V = ShuffleBuilder.finalize(V);
8154 
8155       E->VectorizedValue = V;
8156       ++NumVectorInstructions;
8157 
8158       return V;
8159     }
8160     default:
8161     llvm_unreachable("unknown inst");
8162   }
8163   return nullptr;
8164 }
8165 
8166 Value *BoUpSLP::vectorizeTree() {
8167   ExtraValueToDebugLocsMap ExternallyUsedValues;
8168   return vectorizeTree(ExternallyUsedValues);
8169 }
8170 
8171 namespace {
8172 /// Data type for handling buildvector sequences with the reused scalars from
8173 /// other tree entries.
8174 struct ShuffledInsertData {
8175   /// List of insertelements to be replaced by shuffles.
8176   SmallVector<InsertElementInst *> InsertElements;
8177   /// The parent vectors and shuffle mask for the given list of inserts.
8178   MapVector<Value *, SmallVector<int>> ValueMasks;
8179 };
8180 } // namespace
8181 
8182 Value *
8183 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
8184   // All blocks must be scheduled before any instructions are inserted.
8185   for (auto &BSIter : BlocksSchedules) {
8186     scheduleBlock(BSIter.second.get());
8187   }
8188 
8189   Builder.SetInsertPoint(&F->getEntryBlock().front());
8190   auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
8191 
8192   // If the vectorized tree can be rewritten in a smaller type, we truncate the
8193   // vectorized root. InstCombine will then rewrite the entire expression. We
8194   // sign extend the extracted values below.
8195   auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
8196   if (MinBWs.count(ScalarRoot)) {
8197     if (auto *I = dyn_cast<Instruction>(VectorRoot)) {
8198       // If current instr is a phi and not the last phi, insert it after the
8199       // last phi node.
8200       if (isa<PHINode>(I))
8201         Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt());
8202       else
8203         Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
8204     }
8205     auto BundleWidth = VectorizableTree[0]->Scalars.size();
8206     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
8207     auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
8208     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
8209     VectorizableTree[0]->VectorizedValue = Trunc;
8210   }
8211 
8212   LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
8213                     << " values .\n");
8214 
8215   SmallVector<ShuffledInsertData> ShuffledInserts;
8216   // Maps vector instruction to original insertelement instruction
8217   DenseMap<Value *, InsertElementInst *> VectorToInsertElement;
8218   // Extract all of the elements with the external uses.
8219   for (const auto &ExternalUse : ExternalUses) {
8220     Value *Scalar = ExternalUse.Scalar;
8221     llvm::User *User = ExternalUse.User;
8222 
8223     // Skip users that we already RAUW. This happens when one instruction
8224     // has multiple uses of the same value.
8225     if (User && !is_contained(Scalar->users(), User))
8226       continue;
8227     TreeEntry *E = getTreeEntry(Scalar);
8228     assert(E && "Invalid scalar");
8229     assert(E->State != TreeEntry::NeedToGather &&
8230            "Extracting from a gather list");
8231 
8232     Value *Vec = E->VectorizedValue;
8233     assert(Vec && "Can't find vectorizable value");
8234 
8235     Value *Lane = Builder.getInt32(ExternalUse.Lane);
8236     auto ExtractAndExtendIfNeeded = [&](Value *Vec) {
8237       if (Scalar->getType() != Vec->getType()) {
8238         Value *Ex;
8239         // "Reuse" the existing extract to improve final codegen.
8240         if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) {
8241           Ex = Builder.CreateExtractElement(ES->getOperand(0),
8242                                             ES->getOperand(1));
8243         } else {
8244           Ex = Builder.CreateExtractElement(Vec, Lane);
8245         }
8246         // If necessary, sign-extend or zero-extend ScalarRoot
8247         // to the larger type.
8248         if (!MinBWs.count(ScalarRoot))
8249           return Ex;
8250         if (MinBWs[ScalarRoot].second)
8251           return Builder.CreateSExt(Ex, Scalar->getType());
8252         return Builder.CreateZExt(Ex, Scalar->getType());
8253       }
8254       assert(isa<FixedVectorType>(Scalar->getType()) &&
8255              isa<InsertElementInst>(Scalar) &&
8256              "In-tree scalar of vector type is not insertelement?");
8257       auto *IE = cast<InsertElementInst>(Scalar);
8258       VectorToInsertElement.try_emplace(Vec, IE);
8259       return Vec;
8260     };
8261     // If User == nullptr, the Scalar is used as extra arg. Generate
8262     // ExtractElement instruction and update the record for this scalar in
8263     // ExternallyUsedValues.
8264     if (!User) {
8265       assert(ExternallyUsedValues.count(Scalar) &&
8266              "Scalar with nullptr as an external user must be registered in "
8267              "ExternallyUsedValues map");
8268       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
8269         Builder.SetInsertPoint(VecI->getParent(),
8270                                std::next(VecI->getIterator()));
8271       } else {
8272         Builder.SetInsertPoint(&F->getEntryBlock().front());
8273       }
8274       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
8275       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
8276       auto &NewInstLocs = ExternallyUsedValues[NewInst];
8277       auto It = ExternallyUsedValues.find(Scalar);
8278       assert(It != ExternallyUsedValues.end() &&
8279              "Externally used scalar is not found in ExternallyUsedValues");
8280       NewInstLocs.append(It->second);
8281       ExternallyUsedValues.erase(Scalar);
8282       // Required to update internally referenced instructions.
8283       Scalar->replaceAllUsesWith(NewInst);
8284       continue;
8285     }
8286 
8287     if (auto *VU = dyn_cast<InsertElementInst>(User)) {
8288       // Skip if the scalar is another vector op or Vec is not an instruction.
8289       if (!Scalar->getType()->isVectorTy() && isa<Instruction>(Vec)) {
8290         if (auto *FTy = dyn_cast<FixedVectorType>(User->getType())) {
8291           Optional<unsigned> InsertIdx = getInsertIndex(VU);
8292           if (InsertIdx) {
8293             auto *It =
8294                 find_if(ShuffledInserts, [VU](const ShuffledInsertData &Data) {
8295                   // Checks if 2 insertelements are from the same buildvector.
8296                   InsertElementInst *VecInsert = Data.InsertElements.front();
8297                   return areTwoInsertFromSameBuildVector(VU, VecInsert);
8298                 });
8299             unsigned Idx = *InsertIdx;
8300             if (It == ShuffledInserts.end()) {
8301               (void)ShuffledInserts.emplace_back();
8302               It = std::next(ShuffledInserts.begin(),
8303                              ShuffledInserts.size() - 1);
8304               SmallVectorImpl<int> &Mask = It->ValueMasks[Vec];
8305               if (Mask.empty())
8306                 Mask.assign(FTy->getNumElements(), UndefMaskElem);
8307               // Find the insertvector, vectorized in tree, if any.
8308               Value *Base = VU;
8309               while (auto *IEBase = dyn_cast<InsertElementInst>(Base)) {
8310                 if (IEBase != User &&
8311                     (!IEBase->hasOneUse() ||
8312                      getInsertIndex(IEBase).getValueOr(Idx) == Idx))
8313                   break;
8314                 // Build the mask for the vectorized insertelement instructions.
8315                 if (const TreeEntry *E = getTreeEntry(IEBase)) {
8316                   do {
8317                     IEBase = cast<InsertElementInst>(Base);
8318                     int IEIdx = *getInsertIndex(IEBase);
8319                     assert(Mask[Idx] == UndefMaskElem &&
8320                            "InsertElementInstruction used already.");
8321                     Mask[IEIdx] = IEIdx;
8322                     Base = IEBase->getOperand(0);
8323                   } while (E == getTreeEntry(Base));
8324                   break;
8325                 }
8326                 Base = cast<InsertElementInst>(Base)->getOperand(0);
8327                 // After the vectorization the def-use chain has changed, need
8328                 // to look through original insertelement instructions, if they
8329                 // get replaced by vector instructions.
8330                 auto It = VectorToInsertElement.find(Base);
8331                 if (It != VectorToInsertElement.end())
8332                   Base = It->second;
8333               }
8334             }
8335             SmallVectorImpl<int> &Mask = It->ValueMasks[Vec];
8336             if (Mask.empty())
8337               Mask.assign(FTy->getNumElements(), UndefMaskElem);
8338             Mask[Idx] = ExternalUse.Lane;
8339             It->InsertElements.push_back(cast<InsertElementInst>(User));
8340             continue;
8341           }
8342         }
8343       }
8344     }
8345 
8346     // Generate extracts for out-of-tree users.
8347     // Find the insertion point for the extractelement lane.
8348     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
8349       if (PHINode *PH = dyn_cast<PHINode>(User)) {
8350         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
8351           if (PH->getIncomingValue(i) == Scalar) {
8352             Instruction *IncomingTerminator =
8353                 PH->getIncomingBlock(i)->getTerminator();
8354             if (isa<CatchSwitchInst>(IncomingTerminator)) {
8355               Builder.SetInsertPoint(VecI->getParent(),
8356                                      std::next(VecI->getIterator()));
8357             } else {
8358               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
8359             }
8360             Value *NewInst = ExtractAndExtendIfNeeded(Vec);
8361             CSEBlocks.insert(PH->getIncomingBlock(i));
8362             PH->setOperand(i, NewInst);
8363           }
8364         }
8365       } else {
8366         Builder.SetInsertPoint(cast<Instruction>(User));
8367         Value *NewInst = ExtractAndExtendIfNeeded(Vec);
8368         CSEBlocks.insert(cast<Instruction>(User)->getParent());
8369         User->replaceUsesOfWith(Scalar, NewInst);
8370       }
8371     } else {
8372       Builder.SetInsertPoint(&F->getEntryBlock().front());
8373       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
8374       CSEBlocks.insert(&F->getEntryBlock());
8375       User->replaceUsesOfWith(Scalar, NewInst);
8376     }
8377 
8378     LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
8379   }
8380 
8381   // Checks if the mask is an identity mask.
8382   auto &&IsIdentityMask = [](ArrayRef<int> Mask, FixedVectorType *VecTy) {
8383     int Limit = Mask.size();
8384     return VecTy->getNumElements() == Mask.size() &&
8385            all_of(Mask, [Limit](int Idx) { return Idx < Limit; }) &&
8386            ShuffleVectorInst::isIdentityMask(Mask);
8387   };
8388   // Tries to combine 2 different masks into single one.
8389   auto &&CombineMasks = [](SmallVectorImpl<int> &Mask, ArrayRef<int> ExtMask) {
8390     SmallVector<int> NewMask(ExtMask.size(), UndefMaskElem);
8391     for (int I = 0, Sz = ExtMask.size(); I < Sz; ++I) {
8392       if (ExtMask[I] == UndefMaskElem)
8393         continue;
8394       NewMask[I] = Mask[ExtMask[I]];
8395     }
8396     Mask.swap(NewMask);
8397   };
8398   // Peek through shuffles, trying to simplify the final shuffle code.
8399   auto &&PeekThroughShuffles =
8400       [&IsIdentityMask, &CombineMasks](Value *&V, SmallVectorImpl<int> &Mask,
8401                                        bool CheckForLengthChange = false) {
8402         while (auto *SV = dyn_cast<ShuffleVectorInst>(V)) {
8403           // Exit if not a fixed vector type or changing size shuffle.
8404           if (!isa<FixedVectorType>(SV->getType()) ||
8405               (CheckForLengthChange && SV->changesLength()))
8406             break;
8407           // Exit if the identity or broadcast mask is found.
8408           if (IsIdentityMask(Mask, cast<FixedVectorType>(SV->getType())) ||
8409               SV->isZeroEltSplat())
8410             break;
8411           bool IsOp1Undef = isUndefVector(SV->getOperand(0));
8412           bool IsOp2Undef = isUndefVector(SV->getOperand(1));
8413           if (!IsOp1Undef && !IsOp2Undef)
8414             break;
8415           SmallVector<int> ShuffleMask(SV->getShuffleMask().begin(),
8416                                        SV->getShuffleMask().end());
8417           CombineMasks(ShuffleMask, Mask);
8418           Mask.swap(ShuffleMask);
8419           if (IsOp2Undef)
8420             V = SV->getOperand(0);
8421           else
8422             V = SV->getOperand(1);
8423         }
8424       };
8425   // Smart shuffle instruction emission, walks through shuffles trees and
8426   // tries to find the best matching vector for the actual shuffle
8427   // instruction.
8428   auto &&CreateShuffle = [this, &IsIdentityMask, &PeekThroughShuffles,
8429                           &CombineMasks](Value *V1, Value *V2,
8430                                          ArrayRef<int> Mask) -> Value * {
8431     assert(V1 && "Expected at least one vector value.");
8432     if (V2 && !isUndefVector(V2)) {
8433       // Peek through shuffles.
8434       Value *Op1 = V1;
8435       Value *Op2 = V2;
8436       int VF =
8437           cast<VectorType>(V1->getType())->getElementCount().getKnownMinValue();
8438       SmallVector<int> CombinedMask1(Mask.size(), UndefMaskElem);
8439       SmallVector<int> CombinedMask2(Mask.size(), UndefMaskElem);
8440       for (int I = 0, E = Mask.size(); I < E; ++I) {
8441         if (Mask[I] < VF)
8442           CombinedMask1[I] = Mask[I];
8443         else
8444           CombinedMask2[I] = Mask[I] - VF;
8445       }
8446       Value *PrevOp1;
8447       Value *PrevOp2;
8448       do {
8449         PrevOp1 = Op1;
8450         PrevOp2 = Op2;
8451         PeekThroughShuffles(Op1, CombinedMask1, /*CheckForLengthChange=*/true);
8452         PeekThroughShuffles(Op2, CombinedMask2, /*CheckForLengthChange=*/true);
8453         // Check if we have 2 resizing shuffles - need to peek through operands
8454         // again.
8455         if (auto *SV1 = dyn_cast<ShuffleVectorInst>(Op1))
8456           if (auto *SV2 = dyn_cast<ShuffleVectorInst>(Op2))
8457             if (SV1->getOperand(0)->getType() ==
8458                     SV2->getOperand(0)->getType() &&
8459                 SV1->getOperand(0)->getType() != SV1->getType() &&
8460                 isUndefVector(SV1->getOperand(1)) &&
8461                 isUndefVector(SV2->getOperand(1))) {
8462               Op1 = SV1->getOperand(0);
8463               Op2 = SV2->getOperand(0);
8464               SmallVector<int> ShuffleMask1(SV1->getShuffleMask().begin(),
8465                                             SV1->getShuffleMask().end());
8466               CombineMasks(ShuffleMask1, CombinedMask1);
8467               CombinedMask1.swap(ShuffleMask1);
8468               SmallVector<int> ShuffleMask2(SV2->getShuffleMask().begin(),
8469                                             SV2->getShuffleMask().end());
8470               CombineMasks(ShuffleMask2, CombinedMask2);
8471               CombinedMask2.swap(ShuffleMask2);
8472             }
8473       } while (PrevOp1 != Op1 || PrevOp2 != Op2);
8474       VF = cast<VectorType>(Op1->getType())
8475                ->getElementCount()
8476                .getKnownMinValue();
8477       for (int I = 0, E = Mask.size(); I < E; ++I) {
8478         if (CombinedMask2[I] != UndefMaskElem) {
8479           assert(CombinedMask1[I] == UndefMaskElem &&
8480                  "Expected undefined mask element");
8481           CombinedMask1[I] = CombinedMask2[I] + (Op1 == Op2 ? 0 : VF);
8482         }
8483       }
8484       Value *Vec = Builder.CreateShuffleVector(
8485           Op1, Op1 == Op2 ? PoisonValue::get(Op1->getType()) : Op2,
8486           CombinedMask1);
8487       if (auto *I = dyn_cast<Instruction>(Vec)) {
8488         GatherShuffleSeq.insert(I);
8489         CSEBlocks.insert(I->getParent());
8490       }
8491       return Vec;
8492     }
8493     if (isa<PoisonValue>(V1))
8494       return PoisonValue::get(FixedVectorType::get(
8495           cast<VectorType>(V1->getType())->getElementType(), Mask.size()));
8496     Value *Op = V1;
8497     SmallVector<int> CombinedMask(Mask.begin(), Mask.end());
8498     PeekThroughShuffles(Op, CombinedMask);
8499     if (!isa<FixedVectorType>(Op->getType()) ||
8500         !IsIdentityMask(CombinedMask, cast<FixedVectorType>(Op->getType()))) {
8501       Value *Vec = Builder.CreateShuffleVector(Op, CombinedMask);
8502       if (auto *I = dyn_cast<Instruction>(Vec)) {
8503         GatherShuffleSeq.insert(I);
8504         CSEBlocks.insert(I->getParent());
8505       }
8506       return Vec;
8507     }
8508     return Op;
8509   };
8510 
8511   auto &&ResizeToVF = [&CreateShuffle](Value *Vec, ArrayRef<int> Mask) {
8512     unsigned VF = Mask.size();
8513     unsigned VecVF = cast<FixedVectorType>(Vec->getType())->getNumElements();
8514     if (VF != VecVF) {
8515       if (any_of(Mask, [VF](int Idx) { return Idx >= static_cast<int>(VF); })) {
8516         Vec = CreateShuffle(Vec, nullptr, Mask);
8517         return std::make_pair(Vec, true);
8518       }
8519       SmallVector<int> ResizeMask(VF, UndefMaskElem);
8520       for (unsigned I = 0; I < VF; ++I) {
8521         if (Mask[I] != UndefMaskElem)
8522           ResizeMask[Mask[I]] = Mask[I];
8523       }
8524       Vec = CreateShuffle(Vec, nullptr, ResizeMask);
8525     }
8526 
8527     return std::make_pair(Vec, false);
8528   };
8529   // Perform shuffling of the vectorize tree entries for better handling of
8530   // external extracts.
8531   for (int I = 0, E = ShuffledInserts.size(); I < E; ++I) {
8532     // Find the first and the last instruction in the list of insertelements.
8533     sort(ShuffledInserts[I].InsertElements, isFirstInsertElement);
8534     InsertElementInst *FirstInsert = ShuffledInserts[I].InsertElements.front();
8535     InsertElementInst *LastInsert = ShuffledInserts[I].InsertElements.back();
8536     Builder.SetInsertPoint(LastInsert);
8537     auto Vector = ShuffledInserts[I].ValueMasks.takeVector();
8538     Value *NewInst = performExtractsShuffleAction<Value>(
8539         makeMutableArrayRef(Vector.data(), Vector.size()),
8540         FirstInsert->getOperand(0),
8541         [](Value *Vec) {
8542           return cast<VectorType>(Vec->getType())
8543               ->getElementCount()
8544               .getKnownMinValue();
8545         },
8546         ResizeToVF,
8547         [FirstInsert, &CreateShuffle](ArrayRef<int> Mask,
8548                                       ArrayRef<Value *> Vals) {
8549           assert((Vals.size() == 1 || Vals.size() == 2) &&
8550                  "Expected exactly 1 or 2 input values.");
8551           if (Vals.size() == 1) {
8552             // Do not create shuffle if the mask is a simple identity
8553             // non-resizing mask.
8554             if (Mask.size() != cast<FixedVectorType>(Vals.front()->getType())
8555                                    ->getNumElements() ||
8556                 !ShuffleVectorInst::isIdentityMask(Mask))
8557               return CreateShuffle(Vals.front(), nullptr, Mask);
8558             return Vals.front();
8559           }
8560           return CreateShuffle(Vals.front() ? Vals.front()
8561                                             : FirstInsert->getOperand(0),
8562                                Vals.back(), Mask);
8563         });
8564     auto It = ShuffledInserts[I].InsertElements.rbegin();
8565     // Rebuild buildvector chain.
8566     InsertElementInst *II = nullptr;
8567     if (It != ShuffledInserts[I].InsertElements.rend())
8568       II = *It;
8569     SmallVector<Instruction *> Inserts;
8570     while (It != ShuffledInserts[I].InsertElements.rend()) {
8571       assert(II && "Must be an insertelement instruction.");
8572       if (*It == II)
8573         ++It;
8574       else
8575         Inserts.push_back(cast<Instruction>(II));
8576       II = dyn_cast<InsertElementInst>(II->getOperand(0));
8577     }
8578     for (Instruction *II : reverse(Inserts)) {
8579       II->replaceUsesOfWith(II->getOperand(0), NewInst);
8580       if (auto *NewI = dyn_cast<Instruction>(NewInst))
8581         if (II->getParent() == NewI->getParent() && II->comesBefore(NewI))
8582           II->moveAfter(NewI);
8583       NewInst = II;
8584     }
8585     LastInsert->replaceAllUsesWith(NewInst);
8586     for (InsertElementInst *IE : reverse(ShuffledInserts[I].InsertElements)) {
8587       IE->replaceUsesOfWith(IE->getOperand(1),
8588                             PoisonValue::get(IE->getOperand(1)->getType()));
8589       eraseInstruction(IE);
8590     }
8591     CSEBlocks.insert(LastInsert->getParent());
8592   }
8593 
8594   // For each vectorized value:
8595   for (auto &TEPtr : VectorizableTree) {
8596     TreeEntry *Entry = TEPtr.get();
8597 
8598     // No need to handle users of gathered values.
8599     if (Entry->State == TreeEntry::NeedToGather)
8600       continue;
8601 
8602     assert(Entry->VectorizedValue && "Can't find vectorizable value");
8603 
8604     // For each lane:
8605     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
8606       Value *Scalar = Entry->Scalars[Lane];
8607 
8608 #ifndef NDEBUG
8609       Type *Ty = Scalar->getType();
8610       if (!Ty->isVoidTy()) {
8611         for (User *U : Scalar->users()) {
8612           LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
8613 
8614           // It is legal to delete users in the ignorelist.
8615           assert((getTreeEntry(U) ||
8616                   (UserIgnoreList && UserIgnoreList->contains(U)) ||
8617                   (isa_and_nonnull<Instruction>(U) &&
8618                    isDeleted(cast<Instruction>(U)))) &&
8619                  "Deleting out-of-tree value");
8620         }
8621       }
8622 #endif
8623       LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
8624       eraseInstruction(cast<Instruction>(Scalar));
8625     }
8626   }
8627 
8628   Builder.ClearInsertionPoint();
8629   InstrElementSize.clear();
8630 
8631   return VectorizableTree[0]->VectorizedValue;
8632 }
8633 
8634 void BoUpSLP::optimizeGatherSequence() {
8635   LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleSeq.size()
8636                     << " gather sequences instructions.\n");
8637   // LICM InsertElementInst sequences.
8638   for (Instruction *I : GatherShuffleSeq) {
8639     if (isDeleted(I))
8640       continue;
8641 
8642     // Check if this block is inside a loop.
8643     Loop *L = LI->getLoopFor(I->getParent());
8644     if (!L)
8645       continue;
8646 
8647     // Check if it has a preheader.
8648     BasicBlock *PreHeader = L->getLoopPreheader();
8649     if (!PreHeader)
8650       continue;
8651 
8652     // If the vector or the element that we insert into it are
8653     // instructions that are defined in this basic block then we can't
8654     // hoist this instruction.
8655     if (any_of(I->operands(), [L](Value *V) {
8656           auto *OpI = dyn_cast<Instruction>(V);
8657           return OpI && L->contains(OpI);
8658         }))
8659       continue;
8660 
8661     // We can hoist this instruction. Move it to the pre-header.
8662     I->moveBefore(PreHeader->getTerminator());
8663   }
8664 
8665   // Make a list of all reachable blocks in our CSE queue.
8666   SmallVector<const DomTreeNode *, 8> CSEWorkList;
8667   CSEWorkList.reserve(CSEBlocks.size());
8668   for (BasicBlock *BB : CSEBlocks)
8669     if (DomTreeNode *N = DT->getNode(BB)) {
8670       assert(DT->isReachableFromEntry(N));
8671       CSEWorkList.push_back(N);
8672     }
8673 
8674   // Sort blocks by domination. This ensures we visit a block after all blocks
8675   // dominating it are visited.
8676   llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) {
8677     assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) &&
8678            "Different nodes should have different DFS numbers");
8679     return A->getDFSNumIn() < B->getDFSNumIn();
8680   });
8681 
8682   // Less defined shuffles can be replaced by the more defined copies.
8683   // Between two shuffles one is less defined if it has the same vector operands
8684   // and its mask indeces are the same as in the first one or undefs. E.g.
8685   // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0,
8686   // poison, <0, 0, 0, 0>.
8687   auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2,
8688                                            SmallVectorImpl<int> &NewMask) {
8689     if (I1->getType() != I2->getType())
8690       return false;
8691     auto *SI1 = dyn_cast<ShuffleVectorInst>(I1);
8692     auto *SI2 = dyn_cast<ShuffleVectorInst>(I2);
8693     if (!SI1 || !SI2)
8694       return I1->isIdenticalTo(I2);
8695     if (SI1->isIdenticalTo(SI2))
8696       return true;
8697     for (int I = 0, E = SI1->getNumOperands(); I < E; ++I)
8698       if (SI1->getOperand(I) != SI2->getOperand(I))
8699         return false;
8700     // Check if the second instruction is more defined than the first one.
8701     NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end());
8702     ArrayRef<int> SM1 = SI1->getShuffleMask();
8703     // Count trailing undefs in the mask to check the final number of used
8704     // registers.
8705     unsigned LastUndefsCnt = 0;
8706     for (int I = 0, E = NewMask.size(); I < E; ++I) {
8707       if (SM1[I] == UndefMaskElem)
8708         ++LastUndefsCnt;
8709       else
8710         LastUndefsCnt = 0;
8711       if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem &&
8712           NewMask[I] != SM1[I])
8713         return false;
8714       if (NewMask[I] == UndefMaskElem)
8715         NewMask[I] = SM1[I];
8716     }
8717     // Check if the last undefs actually change the final number of used vector
8718     // registers.
8719     return SM1.size() - LastUndefsCnt > 1 &&
8720            TTI->getNumberOfParts(SI1->getType()) ==
8721                TTI->getNumberOfParts(
8722                    FixedVectorType::get(SI1->getType()->getElementType(),
8723                                         SM1.size() - LastUndefsCnt));
8724   };
8725   // Perform O(N^2) search over the gather/shuffle sequences and merge identical
8726   // instructions. TODO: We can further optimize this scan if we split the
8727   // instructions into different buckets based on the insert lane.
8728   SmallVector<Instruction *, 16> Visited;
8729   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
8730     assert(*I &&
8731            (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
8732            "Worklist not sorted properly!");
8733     BasicBlock *BB = (*I)->getBlock();
8734     // For all instructions in blocks containing gather sequences:
8735     for (Instruction &In : llvm::make_early_inc_range(*BB)) {
8736       if (isDeleted(&In))
8737         continue;
8738       if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) &&
8739           !isa<ShuffleVectorInst>(&In) && !GatherShuffleSeq.contains(&In))
8740         continue;
8741 
8742       // Check if we can replace this instruction with any of the
8743       // visited instructions.
8744       bool Replaced = false;
8745       for (Instruction *&V : Visited) {
8746         SmallVector<int> NewMask;
8747         if (IsIdenticalOrLessDefined(&In, V, NewMask) &&
8748             DT->dominates(V->getParent(), In.getParent())) {
8749           In.replaceAllUsesWith(V);
8750           eraseInstruction(&In);
8751           if (auto *SI = dyn_cast<ShuffleVectorInst>(V))
8752             if (!NewMask.empty())
8753               SI->setShuffleMask(NewMask);
8754           Replaced = true;
8755           break;
8756         }
8757         if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) &&
8758             GatherShuffleSeq.contains(V) &&
8759             IsIdenticalOrLessDefined(V, &In, NewMask) &&
8760             DT->dominates(In.getParent(), V->getParent())) {
8761           In.moveAfter(V);
8762           V->replaceAllUsesWith(&In);
8763           eraseInstruction(V);
8764           if (auto *SI = dyn_cast<ShuffleVectorInst>(&In))
8765             if (!NewMask.empty())
8766               SI->setShuffleMask(NewMask);
8767           V = &In;
8768           Replaced = true;
8769           break;
8770         }
8771       }
8772       if (!Replaced) {
8773         assert(!is_contained(Visited, &In));
8774         Visited.push_back(&In);
8775       }
8776     }
8777   }
8778   CSEBlocks.clear();
8779   GatherShuffleSeq.clear();
8780 }
8781 
8782 BoUpSLP::ScheduleData *
8783 BoUpSLP::BlockScheduling::buildBundle(ArrayRef<Value *> VL) {
8784   ScheduleData *Bundle = nullptr;
8785   ScheduleData *PrevInBundle = nullptr;
8786   for (Value *V : VL) {
8787     if (doesNotNeedToBeScheduled(V))
8788       continue;
8789     ScheduleData *BundleMember = getScheduleData(V);
8790     assert(BundleMember &&
8791            "no ScheduleData for bundle member "
8792            "(maybe not in same basic block)");
8793     assert(BundleMember->isSchedulingEntity() &&
8794            "bundle member already part of other bundle");
8795     if (PrevInBundle) {
8796       PrevInBundle->NextInBundle = BundleMember;
8797     } else {
8798       Bundle = BundleMember;
8799     }
8800 
8801     // Group the instructions to a bundle.
8802     BundleMember->FirstInBundle = Bundle;
8803     PrevInBundle = BundleMember;
8804   }
8805   assert(Bundle && "Failed to find schedule bundle");
8806   return Bundle;
8807 }
8808 
8809 // Groups the instructions to a bundle (which is then a single scheduling entity)
8810 // and schedules instructions until the bundle gets ready.
8811 Optional<BoUpSLP::ScheduleData *>
8812 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
8813                                             const InstructionsState &S) {
8814   // No need to schedule PHIs, insertelement, extractelement and extractvalue
8815   // instructions.
8816   if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue) ||
8817       doesNotNeedToSchedule(VL))
8818     return nullptr;
8819 
8820   // Initialize the instruction bundle.
8821   Instruction *OldScheduleEnd = ScheduleEnd;
8822   LLVM_DEBUG(dbgs() << "SLP:  bundle: " << *S.OpValue << "\n");
8823 
8824   auto TryScheduleBundleImpl = [this, OldScheduleEnd, SLP](bool ReSchedule,
8825                                                          ScheduleData *Bundle) {
8826     // The scheduling region got new instructions at the lower end (or it is a
8827     // new region for the first bundle). This makes it necessary to
8828     // recalculate all dependencies.
8829     // It is seldom that this needs to be done a second time after adding the
8830     // initial bundle to the region.
8831     if (ScheduleEnd != OldScheduleEnd) {
8832       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode())
8833         doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); });
8834       ReSchedule = true;
8835     }
8836     if (Bundle) {
8837       LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle
8838                         << " in block " << BB->getName() << "\n");
8839       calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP);
8840     }
8841 
8842     if (ReSchedule) {
8843       resetSchedule();
8844       initialFillReadyList(ReadyInsts);
8845     }
8846 
8847     // Now try to schedule the new bundle or (if no bundle) just calculate
8848     // dependencies. As soon as the bundle is "ready" it means that there are no
8849     // cyclic dependencies and we can schedule it. Note that's important that we
8850     // don't "schedule" the bundle yet (see cancelScheduling).
8851     while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) &&
8852            !ReadyInsts.empty()) {
8853       ScheduleData *Picked = ReadyInsts.pop_back_val();
8854       assert(Picked->isSchedulingEntity() && Picked->isReady() &&
8855              "must be ready to schedule");
8856       schedule(Picked, ReadyInsts);
8857     }
8858   };
8859 
8860   // Make sure that the scheduling region contains all
8861   // instructions of the bundle.
8862   for (Value *V : VL) {
8863     if (doesNotNeedToBeScheduled(V))
8864       continue;
8865     if (!extendSchedulingRegion(V, S)) {
8866       // If the scheduling region got new instructions at the lower end (or it
8867       // is a new region for the first bundle). This makes it necessary to
8868       // recalculate all dependencies.
8869       // Otherwise the compiler may crash trying to incorrectly calculate
8870       // dependencies and emit instruction in the wrong order at the actual
8871       // scheduling.
8872       TryScheduleBundleImpl(/*ReSchedule=*/false, nullptr);
8873       return None;
8874     }
8875   }
8876 
8877   bool ReSchedule = false;
8878   for (Value *V : VL) {
8879     if (doesNotNeedToBeScheduled(V))
8880       continue;
8881     ScheduleData *BundleMember = getScheduleData(V);
8882     assert(BundleMember &&
8883            "no ScheduleData for bundle member (maybe not in same basic block)");
8884 
8885     // Make sure we don't leave the pieces of the bundle in the ready list when
8886     // whole bundle might not be ready.
8887     ReadyInsts.remove(BundleMember);
8888 
8889     if (!BundleMember->IsScheduled)
8890       continue;
8891     // A bundle member was scheduled as single instruction before and now
8892     // needs to be scheduled as part of the bundle. We just get rid of the
8893     // existing schedule.
8894     LLVM_DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
8895                       << " was already scheduled\n");
8896     ReSchedule = true;
8897   }
8898 
8899   auto *Bundle = buildBundle(VL);
8900   TryScheduleBundleImpl(ReSchedule, Bundle);
8901   if (!Bundle->isReady()) {
8902     cancelScheduling(VL, S.OpValue);
8903     return None;
8904   }
8905   return Bundle;
8906 }
8907 
8908 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
8909                                                 Value *OpValue) {
8910   if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue) ||
8911       doesNotNeedToSchedule(VL))
8912     return;
8913 
8914   if (doesNotNeedToBeScheduled(OpValue))
8915     OpValue = *find_if_not(VL, doesNotNeedToBeScheduled);
8916   ScheduleData *Bundle = getScheduleData(OpValue);
8917   LLVM_DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
8918   assert(!Bundle->IsScheduled &&
8919          "Can't cancel bundle which is already scheduled");
8920   assert(Bundle->isSchedulingEntity() &&
8921          (Bundle->isPartOfBundle() || needToScheduleSingleInstruction(VL)) &&
8922          "tried to unbundle something which is not a bundle");
8923 
8924   // Remove the bundle from the ready list.
8925   if (Bundle->isReady())
8926     ReadyInsts.remove(Bundle);
8927 
8928   // Un-bundle: make single instructions out of the bundle.
8929   ScheduleData *BundleMember = Bundle;
8930   while (BundleMember) {
8931     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
8932     BundleMember->FirstInBundle = BundleMember;
8933     ScheduleData *Next = BundleMember->NextInBundle;
8934     BundleMember->NextInBundle = nullptr;
8935     BundleMember->TE = nullptr;
8936     if (BundleMember->unscheduledDepsInBundle() == 0) {
8937       ReadyInsts.insert(BundleMember);
8938     }
8939     BundleMember = Next;
8940   }
8941 }
8942 
8943 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
8944   // Allocate a new ScheduleData for the instruction.
8945   if (ChunkPos >= ChunkSize) {
8946     ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
8947     ChunkPos = 0;
8948   }
8949   return &(ScheduleDataChunks.back()[ChunkPos++]);
8950 }
8951 
8952 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
8953                                                       const InstructionsState &S) {
8954   if (getScheduleData(V, isOneOf(S, V)))
8955     return true;
8956   Instruction *I = dyn_cast<Instruction>(V);
8957   assert(I && "bundle member must be an instruction");
8958   assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) &&
8959          !doesNotNeedToBeScheduled(I) &&
8960          "phi nodes/insertelements/extractelements/extractvalues don't need to "
8961          "be scheduled");
8962   auto &&CheckScheduleForI = [this, &S](Instruction *I) -> bool {
8963     ScheduleData *ISD = getScheduleData(I);
8964     if (!ISD)
8965       return false;
8966     assert(isInSchedulingRegion(ISD) &&
8967            "ScheduleData not in scheduling region");
8968     ScheduleData *SD = allocateScheduleDataChunks();
8969     SD->Inst = I;
8970     SD->init(SchedulingRegionID, S.OpValue);
8971     ExtraScheduleDataMap[I][S.OpValue] = SD;
8972     return true;
8973   };
8974   if (CheckScheduleForI(I))
8975     return true;
8976   if (!ScheduleStart) {
8977     // It's the first instruction in the new region.
8978     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
8979     ScheduleStart = I;
8980     ScheduleEnd = I->getNextNode();
8981     if (isOneOf(S, I) != I)
8982       CheckScheduleForI(I);
8983     assert(ScheduleEnd && "tried to vectorize a terminator?");
8984     LLVM_DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
8985     return true;
8986   }
8987   // Search up and down at the same time, because we don't know if the new
8988   // instruction is above or below the existing scheduling region.
8989   BasicBlock::reverse_iterator UpIter =
8990       ++ScheduleStart->getIterator().getReverse();
8991   BasicBlock::reverse_iterator UpperEnd = BB->rend();
8992   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
8993   BasicBlock::iterator LowerEnd = BB->end();
8994   while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I &&
8995          &*DownIter != I) {
8996     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
8997       LLVM_DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
8998       return false;
8999     }
9000 
9001     ++UpIter;
9002     ++DownIter;
9003   }
9004   if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) {
9005     assert(I->getParent() == ScheduleStart->getParent() &&
9006            "Instruction is in wrong basic block.");
9007     initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
9008     ScheduleStart = I;
9009     if (isOneOf(S, I) != I)
9010       CheckScheduleForI(I);
9011     LLVM_DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I
9012                       << "\n");
9013     return true;
9014   }
9015   assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) &&
9016          "Expected to reach top of the basic block or instruction down the "
9017          "lower end.");
9018   assert(I->getParent() == ScheduleEnd->getParent() &&
9019          "Instruction is in wrong basic block.");
9020   initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
9021                    nullptr);
9022   ScheduleEnd = I->getNextNode();
9023   if (isOneOf(S, I) != I)
9024     CheckScheduleForI(I);
9025   assert(ScheduleEnd && "tried to vectorize a terminator?");
9026   LLVM_DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
9027   return true;
9028 }
9029 
9030 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
9031                                                 Instruction *ToI,
9032                                                 ScheduleData *PrevLoadStore,
9033                                                 ScheduleData *NextLoadStore) {
9034   ScheduleData *CurrentLoadStore = PrevLoadStore;
9035   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
9036     // No need to allocate data for non-schedulable instructions.
9037     if (doesNotNeedToBeScheduled(I))
9038       continue;
9039     ScheduleData *SD = ScheduleDataMap.lookup(I);
9040     if (!SD) {
9041       SD = allocateScheduleDataChunks();
9042       ScheduleDataMap[I] = SD;
9043       SD->Inst = I;
9044     }
9045     assert(!isInSchedulingRegion(SD) &&
9046            "new ScheduleData already in scheduling region");
9047     SD->init(SchedulingRegionID, I);
9048 
9049     if (I->mayReadOrWriteMemory() &&
9050         (!isa<IntrinsicInst>(I) ||
9051          (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect &&
9052           cast<IntrinsicInst>(I)->getIntrinsicID() !=
9053               Intrinsic::pseudoprobe))) {
9054       // Update the linked list of memory accessing instructions.
9055       if (CurrentLoadStore) {
9056         CurrentLoadStore->NextLoadStore = SD;
9057       } else {
9058         FirstLoadStoreInRegion = SD;
9059       }
9060       CurrentLoadStore = SD;
9061     }
9062 
9063     if (match(I, m_Intrinsic<Intrinsic::stacksave>()) ||
9064         match(I, m_Intrinsic<Intrinsic::stackrestore>()))
9065       RegionHasStackSave = true;
9066   }
9067   if (NextLoadStore) {
9068     if (CurrentLoadStore)
9069       CurrentLoadStore->NextLoadStore = NextLoadStore;
9070   } else {
9071     LastLoadStoreInRegion = CurrentLoadStore;
9072   }
9073 }
9074 
9075 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
9076                                                      bool InsertInReadyList,
9077                                                      BoUpSLP *SLP) {
9078   assert(SD->isSchedulingEntity());
9079 
9080   SmallVector<ScheduleData *, 10> WorkList;
9081   WorkList.push_back(SD);
9082 
9083   while (!WorkList.empty()) {
9084     ScheduleData *SD = WorkList.pop_back_val();
9085     for (ScheduleData *BundleMember = SD; BundleMember;
9086          BundleMember = BundleMember->NextInBundle) {
9087       assert(isInSchedulingRegion(BundleMember));
9088       if (BundleMember->hasValidDependencies())
9089         continue;
9090 
9091       LLVM_DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember
9092                  << "\n");
9093       BundleMember->Dependencies = 0;
9094       BundleMember->resetUnscheduledDeps();
9095 
9096       // Handle def-use chain dependencies.
9097       if (BundleMember->OpValue != BundleMember->Inst) {
9098         if (ScheduleData *UseSD = getScheduleData(BundleMember->Inst)) {
9099           BundleMember->Dependencies++;
9100           ScheduleData *DestBundle = UseSD->FirstInBundle;
9101           if (!DestBundle->IsScheduled)
9102             BundleMember->incrementUnscheduledDeps(1);
9103           if (!DestBundle->hasValidDependencies())
9104             WorkList.push_back(DestBundle);
9105         }
9106       } else {
9107         for (User *U : BundleMember->Inst->users()) {
9108           if (ScheduleData *UseSD = getScheduleData(cast<Instruction>(U))) {
9109             BundleMember->Dependencies++;
9110             ScheduleData *DestBundle = UseSD->FirstInBundle;
9111             if (!DestBundle->IsScheduled)
9112               BundleMember->incrementUnscheduledDeps(1);
9113             if (!DestBundle->hasValidDependencies())
9114               WorkList.push_back(DestBundle);
9115           }
9116         }
9117       }
9118 
9119       auto makeControlDependent = [&](Instruction *I) {
9120         auto *DepDest = getScheduleData(I);
9121         assert(DepDest && "must be in schedule window");
9122         DepDest->ControlDependencies.push_back(BundleMember);
9123         BundleMember->Dependencies++;
9124         ScheduleData *DestBundle = DepDest->FirstInBundle;
9125         if (!DestBundle->IsScheduled)
9126           BundleMember->incrementUnscheduledDeps(1);
9127         if (!DestBundle->hasValidDependencies())
9128           WorkList.push_back(DestBundle);
9129       };
9130 
9131       // Any instruction which isn't safe to speculate at the begining of the
9132       // block is control dependend on any early exit or non-willreturn call
9133       // which proceeds it.
9134       if (!isGuaranteedToTransferExecutionToSuccessor(BundleMember->Inst)) {
9135         for (Instruction *I = BundleMember->Inst->getNextNode();
9136              I != ScheduleEnd; I = I->getNextNode()) {
9137           if (isSafeToSpeculativelyExecute(I, &*BB->begin()))
9138             continue;
9139 
9140           // Add the dependency
9141           makeControlDependent(I);
9142 
9143           if (!isGuaranteedToTransferExecutionToSuccessor(I))
9144             // Everything past here must be control dependent on I.
9145             break;
9146         }
9147       }
9148 
9149       if (RegionHasStackSave) {
9150         // If we have an inalloc alloca instruction, it needs to be scheduled
9151         // after any preceeding stacksave.  We also need to prevent any alloca
9152         // from reordering above a preceeding stackrestore.
9153         if (match(BundleMember->Inst, m_Intrinsic<Intrinsic::stacksave>()) ||
9154             match(BundleMember->Inst, m_Intrinsic<Intrinsic::stackrestore>())) {
9155           for (Instruction *I = BundleMember->Inst->getNextNode();
9156                I != ScheduleEnd; I = I->getNextNode()) {
9157             if (match(I, m_Intrinsic<Intrinsic::stacksave>()) ||
9158                 match(I, m_Intrinsic<Intrinsic::stackrestore>()))
9159               // Any allocas past here must be control dependent on I, and I
9160               // must be memory dependend on BundleMember->Inst.
9161               break;
9162 
9163             if (!isa<AllocaInst>(I))
9164               continue;
9165 
9166             // Add the dependency
9167             makeControlDependent(I);
9168           }
9169         }
9170 
9171         // In addition to the cases handle just above, we need to prevent
9172         // allocas from moving below a stacksave.  The stackrestore case
9173         // is currently thought to be conservatism.
9174         if (isa<AllocaInst>(BundleMember->Inst)) {
9175           for (Instruction *I = BundleMember->Inst->getNextNode();
9176                I != ScheduleEnd; I = I->getNextNode()) {
9177             if (!match(I, m_Intrinsic<Intrinsic::stacksave>()) &&
9178                 !match(I, m_Intrinsic<Intrinsic::stackrestore>()))
9179               continue;
9180 
9181             // Add the dependency
9182             makeControlDependent(I);
9183             break;
9184           }
9185         }
9186       }
9187 
9188       // Handle the memory dependencies (if any).
9189       ScheduleData *DepDest = BundleMember->NextLoadStore;
9190       if (!DepDest)
9191         continue;
9192       Instruction *SrcInst = BundleMember->Inst;
9193       assert(SrcInst->mayReadOrWriteMemory() &&
9194              "NextLoadStore list for non memory effecting bundle?");
9195       MemoryLocation SrcLoc = getLocation(SrcInst);
9196       bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
9197       unsigned numAliased = 0;
9198       unsigned DistToSrc = 1;
9199 
9200       for ( ; DepDest; DepDest = DepDest->NextLoadStore) {
9201         assert(isInSchedulingRegion(DepDest));
9202 
9203         // We have two limits to reduce the complexity:
9204         // 1) AliasedCheckLimit: It's a small limit to reduce calls to
9205         //    SLP->isAliased (which is the expensive part in this loop).
9206         // 2) MaxMemDepDistance: It's for very large blocks and it aborts
9207         //    the whole loop (even if the loop is fast, it's quadratic).
9208         //    It's important for the loop break condition (see below) to
9209         //    check this limit even between two read-only instructions.
9210         if (DistToSrc >= MaxMemDepDistance ||
9211             ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
9212              (numAliased >= AliasedCheckLimit ||
9213               SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
9214 
9215           // We increment the counter only if the locations are aliased
9216           // (instead of counting all alias checks). This gives a better
9217           // balance between reduced runtime and accurate dependencies.
9218           numAliased++;
9219 
9220           DepDest->MemoryDependencies.push_back(BundleMember);
9221           BundleMember->Dependencies++;
9222           ScheduleData *DestBundle = DepDest->FirstInBundle;
9223           if (!DestBundle->IsScheduled) {
9224             BundleMember->incrementUnscheduledDeps(1);
9225           }
9226           if (!DestBundle->hasValidDependencies()) {
9227             WorkList.push_back(DestBundle);
9228           }
9229         }
9230 
9231         // Example, explaining the loop break condition: Let's assume our
9232         // starting instruction is i0 and MaxMemDepDistance = 3.
9233         //
9234         //                      +--------v--v--v
9235         //             i0,i1,i2,i3,i4,i5,i6,i7,i8
9236         //             +--------^--^--^
9237         //
9238         // MaxMemDepDistance let us stop alias-checking at i3 and we add
9239         // dependencies from i0 to i3,i4,.. (even if they are not aliased).
9240         // Previously we already added dependencies from i3 to i6,i7,i8
9241         // (because of MaxMemDepDistance). As we added a dependency from
9242         // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
9243         // and we can abort this loop at i6.
9244         if (DistToSrc >= 2 * MaxMemDepDistance)
9245           break;
9246         DistToSrc++;
9247       }
9248     }
9249     if (InsertInReadyList && SD->isReady()) {
9250       ReadyInsts.insert(SD);
9251       LLVM_DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst
9252                         << "\n");
9253     }
9254   }
9255 }
9256 
9257 void BoUpSLP::BlockScheduling::resetSchedule() {
9258   assert(ScheduleStart &&
9259          "tried to reset schedule on block which has not been scheduled");
9260   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
9261     doForAllOpcodes(I, [&](ScheduleData *SD) {
9262       assert(isInSchedulingRegion(SD) &&
9263              "ScheduleData not in scheduling region");
9264       SD->IsScheduled = false;
9265       SD->resetUnscheduledDeps();
9266     });
9267   }
9268   ReadyInsts.clear();
9269 }
9270 
9271 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
9272   if (!BS->ScheduleStart)
9273     return;
9274 
9275   LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
9276 
9277   // A key point - if we got here, pre-scheduling was able to find a valid
9278   // scheduling of the sub-graph of the scheduling window which consists
9279   // of all vector bundles and their transitive users.  As such, we do not
9280   // need to reschedule anything *outside of* that subgraph.
9281 
9282   BS->resetSchedule();
9283 
9284   // For the real scheduling we use a more sophisticated ready-list: it is
9285   // sorted by the original instruction location. This lets the final schedule
9286   // be as  close as possible to the original instruction order.
9287   // WARNING: If changing this order causes a correctness issue, that means
9288   // there is some missing dependence edge in the schedule data graph.
9289   struct ScheduleDataCompare {
9290     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
9291       return SD2->SchedulingPriority < SD1->SchedulingPriority;
9292     }
9293   };
9294   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
9295 
9296   // Ensure that all dependency data is updated (for nodes in the sub-graph)
9297   // and fill the ready-list with initial instructions.
9298   int Idx = 0;
9299   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
9300        I = I->getNextNode()) {
9301     BS->doForAllOpcodes(I, [this, &Idx, BS](ScheduleData *SD) {
9302       TreeEntry *SDTE = getTreeEntry(SD->Inst);
9303       (void)SDTE;
9304       assert((isVectorLikeInstWithConstOps(SD->Inst) ||
9305               SD->isPartOfBundle() ==
9306                   (SDTE && !doesNotNeedToSchedule(SDTE->Scalars))) &&
9307              "scheduler and vectorizer bundle mismatch");
9308       SD->FirstInBundle->SchedulingPriority = Idx++;
9309 
9310       if (SD->isSchedulingEntity() && SD->isPartOfBundle())
9311         BS->calculateDependencies(SD, false, this);
9312     });
9313   }
9314   BS->initialFillReadyList(ReadyInsts);
9315 
9316   Instruction *LastScheduledInst = BS->ScheduleEnd;
9317 
9318   // Do the "real" scheduling.
9319   while (!ReadyInsts.empty()) {
9320     ScheduleData *picked = *ReadyInsts.begin();
9321     ReadyInsts.erase(ReadyInsts.begin());
9322 
9323     // Move the scheduled instruction(s) to their dedicated places, if not
9324     // there yet.
9325     for (ScheduleData *BundleMember = picked; BundleMember;
9326          BundleMember = BundleMember->NextInBundle) {
9327       Instruction *pickedInst = BundleMember->Inst;
9328       if (pickedInst->getNextNode() != LastScheduledInst)
9329         pickedInst->moveBefore(LastScheduledInst);
9330       LastScheduledInst = pickedInst;
9331     }
9332 
9333     BS->schedule(picked, ReadyInsts);
9334   }
9335 
9336   // Check that we didn't break any of our invariants.
9337 #ifdef EXPENSIVE_CHECKS
9338   BS->verify();
9339 #endif
9340 
9341 #if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS)
9342   // Check that all schedulable entities got scheduled
9343   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; I = I->getNextNode()) {
9344     BS->doForAllOpcodes(I, [&](ScheduleData *SD) {
9345       if (SD->isSchedulingEntity() && SD->hasValidDependencies()) {
9346         assert(SD->IsScheduled && "must be scheduled at this point");
9347       }
9348     });
9349   }
9350 #endif
9351 
9352   // Avoid duplicate scheduling of the block.
9353   BS->ScheduleStart = nullptr;
9354 }
9355 
9356 unsigned BoUpSLP::getVectorElementSize(Value *V) {
9357   // If V is a store, just return the width of the stored value (or value
9358   // truncated just before storing) without traversing the expression tree.
9359   // This is the common case.
9360   if (auto *Store = dyn_cast<StoreInst>(V))
9361     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
9362 
9363   if (auto *IEI = dyn_cast<InsertElementInst>(V))
9364     return getVectorElementSize(IEI->getOperand(1));
9365 
9366   auto E = InstrElementSize.find(V);
9367   if (E != InstrElementSize.end())
9368     return E->second;
9369 
9370   // If V is not a store, we can traverse the expression tree to find loads
9371   // that feed it. The type of the loaded value may indicate a more suitable
9372   // width than V's type. We want to base the vector element size on the width
9373   // of memory operations where possible.
9374   SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist;
9375   SmallPtrSet<Instruction *, 16> Visited;
9376   if (auto *I = dyn_cast<Instruction>(V)) {
9377     Worklist.emplace_back(I, I->getParent());
9378     Visited.insert(I);
9379   }
9380 
9381   // Traverse the expression tree in bottom-up order looking for loads. If we
9382   // encounter an instruction we don't yet handle, we give up.
9383   auto Width = 0u;
9384   while (!Worklist.empty()) {
9385     Instruction *I;
9386     BasicBlock *Parent;
9387     std::tie(I, Parent) = Worklist.pop_back_val();
9388 
9389     // We should only be looking at scalar instructions here. If the current
9390     // instruction has a vector type, skip.
9391     auto *Ty = I->getType();
9392     if (isa<VectorType>(Ty))
9393       continue;
9394 
9395     // If the current instruction is a load, update MaxWidth to reflect the
9396     // width of the loaded value.
9397     if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) ||
9398         isa<ExtractValueInst>(I))
9399       Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty));
9400 
9401     // Otherwise, we need to visit the operands of the instruction. We only
9402     // handle the interesting cases from buildTree here. If an operand is an
9403     // instruction we haven't yet visited and from the same basic block as the
9404     // user or the use is a PHI node, we add it to the worklist.
9405     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
9406              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) ||
9407              isa<UnaryOperator>(I)) {
9408       for (Use &U : I->operands())
9409         if (auto *J = dyn_cast<Instruction>(U.get()))
9410           if (Visited.insert(J).second &&
9411               (isa<PHINode>(I) || J->getParent() == Parent))
9412             Worklist.emplace_back(J, J->getParent());
9413     } else {
9414       break;
9415     }
9416   }
9417 
9418   // If we didn't encounter a memory access in the expression tree, or if we
9419   // gave up for some reason, just return the width of V. Otherwise, return the
9420   // maximum width we found.
9421   if (!Width) {
9422     if (auto *CI = dyn_cast<CmpInst>(V))
9423       V = CI->getOperand(0);
9424     Width = DL->getTypeSizeInBits(V->getType());
9425   }
9426 
9427   for (Instruction *I : Visited)
9428     InstrElementSize[I] = Width;
9429 
9430   return Width;
9431 }
9432 
9433 // Determine if a value V in a vectorizable expression Expr can be demoted to a
9434 // smaller type with a truncation. We collect the values that will be demoted
9435 // in ToDemote and additional roots that require investigating in Roots.
9436 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
9437                                   SmallVectorImpl<Value *> &ToDemote,
9438                                   SmallVectorImpl<Value *> &Roots) {
9439   // We can always demote constants.
9440   if (isa<Constant>(V)) {
9441     ToDemote.push_back(V);
9442     return true;
9443   }
9444 
9445   // If the value is not an instruction in the expression with only one use, it
9446   // cannot be demoted.
9447   auto *I = dyn_cast<Instruction>(V);
9448   if (!I || !I->hasOneUse() || !Expr.count(I))
9449     return false;
9450 
9451   switch (I->getOpcode()) {
9452 
9453   // We can always demote truncations and extensions. Since truncations can
9454   // seed additional demotion, we save the truncated value.
9455   case Instruction::Trunc:
9456     Roots.push_back(I->getOperand(0));
9457     break;
9458   case Instruction::ZExt:
9459   case Instruction::SExt:
9460     if (isa<ExtractElementInst>(I->getOperand(0)) ||
9461         isa<InsertElementInst>(I->getOperand(0)))
9462       return false;
9463     break;
9464 
9465   // We can demote certain binary operations if we can demote both of their
9466   // operands.
9467   case Instruction::Add:
9468   case Instruction::Sub:
9469   case Instruction::Mul:
9470   case Instruction::And:
9471   case Instruction::Or:
9472   case Instruction::Xor:
9473     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
9474         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
9475       return false;
9476     break;
9477 
9478   // We can demote selects if we can demote their true and false values.
9479   case Instruction::Select: {
9480     SelectInst *SI = cast<SelectInst>(I);
9481     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
9482         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
9483       return false;
9484     break;
9485   }
9486 
9487   // We can demote phis if we can demote all their incoming operands. Note that
9488   // we don't need to worry about cycles since we ensure single use above.
9489   case Instruction::PHI: {
9490     PHINode *PN = cast<PHINode>(I);
9491     for (Value *IncValue : PN->incoming_values())
9492       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
9493         return false;
9494     break;
9495   }
9496 
9497   // Otherwise, conservatively give up.
9498   default:
9499     return false;
9500   }
9501 
9502   // Record the value that we can demote.
9503   ToDemote.push_back(V);
9504   return true;
9505 }
9506 
9507 void BoUpSLP::computeMinimumValueSizes() {
9508   // If there are no external uses, the expression tree must be rooted by a
9509   // store. We can't demote in-memory values, so there is nothing to do here.
9510   if (ExternalUses.empty())
9511     return;
9512 
9513   // We only attempt to truncate integer expressions.
9514   auto &TreeRoot = VectorizableTree[0]->Scalars;
9515   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
9516   if (!TreeRootIT)
9517     return;
9518 
9519   // If the expression is not rooted by a store, these roots should have
9520   // external uses. We will rely on InstCombine to rewrite the expression in
9521   // the narrower type. However, InstCombine only rewrites single-use values.
9522   // This means that if a tree entry other than a root is used externally, it
9523   // must have multiple uses and InstCombine will not rewrite it. The code
9524   // below ensures that only the roots are used externally.
9525   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
9526   for (auto &EU : ExternalUses)
9527     if (!Expr.erase(EU.Scalar))
9528       return;
9529   if (!Expr.empty())
9530     return;
9531 
9532   // Collect the scalar values of the vectorizable expression. We will use this
9533   // context to determine which values can be demoted. If we see a truncation,
9534   // we mark it as seeding another demotion.
9535   for (auto &EntryPtr : VectorizableTree)
9536     Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
9537 
9538   // Ensure the roots of the vectorizable tree don't form a cycle. They must
9539   // have a single external user that is not in the vectorizable tree.
9540   for (auto *Root : TreeRoot)
9541     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
9542       return;
9543 
9544   // Conservatively determine if we can actually truncate the roots of the
9545   // expression. Collect the values that can be demoted in ToDemote and
9546   // additional roots that require investigating in Roots.
9547   SmallVector<Value *, 32> ToDemote;
9548   SmallVector<Value *, 4> Roots;
9549   for (auto *Root : TreeRoot)
9550     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
9551       return;
9552 
9553   // The maximum bit width required to represent all the values that can be
9554   // demoted without loss of precision. It would be safe to truncate the roots
9555   // of the expression to this width.
9556   auto MaxBitWidth = 8u;
9557 
9558   // We first check if all the bits of the roots are demanded. If they're not,
9559   // we can truncate the roots to this narrower type.
9560   for (auto *Root : TreeRoot) {
9561     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
9562     MaxBitWidth = std::max<unsigned>(
9563         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
9564   }
9565 
9566   // True if the roots can be zero-extended back to their original type, rather
9567   // than sign-extended. We know that if the leading bits are not demanded, we
9568   // can safely zero-extend. So we initialize IsKnownPositive to True.
9569   bool IsKnownPositive = true;
9570 
9571   // If all the bits of the roots are demanded, we can try a little harder to
9572   // compute a narrower type. This can happen, for example, if the roots are
9573   // getelementptr indices. InstCombine promotes these indices to the pointer
9574   // width. Thus, all their bits are technically demanded even though the
9575   // address computation might be vectorized in a smaller type.
9576   //
9577   // We start by looking at each entry that can be demoted. We compute the
9578   // maximum bit width required to store the scalar by using ValueTracking to
9579   // compute the number of high-order bits we can truncate.
9580   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
9581       llvm::all_of(TreeRoot, [](Value *R) {
9582         assert(R->hasOneUse() && "Root should have only one use!");
9583         return isa<GetElementPtrInst>(R->user_back());
9584       })) {
9585     MaxBitWidth = 8u;
9586 
9587     // Determine if the sign bit of all the roots is known to be zero. If not,
9588     // IsKnownPositive is set to False.
9589     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
9590       KnownBits Known = computeKnownBits(R, *DL);
9591       return Known.isNonNegative();
9592     });
9593 
9594     // Determine the maximum number of bits required to store the scalar
9595     // values.
9596     for (auto *Scalar : ToDemote) {
9597       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
9598       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
9599       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
9600     }
9601 
9602     // If we can't prove that the sign bit is zero, we must add one to the
9603     // maximum bit width to account for the unknown sign bit. This preserves
9604     // the existing sign bit so we can safely sign-extend the root back to the
9605     // original type. Otherwise, if we know the sign bit is zero, we will
9606     // zero-extend the root instead.
9607     //
9608     // FIXME: This is somewhat suboptimal, as there will be cases where adding
9609     //        one to the maximum bit width will yield a larger-than-necessary
9610     //        type. In general, we need to add an extra bit only if we can't
9611     //        prove that the upper bit of the original type is equal to the
9612     //        upper bit of the proposed smaller type. If these two bits are the
9613     //        same (either zero or one) we know that sign-extending from the
9614     //        smaller type will result in the same value. Here, since we can't
9615     //        yet prove this, we are just making the proposed smaller type
9616     //        larger to ensure correctness.
9617     if (!IsKnownPositive)
9618       ++MaxBitWidth;
9619   }
9620 
9621   // Round MaxBitWidth up to the next power-of-two.
9622   if (!isPowerOf2_64(MaxBitWidth))
9623     MaxBitWidth = NextPowerOf2(MaxBitWidth);
9624 
9625   // If the maximum bit width we compute is less than the with of the roots'
9626   // type, we can proceed with the narrowing. Otherwise, do nothing.
9627   if (MaxBitWidth >= TreeRootIT->getBitWidth())
9628     return;
9629 
9630   // If we can truncate the root, we must collect additional values that might
9631   // be demoted as a result. That is, those seeded by truncations we will
9632   // modify.
9633   while (!Roots.empty())
9634     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
9635 
9636   // Finally, map the values we can demote to the maximum bit with we computed.
9637   for (auto *Scalar : ToDemote)
9638     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
9639 }
9640 
9641 namespace {
9642 
9643 /// The SLPVectorizer Pass.
9644 struct SLPVectorizer : public FunctionPass {
9645   SLPVectorizerPass Impl;
9646 
9647   /// Pass identification, replacement for typeid
9648   static char ID;
9649 
9650   explicit SLPVectorizer() : FunctionPass(ID) {
9651     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
9652   }
9653 
9654   bool doInitialization(Module &M) override { return false; }
9655 
9656   bool runOnFunction(Function &F) override {
9657     if (skipFunction(F))
9658       return false;
9659 
9660     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
9661     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
9662     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
9663     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
9664     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
9665     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
9666     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
9667     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
9668     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
9669     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
9670 
9671     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
9672   }
9673 
9674   void getAnalysisUsage(AnalysisUsage &AU) const override {
9675     FunctionPass::getAnalysisUsage(AU);
9676     AU.addRequired<AssumptionCacheTracker>();
9677     AU.addRequired<ScalarEvolutionWrapperPass>();
9678     AU.addRequired<AAResultsWrapperPass>();
9679     AU.addRequired<TargetTransformInfoWrapperPass>();
9680     AU.addRequired<LoopInfoWrapperPass>();
9681     AU.addRequired<DominatorTreeWrapperPass>();
9682     AU.addRequired<DemandedBitsWrapperPass>();
9683     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
9684     AU.addRequired<InjectTLIMappingsLegacy>();
9685     AU.addPreserved<LoopInfoWrapperPass>();
9686     AU.addPreserved<DominatorTreeWrapperPass>();
9687     AU.addPreserved<AAResultsWrapperPass>();
9688     AU.addPreserved<GlobalsAAWrapperPass>();
9689     AU.setPreservesCFG();
9690   }
9691 };
9692 
9693 } // end anonymous namespace
9694 
9695 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
9696   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
9697   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
9698   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
9699   auto *AA = &AM.getResult<AAManager>(F);
9700   auto *LI = &AM.getResult<LoopAnalysis>(F);
9701   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
9702   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
9703   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
9704   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
9705 
9706   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
9707   if (!Changed)
9708     return PreservedAnalyses::all();
9709 
9710   PreservedAnalyses PA;
9711   PA.preserveSet<CFGAnalyses>();
9712   return PA;
9713 }
9714 
9715 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
9716                                 TargetTransformInfo *TTI_,
9717                                 TargetLibraryInfo *TLI_, AAResults *AA_,
9718                                 LoopInfo *LI_, DominatorTree *DT_,
9719                                 AssumptionCache *AC_, DemandedBits *DB_,
9720                                 OptimizationRemarkEmitter *ORE_) {
9721   if (!RunSLPVectorization)
9722     return false;
9723   SE = SE_;
9724   TTI = TTI_;
9725   TLI = TLI_;
9726   AA = AA_;
9727   LI = LI_;
9728   DT = DT_;
9729   AC = AC_;
9730   DB = DB_;
9731   DL = &F.getParent()->getDataLayout();
9732 
9733   Stores.clear();
9734   GEPs.clear();
9735   bool Changed = false;
9736 
9737   // If the target claims to have no vector registers don't attempt
9738   // vectorization.
9739   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true))) {
9740     LLVM_DEBUG(
9741         dbgs() << "SLP: Didn't find any vector registers for target, abort.\n");
9742     return false;
9743   }
9744 
9745   // Don't vectorize when the attribute NoImplicitFloat is used.
9746   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
9747     return false;
9748 
9749   LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
9750 
9751   // Use the bottom up slp vectorizer to construct chains that start with
9752   // store instructions.
9753   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
9754 
9755   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
9756   // delete instructions.
9757 
9758   // Update DFS numbers now so that we can use them for ordering.
9759   DT->updateDFSNumbers();
9760 
9761   // Scan the blocks in the function in post order.
9762   for (auto BB : post_order(&F.getEntryBlock())) {
9763     // Start new block - clear the list of reduction roots.
9764     R.clearReductionData();
9765     collectSeedInstructions(BB);
9766 
9767     // Vectorize trees that end at stores.
9768     if (!Stores.empty()) {
9769       LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
9770                         << " underlying objects.\n");
9771       Changed |= vectorizeStoreChains(R);
9772     }
9773 
9774     // Vectorize trees that end at reductions.
9775     Changed |= vectorizeChainsInBlock(BB, R);
9776 
9777     // Vectorize the index computations of getelementptr instructions. This
9778     // is primarily intended to catch gather-like idioms ending at
9779     // non-consecutive loads.
9780     if (!GEPs.empty()) {
9781       LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
9782                         << " underlying objects.\n");
9783       Changed |= vectorizeGEPIndices(BB, R);
9784     }
9785   }
9786 
9787   if (Changed) {
9788     R.optimizeGatherSequence();
9789     LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
9790   }
9791   return Changed;
9792 }
9793 
9794 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
9795                                             unsigned Idx, unsigned MinVF) {
9796   LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()
9797                     << "\n");
9798   const unsigned Sz = R.getVectorElementSize(Chain[0]);
9799   unsigned VF = Chain.size();
9800 
9801   if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
9802     return false;
9803 
9804   LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx
9805                     << "\n");
9806 
9807   R.buildTree(Chain);
9808   if (R.isTreeTinyAndNotFullyVectorizable())
9809     return false;
9810   if (R.isLoadCombineCandidate())
9811     return false;
9812   R.reorderTopToBottom();
9813   R.reorderBottomToTop();
9814   R.buildExternalUses();
9815 
9816   R.computeMinimumValueSizes();
9817 
9818   InstructionCost Cost = R.getTreeCost();
9819 
9820   LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n");
9821   if (Cost < -SLPCostThreshold) {
9822     LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n");
9823 
9824     using namespace ore;
9825 
9826     R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
9827                                         cast<StoreInst>(Chain[0]))
9828                      << "Stores SLP vectorized with cost " << NV("Cost", Cost)
9829                      << " and with tree size "
9830                      << NV("TreeSize", R.getTreeSize()));
9831 
9832     R.vectorizeTree();
9833     return true;
9834   }
9835 
9836   return false;
9837 }
9838 
9839 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
9840                                         BoUpSLP &R) {
9841   // We may run into multiple chains that merge into a single chain. We mark the
9842   // stores that we vectorized so that we don't visit the same store twice.
9843   BoUpSLP::ValueSet VectorizedStores;
9844   bool Changed = false;
9845 
9846   int E = Stores.size();
9847   SmallBitVector Tails(E, false);
9848   int MaxIter = MaxStoreLookup.getValue();
9849   SmallVector<std::pair<int, int>, 16> ConsecutiveChain(
9850       E, std::make_pair(E, INT_MAX));
9851   SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false));
9852   int IterCnt;
9853   auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
9854                                   &CheckedPairs,
9855                                   &ConsecutiveChain](int K, int Idx) {
9856     if (IterCnt >= MaxIter)
9857       return true;
9858     if (CheckedPairs[Idx].test(K))
9859       return ConsecutiveChain[K].second == 1 &&
9860              ConsecutiveChain[K].first == Idx;
9861     ++IterCnt;
9862     CheckedPairs[Idx].set(K);
9863     CheckedPairs[K].set(Idx);
9864     Optional<int> Diff = getPointersDiff(
9865         Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(),
9866         Stores[Idx]->getValueOperand()->getType(),
9867         Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true);
9868     if (!Diff || *Diff == 0)
9869       return false;
9870     int Val = *Diff;
9871     if (Val < 0) {
9872       if (ConsecutiveChain[Idx].second > -Val) {
9873         Tails.set(K);
9874         ConsecutiveChain[Idx] = std::make_pair(K, -Val);
9875       }
9876       return false;
9877     }
9878     if (ConsecutiveChain[K].second <= Val)
9879       return false;
9880 
9881     Tails.set(Idx);
9882     ConsecutiveChain[K] = std::make_pair(Idx, Val);
9883     return Val == 1;
9884   };
9885   // Do a quadratic search on all of the given stores in reverse order and find
9886   // all of the pairs of stores that follow each other.
9887   for (int Idx = E - 1; Idx >= 0; --Idx) {
9888     // If a store has multiple consecutive store candidates, search according
9889     // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
9890     // This is because usually pairing with immediate succeeding or preceding
9891     // candidate create the best chance to find slp vectorization opportunity.
9892     const int MaxLookDepth = std::max(E - Idx, Idx + 1);
9893     IterCnt = 0;
9894     for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
9895       if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
9896           (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
9897         break;
9898   }
9899 
9900   // Tracks if we tried to vectorize stores starting from the given tail
9901   // already.
9902   SmallBitVector TriedTails(E, false);
9903   // For stores that start but don't end a link in the chain:
9904   for (int Cnt = E; Cnt > 0; --Cnt) {
9905     int I = Cnt - 1;
9906     if (ConsecutiveChain[I].first == E || Tails.test(I))
9907       continue;
9908     // We found a store instr that starts a chain. Now follow the chain and try
9909     // to vectorize it.
9910     BoUpSLP::ValueList Operands;
9911     // Collect the chain into a list.
9912     while (I != E && !VectorizedStores.count(Stores[I])) {
9913       Operands.push_back(Stores[I]);
9914       Tails.set(I);
9915       if (ConsecutiveChain[I].second != 1) {
9916         // Mark the new end in the chain and go back, if required. It might be
9917         // required if the original stores come in reversed order, for example.
9918         if (ConsecutiveChain[I].first != E &&
9919             Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) &&
9920             !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) {
9921           TriedTails.set(I);
9922           Tails.reset(ConsecutiveChain[I].first);
9923           if (Cnt < ConsecutiveChain[I].first + 2)
9924             Cnt = ConsecutiveChain[I].first + 2;
9925         }
9926         break;
9927       }
9928       // Move to the next value in the chain.
9929       I = ConsecutiveChain[I].first;
9930     }
9931     assert(!Operands.empty() && "Expected non-empty list of stores.");
9932 
9933     unsigned MaxVecRegSize = R.getMaxVecRegSize();
9934     unsigned EltSize = R.getVectorElementSize(Operands[0]);
9935     unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize);
9936 
9937     unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store),
9938                               MaxElts);
9939     auto *Store = cast<StoreInst>(Operands[0]);
9940     Type *StoreTy = Store->getValueOperand()->getType();
9941     Type *ValueTy = StoreTy;
9942     if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand()))
9943       ValueTy = Trunc->getSrcTy();
9944     unsigned MinVF = TTI->getStoreMinimumVF(
9945         R.getMinVF(DL->getTypeSizeInBits(ValueTy)), StoreTy, ValueTy);
9946 
9947     // FIXME: Is division-by-2 the correct step? Should we assert that the
9948     // register size is a power-of-2?
9949     unsigned StartIdx = 0;
9950     for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) {
9951       for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
9952         ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size);
9953         if (!VectorizedStores.count(Slice.front()) &&
9954             !VectorizedStores.count(Slice.back()) &&
9955             vectorizeStoreChain(Slice, R, Cnt, MinVF)) {
9956           // Mark the vectorized stores so that we don't vectorize them again.
9957           VectorizedStores.insert(Slice.begin(), Slice.end());
9958           Changed = true;
9959           // If we vectorized initial block, no need to try to vectorize it
9960           // again.
9961           if (Cnt == StartIdx)
9962             StartIdx += Size;
9963           Cnt += Size;
9964           continue;
9965         }
9966         ++Cnt;
9967       }
9968       // Check if the whole array was vectorized already - exit.
9969       if (StartIdx >= Operands.size())
9970         break;
9971     }
9972   }
9973 
9974   return Changed;
9975 }
9976 
9977 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
9978   // Initialize the collections. We will make a single pass over the block.
9979   Stores.clear();
9980   GEPs.clear();
9981 
9982   // Visit the store and getelementptr instructions in BB and organize them in
9983   // Stores and GEPs according to the underlying objects of their pointer
9984   // operands.
9985   for (Instruction &I : *BB) {
9986     // Ignore store instructions that are volatile or have a pointer operand
9987     // that doesn't point to a scalar type.
9988     if (auto *SI = dyn_cast<StoreInst>(&I)) {
9989       if (!SI->isSimple())
9990         continue;
9991       if (!isValidElementType(SI->getValueOperand()->getType()))
9992         continue;
9993       Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI);
9994     }
9995 
9996     // Ignore getelementptr instructions that have more than one index, a
9997     // constant index, or a pointer operand that doesn't point to a scalar
9998     // type.
9999     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
10000       auto Idx = GEP->idx_begin()->get();
10001       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
10002         continue;
10003       if (!isValidElementType(Idx->getType()))
10004         continue;
10005       if (GEP->getType()->isVectorTy())
10006         continue;
10007       GEPs[GEP->getPointerOperand()].push_back(GEP);
10008     }
10009   }
10010 }
10011 
10012 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
10013   if (!A || !B)
10014     return false;
10015   if (isa<InsertElementInst>(A) || isa<InsertElementInst>(B))
10016     return false;
10017   Value *VL[] = {A, B};
10018   return tryToVectorizeList(VL, R);
10019 }
10020 
10021 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
10022                                            bool LimitForRegisterSize) {
10023   if (VL.size() < 2)
10024     return false;
10025 
10026   LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
10027                     << VL.size() << ".\n");
10028 
10029   // Check that all of the parts are instructions of the same type,
10030   // we permit an alternate opcode via InstructionsState.
10031   InstructionsState S = getSameOpcode(VL);
10032   if (!S.getOpcode())
10033     return false;
10034 
10035   Instruction *I0 = cast<Instruction>(S.OpValue);
10036   // Make sure invalid types (including vector type) are rejected before
10037   // determining vectorization factor for scalar instructions.
10038   for (Value *V : VL) {
10039     Type *Ty = V->getType();
10040     if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) {
10041       // NOTE: the following will give user internal llvm type name, which may
10042       // not be useful.
10043       R.getORE()->emit([&]() {
10044         std::string type_str;
10045         llvm::raw_string_ostream rso(type_str);
10046         Ty->print(rso);
10047         return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
10048                << "Cannot SLP vectorize list: type "
10049                << rso.str() + " is unsupported by vectorizer";
10050       });
10051       return false;
10052     }
10053   }
10054 
10055   unsigned Sz = R.getVectorElementSize(I0);
10056   unsigned MinVF = R.getMinVF(Sz);
10057   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
10058   MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF);
10059   if (MaxVF < 2) {
10060     R.getORE()->emit([&]() {
10061       return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
10062              << "Cannot SLP vectorize list: vectorization factor "
10063              << "less than 2 is not supported";
10064     });
10065     return false;
10066   }
10067 
10068   bool Changed = false;
10069   bool CandidateFound = false;
10070   InstructionCost MinCost = SLPCostThreshold.getValue();
10071   Type *ScalarTy = VL[0]->getType();
10072   if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
10073     ScalarTy = IE->getOperand(1)->getType();
10074 
10075   unsigned NextInst = 0, MaxInst = VL.size();
10076   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
10077     // No actual vectorization should happen, if number of parts is the same as
10078     // provided vectorization factor (i.e. the scalar type is used for vector
10079     // code during codegen).
10080     auto *VecTy = FixedVectorType::get(ScalarTy, VF);
10081     if (TTI->getNumberOfParts(VecTy) == VF)
10082       continue;
10083     for (unsigned I = NextInst; I < MaxInst; ++I) {
10084       unsigned OpsWidth = 0;
10085 
10086       if (I + VF > MaxInst)
10087         OpsWidth = MaxInst - I;
10088       else
10089         OpsWidth = VF;
10090 
10091       if (!isPowerOf2_32(OpsWidth))
10092         continue;
10093 
10094       if ((LimitForRegisterSize && OpsWidth < MaxVF) ||
10095           (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2))
10096         break;
10097 
10098       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
10099       // Check that a previous iteration of this loop did not delete the Value.
10100       if (llvm::any_of(Ops, [&R](Value *V) {
10101             auto *I = dyn_cast<Instruction>(V);
10102             return I && R.isDeleted(I);
10103           }))
10104         continue;
10105 
10106       LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
10107                         << "\n");
10108 
10109       R.buildTree(Ops);
10110       if (R.isTreeTinyAndNotFullyVectorizable())
10111         continue;
10112       R.reorderTopToBottom();
10113       R.reorderBottomToTop(!isa<InsertElementInst>(Ops.front()));
10114       R.buildExternalUses();
10115 
10116       R.computeMinimumValueSizes();
10117       InstructionCost Cost = R.getTreeCost();
10118       CandidateFound = true;
10119       MinCost = std::min(MinCost, Cost);
10120 
10121       if (Cost < -SLPCostThreshold) {
10122         LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
10123         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
10124                                                     cast<Instruction>(Ops[0]))
10125                                  << "SLP vectorized with cost " << ore::NV("Cost", Cost)
10126                                  << " and with tree size "
10127                                  << ore::NV("TreeSize", R.getTreeSize()));
10128 
10129         R.vectorizeTree();
10130         // Move to the next bundle.
10131         I += VF - 1;
10132         NextInst = I + 1;
10133         Changed = true;
10134       }
10135     }
10136   }
10137 
10138   if (!Changed && CandidateFound) {
10139     R.getORE()->emit([&]() {
10140       return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
10141              << "List vectorization was possible but not beneficial with cost "
10142              << ore::NV("Cost", MinCost) << " >= "
10143              << ore::NV("Treshold", -SLPCostThreshold);
10144     });
10145   } else if (!Changed) {
10146     R.getORE()->emit([&]() {
10147       return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
10148              << "Cannot SLP vectorize list: vectorization was impossible"
10149              << " with available vectorization factors";
10150     });
10151   }
10152   return Changed;
10153 }
10154 
10155 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
10156   if (!I)
10157     return false;
10158 
10159   if ((!isa<BinaryOperator>(I) && !isa<CmpInst>(I)) ||
10160       isa<VectorType>(I->getType()))
10161     return false;
10162 
10163   Value *P = I->getParent();
10164 
10165   // Vectorize in current basic block only.
10166   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
10167   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
10168   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
10169     return false;
10170 
10171   // First collect all possible candidates
10172   SmallVector<std::pair<Value *, Value *>, 4> Candidates;
10173   Candidates.emplace_back(Op0, Op1);
10174 
10175   auto *A = dyn_cast<BinaryOperator>(Op0);
10176   auto *B = dyn_cast<BinaryOperator>(Op1);
10177   // Try to skip B.
10178   if (A && B && B->hasOneUse()) {
10179     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
10180     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
10181     if (B0 && B0->getParent() == P)
10182       Candidates.emplace_back(A, B0);
10183     if (B1 && B1->getParent() == P)
10184       Candidates.emplace_back(A, B1);
10185   }
10186   // Try to skip A.
10187   if (B && A && A->hasOneUse()) {
10188     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
10189     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
10190     if (A0 && A0->getParent() == P)
10191       Candidates.emplace_back(A0, B);
10192     if (A1 && A1->getParent() == P)
10193       Candidates.emplace_back(A1, B);
10194   }
10195 
10196   if (Candidates.size() == 1)
10197     return tryToVectorizePair(Op0, Op1, R);
10198 
10199   // We have multiple options. Try to pick the single best.
10200   Optional<int> BestCandidate = R.findBestRootPair(Candidates);
10201   if (!BestCandidate)
10202     return false;
10203   return tryToVectorizePair(Candidates[*BestCandidate].first,
10204                             Candidates[*BestCandidate].second, R);
10205 }
10206 
10207 namespace {
10208 
10209 /// Model horizontal reductions.
10210 ///
10211 /// A horizontal reduction is a tree of reduction instructions that has values
10212 /// that can be put into a vector as its leaves. For example:
10213 ///
10214 /// mul mul mul mul
10215 ///  \  /    \  /
10216 ///   +       +
10217 ///    \     /
10218 ///       +
10219 /// This tree has "mul" as its leaf values and "+" as its reduction
10220 /// instructions. A reduction can feed into a store or a binary operation
10221 /// feeding a phi.
10222 ///    ...
10223 ///    \  /
10224 ///     +
10225 ///     |
10226 ///  phi +=
10227 ///
10228 ///  Or:
10229 ///    ...
10230 ///    \  /
10231 ///     +
10232 ///     |
10233 ///   *p =
10234 ///
10235 class HorizontalReduction {
10236   using ReductionOpsType = SmallVector<Value *, 16>;
10237   using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
10238   ReductionOpsListType ReductionOps;
10239   /// List of possibly reduced values.
10240   SmallVector<SmallVector<Value *>> ReducedVals;
10241   /// Maps reduced value to the corresponding reduction operation.
10242   DenseMap<Value *, SmallVector<Instruction *>> ReducedValsToOps;
10243   // Use map vector to make stable output.
10244   MapVector<Instruction *, Value *> ExtraArgs;
10245   WeakTrackingVH ReductionRoot;
10246   /// The type of reduction operation.
10247   RecurKind RdxKind;
10248 
10249   static bool isCmpSelMinMax(Instruction *I) {
10250     return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) &&
10251            RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I));
10252   }
10253 
10254   // And/or are potentially poison-safe logical patterns like:
10255   // select x, y, false
10256   // select x, true, y
10257   static bool isBoolLogicOp(Instruction *I) {
10258     return match(I, m_LogicalAnd(m_Value(), m_Value())) ||
10259            match(I, m_LogicalOr(m_Value(), m_Value()));
10260   }
10261 
10262   /// Checks if instruction is associative and can be vectorized.
10263   static bool isVectorizable(RecurKind Kind, Instruction *I) {
10264     if (Kind == RecurKind::None)
10265       return false;
10266 
10267     // Integer ops that map to select instructions or intrinsics are fine.
10268     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) ||
10269         isBoolLogicOp(I))
10270       return true;
10271 
10272     if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) {
10273       // FP min/max are associative except for NaN and -0.0. We do not
10274       // have to rule out -0.0 here because the intrinsic semantics do not
10275       // specify a fixed result for it.
10276       return I->getFastMathFlags().noNaNs();
10277     }
10278 
10279     return I->isAssociative();
10280   }
10281 
10282   static Value *getRdxOperand(Instruction *I, unsigned Index) {
10283     // Poison-safe 'or' takes the form: select X, true, Y
10284     // To make that work with the normal operand processing, we skip the
10285     // true value operand.
10286     // TODO: Change the code and data structures to handle this without a hack.
10287     if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1)
10288       return I->getOperand(2);
10289     return I->getOperand(Index);
10290   }
10291 
10292   /// Creates reduction operation with the current opcode.
10293   static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS,
10294                          Value *RHS, const Twine &Name, bool UseSelect) {
10295     unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind);
10296     switch (Kind) {
10297     case RecurKind::Or:
10298       if (UseSelect &&
10299           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
10300         return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name);
10301       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
10302                                  Name);
10303     case RecurKind::And:
10304       if (UseSelect &&
10305           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
10306         return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name);
10307       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
10308                                  Name);
10309     case RecurKind::Add:
10310     case RecurKind::Mul:
10311     case RecurKind::Xor:
10312     case RecurKind::FAdd:
10313     case RecurKind::FMul:
10314       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
10315                                  Name);
10316     case RecurKind::FMax:
10317       return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS);
10318     case RecurKind::FMin:
10319       return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS);
10320     case RecurKind::SMax:
10321       if (UseSelect) {
10322         Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name);
10323         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
10324       }
10325       return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS);
10326     case RecurKind::SMin:
10327       if (UseSelect) {
10328         Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name);
10329         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
10330       }
10331       return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS);
10332     case RecurKind::UMax:
10333       if (UseSelect) {
10334         Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name);
10335         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
10336       }
10337       return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS);
10338     case RecurKind::UMin:
10339       if (UseSelect) {
10340         Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name);
10341         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
10342       }
10343       return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS);
10344     default:
10345       llvm_unreachable("Unknown reduction operation.");
10346     }
10347   }
10348 
10349   /// Creates reduction operation with the current opcode with the IR flags
10350   /// from \p ReductionOps, dropping nuw/nsw flags.
10351   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
10352                          Value *RHS, const Twine &Name,
10353                          const ReductionOpsListType &ReductionOps) {
10354     bool UseSelect = ReductionOps.size() == 2 ||
10355                      // Logical or/and.
10356                      (ReductionOps.size() == 1 &&
10357                       isa<SelectInst>(ReductionOps.front().front()));
10358     assert((!UseSelect || ReductionOps.size() != 2 ||
10359             isa<SelectInst>(ReductionOps[1][0])) &&
10360            "Expected cmp + select pairs for reduction");
10361     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect);
10362     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
10363       if (auto *Sel = dyn_cast<SelectInst>(Op)) {
10364         propagateIRFlags(Sel->getCondition(), ReductionOps[0], nullptr,
10365                          /*IncludeWrapFlags=*/false);
10366         propagateIRFlags(Op, ReductionOps[1], nullptr,
10367                          /*IncludeWrapFlags=*/false);
10368         return Op;
10369       }
10370     }
10371     propagateIRFlags(Op, ReductionOps[0], nullptr, /*IncludeWrapFlags=*/false);
10372     return Op;
10373   }
10374 
10375   static RecurKind getRdxKind(Value *V) {
10376     auto *I = dyn_cast<Instruction>(V);
10377     if (!I)
10378       return RecurKind::None;
10379     if (match(I, m_Add(m_Value(), m_Value())))
10380       return RecurKind::Add;
10381     if (match(I, m_Mul(m_Value(), m_Value())))
10382       return RecurKind::Mul;
10383     if (match(I, m_And(m_Value(), m_Value())) ||
10384         match(I, m_LogicalAnd(m_Value(), m_Value())))
10385       return RecurKind::And;
10386     if (match(I, m_Or(m_Value(), m_Value())) ||
10387         match(I, m_LogicalOr(m_Value(), m_Value())))
10388       return RecurKind::Or;
10389     if (match(I, m_Xor(m_Value(), m_Value())))
10390       return RecurKind::Xor;
10391     if (match(I, m_FAdd(m_Value(), m_Value())))
10392       return RecurKind::FAdd;
10393     if (match(I, m_FMul(m_Value(), m_Value())))
10394       return RecurKind::FMul;
10395 
10396     if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value())))
10397       return RecurKind::FMax;
10398     if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value())))
10399       return RecurKind::FMin;
10400 
10401     // This matches either cmp+select or intrinsics. SLP is expected to handle
10402     // either form.
10403     // TODO: If we are canonicalizing to intrinsics, we can remove several
10404     //       special-case paths that deal with selects.
10405     if (match(I, m_SMax(m_Value(), m_Value())))
10406       return RecurKind::SMax;
10407     if (match(I, m_SMin(m_Value(), m_Value())))
10408       return RecurKind::SMin;
10409     if (match(I, m_UMax(m_Value(), m_Value())))
10410       return RecurKind::UMax;
10411     if (match(I, m_UMin(m_Value(), m_Value())))
10412       return RecurKind::UMin;
10413 
10414     if (auto *Select = dyn_cast<SelectInst>(I)) {
10415       // Try harder: look for min/max pattern based on instructions producing
10416       // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
10417       // During the intermediate stages of SLP, it's very common to have
10418       // pattern like this (since optimizeGatherSequence is run only once
10419       // at the end):
10420       // %1 = extractelement <2 x i32> %a, i32 0
10421       // %2 = extractelement <2 x i32> %a, i32 1
10422       // %cond = icmp sgt i32 %1, %2
10423       // %3 = extractelement <2 x i32> %a, i32 0
10424       // %4 = extractelement <2 x i32> %a, i32 1
10425       // %select = select i1 %cond, i32 %3, i32 %4
10426       CmpInst::Predicate Pred;
10427       Instruction *L1;
10428       Instruction *L2;
10429 
10430       Value *LHS = Select->getTrueValue();
10431       Value *RHS = Select->getFalseValue();
10432       Value *Cond = Select->getCondition();
10433 
10434       // TODO: Support inverse predicates.
10435       if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
10436         if (!isa<ExtractElementInst>(RHS) ||
10437             !L2->isIdenticalTo(cast<Instruction>(RHS)))
10438           return RecurKind::None;
10439       } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
10440         if (!isa<ExtractElementInst>(LHS) ||
10441             !L1->isIdenticalTo(cast<Instruction>(LHS)))
10442           return RecurKind::None;
10443       } else {
10444         if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
10445           return RecurKind::None;
10446         if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
10447             !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
10448             !L2->isIdenticalTo(cast<Instruction>(RHS)))
10449           return RecurKind::None;
10450       }
10451 
10452       switch (Pred) {
10453       default:
10454         return RecurKind::None;
10455       case CmpInst::ICMP_SGT:
10456       case CmpInst::ICMP_SGE:
10457         return RecurKind::SMax;
10458       case CmpInst::ICMP_SLT:
10459       case CmpInst::ICMP_SLE:
10460         return RecurKind::SMin;
10461       case CmpInst::ICMP_UGT:
10462       case CmpInst::ICMP_UGE:
10463         return RecurKind::UMax;
10464       case CmpInst::ICMP_ULT:
10465       case CmpInst::ICMP_ULE:
10466         return RecurKind::UMin;
10467       }
10468     }
10469     return RecurKind::None;
10470   }
10471 
10472   /// Get the index of the first operand.
10473   static unsigned getFirstOperandIndex(Instruction *I) {
10474     return isCmpSelMinMax(I) ? 1 : 0;
10475   }
10476 
10477   /// Total number of operands in the reduction operation.
10478   static unsigned getNumberOfOperands(Instruction *I) {
10479     return isCmpSelMinMax(I) ? 3 : 2;
10480   }
10481 
10482   /// Checks if the instruction is in basic block \p BB.
10483   /// For a cmp+sel min/max reduction check that both ops are in \p BB.
10484   static bool hasSameParent(Instruction *I, BasicBlock *BB) {
10485     if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) {
10486       auto *Sel = cast<SelectInst>(I);
10487       auto *Cmp = dyn_cast<Instruction>(Sel->getCondition());
10488       return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB;
10489     }
10490     return I->getParent() == BB;
10491   }
10492 
10493   /// Expected number of uses for reduction operations/reduced values.
10494   static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) {
10495     if (IsCmpSelMinMax) {
10496       // SelectInst must be used twice while the condition op must have single
10497       // use only.
10498       if (auto *Sel = dyn_cast<SelectInst>(I))
10499         return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse();
10500       return I->hasNUses(2);
10501     }
10502 
10503     // Arithmetic reduction operation must be used once only.
10504     return I->hasOneUse();
10505   }
10506 
10507   /// Initializes the list of reduction operations.
10508   void initReductionOps(Instruction *I) {
10509     if (isCmpSelMinMax(I))
10510       ReductionOps.assign(2, ReductionOpsType());
10511     else
10512       ReductionOps.assign(1, ReductionOpsType());
10513   }
10514 
10515   /// Add all reduction operations for the reduction instruction \p I.
10516   void addReductionOps(Instruction *I) {
10517     if (isCmpSelMinMax(I)) {
10518       ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
10519       ReductionOps[1].emplace_back(I);
10520     } else {
10521       ReductionOps[0].emplace_back(I);
10522     }
10523   }
10524 
10525   static Value *getLHS(RecurKind Kind, Instruction *I) {
10526     if (Kind == RecurKind::None)
10527       return nullptr;
10528     return I->getOperand(getFirstOperandIndex(I));
10529   }
10530   static Value *getRHS(RecurKind Kind, Instruction *I) {
10531     if (Kind == RecurKind::None)
10532       return nullptr;
10533     return I->getOperand(getFirstOperandIndex(I) + 1);
10534   }
10535 
10536 public:
10537   HorizontalReduction() = default;
10538 
10539   /// Try to find a reduction tree.
10540   bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst,
10541                                  ScalarEvolution &SE, const DataLayout &DL,
10542                                  const TargetLibraryInfo &TLI) {
10543     assert((!Phi || is_contained(Phi->operands(), Inst)) &&
10544            "Phi needs to use the binary operator");
10545     assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) ||
10546             isa<IntrinsicInst>(Inst)) &&
10547            "Expected binop, select, or intrinsic for reduction matching");
10548     RdxKind = getRdxKind(Inst);
10549 
10550     // We could have a initial reductions that is not an add.
10551     //  r *= v1 + v2 + v3 + v4
10552     // In such a case start looking for a tree rooted in the first '+'.
10553     if (Phi) {
10554       if (getLHS(RdxKind, Inst) == Phi) {
10555         Phi = nullptr;
10556         Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst));
10557         if (!Inst)
10558           return false;
10559         RdxKind = getRdxKind(Inst);
10560       } else if (getRHS(RdxKind, Inst) == Phi) {
10561         Phi = nullptr;
10562         Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst));
10563         if (!Inst)
10564           return false;
10565         RdxKind = getRdxKind(Inst);
10566       }
10567     }
10568 
10569     if (!isVectorizable(RdxKind, Inst))
10570       return false;
10571 
10572     // Analyze "regular" integer/FP types for reductions - no target-specific
10573     // types or pointers.
10574     Type *Ty = Inst->getType();
10575     if (!isValidElementType(Ty) || Ty->isPointerTy())
10576       return false;
10577 
10578     // Though the ultimate reduction may have multiple uses, its condition must
10579     // have only single use.
10580     if (auto *Sel = dyn_cast<SelectInst>(Inst))
10581       if (!Sel->getCondition()->hasOneUse())
10582         return false;
10583 
10584     ReductionRoot = Inst;
10585 
10586     // Iterate through all the operands of the possible reduction tree and
10587     // gather all the reduced values, sorting them by their value id.
10588     BasicBlock *BB = Inst->getParent();
10589     bool IsCmpSelMinMax = isCmpSelMinMax(Inst);
10590     SmallVector<Instruction *> Worklist(1, Inst);
10591     // Checks if the operands of the \p TreeN instruction are also reduction
10592     // operations or should be treated as reduced values or an extra argument,
10593     // which is not part of the reduction.
10594     auto &&CheckOperands = [this, IsCmpSelMinMax,
10595                             BB](Instruction *TreeN,
10596                                 SmallVectorImpl<Value *> &ExtraArgs,
10597                                 SmallVectorImpl<Value *> &PossibleReducedVals,
10598                                 SmallVectorImpl<Instruction *> &ReductionOps) {
10599       for (int I = getFirstOperandIndex(TreeN),
10600                End = getNumberOfOperands(TreeN);
10601            I < End; ++I) {
10602         Value *EdgeVal = getRdxOperand(TreeN, I);
10603         ReducedValsToOps[EdgeVal].push_back(TreeN);
10604         auto *EdgeInst = dyn_cast<Instruction>(EdgeVal);
10605         // Edge has wrong parent - mark as an extra argument.
10606         if (EdgeInst && !isVectorLikeInstWithConstOps(EdgeInst) &&
10607             !hasSameParent(EdgeInst, BB)) {
10608           ExtraArgs.push_back(EdgeVal);
10609           continue;
10610         }
10611         // If the edge is not an instruction, or it is different from the main
10612         // reduction opcode or has too many uses - possible reduced value.
10613         if (!EdgeInst || getRdxKind(EdgeInst) != RdxKind ||
10614             IsCmpSelMinMax != isCmpSelMinMax(EdgeInst) ||
10615             !hasRequiredNumberOfUses(IsCmpSelMinMax, EdgeInst) ||
10616             !isVectorizable(getRdxKind(EdgeInst), EdgeInst)) {
10617           PossibleReducedVals.push_back(EdgeVal);
10618           continue;
10619         }
10620         ReductionOps.push_back(EdgeInst);
10621       }
10622     };
10623     // Try to regroup reduced values so that it gets more profitable to try to
10624     // reduce them. Values are grouped by their value ids, instructions - by
10625     // instruction op id and/or alternate op id, plus do extra analysis for
10626     // loads (grouping them by the distabce between pointers) and cmp
10627     // instructions (grouping them by the predicate).
10628     MapVector<size_t, MapVector<size_t, MapVector<Value *, unsigned>>>
10629         PossibleReducedVals;
10630     initReductionOps(Inst);
10631     while (!Worklist.empty()) {
10632       Instruction *TreeN = Worklist.pop_back_val();
10633       SmallVector<Value *> Args;
10634       SmallVector<Value *> PossibleRedVals;
10635       SmallVector<Instruction *> PossibleReductionOps;
10636       CheckOperands(TreeN, Args, PossibleRedVals, PossibleReductionOps);
10637       // If too many extra args - mark the instruction itself as a reduction
10638       // value, not a reduction operation.
10639       if (Args.size() < 2) {
10640         addReductionOps(TreeN);
10641         // Add extra args.
10642         if (!Args.empty()) {
10643           assert(Args.size() == 1 && "Expected only single argument.");
10644           ExtraArgs[TreeN] = Args.front();
10645         }
10646         // Add reduction values. The values are sorted for better vectorization
10647         // results.
10648         for (Value *V : PossibleRedVals) {
10649           size_t Key, Idx;
10650           std::tie(Key, Idx) = generateKeySubkey(
10651               V, &TLI,
10652               [&PossibleReducedVals, &DL, &SE](size_t Key, LoadInst *LI) {
10653                 auto It = PossibleReducedVals.find(Key);
10654                 if (It != PossibleReducedVals.end()) {
10655                   for (const auto &LoadData : It->second) {
10656                     auto *RLI = cast<LoadInst>(LoadData.second.front().first);
10657                     if (getPointersDiff(RLI->getType(),
10658                                         RLI->getPointerOperand(), LI->getType(),
10659                                         LI->getPointerOperand(), DL, SE,
10660                                         /*StrictCheck=*/true))
10661                       return hash_value(RLI->getPointerOperand());
10662                   }
10663                 }
10664                 return hash_value(LI->getPointerOperand());
10665               },
10666               /*AllowAlternate=*/false);
10667           ++PossibleReducedVals[Key][Idx]
10668                 .insert(std::make_pair(V, 0))
10669                 .first->second;
10670         }
10671         Worklist.append(PossibleReductionOps.rbegin(),
10672                         PossibleReductionOps.rend());
10673       } else {
10674         size_t Key, Idx;
10675         std::tie(Key, Idx) = generateKeySubkey(
10676             TreeN, &TLI,
10677             [&PossibleReducedVals, &DL, &SE](size_t Key, LoadInst *LI) {
10678               auto It = PossibleReducedVals.find(Key);
10679               if (It != PossibleReducedVals.end()) {
10680                 for (const auto &LoadData : It->second) {
10681                   auto *RLI = cast<LoadInst>(LoadData.second.front().first);
10682                   if (getPointersDiff(RLI->getType(), RLI->getPointerOperand(),
10683                                       LI->getType(), LI->getPointerOperand(),
10684                                       DL, SE, /*StrictCheck=*/true))
10685                     return hash_value(RLI->getPointerOperand());
10686                 }
10687               }
10688               return hash_value(LI->getPointerOperand());
10689             },
10690             /*AllowAlternate=*/false);
10691         ++PossibleReducedVals[Key][Idx]
10692               .insert(std::make_pair(TreeN, 0))
10693               .first->second;
10694       }
10695     }
10696     auto PossibleReducedValsVect = PossibleReducedVals.takeVector();
10697     // Sort values by the total number of values kinds to start the reduction
10698     // from the longest possible reduced values sequences.
10699     for (auto &PossibleReducedVals : PossibleReducedValsVect) {
10700       auto PossibleRedVals = PossibleReducedVals.second.takeVector();
10701       SmallVector<SmallVector<Value *>> PossibleRedValsVect;
10702       for (auto It = PossibleRedVals.begin(), E = PossibleRedVals.end();
10703            It != E; ++It) {
10704         PossibleRedValsVect.emplace_back();
10705         auto RedValsVect = It->second.takeVector();
10706         stable_sort(RedValsVect, [](const auto &P1, const auto &P2) {
10707           return P1.second < P2.second;
10708         });
10709         for (const std::pair<Value *, unsigned> &Data : RedValsVect)
10710           PossibleRedValsVect.back().append(Data.second, Data.first);
10711       }
10712       stable_sort(PossibleRedValsVect, [](const auto &P1, const auto &P2) {
10713         return P1.size() > P2.size();
10714       });
10715       ReducedVals.emplace_back();
10716       for (ArrayRef<Value *> Data : PossibleRedValsVect)
10717         ReducedVals.back().append(Data.rbegin(), Data.rend());
10718     }
10719     // Sort the reduced values by number of same/alternate opcode and/or pointer
10720     // operand.
10721     stable_sort(ReducedVals, [](ArrayRef<Value *> P1, ArrayRef<Value *> P2) {
10722       return P1.size() > P2.size();
10723     });
10724     return true;
10725   }
10726 
10727   /// Attempt to vectorize the tree found by matchAssociativeReduction.
10728   Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
10729     constexpr int ReductionLimit = 4;
10730     constexpr unsigned RegMaxNumber = 4;
10731     constexpr unsigned RedValsMaxNumber = 128;
10732     // If there are a sufficient number of reduction values, reduce
10733     // to a nearby power-of-2. We can safely generate oversized
10734     // vectors and rely on the backend to split them to legal sizes.
10735     unsigned NumReducedVals = std::accumulate(
10736         ReducedVals.begin(), ReducedVals.end(), 0,
10737         [](int Num, ArrayRef<Value *> Vals) { return Num + Vals.size(); });
10738     if (NumReducedVals < ReductionLimit)
10739       return nullptr;
10740 
10741     IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
10742 
10743     // Track the reduced values in case if they are replaced by extractelement
10744     // because of the vectorization.
10745     DenseMap<Value *, WeakTrackingVH> TrackedVals;
10746     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
10747     // The same extra argument may be used several times, so log each attempt
10748     // to use it.
10749     for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) {
10750       assert(Pair.first && "DebugLoc must be set.");
10751       ExternallyUsedValues[Pair.second].push_back(Pair.first);
10752       TrackedVals.try_emplace(Pair.second, Pair.second);
10753     }
10754 
10755     // The compare instruction of a min/max is the insertion point for new
10756     // instructions and may be replaced with a new compare instruction.
10757     auto &&GetCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
10758       assert(isa<SelectInst>(RdxRootInst) &&
10759              "Expected min/max reduction to have select root instruction");
10760       Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
10761       assert(isa<Instruction>(ScalarCond) &&
10762              "Expected min/max reduction to have compare condition");
10763       return cast<Instruction>(ScalarCond);
10764     };
10765 
10766     // The reduction root is used as the insertion point for new instructions,
10767     // so set it as externally used to prevent it from being deleted.
10768     ExternallyUsedValues[ReductionRoot];
10769     SmallDenseSet<Value *> IgnoreList;
10770     for (ReductionOpsType &RdxOps : ReductionOps)
10771       for (Value *RdxOp : RdxOps) {
10772         if (!RdxOp)
10773           continue;
10774         IgnoreList.insert(RdxOp);
10775       }
10776     bool IsCmpSelMinMax = isCmpSelMinMax(cast<Instruction>(ReductionRoot));
10777 
10778     // Need to track reduced vals, they may be changed during vectorization of
10779     // subvectors.
10780     for (ArrayRef<Value *> Candidates : ReducedVals)
10781       for (Value *V : Candidates)
10782         TrackedVals.try_emplace(V, V);
10783 
10784     DenseMap<Value *, unsigned> VectorizedVals;
10785     Value *VectorizedTree = nullptr;
10786     bool CheckForReusedReductionOps = false;
10787     // Try to vectorize elements based on their type.
10788     for (unsigned I = 0, E = ReducedVals.size(); I < E; ++I) {
10789       ArrayRef<Value *> OrigReducedVals = ReducedVals[I];
10790       InstructionsState S = getSameOpcode(OrigReducedVals);
10791       SmallVector<Value *> Candidates;
10792       DenseMap<Value *, Value *> TrackedToOrig;
10793       for (unsigned Cnt = 0, Sz = OrigReducedVals.size(); Cnt < Sz; ++Cnt) {
10794         Value *RdxVal = TrackedVals.find(OrigReducedVals[Cnt])->second;
10795         // Check if the reduction value was not overriden by the extractelement
10796         // instruction because of the vectorization and exclude it, if it is not
10797         // compatible with other values.
10798         if (auto *Inst = dyn_cast<Instruction>(RdxVal))
10799           if (isVectorLikeInstWithConstOps(Inst) &&
10800               (!S.getOpcode() || !S.isOpcodeOrAlt(Inst)))
10801             continue;
10802         Candidates.push_back(RdxVal);
10803         TrackedToOrig.try_emplace(RdxVal, OrigReducedVals[Cnt]);
10804       }
10805       bool ShuffledExtracts = false;
10806       // Try to handle shuffled extractelements.
10807       if (S.getOpcode() == Instruction::ExtractElement && !S.isAltShuffle() &&
10808           I + 1 < E) {
10809         InstructionsState NextS = getSameOpcode(ReducedVals[I + 1]);
10810         if (NextS.getOpcode() == Instruction::ExtractElement &&
10811             !NextS.isAltShuffle()) {
10812           SmallVector<Value *> CommonCandidates(Candidates);
10813           for (Value *RV : ReducedVals[I + 1]) {
10814             Value *RdxVal = TrackedVals.find(RV)->second;
10815             // Check if the reduction value was not overriden by the
10816             // extractelement instruction because of the vectorization and
10817             // exclude it, if it is not compatible with other values.
10818             if (auto *Inst = dyn_cast<Instruction>(RdxVal))
10819               if (!NextS.getOpcode() || !NextS.isOpcodeOrAlt(Inst))
10820                 continue;
10821             CommonCandidates.push_back(RdxVal);
10822             TrackedToOrig.try_emplace(RdxVal, RV);
10823           }
10824           SmallVector<int> Mask;
10825           if (isFixedVectorShuffle(CommonCandidates, Mask)) {
10826             ++I;
10827             Candidates.swap(CommonCandidates);
10828             ShuffledExtracts = true;
10829           }
10830         }
10831       }
10832       unsigned NumReducedVals = Candidates.size();
10833       if (NumReducedVals < ReductionLimit)
10834         continue;
10835 
10836       unsigned MaxVecRegSize = V.getMaxVecRegSize();
10837       unsigned EltSize = V.getVectorElementSize(Candidates[0]);
10838       unsigned MaxElts = RegMaxNumber * PowerOf2Floor(MaxVecRegSize / EltSize);
10839 
10840       unsigned ReduxWidth = std::min<unsigned>(
10841           PowerOf2Floor(NumReducedVals), std::max(RedValsMaxNumber, MaxElts));
10842       unsigned Start = 0;
10843       unsigned Pos = Start;
10844       // Restarts vectorization attempt with lower vector factor.
10845       unsigned PrevReduxWidth = ReduxWidth;
10846       bool CheckForReusedReductionOpsLocal = false;
10847       auto &&AdjustReducedVals = [&Pos, &Start, &ReduxWidth, NumReducedVals,
10848                                   &CheckForReusedReductionOpsLocal,
10849                                   &PrevReduxWidth, &V,
10850                                   &IgnoreList](bool IgnoreVL = false) {
10851         bool IsAnyRedOpGathered = !IgnoreVL && V.isAnyGathered(IgnoreList);
10852         if (!CheckForReusedReductionOpsLocal && PrevReduxWidth == ReduxWidth) {
10853           // Check if any of the reduction ops are gathered. If so, worth
10854           // trying again with less number of reduction ops.
10855           CheckForReusedReductionOpsLocal |= IsAnyRedOpGathered;
10856         }
10857         ++Pos;
10858         if (Pos < NumReducedVals - ReduxWidth + 1)
10859           return IsAnyRedOpGathered;
10860         Pos = Start;
10861         ReduxWidth /= 2;
10862         return IsAnyRedOpGathered;
10863       };
10864       while (Pos < NumReducedVals - ReduxWidth + 1 &&
10865              ReduxWidth >= ReductionLimit) {
10866         // Dependency in tree of the reduction ops - drop this attempt, try
10867         // later.
10868         if (CheckForReusedReductionOpsLocal && PrevReduxWidth != ReduxWidth &&
10869             Start == 0) {
10870           CheckForReusedReductionOps = true;
10871           break;
10872         }
10873         PrevReduxWidth = ReduxWidth;
10874         ArrayRef<Value *> VL(std::next(Candidates.begin(), Pos), ReduxWidth);
10875         // Beeing analyzed already - skip.
10876         if (V.areAnalyzedReductionVals(VL)) {
10877           (void)AdjustReducedVals(/*IgnoreVL=*/true);
10878           continue;
10879         }
10880         // Early exit if any of the reduction values were deleted during
10881         // previous vectorization attempts.
10882         if (any_of(VL, [&V](Value *RedVal) {
10883               auto *RedValI = dyn_cast<Instruction>(RedVal);
10884               if (!RedValI)
10885                 return false;
10886               return V.isDeleted(RedValI);
10887             }))
10888           break;
10889         V.buildTree(VL, IgnoreList);
10890         if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true)) {
10891           if (!AdjustReducedVals())
10892             V.analyzedReductionVals(VL);
10893           continue;
10894         }
10895         if (V.isLoadCombineReductionCandidate(RdxKind)) {
10896           if (!AdjustReducedVals())
10897             V.analyzedReductionVals(VL);
10898           continue;
10899         }
10900         V.reorderTopToBottom();
10901         // No need to reorder the root node at all.
10902         V.reorderBottomToTop(/*IgnoreReorder=*/true);
10903         // Keep extracted other reduction values, if they are used in the
10904         // vectorization trees.
10905         BoUpSLP::ExtraValueToDebugLocsMap LocalExternallyUsedValues(
10906             ExternallyUsedValues);
10907         for (unsigned Cnt = 0, Sz = ReducedVals.size(); Cnt < Sz; ++Cnt) {
10908           if (Cnt == I || (ShuffledExtracts && Cnt == I - 1))
10909             continue;
10910           for_each(ReducedVals[Cnt],
10911                    [&LocalExternallyUsedValues, &TrackedVals](Value *V) {
10912                      if (isa<Instruction>(V))
10913                        LocalExternallyUsedValues[TrackedVals[V]];
10914                    });
10915         }
10916         // Number of uses of the candidates in the vector of values.
10917         SmallDenseMap<Value *, unsigned> NumUses;
10918         for (unsigned Cnt = 0; Cnt < Pos; ++Cnt) {
10919           Value *V = Candidates[Cnt];
10920           if (NumUses.count(V) > 0)
10921             continue;
10922           NumUses[V] = std::count(VL.begin(), VL.end(), V);
10923         }
10924         for (unsigned Cnt = Pos + ReduxWidth; Cnt < NumReducedVals; ++Cnt) {
10925           Value *V = Candidates[Cnt];
10926           if (NumUses.count(V) > 0)
10927             continue;
10928           NumUses[V] = std::count(VL.begin(), VL.end(), V);
10929         }
10930         // Gather externally used values.
10931         SmallPtrSet<Value *, 4> Visited;
10932         for (unsigned Cnt = 0; Cnt < Pos; ++Cnt) {
10933           Value *V = Candidates[Cnt];
10934           if (!Visited.insert(V).second)
10935             continue;
10936           unsigned NumOps = VectorizedVals.lookup(V) + NumUses[V];
10937           if (NumOps != ReducedValsToOps.find(V)->second.size())
10938             LocalExternallyUsedValues[V];
10939         }
10940         for (unsigned Cnt = Pos + ReduxWidth; Cnt < NumReducedVals; ++Cnt) {
10941           Value *V = Candidates[Cnt];
10942           if (!Visited.insert(V).second)
10943             continue;
10944           unsigned NumOps = VectorizedVals.lookup(V) + NumUses[V];
10945           if (NumOps != ReducedValsToOps.find(V)->second.size())
10946             LocalExternallyUsedValues[V];
10947         }
10948         V.buildExternalUses(LocalExternallyUsedValues);
10949 
10950         V.computeMinimumValueSizes();
10951 
10952         // Intersect the fast-math-flags from all reduction operations.
10953         FastMathFlags RdxFMF;
10954         RdxFMF.set();
10955         for (Value *U : IgnoreList)
10956           if (auto *FPMO = dyn_cast<FPMathOperator>(U))
10957             RdxFMF &= FPMO->getFastMathFlags();
10958         // Estimate cost.
10959         InstructionCost TreeCost = V.getTreeCost(VL);
10960         InstructionCost ReductionCost =
10961             getReductionCost(TTI, VL, ReduxWidth, RdxFMF);
10962         InstructionCost Cost = TreeCost + ReductionCost;
10963         if (!Cost.isValid()) {
10964           LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n");
10965           return nullptr;
10966         }
10967         if (Cost >= -SLPCostThreshold) {
10968           V.getORE()->emit([&]() {
10969             return OptimizationRemarkMissed(
10970                        SV_NAME, "HorSLPNotBeneficial",
10971                        ReducedValsToOps.find(VL[0])->second.front())
10972                    << "Vectorizing horizontal reduction is possible"
10973                    << "but not beneficial with cost " << ore::NV("Cost", Cost)
10974                    << " and threshold "
10975                    << ore::NV("Threshold", -SLPCostThreshold);
10976           });
10977           if (!AdjustReducedVals())
10978             V.analyzedReductionVals(VL);
10979           continue;
10980         }
10981 
10982         LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
10983                           << Cost << ". (HorRdx)\n");
10984         V.getORE()->emit([&]() {
10985           return OptimizationRemark(
10986                      SV_NAME, "VectorizedHorizontalReduction",
10987                      ReducedValsToOps.find(VL[0])->second.front())
10988                  << "Vectorized horizontal reduction with cost "
10989                  << ore::NV("Cost", Cost) << " and with tree size "
10990                  << ore::NV("TreeSize", V.getTreeSize());
10991         });
10992 
10993         Builder.setFastMathFlags(RdxFMF);
10994 
10995         // Vectorize a tree.
10996         Value *VectorizedRoot = V.vectorizeTree(LocalExternallyUsedValues);
10997 
10998         // Emit a reduction. If the root is a select (min/max idiom), the insert
10999         // point is the compare condition of that select.
11000         Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
11001         if (IsCmpSelMinMax)
11002           Builder.SetInsertPoint(GetCmpForMinMaxReduction(RdxRootInst));
11003         else
11004           Builder.SetInsertPoint(RdxRootInst);
11005 
11006         // To prevent poison from leaking across what used to be sequential,
11007         // safe, scalar boolean logic operations, the reduction operand must be
11008         // frozen.
11009         if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst))
11010           VectorizedRoot = Builder.CreateFreeze(VectorizedRoot);
11011 
11012         Value *ReducedSubTree =
11013             emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
11014 
11015         if (!VectorizedTree) {
11016           // Initialize the final value in the reduction.
11017           VectorizedTree = ReducedSubTree;
11018         } else {
11019           // Update the final value in the reduction.
11020           Builder.SetCurrentDebugLocation(
11021               cast<Instruction>(ReductionOps.front().front())->getDebugLoc());
11022           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
11023                                     ReducedSubTree, "op.rdx", ReductionOps);
11024         }
11025         // Count vectorized reduced values to exclude them from final reduction.
11026         for (Value *V : VL)
11027           ++VectorizedVals.try_emplace(TrackedToOrig.find(V)->second, 0)
11028                 .first->getSecond();
11029         Pos += ReduxWidth;
11030         Start = Pos;
11031         ReduxWidth = PowerOf2Floor(NumReducedVals - Pos);
11032       }
11033     }
11034     if (VectorizedTree) {
11035       // Finish the reduction.
11036       // Need to add extra arguments and not vectorized possible reduction
11037       // values.
11038       // Try to avoid dependencies between the scalar remainders after
11039       // reductions.
11040       auto &&FinalGen =
11041           [this, &Builder,
11042            &TrackedVals](ArrayRef<std::pair<Instruction *, Value *>> InstVals) {
11043             unsigned Sz = InstVals.size();
11044             SmallVector<std::pair<Instruction *, Value *>> ExtraReds(Sz / 2 +
11045                                                                      Sz % 2);
11046             for (unsigned I = 0, E = (Sz / 2) * 2; I < E; I += 2) {
11047               Instruction *RedOp = InstVals[I + 1].first;
11048               Builder.SetCurrentDebugLocation(RedOp->getDebugLoc());
11049               Value *RdxVal1 = InstVals[I].second;
11050               Value *StableRdxVal1 = RdxVal1;
11051               auto It1 = TrackedVals.find(RdxVal1);
11052               if (It1 != TrackedVals.end())
11053                 StableRdxVal1 = It1->second;
11054               Value *RdxVal2 = InstVals[I + 1].second;
11055               Value *StableRdxVal2 = RdxVal2;
11056               auto It2 = TrackedVals.find(RdxVal2);
11057               if (It2 != TrackedVals.end())
11058                 StableRdxVal2 = It2->second;
11059               Value *ExtraRed = createOp(Builder, RdxKind, StableRdxVal1,
11060                                          StableRdxVal2, "op.rdx", ReductionOps);
11061               ExtraReds[I / 2] = std::make_pair(InstVals[I].first, ExtraRed);
11062             }
11063             if (Sz % 2 == 1)
11064               ExtraReds[Sz / 2] = InstVals.back();
11065             return ExtraReds;
11066           };
11067       SmallVector<std::pair<Instruction *, Value *>> ExtraReductions;
11068       SmallPtrSet<Value *, 8> Visited;
11069       for (ArrayRef<Value *> Candidates : ReducedVals) {
11070         for (Value *RdxVal : Candidates) {
11071           if (!Visited.insert(RdxVal).second)
11072             continue;
11073           unsigned NumOps = VectorizedVals.lookup(RdxVal);
11074           for (Instruction *RedOp :
11075                makeArrayRef(ReducedValsToOps.find(RdxVal)->second)
11076                    .drop_back(NumOps))
11077             ExtraReductions.emplace_back(RedOp, RdxVal);
11078         }
11079       }
11080       for (auto &Pair : ExternallyUsedValues) {
11081         // Add each externally used value to the final reduction.
11082         for (auto *I : Pair.second)
11083           ExtraReductions.emplace_back(I, Pair.first);
11084       }
11085       // Iterate through all not-vectorized reduction values/extra arguments.
11086       while (ExtraReductions.size() > 1) {
11087         SmallVector<std::pair<Instruction *, Value *>> NewReds =
11088             FinalGen(ExtraReductions);
11089         ExtraReductions.swap(NewReds);
11090       }
11091       // Final reduction.
11092       if (ExtraReductions.size() == 1) {
11093         Instruction *RedOp = ExtraReductions.back().first;
11094         Builder.SetCurrentDebugLocation(RedOp->getDebugLoc());
11095         Value *RdxVal = ExtraReductions.back().second;
11096         Value *StableRdxVal = RdxVal;
11097         auto It = TrackedVals.find(RdxVal);
11098         if (It != TrackedVals.end())
11099           StableRdxVal = It->second;
11100         VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
11101                                   StableRdxVal, "op.rdx", ReductionOps);
11102       }
11103 
11104       ReductionRoot->replaceAllUsesWith(VectorizedTree);
11105 
11106       // The original scalar reduction is expected to have no remaining
11107       // uses outside the reduction tree itself.  Assert that we got this
11108       // correct, replace internal uses with undef, and mark for eventual
11109       // deletion.
11110 #ifndef NDEBUG
11111       SmallSet<Value *, 4> IgnoreSet;
11112       for (ArrayRef<Value *> RdxOps : ReductionOps)
11113         IgnoreSet.insert(RdxOps.begin(), RdxOps.end());
11114 #endif
11115       for (ArrayRef<Value *> RdxOps : ReductionOps) {
11116         for (Value *Ignore : RdxOps) {
11117           if (!Ignore)
11118             continue;
11119 #ifndef NDEBUG
11120           for (auto *U : Ignore->users()) {
11121             assert(IgnoreSet.count(U) &&
11122                    "All users must be either in the reduction ops list.");
11123           }
11124 #endif
11125           if (!Ignore->use_empty()) {
11126             Value *Undef = UndefValue::get(Ignore->getType());
11127             Ignore->replaceAllUsesWith(Undef);
11128           }
11129           V.eraseInstruction(cast<Instruction>(Ignore));
11130         }
11131       }
11132     } else if (!CheckForReusedReductionOps) {
11133       for (ReductionOpsType &RdxOps : ReductionOps)
11134         for (Value *RdxOp : RdxOps)
11135           V.analyzedReductionRoot(cast<Instruction>(RdxOp));
11136     }
11137     return VectorizedTree;
11138   }
11139 
11140 private:
11141   /// Calculate the cost of a reduction.
11142   InstructionCost getReductionCost(TargetTransformInfo *TTI,
11143                                    ArrayRef<Value *> ReducedVals,
11144                                    unsigned ReduxWidth, FastMathFlags FMF) {
11145     TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
11146     Value *FirstReducedVal = ReducedVals.front();
11147     Type *ScalarTy = FirstReducedVal->getType();
11148     FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth);
11149     InstructionCost VectorCost = 0, ScalarCost;
11150     // If all of the reduced values are constant, the vector cost is 0, since
11151     // the reduction value can be calculated at the compile time.
11152     bool AllConsts = all_of(ReducedVals, isConstant);
11153     switch (RdxKind) {
11154     case RecurKind::Add:
11155     case RecurKind::Mul:
11156     case RecurKind::Or:
11157     case RecurKind::And:
11158     case RecurKind::Xor:
11159     case RecurKind::FAdd:
11160     case RecurKind::FMul: {
11161       unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind);
11162       if (!AllConsts)
11163         VectorCost =
11164             TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind);
11165       ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind);
11166       break;
11167     }
11168     case RecurKind::FMax:
11169     case RecurKind::FMin: {
11170       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
11171       if (!AllConsts) {
11172         auto *VecCondTy =
11173             cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
11174         VectorCost =
11175             TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
11176                                         /*IsUnsigned=*/false, CostKind);
11177       }
11178       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
11179       ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy,
11180                                            SclCondTy, RdxPred, CostKind) +
11181                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
11182                                            SclCondTy, RdxPred, CostKind);
11183       break;
11184     }
11185     case RecurKind::SMax:
11186     case RecurKind::SMin:
11187     case RecurKind::UMax:
11188     case RecurKind::UMin: {
11189       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
11190       if (!AllConsts) {
11191         auto *VecCondTy =
11192             cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
11193         bool IsUnsigned =
11194             RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin;
11195         VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
11196                                                  IsUnsigned, CostKind);
11197       }
11198       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
11199       ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
11200                                            SclCondTy, RdxPred, CostKind) +
11201                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
11202                                            SclCondTy, RdxPred, CostKind);
11203       break;
11204     }
11205     default:
11206       llvm_unreachable("Expected arithmetic or min/max reduction operation");
11207     }
11208 
11209     // Scalar cost is repeated for N-1 elements.
11210     ScalarCost *= (ReduxWidth - 1);
11211     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost
11212                       << " for reduction that starts with " << *FirstReducedVal
11213                       << " (It is a splitting reduction)\n");
11214     return VectorCost - ScalarCost;
11215   }
11216 
11217   /// Emit a horizontal reduction of the vectorized value.
11218   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
11219                        unsigned ReduxWidth, const TargetTransformInfo *TTI) {
11220     assert(VectorizedValue && "Need to have a vectorized tree node");
11221     assert(isPowerOf2_32(ReduxWidth) &&
11222            "We only handle power-of-two reductions for now");
11223     assert(RdxKind != RecurKind::FMulAdd &&
11224            "A call to the llvm.fmuladd intrinsic is not handled yet");
11225 
11226     ++NumVectorInstructions;
11227     return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind);
11228   }
11229 };
11230 
11231 } // end anonymous namespace
11232 
11233 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) {
11234   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
11235     return cast<FixedVectorType>(IE->getType())->getNumElements();
11236 
11237   unsigned AggregateSize = 1;
11238   auto *IV = cast<InsertValueInst>(InsertInst);
11239   Type *CurrentType = IV->getType();
11240   do {
11241     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
11242       for (auto *Elt : ST->elements())
11243         if (Elt != ST->getElementType(0)) // check homogeneity
11244           return None;
11245       AggregateSize *= ST->getNumElements();
11246       CurrentType = ST->getElementType(0);
11247     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
11248       AggregateSize *= AT->getNumElements();
11249       CurrentType = AT->getElementType();
11250     } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
11251       AggregateSize *= VT->getNumElements();
11252       return AggregateSize;
11253     } else if (CurrentType->isSingleValueType()) {
11254       return AggregateSize;
11255     } else {
11256       return None;
11257     }
11258   } while (true);
11259 }
11260 
11261 static void findBuildAggregate_rec(Instruction *LastInsertInst,
11262                                    TargetTransformInfo *TTI,
11263                                    SmallVectorImpl<Value *> &BuildVectorOpds,
11264                                    SmallVectorImpl<Value *> &InsertElts,
11265                                    unsigned OperandOffset) {
11266   do {
11267     Value *InsertedOperand = LastInsertInst->getOperand(1);
11268     Optional<unsigned> OperandIndex =
11269         getInsertIndex(LastInsertInst, OperandOffset);
11270     if (!OperandIndex)
11271       return;
11272     if (isa<InsertElementInst>(InsertedOperand) ||
11273         isa<InsertValueInst>(InsertedOperand)) {
11274       findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI,
11275                              BuildVectorOpds, InsertElts, *OperandIndex);
11276 
11277     } else {
11278       BuildVectorOpds[*OperandIndex] = InsertedOperand;
11279       InsertElts[*OperandIndex] = LastInsertInst;
11280     }
11281     LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0));
11282   } while (LastInsertInst != nullptr &&
11283            (isa<InsertValueInst>(LastInsertInst) ||
11284             isa<InsertElementInst>(LastInsertInst)) &&
11285            LastInsertInst->hasOneUse());
11286 }
11287 
11288 /// Recognize construction of vectors like
11289 ///  %ra = insertelement <4 x float> poison, float %s0, i32 0
11290 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
11291 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
11292 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
11293 ///  starting from the last insertelement or insertvalue instruction.
11294 ///
11295 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>},
11296 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
11297 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
11298 ///
11299 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
11300 ///
11301 /// \return true if it matches.
11302 static bool findBuildAggregate(Instruction *LastInsertInst,
11303                                TargetTransformInfo *TTI,
11304                                SmallVectorImpl<Value *> &BuildVectorOpds,
11305                                SmallVectorImpl<Value *> &InsertElts) {
11306 
11307   assert((isa<InsertElementInst>(LastInsertInst) ||
11308           isa<InsertValueInst>(LastInsertInst)) &&
11309          "Expected insertelement or insertvalue instruction!");
11310 
11311   assert((BuildVectorOpds.empty() && InsertElts.empty()) &&
11312          "Expected empty result vectors!");
11313 
11314   Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst);
11315   if (!AggregateSize)
11316     return false;
11317   BuildVectorOpds.resize(*AggregateSize);
11318   InsertElts.resize(*AggregateSize);
11319 
11320   findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts, 0);
11321   llvm::erase_value(BuildVectorOpds, nullptr);
11322   llvm::erase_value(InsertElts, nullptr);
11323   if (BuildVectorOpds.size() >= 2)
11324     return true;
11325 
11326   return false;
11327 }
11328 
11329 /// Try and get a reduction value from a phi node.
11330 ///
11331 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
11332 /// if they come from either \p ParentBB or a containing loop latch.
11333 ///
11334 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
11335 /// if not possible.
11336 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
11337                                 BasicBlock *ParentBB, LoopInfo *LI) {
11338   // There are situations where the reduction value is not dominated by the
11339   // reduction phi. Vectorizing such cases has been reported to cause
11340   // miscompiles. See PR25787.
11341   auto DominatedReduxValue = [&](Value *R) {
11342     return isa<Instruction>(R) &&
11343            DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
11344   };
11345 
11346   Value *Rdx = nullptr;
11347 
11348   // Return the incoming value if it comes from the same BB as the phi node.
11349   if (P->getIncomingBlock(0) == ParentBB) {
11350     Rdx = P->getIncomingValue(0);
11351   } else if (P->getIncomingBlock(1) == ParentBB) {
11352     Rdx = P->getIncomingValue(1);
11353   }
11354 
11355   if (Rdx && DominatedReduxValue(Rdx))
11356     return Rdx;
11357 
11358   // Otherwise, check whether we have a loop latch to look at.
11359   Loop *BBL = LI->getLoopFor(ParentBB);
11360   if (!BBL)
11361     return nullptr;
11362   BasicBlock *BBLatch = BBL->getLoopLatch();
11363   if (!BBLatch)
11364     return nullptr;
11365 
11366   // There is a loop latch, return the incoming value if it comes from
11367   // that. This reduction pattern occasionally turns up.
11368   if (P->getIncomingBlock(0) == BBLatch) {
11369     Rdx = P->getIncomingValue(0);
11370   } else if (P->getIncomingBlock(1) == BBLatch) {
11371     Rdx = P->getIncomingValue(1);
11372   }
11373 
11374   if (Rdx && DominatedReduxValue(Rdx))
11375     return Rdx;
11376 
11377   return nullptr;
11378 }
11379 
11380 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) {
11381   if (match(I, m_BinOp(m_Value(V0), m_Value(V1))))
11382     return true;
11383   if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1))))
11384     return true;
11385   if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1))))
11386     return true;
11387   if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1))))
11388     return true;
11389   if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1))))
11390     return true;
11391   if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1))))
11392     return true;
11393   if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1))))
11394     return true;
11395   return false;
11396 }
11397 
11398 /// Attempt to reduce a horizontal reduction.
11399 /// If it is legal to match a horizontal reduction feeding the phi node \a P
11400 /// with reduction operators \a Root (or one of its operands) in a basic block
11401 /// \a BB, then check if it can be done. If horizontal reduction is not found
11402 /// and root instruction is a binary operation, vectorization of the operands is
11403 /// attempted.
11404 /// \returns true if a horizontal reduction was matched and reduced or operands
11405 /// of one of the binary instruction were vectorized.
11406 /// \returns false if a horizontal reduction was not matched (or not possible)
11407 /// or no vectorization of any binary operation feeding \a Root instruction was
11408 /// performed.
11409 static bool tryToVectorizeHorReductionOrInstOperands(
11410     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
11411     TargetTransformInfo *TTI, ScalarEvolution &SE, const DataLayout &DL,
11412     const TargetLibraryInfo &TLI,
11413     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
11414   if (!ShouldVectorizeHor)
11415     return false;
11416 
11417   if (!Root)
11418     return false;
11419 
11420   if (Root->getParent() != BB || isa<PHINode>(Root))
11421     return false;
11422   // Start analysis starting from Root instruction. If horizontal reduction is
11423   // found, try to vectorize it. If it is not a horizontal reduction or
11424   // vectorization is not possible or not effective, and currently analyzed
11425   // instruction is a binary operation, try to vectorize the operands, using
11426   // pre-order DFS traversal order. If the operands were not vectorized, repeat
11427   // the same procedure considering each operand as a possible root of the
11428   // horizontal reduction.
11429   // Interrupt the process if the Root instruction itself was vectorized or all
11430   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
11431   // Skip the analysis of CmpInsts. Compiler implements postanalysis of the
11432   // CmpInsts so we can skip extra attempts in
11433   // tryToVectorizeHorReductionOrInstOperands and save compile time.
11434   std::queue<std::pair<Instruction *, unsigned>> Stack;
11435   Stack.emplace(Root, 0);
11436   SmallPtrSet<Value *, 8> VisitedInstrs;
11437   SmallVector<WeakTrackingVH> PostponedInsts;
11438   bool Res = false;
11439   auto &&TryToReduce = [TTI, &SE, &DL, &P, &R, &TLI](Instruction *Inst,
11440                                                      Value *&B0,
11441                                                      Value *&B1) -> Value * {
11442     if (R.isAnalyzedReductionRoot(Inst))
11443       return nullptr;
11444     bool IsBinop = matchRdxBop(Inst, B0, B1);
11445     bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value()));
11446     if (IsBinop || IsSelect) {
11447       HorizontalReduction HorRdx;
11448       if (HorRdx.matchAssociativeReduction(P, Inst, SE, DL, TLI))
11449         return HorRdx.tryToReduce(R, TTI);
11450     }
11451     return nullptr;
11452   };
11453   while (!Stack.empty()) {
11454     Instruction *Inst;
11455     unsigned Level;
11456     std::tie(Inst, Level) = Stack.front();
11457     Stack.pop();
11458     // Do not try to analyze instruction that has already been vectorized.
11459     // This may happen when we vectorize instruction operands on a previous
11460     // iteration while stack was populated before that happened.
11461     if (R.isDeleted(Inst))
11462       continue;
11463     Value *B0 = nullptr, *B1 = nullptr;
11464     if (Value *V = TryToReduce(Inst, B0, B1)) {
11465       Res = true;
11466       // Set P to nullptr to avoid re-analysis of phi node in
11467       // matchAssociativeReduction function unless this is the root node.
11468       P = nullptr;
11469       if (auto *I = dyn_cast<Instruction>(V)) {
11470         // Try to find another reduction.
11471         Stack.emplace(I, Level);
11472         continue;
11473       }
11474     } else {
11475       bool IsBinop = B0 && B1;
11476       if (P && IsBinop) {
11477         Inst = dyn_cast<Instruction>(B0);
11478         if (Inst == P)
11479           Inst = dyn_cast<Instruction>(B1);
11480         if (!Inst) {
11481           // Set P to nullptr to avoid re-analysis of phi node in
11482           // matchAssociativeReduction function unless this is the root node.
11483           P = nullptr;
11484           continue;
11485         }
11486       }
11487       // Set P to nullptr to avoid re-analysis of phi node in
11488       // matchAssociativeReduction function unless this is the root node.
11489       P = nullptr;
11490       // Do not try to vectorize CmpInst operands, this is done separately.
11491       // Final attempt for binop args vectorization should happen after the loop
11492       // to try to find reductions.
11493       if (!isa<CmpInst, InsertElementInst, InsertValueInst>(Inst))
11494         PostponedInsts.push_back(Inst);
11495     }
11496 
11497     // Try to vectorize operands.
11498     // Continue analysis for the instruction from the same basic block only to
11499     // save compile time.
11500     if (++Level < RecursionMaxDepth)
11501       for (auto *Op : Inst->operand_values())
11502         if (VisitedInstrs.insert(Op).second)
11503           if (auto *I = dyn_cast<Instruction>(Op))
11504             // Do not try to vectorize CmpInst operands,  this is done
11505             // separately.
11506             if (!isa<PHINode, CmpInst, InsertElementInst, InsertValueInst>(I) &&
11507                 !R.isDeleted(I) && I->getParent() == BB)
11508               Stack.emplace(I, Level);
11509   }
11510   // Try to vectorized binops where reductions were not found.
11511   for (Value *V : PostponedInsts)
11512     if (auto *Inst = dyn_cast<Instruction>(V))
11513       if (!R.isDeleted(Inst))
11514         Res |= Vectorize(Inst, R);
11515   return Res;
11516 }
11517 
11518 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
11519                                                  BasicBlock *BB, BoUpSLP &R,
11520                                                  TargetTransformInfo *TTI) {
11521   auto *I = dyn_cast_or_null<Instruction>(V);
11522   if (!I)
11523     return false;
11524 
11525   if (!isa<BinaryOperator>(I))
11526     P = nullptr;
11527   // Try to match and vectorize a horizontal reduction.
11528   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
11529     return tryToVectorize(I, R);
11530   };
11531   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI, *SE, *DL,
11532                                                   *TLI, ExtraVectorization);
11533 }
11534 
11535 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
11536                                                  BasicBlock *BB, BoUpSLP &R) {
11537   const DataLayout &DL = BB->getModule()->getDataLayout();
11538   if (!R.canMapToVector(IVI->getType(), DL))
11539     return false;
11540 
11541   SmallVector<Value *, 16> BuildVectorOpds;
11542   SmallVector<Value *, 16> BuildVectorInsts;
11543   if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts))
11544     return false;
11545 
11546   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
11547   // Aggregate value is unlikely to be processed in vector register.
11548   return tryToVectorizeList(BuildVectorOpds, R);
11549 }
11550 
11551 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
11552                                                    BasicBlock *BB, BoUpSLP &R) {
11553   SmallVector<Value *, 16> BuildVectorInsts;
11554   SmallVector<Value *, 16> BuildVectorOpds;
11555   SmallVector<int> Mask;
11556   if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
11557       (llvm::all_of(
11558            BuildVectorOpds,
11559            [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) &&
11560        isFixedVectorShuffle(BuildVectorOpds, Mask)))
11561     return false;
11562 
11563   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n");
11564   return tryToVectorizeList(BuildVectorInsts, R);
11565 }
11566 
11567 template <typename T>
11568 static bool
11569 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming,
11570                        function_ref<unsigned(T *)> Limit,
11571                        function_ref<bool(T *, T *)> Comparator,
11572                        function_ref<bool(T *, T *)> AreCompatible,
11573                        function_ref<bool(ArrayRef<T *>, bool)> TryToVectorizeHelper,
11574                        bool LimitForRegisterSize) {
11575   bool Changed = false;
11576   // Sort by type, parent, operands.
11577   stable_sort(Incoming, Comparator);
11578 
11579   // Try to vectorize elements base on their type.
11580   SmallVector<T *> Candidates;
11581   for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) {
11582     // Look for the next elements with the same type, parent and operand
11583     // kinds.
11584     auto *SameTypeIt = IncIt;
11585     while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt))
11586       ++SameTypeIt;
11587 
11588     // Try to vectorize them.
11589     unsigned NumElts = (SameTypeIt - IncIt);
11590     LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes ("
11591                       << NumElts << ")\n");
11592     // The vectorization is a 3-state attempt:
11593     // 1. Try to vectorize instructions with the same/alternate opcodes with the
11594     // size of maximal register at first.
11595     // 2. Try to vectorize remaining instructions with the same type, if
11596     // possible. This may result in the better vectorization results rather than
11597     // if we try just to vectorize instructions with the same/alternate opcodes.
11598     // 3. Final attempt to try to vectorize all instructions with the
11599     // same/alternate ops only, this may result in some extra final
11600     // vectorization.
11601     if (NumElts > 1 &&
11602         TryToVectorizeHelper(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) {
11603       // Success start over because instructions might have been changed.
11604       Changed = true;
11605     } else if (NumElts < Limit(*IncIt) &&
11606                (Candidates.empty() ||
11607                 Candidates.front()->getType() == (*IncIt)->getType())) {
11608       Candidates.append(IncIt, std::next(IncIt, NumElts));
11609     }
11610     // Final attempt to vectorize instructions with the same types.
11611     if (Candidates.size() > 1 &&
11612         (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) {
11613       if (TryToVectorizeHelper(Candidates, /*LimitForRegisterSize=*/false)) {
11614         // Success start over because instructions might have been changed.
11615         Changed = true;
11616       } else if (LimitForRegisterSize) {
11617         // Try to vectorize using small vectors.
11618         for (auto *It = Candidates.begin(), *End = Candidates.end();
11619              It != End;) {
11620           auto *SameTypeIt = It;
11621           while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It))
11622             ++SameTypeIt;
11623           unsigned NumElts = (SameTypeIt - It);
11624           if (NumElts > 1 && TryToVectorizeHelper(makeArrayRef(It, NumElts),
11625                                             /*LimitForRegisterSize=*/false))
11626             Changed = true;
11627           It = SameTypeIt;
11628         }
11629       }
11630       Candidates.clear();
11631     }
11632 
11633     // Start over at the next instruction of a different type (or the end).
11634     IncIt = SameTypeIt;
11635   }
11636   return Changed;
11637 }
11638 
11639 /// Compare two cmp instructions. If IsCompatibility is true, function returns
11640 /// true if 2 cmps have same/swapped predicates and mos compatible corresponding
11641 /// operands. If IsCompatibility is false, function implements strict weak
11642 /// ordering relation between two cmp instructions, returning true if the first
11643 /// instruction is "less" than the second, i.e. its predicate is less than the
11644 /// predicate of the second or the operands IDs are less than the operands IDs
11645 /// of the second cmp instruction.
11646 template <bool IsCompatibility>
11647 static bool compareCmp(Value *V, Value *V2,
11648                        function_ref<bool(Instruction *)> IsDeleted) {
11649   auto *CI1 = cast<CmpInst>(V);
11650   auto *CI2 = cast<CmpInst>(V2);
11651   if (IsDeleted(CI2) || !isValidElementType(CI2->getType()))
11652     return false;
11653   if (CI1->getOperand(0)->getType()->getTypeID() <
11654       CI2->getOperand(0)->getType()->getTypeID())
11655     return !IsCompatibility;
11656   if (CI1->getOperand(0)->getType()->getTypeID() >
11657       CI2->getOperand(0)->getType()->getTypeID())
11658     return false;
11659   CmpInst::Predicate Pred1 = CI1->getPredicate();
11660   CmpInst::Predicate Pred2 = CI2->getPredicate();
11661   CmpInst::Predicate SwapPred1 = CmpInst::getSwappedPredicate(Pred1);
11662   CmpInst::Predicate SwapPred2 = CmpInst::getSwappedPredicate(Pred2);
11663   CmpInst::Predicate BasePred1 = std::min(Pred1, SwapPred1);
11664   CmpInst::Predicate BasePred2 = std::min(Pred2, SwapPred2);
11665   if (BasePred1 < BasePred2)
11666     return !IsCompatibility;
11667   if (BasePred1 > BasePred2)
11668     return false;
11669   // Compare operands.
11670   bool LEPreds = Pred1 <= Pred2;
11671   bool GEPreds = Pred1 >= Pred2;
11672   for (int I = 0, E = CI1->getNumOperands(); I < E; ++I) {
11673     auto *Op1 = CI1->getOperand(LEPreds ? I : E - I - 1);
11674     auto *Op2 = CI2->getOperand(GEPreds ? I : E - I - 1);
11675     if (Op1->getValueID() < Op2->getValueID())
11676       return !IsCompatibility;
11677     if (Op1->getValueID() > Op2->getValueID())
11678       return false;
11679     if (auto *I1 = dyn_cast<Instruction>(Op1))
11680       if (auto *I2 = dyn_cast<Instruction>(Op2)) {
11681         if (I1->getParent() != I2->getParent())
11682           return false;
11683         InstructionsState S = getSameOpcode({I1, I2});
11684         if (S.getOpcode())
11685           continue;
11686         return false;
11687       }
11688   }
11689   return IsCompatibility;
11690 }
11691 
11692 bool SLPVectorizerPass::vectorizeSimpleInstructions(
11693     SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R,
11694     bool AtTerminator) {
11695   bool OpsChanged = false;
11696   SmallVector<Instruction *, 4> PostponedCmps;
11697   for (auto *I : reverse(Instructions)) {
11698     if (R.isDeleted(I))
11699       continue;
11700     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I)) {
11701       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
11702     } else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I)) {
11703       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
11704     } else if (isa<CmpInst>(I)) {
11705       PostponedCmps.push_back(I);
11706       continue;
11707     }
11708     // Try to find reductions in buildvector sequnces.
11709     OpsChanged |= vectorizeRootInstruction(nullptr, I, BB, R, TTI);
11710   }
11711   if (AtTerminator) {
11712     // Try to find reductions first.
11713     for (Instruction *I : PostponedCmps) {
11714       if (R.isDeleted(I))
11715         continue;
11716       for (Value *Op : I->operands())
11717         OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI);
11718     }
11719     // Try to vectorize operands as vector bundles.
11720     for (Instruction *I : PostponedCmps) {
11721       if (R.isDeleted(I))
11722         continue;
11723       OpsChanged |= tryToVectorize(I, R);
11724     }
11725     // Try to vectorize list of compares.
11726     // Sort by type, compare predicate, etc.
11727     auto &&CompareSorter = [&R](Value *V, Value *V2) {
11728       return compareCmp<false>(V, V2,
11729                                [&R](Instruction *I) { return R.isDeleted(I); });
11730     };
11731 
11732     auto &&AreCompatibleCompares = [&R](Value *V1, Value *V2) {
11733       if (V1 == V2)
11734         return true;
11735       return compareCmp<true>(V1, V2,
11736                               [&R](Instruction *I) { return R.isDeleted(I); });
11737     };
11738     auto Limit = [&R](Value *V) {
11739       unsigned EltSize = R.getVectorElementSize(V);
11740       return std::max(2U, R.getMaxVecRegSize() / EltSize);
11741     };
11742 
11743     SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end());
11744     OpsChanged |= tryToVectorizeSequence<Value>(
11745         Vals, Limit, CompareSorter, AreCompatibleCompares,
11746         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
11747           // Exclude possible reductions from other blocks.
11748           bool ArePossiblyReducedInOtherBlock =
11749               any_of(Candidates, [](Value *V) {
11750                 return any_of(V->users(), [V](User *U) {
11751                   return isa<SelectInst>(U) &&
11752                          cast<SelectInst>(U)->getParent() !=
11753                              cast<Instruction>(V)->getParent();
11754                 });
11755               });
11756           if (ArePossiblyReducedInOtherBlock)
11757             return false;
11758           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
11759         },
11760         /*LimitForRegisterSize=*/true);
11761     Instructions.clear();
11762   } else {
11763     // Insert in reverse order since the PostponedCmps vector was filled in
11764     // reverse order.
11765     Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend());
11766   }
11767   return OpsChanged;
11768 }
11769 
11770 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
11771   bool Changed = false;
11772   SmallVector<Value *, 4> Incoming;
11773   SmallPtrSet<Value *, 16> VisitedInstrs;
11774   // Maps phi nodes to the non-phi nodes found in the use tree for each phi
11775   // node. Allows better to identify the chains that can be vectorized in the
11776   // better way.
11777   DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes;
11778   auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) {
11779     assert(isValidElementType(V1->getType()) &&
11780            isValidElementType(V2->getType()) &&
11781            "Expected vectorizable types only.");
11782     // It is fine to compare type IDs here, since we expect only vectorizable
11783     // types, like ints, floats and pointers, we don't care about other type.
11784     if (V1->getType()->getTypeID() < V2->getType()->getTypeID())
11785       return true;
11786     if (V1->getType()->getTypeID() > V2->getType()->getTypeID())
11787       return false;
11788     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
11789     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
11790     if (Opcodes1.size() < Opcodes2.size())
11791       return true;
11792     if (Opcodes1.size() > Opcodes2.size())
11793       return false;
11794     Optional<bool> ConstOrder;
11795     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
11796       // Undefs are compatible with any other value.
11797       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) {
11798         if (!ConstOrder)
11799           ConstOrder =
11800               !isa<UndefValue>(Opcodes1[I]) && isa<UndefValue>(Opcodes2[I]);
11801         continue;
11802       }
11803       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
11804         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
11805           DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent());
11806           DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent());
11807           if (!NodeI1)
11808             return NodeI2 != nullptr;
11809           if (!NodeI2)
11810             return false;
11811           assert((NodeI1 == NodeI2) ==
11812                      (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
11813                  "Different nodes should have different DFS numbers");
11814           if (NodeI1 != NodeI2)
11815             return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
11816           InstructionsState S = getSameOpcode({I1, I2});
11817           if (S.getOpcode())
11818             continue;
11819           return I1->getOpcode() < I2->getOpcode();
11820         }
11821       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) {
11822         if (!ConstOrder)
11823           ConstOrder = Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID();
11824         continue;
11825       }
11826       if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID())
11827         return true;
11828       if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID())
11829         return false;
11830     }
11831     return ConstOrder && *ConstOrder;
11832   };
11833   auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) {
11834     if (V1 == V2)
11835       return true;
11836     if (V1->getType() != V2->getType())
11837       return false;
11838     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
11839     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
11840     if (Opcodes1.size() != Opcodes2.size())
11841       return false;
11842     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
11843       // Undefs are compatible with any other value.
11844       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
11845         continue;
11846       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
11847         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
11848           if (I1->getParent() != I2->getParent())
11849             return false;
11850           InstructionsState S = getSameOpcode({I1, I2});
11851           if (S.getOpcode())
11852             continue;
11853           return false;
11854         }
11855       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
11856         continue;
11857       if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID())
11858         return false;
11859     }
11860     return true;
11861   };
11862   auto Limit = [&R](Value *V) {
11863     unsigned EltSize = R.getVectorElementSize(V);
11864     return std::max(2U, R.getMaxVecRegSize() / EltSize);
11865   };
11866 
11867   bool HaveVectorizedPhiNodes = false;
11868   do {
11869     // Collect the incoming values from the PHIs.
11870     Incoming.clear();
11871     for (Instruction &I : *BB) {
11872       PHINode *P = dyn_cast<PHINode>(&I);
11873       if (!P)
11874         break;
11875 
11876       // No need to analyze deleted, vectorized and non-vectorizable
11877       // instructions.
11878       if (!VisitedInstrs.count(P) && !R.isDeleted(P) &&
11879           isValidElementType(P->getType()))
11880         Incoming.push_back(P);
11881     }
11882 
11883     // Find the corresponding non-phi nodes for better matching when trying to
11884     // build the tree.
11885     for (Value *V : Incoming) {
11886       SmallVectorImpl<Value *> &Opcodes =
11887           PHIToOpcodes.try_emplace(V).first->getSecond();
11888       if (!Opcodes.empty())
11889         continue;
11890       SmallVector<Value *, 4> Nodes(1, V);
11891       SmallPtrSet<Value *, 4> Visited;
11892       while (!Nodes.empty()) {
11893         auto *PHI = cast<PHINode>(Nodes.pop_back_val());
11894         if (!Visited.insert(PHI).second)
11895           continue;
11896         for (Value *V : PHI->incoming_values()) {
11897           if (auto *PHI1 = dyn_cast<PHINode>((V))) {
11898             Nodes.push_back(PHI1);
11899             continue;
11900           }
11901           Opcodes.emplace_back(V);
11902         }
11903       }
11904     }
11905 
11906     HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>(
11907         Incoming, Limit, PHICompare, AreCompatiblePHIs,
11908         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
11909           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
11910         },
11911         /*LimitForRegisterSize=*/true);
11912     Changed |= HaveVectorizedPhiNodes;
11913     VisitedInstrs.insert(Incoming.begin(), Incoming.end());
11914   } while (HaveVectorizedPhiNodes);
11915 
11916   VisitedInstrs.clear();
11917 
11918   SmallVector<Instruction *, 8> PostProcessInstructions;
11919   SmallDenseSet<Instruction *, 4> KeyNodes;
11920   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
11921     // Skip instructions with scalable type. The num of elements is unknown at
11922     // compile-time for scalable type.
11923     if (isa<ScalableVectorType>(it->getType()))
11924       continue;
11925 
11926     // Skip instructions marked for the deletion.
11927     if (R.isDeleted(&*it))
11928       continue;
11929     // We may go through BB multiple times so skip the one we have checked.
11930     if (!VisitedInstrs.insert(&*it).second) {
11931       if (it->use_empty() && KeyNodes.contains(&*it) &&
11932           vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
11933                                       it->isTerminator())) {
11934         // We would like to start over since some instructions are deleted
11935         // and the iterator may become invalid value.
11936         Changed = true;
11937         it = BB->begin();
11938         e = BB->end();
11939       }
11940       continue;
11941     }
11942 
11943     if (isa<DbgInfoIntrinsic>(it))
11944       continue;
11945 
11946     // Try to vectorize reductions that use PHINodes.
11947     if (PHINode *P = dyn_cast<PHINode>(it)) {
11948       // Check that the PHI is a reduction PHI.
11949       if (P->getNumIncomingValues() == 2) {
11950         // Try to match and vectorize a horizontal reduction.
11951         if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
11952                                      TTI)) {
11953           Changed = true;
11954           it = BB->begin();
11955           e = BB->end();
11956           continue;
11957         }
11958       }
11959       // Try to vectorize the incoming values of the PHI, to catch reductions
11960       // that feed into PHIs.
11961       for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) {
11962         // Skip if the incoming block is the current BB for now. Also, bypass
11963         // unreachable IR for efficiency and to avoid crashing.
11964         // TODO: Collect the skipped incoming values and try to vectorize them
11965         // after processing BB.
11966         if (BB == P->getIncomingBlock(I) ||
11967             !DT->isReachableFromEntry(P->getIncomingBlock(I)))
11968           continue;
11969 
11970         Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I),
11971                                             P->getIncomingBlock(I), R, TTI);
11972       }
11973       continue;
11974     }
11975 
11976     // Ran into an instruction without users, like terminator, or function call
11977     // with ignored return value, store. Ignore unused instructions (basing on
11978     // instruction type, except for CallInst and InvokeInst).
11979     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
11980                             isa<InvokeInst>(it))) {
11981       KeyNodes.insert(&*it);
11982       bool OpsChanged = false;
11983       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
11984         for (auto *V : it->operand_values()) {
11985           // Try to match and vectorize a horizontal reduction.
11986           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
11987         }
11988       }
11989       // Start vectorization of post-process list of instructions from the
11990       // top-tree instructions to try to vectorize as many instructions as
11991       // possible.
11992       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
11993                                                 it->isTerminator());
11994       if (OpsChanged) {
11995         // We would like to start over since some instructions are deleted
11996         // and the iterator may become invalid value.
11997         Changed = true;
11998         it = BB->begin();
11999         e = BB->end();
12000         continue;
12001       }
12002     }
12003 
12004     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
12005         isa<InsertValueInst>(it))
12006       PostProcessInstructions.push_back(&*it);
12007   }
12008 
12009   return Changed;
12010 }
12011 
12012 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
12013   auto Changed = false;
12014   for (auto &Entry : GEPs) {
12015     // If the getelementptr list has fewer than two elements, there's nothing
12016     // to do.
12017     if (Entry.second.size() < 2)
12018       continue;
12019 
12020     LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
12021                       << Entry.second.size() << ".\n");
12022 
12023     // Process the GEP list in chunks suitable for the target's supported
12024     // vector size. If a vector register can't hold 1 element, we are done. We
12025     // are trying to vectorize the index computations, so the maximum number of
12026     // elements is based on the size of the index expression, rather than the
12027     // size of the GEP itself (the target's pointer size).
12028     unsigned MaxVecRegSize = R.getMaxVecRegSize();
12029     unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin());
12030     if (MaxVecRegSize < EltSize)
12031       continue;
12032 
12033     unsigned MaxElts = MaxVecRegSize / EltSize;
12034     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
12035       auto Len = std::min<unsigned>(BE - BI, MaxElts);
12036       ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len);
12037 
12038       // Initialize a set a candidate getelementptrs. Note that we use a
12039       // SetVector here to preserve program order. If the index computations
12040       // are vectorizable and begin with loads, we want to minimize the chance
12041       // of having to reorder them later.
12042       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
12043 
12044       // Some of the candidates may have already been vectorized after we
12045       // initially collected them. If so, they are marked as deleted, so remove
12046       // them from the set of candidates.
12047       Candidates.remove_if(
12048           [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
12049 
12050       // Remove from the set of candidates all pairs of getelementptrs with
12051       // constant differences. Such getelementptrs are likely not good
12052       // candidates for vectorization in a bottom-up phase since one can be
12053       // computed from the other. We also ensure all candidate getelementptr
12054       // indices are unique.
12055       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
12056         auto *GEPI = GEPList[I];
12057         if (!Candidates.count(GEPI))
12058           continue;
12059         auto *SCEVI = SE->getSCEV(GEPList[I]);
12060         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
12061           auto *GEPJ = GEPList[J];
12062           auto *SCEVJ = SE->getSCEV(GEPList[J]);
12063           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
12064             Candidates.remove(GEPI);
12065             Candidates.remove(GEPJ);
12066           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
12067             Candidates.remove(GEPJ);
12068           }
12069         }
12070       }
12071 
12072       // We break out of the above computation as soon as we know there are
12073       // fewer than two candidates remaining.
12074       if (Candidates.size() < 2)
12075         continue;
12076 
12077       // Add the single, non-constant index of each candidate to the bundle. We
12078       // ensured the indices met these constraints when we originally collected
12079       // the getelementptrs.
12080       SmallVector<Value *, 16> Bundle(Candidates.size());
12081       auto BundleIndex = 0u;
12082       for (auto *V : Candidates) {
12083         auto *GEP = cast<GetElementPtrInst>(V);
12084         auto *GEPIdx = GEP->idx_begin()->get();
12085         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
12086         Bundle[BundleIndex++] = GEPIdx;
12087       }
12088 
12089       // Try and vectorize the indices. We are currently only interested in
12090       // gather-like cases of the form:
12091       //
12092       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
12093       //
12094       // where the loads of "a", the loads of "b", and the subtractions can be
12095       // performed in parallel. It's likely that detecting this pattern in a
12096       // bottom-up phase will be simpler and less costly than building a
12097       // full-blown top-down phase beginning at the consecutive loads.
12098       Changed |= tryToVectorizeList(Bundle, R);
12099     }
12100   }
12101   return Changed;
12102 }
12103 
12104 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
12105   bool Changed = false;
12106   // Sort by type, base pointers and values operand. Value operands must be
12107   // compatible (have the same opcode, same parent), otherwise it is
12108   // definitely not profitable to try to vectorize them.
12109   auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) {
12110     if (V->getPointerOperandType()->getTypeID() <
12111         V2->getPointerOperandType()->getTypeID())
12112       return true;
12113     if (V->getPointerOperandType()->getTypeID() >
12114         V2->getPointerOperandType()->getTypeID())
12115       return false;
12116     // UndefValues are compatible with all other values.
12117     if (isa<UndefValue>(V->getValueOperand()) ||
12118         isa<UndefValue>(V2->getValueOperand()))
12119       return false;
12120     if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand()))
12121       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
12122         DomTreeNodeBase<llvm::BasicBlock> *NodeI1 =
12123             DT->getNode(I1->getParent());
12124         DomTreeNodeBase<llvm::BasicBlock> *NodeI2 =
12125             DT->getNode(I2->getParent());
12126         assert(NodeI1 && "Should only process reachable instructions");
12127         assert(NodeI2 && "Should only process reachable instructions");
12128         assert((NodeI1 == NodeI2) ==
12129                    (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
12130                "Different nodes should have different DFS numbers");
12131         if (NodeI1 != NodeI2)
12132           return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
12133         InstructionsState S = getSameOpcode({I1, I2});
12134         if (S.getOpcode())
12135           return false;
12136         return I1->getOpcode() < I2->getOpcode();
12137       }
12138     if (isa<Constant>(V->getValueOperand()) &&
12139         isa<Constant>(V2->getValueOperand()))
12140       return false;
12141     return V->getValueOperand()->getValueID() <
12142            V2->getValueOperand()->getValueID();
12143   };
12144 
12145   auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) {
12146     if (V1 == V2)
12147       return true;
12148     if (V1->getPointerOperandType() != V2->getPointerOperandType())
12149       return false;
12150     // Undefs are compatible with any other value.
12151     if (isa<UndefValue>(V1->getValueOperand()) ||
12152         isa<UndefValue>(V2->getValueOperand()))
12153       return true;
12154     if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand()))
12155       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
12156         if (I1->getParent() != I2->getParent())
12157           return false;
12158         InstructionsState S = getSameOpcode({I1, I2});
12159         return S.getOpcode() > 0;
12160       }
12161     if (isa<Constant>(V1->getValueOperand()) &&
12162         isa<Constant>(V2->getValueOperand()))
12163       return true;
12164     return V1->getValueOperand()->getValueID() ==
12165            V2->getValueOperand()->getValueID();
12166   };
12167   auto Limit = [&R, this](StoreInst *SI) {
12168     unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
12169     return R.getMinVF(EltSize);
12170   };
12171 
12172   // Attempt to sort and vectorize each of the store-groups.
12173   for (auto &Pair : Stores) {
12174     if (Pair.second.size() < 2)
12175       continue;
12176 
12177     LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
12178                       << Pair.second.size() << ".\n");
12179 
12180     if (!isValidElementType(Pair.second.front()->getValueOperand()->getType()))
12181       continue;
12182 
12183     Changed |= tryToVectorizeSequence<StoreInst>(
12184         Pair.second, Limit, StoreSorter, AreCompatibleStores,
12185         [this, &R](ArrayRef<StoreInst *> Candidates, bool) {
12186           return vectorizeStores(Candidates, R);
12187         },
12188         /*LimitForRegisterSize=*/false);
12189   }
12190   return Changed;
12191 }
12192 
12193 char SLPVectorizer::ID = 0;
12194 
12195 static const char lv_name[] = "SLP Vectorizer";
12196 
12197 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
12198 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
12199 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
12200 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
12201 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
12202 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
12203 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
12204 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
12205 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
12206 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
12207 
12208 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
12209