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                  ArrayRef<Value *> UserIgnoreLst = None);
899 
900   /// Builds external uses of the vectorized scalars, i.e. the list of
901   /// vectorized scalars to be extracted, their lanes and their scalar users. \p
902   /// ExternallyUsedValues contains additional list of external uses to handle
903   /// vectorization of reductions.
904   void
905   buildExternalUses(const ExtraValueToDebugLocsMap &ExternallyUsedValues = {});
906 
907   /// Clear the internal data structures that are created by 'buildTree'.
908   void deleteTree() {
909     VectorizableTree.clear();
910     ScalarToTreeEntry.clear();
911     MustGather.clear();
912     ExternalUses.clear();
913     for (auto &Iter : BlocksSchedules) {
914       BlockScheduling *BS = Iter.second.get();
915       BS->clear();
916     }
917     MinBWs.clear();
918     InstrElementSize.clear();
919   }
920 
921   unsigned getTreeSize() const { return VectorizableTree.size(); }
922 
923   /// Perform LICM and CSE on the newly generated gather sequences.
924   void optimizeGatherSequence();
925 
926   /// Checks if the specified gather tree entry \p TE can be represented as a
927   /// shuffled vector entry + (possibly) permutation with other gathers. It
928   /// implements the checks only for possibly ordered scalars (Loads,
929   /// ExtractElement, ExtractValue), which can be part of the graph.
930   Optional<OrdersType> findReusedOrderedScalars(const TreeEntry &TE);
931 
932   /// Sort loads into increasing pointers offsets to allow greater clustering.
933   Optional<OrdersType> findPartiallyOrderedLoads(const TreeEntry &TE);
934 
935   /// Gets reordering data for the given tree entry. If the entry is vectorized
936   /// - just return ReorderIndices, otherwise check if the scalars can be
937   /// reordered and return the most optimal order.
938   /// \param TopToBottom If true, include the order of vectorized stores and
939   /// insertelement nodes, otherwise skip them.
940   Optional<OrdersType> getReorderingData(const TreeEntry &TE, bool TopToBottom);
941 
942   /// Reorders the current graph to the most profitable order starting from the
943   /// root node to the leaf nodes. The best order is chosen only from the nodes
944   /// of the same size (vectorization factor). Smaller nodes are considered
945   /// parts of subgraph with smaller VF and they are reordered independently. We
946   /// can make it because we still need to extend smaller nodes to the wider VF
947   /// and we can merge reordering shuffles with the widening shuffles.
948   void reorderTopToBottom();
949 
950   /// Reorders the current graph to the most profitable order starting from
951   /// leaves to the root. It allows to rotate small subgraphs and reduce the
952   /// number of reshuffles if the leaf nodes use the same order. In this case we
953   /// can merge the orders and just shuffle user node instead of shuffling its
954   /// operands. Plus, even the leaf nodes have different orders, it allows to
955   /// sink reordering in the graph closer to the root node and merge it later
956   /// during analysis.
957   void reorderBottomToTop(bool IgnoreReorder = false);
958 
959   /// \return The vector element size in bits to use when vectorizing the
960   /// expression tree ending at \p V. If V is a store, the size is the width of
961   /// the stored value. Otherwise, the size is the width of the largest loaded
962   /// value reaching V. This method is used by the vectorizer to calculate
963   /// vectorization factors.
964   unsigned getVectorElementSize(Value *V);
965 
966   /// Compute the minimum type sizes required to represent the entries in a
967   /// vectorizable tree.
968   void computeMinimumValueSizes();
969 
970   // \returns maximum vector register size as set by TTI or overridden by cl::opt.
971   unsigned getMaxVecRegSize() const {
972     return MaxVecRegSize;
973   }
974 
975   // \returns minimum vector register size as set by cl::opt.
976   unsigned getMinVecRegSize() const {
977     return MinVecRegSize;
978   }
979 
980   unsigned getMinVF(unsigned Sz) const {
981     return std::max(2U, getMinVecRegSize() / Sz);
982   }
983 
984   unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const {
985     unsigned MaxVF = MaxVFOption.getNumOccurrences() ?
986       MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode);
987     return MaxVF ? MaxVF : UINT_MAX;
988   }
989 
990   /// Check if homogeneous aggregate is isomorphic to some VectorType.
991   /// Accepts homogeneous multidimensional aggregate of scalars/vectors like
992   /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> },
993   /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on.
994   ///
995   /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
996   unsigned canMapToVector(Type *T, const DataLayout &DL) const;
997 
998   /// \returns True if the VectorizableTree is both tiny and not fully
999   /// vectorizable. We do not vectorize such trees.
1000   bool isTreeTinyAndNotFullyVectorizable(bool ForReduction = false) const;
1001 
1002   /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values
1003   /// can be load combined in the backend. Load combining may not be allowed in
1004   /// the IR optimizer, so we do not want to alter the pattern. For example,
1005   /// partially transforming a scalar bswap() pattern into vector code is
1006   /// effectively impossible for the backend to undo.
1007   /// TODO: If load combining is allowed in the IR optimizer, this analysis
1008   ///       may not be necessary.
1009   bool isLoadCombineReductionCandidate(RecurKind RdxKind) const;
1010 
1011   /// Assume that a vector of stores of bitwise-or/shifted/zexted loaded values
1012   /// can be load combined in the backend. Load combining may not be allowed in
1013   /// the IR optimizer, so we do not want to alter the pattern. For example,
1014   /// partially transforming a scalar bswap() pattern into vector code is
1015   /// effectively impossible for the backend to undo.
1016   /// TODO: If load combining is allowed in the IR optimizer, this analysis
1017   ///       may not be necessary.
1018   bool isLoadCombineCandidate() const;
1019 
1020   OptimizationRemarkEmitter *getORE() { return ORE; }
1021 
1022   /// This structure holds any data we need about the edges being traversed
1023   /// during buildTree_rec(). We keep track of:
1024   /// (i) the user TreeEntry index, and
1025   /// (ii) the index of the edge.
1026   struct EdgeInfo {
1027     EdgeInfo() = default;
1028     EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx)
1029         : UserTE(UserTE), EdgeIdx(EdgeIdx) {}
1030     /// The user TreeEntry.
1031     TreeEntry *UserTE = nullptr;
1032     /// The operand index of the use.
1033     unsigned EdgeIdx = UINT_MAX;
1034 #ifndef NDEBUG
1035     friend inline raw_ostream &operator<<(raw_ostream &OS,
1036                                           const BoUpSLP::EdgeInfo &EI) {
1037       EI.dump(OS);
1038       return OS;
1039     }
1040     /// Debug print.
1041     void dump(raw_ostream &OS) const {
1042       OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null")
1043          << " EdgeIdx:" << EdgeIdx << "}";
1044     }
1045     LLVM_DUMP_METHOD void dump() const { dump(dbgs()); }
1046 #endif
1047   };
1048 
1049   /// A helper class used for scoring candidates for two consecutive lanes.
1050   class LookAheadHeuristics {
1051     const DataLayout &DL;
1052     ScalarEvolution &SE;
1053     const BoUpSLP &R;
1054     int NumLanes; // Total number of lanes (aka vectorization factor).
1055     int MaxLevel; // The maximum recursion depth for accumulating score.
1056 
1057   public:
1058     LookAheadHeuristics(const DataLayout &DL, ScalarEvolution &SE,
1059                         const BoUpSLP &R, int NumLanes, int MaxLevel)
1060         : DL(DL), SE(SE), R(R), NumLanes(NumLanes), MaxLevel(MaxLevel) {}
1061 
1062     // The hard-coded scores listed here are not very important, though it shall
1063     // be higher for better matches to improve the resulting cost. When
1064     // computing the scores of matching one sub-tree with another, we are
1065     // basically counting the number of values that are matching. So even if all
1066     // scores are set to 1, we would still get a decent matching result.
1067     // However, sometimes we have to break ties. For example we may have to
1068     // choose between matching loads vs matching opcodes. This is what these
1069     // scores are helping us with: they provide the order of preference. Also,
1070     // this is important if the scalar is externally used or used in another
1071     // tree entry node in the different lane.
1072 
1073     /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]).
1074     static const int ScoreConsecutiveLoads = 4;
1075     /// The same load multiple times. This should have a better score than
1076     /// `ScoreSplat` because it in x86 for a 2-lane vector we can represent it
1077     /// with `movddup (%reg), xmm0` which has a throughput of 0.5 versus 0.5 for
1078     /// a vector load and 1.0 for a broadcast.
1079     static const int ScoreSplatLoads = 3;
1080     /// Loads from reversed memory addresses, e.g. load(A[i+1]), load(A[i]).
1081     static const int ScoreReversedLoads = 3;
1082     /// ExtractElementInst from same vector and consecutive indexes.
1083     static const int ScoreConsecutiveExtracts = 4;
1084     /// ExtractElementInst from same vector and reversed indices.
1085     static const int ScoreReversedExtracts = 3;
1086     /// Constants.
1087     static const int ScoreConstants = 2;
1088     /// Instructions with the same opcode.
1089     static const int ScoreSameOpcode = 2;
1090     /// Instructions with alt opcodes (e.g, add + sub).
1091     static const int ScoreAltOpcodes = 1;
1092     /// Identical instructions (a.k.a. splat or broadcast).
1093     static const int ScoreSplat = 1;
1094     /// Matching with an undef is preferable to failing.
1095     static const int ScoreUndef = 1;
1096     /// Score for failing to find a decent match.
1097     static const int ScoreFail = 0;
1098     /// Score if all users are vectorized.
1099     static const int ScoreAllUserVectorized = 1;
1100 
1101     /// \returns the score of placing \p V1 and \p V2 in consecutive lanes.
1102     /// \p U1 and \p U2 are the users of \p V1 and \p V2.
1103     /// Also, checks if \p V1 and \p V2 are compatible with instructions in \p
1104     /// MainAltOps.
1105     int getShallowScore(Value *V1, Value *V2, Instruction *U1, Instruction *U2,
1106                         ArrayRef<Value *> MainAltOps) const {
1107       if (V1 == V2) {
1108         if (isa<LoadInst>(V1)) {
1109           // Retruns true if the users of V1 and V2 won't need to be extracted.
1110           auto AllUsersAreInternal = [U1, U2, this](Value *V1, Value *V2) {
1111             // Bail out if we have too many uses to save compilation time.
1112             static constexpr unsigned Limit = 8;
1113             if (V1->hasNUsesOrMore(Limit) || V2->hasNUsesOrMore(Limit))
1114               return false;
1115 
1116             auto AllUsersVectorized = [U1, U2, this](Value *V) {
1117               return llvm::all_of(V->users(), [U1, U2, this](Value *U) {
1118                 return U == U1 || U == U2 || R.getTreeEntry(U) != nullptr;
1119               });
1120             };
1121             return AllUsersVectorized(V1) && AllUsersVectorized(V2);
1122           };
1123           // A broadcast of a load can be cheaper on some targets.
1124           if (R.TTI->isLegalBroadcastLoad(V1->getType(),
1125                                           ElementCount::getFixed(NumLanes)) &&
1126               ((int)V1->getNumUses() == NumLanes ||
1127                AllUsersAreInternal(V1, V2)))
1128             return LookAheadHeuristics::ScoreSplatLoads;
1129         }
1130         return LookAheadHeuristics::ScoreSplat;
1131       }
1132 
1133       auto *LI1 = dyn_cast<LoadInst>(V1);
1134       auto *LI2 = dyn_cast<LoadInst>(V2);
1135       if (LI1 && LI2) {
1136         if (LI1->getParent() != LI2->getParent())
1137           return LookAheadHeuristics::ScoreFail;
1138 
1139         Optional<int> Dist = getPointersDiff(
1140             LI1->getType(), LI1->getPointerOperand(), LI2->getType(),
1141             LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true);
1142         if (!Dist || *Dist == 0)
1143           return LookAheadHeuristics::ScoreFail;
1144         // The distance is too large - still may be profitable to use masked
1145         // loads/gathers.
1146         if (std::abs(*Dist) > NumLanes / 2)
1147           return LookAheadHeuristics::ScoreAltOpcodes;
1148         // This still will detect consecutive loads, but we might have "holes"
1149         // in some cases. It is ok for non-power-2 vectorization and may produce
1150         // better results. It should not affect current vectorization.
1151         return (*Dist > 0) ? LookAheadHeuristics::ScoreConsecutiveLoads
1152                            : LookAheadHeuristics::ScoreReversedLoads;
1153       }
1154 
1155       auto *C1 = dyn_cast<Constant>(V1);
1156       auto *C2 = dyn_cast<Constant>(V2);
1157       if (C1 && C2)
1158         return LookAheadHeuristics::ScoreConstants;
1159 
1160       // Extracts from consecutive indexes of the same vector better score as
1161       // the extracts could be optimized away.
1162       Value *EV1;
1163       ConstantInt *Ex1Idx;
1164       if (match(V1, m_ExtractElt(m_Value(EV1), m_ConstantInt(Ex1Idx)))) {
1165         // Undefs are always profitable for extractelements.
1166         if (isa<UndefValue>(V2))
1167           return LookAheadHeuristics::ScoreConsecutiveExtracts;
1168         Value *EV2 = nullptr;
1169         ConstantInt *Ex2Idx = nullptr;
1170         if (match(V2,
1171                   m_ExtractElt(m_Value(EV2), m_CombineOr(m_ConstantInt(Ex2Idx),
1172                                                          m_Undef())))) {
1173           // Undefs are always profitable for extractelements.
1174           if (!Ex2Idx)
1175             return LookAheadHeuristics::ScoreConsecutiveExtracts;
1176           if (isUndefVector(EV2) && EV2->getType() == EV1->getType())
1177             return LookAheadHeuristics::ScoreConsecutiveExtracts;
1178           if (EV2 == EV1) {
1179             int Idx1 = Ex1Idx->getZExtValue();
1180             int Idx2 = Ex2Idx->getZExtValue();
1181             int Dist = Idx2 - Idx1;
1182             // The distance is too large - still may be profitable to use
1183             // shuffles.
1184             if (std::abs(Dist) == 0)
1185               return LookAheadHeuristics::ScoreSplat;
1186             if (std::abs(Dist) > NumLanes / 2)
1187               return LookAheadHeuristics::ScoreSameOpcode;
1188             return (Dist > 0) ? LookAheadHeuristics::ScoreConsecutiveExtracts
1189                               : LookAheadHeuristics::ScoreReversedExtracts;
1190           }
1191           return LookAheadHeuristics::ScoreAltOpcodes;
1192         }
1193         return LookAheadHeuristics::ScoreFail;
1194       }
1195 
1196       auto *I1 = dyn_cast<Instruction>(V1);
1197       auto *I2 = dyn_cast<Instruction>(V2);
1198       if (I1 && I2) {
1199         if (I1->getParent() != I2->getParent())
1200           return LookAheadHeuristics::ScoreFail;
1201         SmallVector<Value *, 4> Ops(MainAltOps.begin(), MainAltOps.end());
1202         Ops.push_back(I1);
1203         Ops.push_back(I2);
1204         InstructionsState S = getSameOpcode(Ops);
1205         // Note: Only consider instructions with <= 2 operands to avoid
1206         // complexity explosion.
1207         if (S.getOpcode() &&
1208             (S.MainOp->getNumOperands() <= 2 || !MainAltOps.empty() ||
1209              !S.isAltShuffle()) &&
1210             all_of(Ops, [&S](Value *V) {
1211               return cast<Instruction>(V)->getNumOperands() ==
1212                      S.MainOp->getNumOperands();
1213             }))
1214           return S.isAltShuffle() ? LookAheadHeuristics::ScoreAltOpcodes
1215                                   : LookAheadHeuristics::ScoreSameOpcode;
1216       }
1217 
1218       if (isa<UndefValue>(V2))
1219         return LookAheadHeuristics::ScoreUndef;
1220 
1221       return LookAheadHeuristics::ScoreFail;
1222     }
1223 
1224     /// Go through the operands of \p LHS and \p RHS recursively until
1225     /// MaxLevel, and return the cummulative score. \p U1 and \p U2 are
1226     /// the users of \p LHS and \p RHS (that is \p LHS and \p RHS are operands
1227     /// of \p U1 and \p U2), except at the beginning of the recursion where
1228     /// these are set to nullptr.
1229     ///
1230     /// For example:
1231     /// \verbatim
1232     ///  A[0]  B[0]  A[1]  B[1]  C[0] D[0]  B[1] A[1]
1233     ///     \ /         \ /         \ /        \ /
1234     ///      +           +           +          +
1235     ///     G1          G2          G3         G4
1236     /// \endverbatim
1237     /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at
1238     /// each level recursively, accumulating the score. It starts from matching
1239     /// the additions at level 0, then moves on to the loads (level 1). The
1240     /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and
1241     /// {B[0],B[1]} match with LookAheadHeuristics::ScoreConsecutiveLoads, while
1242     /// {A[0],C[0]} has a score of LookAheadHeuristics::ScoreFail.
1243     /// Please note that the order of the operands does not matter, as we
1244     /// evaluate the score of all profitable combinations of operands. In
1245     /// other words the score of G1 and G4 is the same as G1 and G2. This
1246     /// heuristic is based on ideas described in:
1247     ///   Look-ahead SLP: Auto-vectorization in the presence of commutative
1248     ///   operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha,
1249     ///   Luís F. W. Góes
1250     int getScoreAtLevelRec(Value *LHS, Value *RHS, Instruction *U1,
1251                            Instruction *U2, int CurrLevel,
1252                            ArrayRef<Value *> MainAltOps) const {
1253 
1254       // Get the shallow score of V1 and V2.
1255       int ShallowScoreAtThisLevel =
1256           getShallowScore(LHS, RHS, U1, U2, MainAltOps);
1257 
1258       // If reached MaxLevel,
1259       //  or if V1 and V2 are not instructions,
1260       //  or if they are SPLAT,
1261       //  or if they are not consecutive,
1262       //  or if profitable to vectorize loads or extractelements, early return
1263       //  the current cost.
1264       auto *I1 = dyn_cast<Instruction>(LHS);
1265       auto *I2 = dyn_cast<Instruction>(RHS);
1266       if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 ||
1267           ShallowScoreAtThisLevel == LookAheadHeuristics::ScoreFail ||
1268           (((isa<LoadInst>(I1) && isa<LoadInst>(I2)) ||
1269             (I1->getNumOperands() > 2 && I2->getNumOperands() > 2) ||
1270             (isa<ExtractElementInst>(I1) && isa<ExtractElementInst>(I2))) &&
1271            ShallowScoreAtThisLevel))
1272         return ShallowScoreAtThisLevel;
1273       assert(I1 && I2 && "Should have early exited.");
1274 
1275       // Contains the I2 operand indexes that got matched with I1 operands.
1276       SmallSet<unsigned, 4> Op2Used;
1277 
1278       // Recursion towards the operands of I1 and I2. We are trying all possible
1279       // operand pairs, and keeping track of the best score.
1280       for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands();
1281            OpIdx1 != NumOperands1; ++OpIdx1) {
1282         // Try to pair op1I with the best operand of I2.
1283         int MaxTmpScore = 0;
1284         unsigned MaxOpIdx2 = 0;
1285         bool FoundBest = false;
1286         // If I2 is commutative try all combinations.
1287         unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1;
1288         unsigned ToIdx = isCommutative(I2)
1289                              ? I2->getNumOperands()
1290                              : std::min(I2->getNumOperands(), OpIdx1 + 1);
1291         assert(FromIdx <= ToIdx && "Bad index");
1292         for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) {
1293           // Skip operands already paired with OpIdx1.
1294           if (Op2Used.count(OpIdx2))
1295             continue;
1296           // Recursively calculate the cost at each level
1297           int TmpScore =
1298               getScoreAtLevelRec(I1->getOperand(OpIdx1), I2->getOperand(OpIdx2),
1299                                  I1, I2, CurrLevel + 1, None);
1300           // Look for the best score.
1301           if (TmpScore > LookAheadHeuristics::ScoreFail &&
1302               TmpScore > MaxTmpScore) {
1303             MaxTmpScore = TmpScore;
1304             MaxOpIdx2 = OpIdx2;
1305             FoundBest = true;
1306           }
1307         }
1308         if (FoundBest) {
1309           // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it.
1310           Op2Used.insert(MaxOpIdx2);
1311           ShallowScoreAtThisLevel += MaxTmpScore;
1312         }
1313       }
1314       return ShallowScoreAtThisLevel;
1315     }
1316   };
1317   /// A helper data structure to hold the operands of a vector of instructions.
1318   /// This supports a fixed vector length for all operand vectors.
1319   class VLOperands {
1320     /// For each operand we need (i) the value, and (ii) the opcode that it
1321     /// would be attached to if the expression was in a left-linearized form.
1322     /// This is required to avoid illegal operand reordering.
1323     /// For example:
1324     /// \verbatim
1325     ///                         0 Op1
1326     ///                         |/
1327     /// Op1 Op2   Linearized    + Op2
1328     ///   \ /     ---------->   |/
1329     ///    -                    -
1330     ///
1331     /// Op1 - Op2            (0 + Op1) - Op2
1332     /// \endverbatim
1333     ///
1334     /// Value Op1 is attached to a '+' operation, and Op2 to a '-'.
1335     ///
1336     /// Another way to think of this is to track all the operations across the
1337     /// path from the operand all the way to the root of the tree and to
1338     /// calculate the operation that corresponds to this path. For example, the
1339     /// path from Op2 to the root crosses the RHS of the '-', therefore the
1340     /// corresponding operation is a '-' (which matches the one in the
1341     /// linearized tree, as shown above).
1342     ///
1343     /// For lack of a better term, we refer to this operation as Accumulated
1344     /// Path Operation (APO).
1345     struct OperandData {
1346       OperandData() = default;
1347       OperandData(Value *V, bool APO, bool IsUsed)
1348           : V(V), APO(APO), IsUsed(IsUsed) {}
1349       /// The operand value.
1350       Value *V = nullptr;
1351       /// TreeEntries only allow a single opcode, or an alternate sequence of
1352       /// them (e.g, +, -). Therefore, we can safely use a boolean value for the
1353       /// APO. It is set to 'true' if 'V' is attached to an inverse operation
1354       /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise
1355       /// (e.g., Add/Mul)
1356       bool APO = false;
1357       /// Helper data for the reordering function.
1358       bool IsUsed = false;
1359     };
1360 
1361     /// During operand reordering, we are trying to select the operand at lane
1362     /// that matches best with the operand at the neighboring lane. Our
1363     /// selection is based on the type of value we are looking for. For example,
1364     /// if the neighboring lane has a load, we need to look for a load that is
1365     /// accessing a consecutive address. These strategies are summarized in the
1366     /// 'ReorderingMode' enumerator.
1367     enum class ReorderingMode {
1368       Load,     ///< Matching loads to consecutive memory addresses
1369       Opcode,   ///< Matching instructions based on opcode (same or alternate)
1370       Constant, ///< Matching constants
1371       Splat,    ///< Matching the same instruction multiple times (broadcast)
1372       Failed,   ///< We failed to create a vectorizable group
1373     };
1374 
1375     using OperandDataVec = SmallVector<OperandData, 2>;
1376 
1377     /// A vector of operand vectors.
1378     SmallVector<OperandDataVec, 4> OpsVec;
1379 
1380     const DataLayout &DL;
1381     ScalarEvolution &SE;
1382     const BoUpSLP &R;
1383 
1384     /// \returns the operand data at \p OpIdx and \p Lane.
1385     OperandData &getData(unsigned OpIdx, unsigned Lane) {
1386       return OpsVec[OpIdx][Lane];
1387     }
1388 
1389     /// \returns the operand data at \p OpIdx and \p Lane. Const version.
1390     const OperandData &getData(unsigned OpIdx, unsigned Lane) const {
1391       return OpsVec[OpIdx][Lane];
1392     }
1393 
1394     /// Clears the used flag for all entries.
1395     void clearUsed() {
1396       for (unsigned OpIdx = 0, NumOperands = getNumOperands();
1397            OpIdx != NumOperands; ++OpIdx)
1398         for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
1399              ++Lane)
1400           OpsVec[OpIdx][Lane].IsUsed = false;
1401     }
1402 
1403     /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2.
1404     void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) {
1405       std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]);
1406     }
1407 
1408     /// \param Lane lane of the operands under analysis.
1409     /// \param OpIdx operand index in \p Lane lane we're looking the best
1410     /// candidate for.
1411     /// \param Idx operand index of the current candidate value.
1412     /// \returns The additional score due to possible broadcasting of the
1413     /// elements in the lane. It is more profitable to have power-of-2 unique
1414     /// elements in the lane, it will be vectorized with higher probability
1415     /// after removing duplicates. Currently the SLP vectorizer supports only
1416     /// vectorization of the power-of-2 number of unique scalars.
1417     int getSplatScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1418       Value *IdxLaneV = getData(Idx, Lane).V;
1419       if (!isa<Instruction>(IdxLaneV) || IdxLaneV == getData(OpIdx, Lane).V)
1420         return 0;
1421       SmallPtrSet<Value *, 4> Uniques;
1422       for (unsigned Ln = 0, E = getNumLanes(); Ln < E; ++Ln) {
1423         if (Ln == Lane)
1424           continue;
1425         Value *OpIdxLnV = getData(OpIdx, Ln).V;
1426         if (!isa<Instruction>(OpIdxLnV))
1427           return 0;
1428         Uniques.insert(OpIdxLnV);
1429       }
1430       int UniquesCount = Uniques.size();
1431       int UniquesCntWithIdxLaneV =
1432           Uniques.contains(IdxLaneV) ? UniquesCount : UniquesCount + 1;
1433       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1434       int UniquesCntWithOpIdxLaneV =
1435           Uniques.contains(OpIdxLaneV) ? UniquesCount : UniquesCount + 1;
1436       if (UniquesCntWithIdxLaneV == UniquesCntWithOpIdxLaneV)
1437         return 0;
1438       return (PowerOf2Ceil(UniquesCntWithOpIdxLaneV) -
1439               UniquesCntWithOpIdxLaneV) -
1440              (PowerOf2Ceil(UniquesCntWithIdxLaneV) - UniquesCntWithIdxLaneV);
1441     }
1442 
1443     /// \param Lane lane of the operands under analysis.
1444     /// \param OpIdx operand index in \p Lane lane we're looking the best
1445     /// candidate for.
1446     /// \param Idx operand index of the current candidate value.
1447     /// \returns The additional score for the scalar which users are all
1448     /// vectorized.
1449     int getExternalUseScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1450       Value *IdxLaneV = getData(Idx, Lane).V;
1451       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1452       // Do not care about number of uses for vector-like instructions
1453       // (extractelement/extractvalue with constant indices), they are extracts
1454       // themselves and already externally used. Vectorization of such
1455       // instructions does not add extra extractelement instruction, just may
1456       // remove it.
1457       if (isVectorLikeInstWithConstOps(IdxLaneV) &&
1458           isVectorLikeInstWithConstOps(OpIdxLaneV))
1459         return LookAheadHeuristics::ScoreAllUserVectorized;
1460       auto *IdxLaneI = dyn_cast<Instruction>(IdxLaneV);
1461       if (!IdxLaneI || !isa<Instruction>(OpIdxLaneV))
1462         return 0;
1463       return R.areAllUsersVectorized(IdxLaneI, None)
1464                  ? LookAheadHeuristics::ScoreAllUserVectorized
1465                  : 0;
1466     }
1467 
1468     /// Score scaling factor for fully compatible instructions but with
1469     /// different number of external uses. Allows better selection of the
1470     /// instructions with less external uses.
1471     static const int ScoreScaleFactor = 10;
1472 
1473     /// \Returns the look-ahead score, which tells us how much the sub-trees
1474     /// rooted at \p LHS and \p RHS match, the more they match the higher the
1475     /// score. This helps break ties in an informed way when we cannot decide on
1476     /// the order of the operands by just considering the immediate
1477     /// predecessors.
1478     int getLookAheadScore(Value *LHS, Value *RHS, ArrayRef<Value *> MainAltOps,
1479                           int Lane, unsigned OpIdx, unsigned Idx,
1480                           bool &IsUsed) {
1481       LookAheadHeuristics LookAhead(DL, SE, R, getNumLanes(),
1482                                     LookAheadMaxDepth);
1483       // Keep track of the instruction stack as we recurse into the operands
1484       // during the look-ahead score exploration.
1485       int Score =
1486           LookAhead.getScoreAtLevelRec(LHS, RHS, /*U1=*/nullptr, /*U2=*/nullptr,
1487                                        /*CurrLevel=*/1, MainAltOps);
1488       if (Score) {
1489         int SplatScore = getSplatScore(Lane, OpIdx, Idx);
1490         if (Score <= -SplatScore) {
1491           // Set the minimum score for splat-like sequence to avoid setting
1492           // failed state.
1493           Score = 1;
1494         } else {
1495           Score += SplatScore;
1496           // Scale score to see the difference between different operands
1497           // and similar operands but all vectorized/not all vectorized
1498           // uses. It does not affect actual selection of the best
1499           // compatible operand in general, just allows to select the
1500           // operand with all vectorized uses.
1501           Score *= ScoreScaleFactor;
1502           Score += getExternalUseScore(Lane, OpIdx, Idx);
1503           IsUsed = true;
1504         }
1505       }
1506       return Score;
1507     }
1508 
1509     /// Best defined scores per lanes between the passes. Used to choose the
1510     /// best operand (with the highest score) between the passes.
1511     /// The key - {Operand Index, Lane}.
1512     /// The value - the best score between the passes for the lane and the
1513     /// operand.
1514     SmallDenseMap<std::pair<unsigned, unsigned>, unsigned, 8>
1515         BestScoresPerLanes;
1516 
1517     // Search all operands in Ops[*][Lane] for the one that matches best
1518     // Ops[OpIdx][LastLane] and return its opreand index.
1519     // If no good match can be found, return None.
1520     Optional<unsigned> getBestOperand(unsigned OpIdx, int Lane, int LastLane,
1521                                       ArrayRef<ReorderingMode> ReorderingModes,
1522                                       ArrayRef<Value *> MainAltOps) {
1523       unsigned NumOperands = getNumOperands();
1524 
1525       // The operand of the previous lane at OpIdx.
1526       Value *OpLastLane = getData(OpIdx, LastLane).V;
1527 
1528       // Our strategy mode for OpIdx.
1529       ReorderingMode RMode = ReorderingModes[OpIdx];
1530       if (RMode == ReorderingMode::Failed)
1531         return None;
1532 
1533       // The linearized opcode of the operand at OpIdx, Lane.
1534       bool OpIdxAPO = getData(OpIdx, Lane).APO;
1535 
1536       // The best operand index and its score.
1537       // Sometimes we have more than one option (e.g., Opcode and Undefs), so we
1538       // are using the score to differentiate between the two.
1539       struct BestOpData {
1540         Optional<unsigned> Idx = None;
1541         unsigned Score = 0;
1542       } BestOp;
1543       BestOp.Score =
1544           BestScoresPerLanes.try_emplace(std::make_pair(OpIdx, Lane), 0)
1545               .first->second;
1546 
1547       // Track if the operand must be marked as used. If the operand is set to
1548       // Score 1 explicitly (because of non power-of-2 unique scalars, we may
1549       // want to reestimate the operands again on the following iterations).
1550       bool IsUsed =
1551           RMode == ReorderingMode::Splat || RMode == ReorderingMode::Constant;
1552       // Iterate through all unused operands and look for the best.
1553       for (unsigned Idx = 0; Idx != NumOperands; ++Idx) {
1554         // Get the operand at Idx and Lane.
1555         OperandData &OpData = getData(Idx, Lane);
1556         Value *Op = OpData.V;
1557         bool OpAPO = OpData.APO;
1558 
1559         // Skip already selected operands.
1560         if (OpData.IsUsed)
1561           continue;
1562 
1563         // Skip if we are trying to move the operand to a position with a
1564         // different opcode in the linearized tree form. This would break the
1565         // semantics.
1566         if (OpAPO != OpIdxAPO)
1567           continue;
1568 
1569         // Look for an operand that matches the current mode.
1570         switch (RMode) {
1571         case ReorderingMode::Load:
1572         case ReorderingMode::Constant:
1573         case ReorderingMode::Opcode: {
1574           bool LeftToRight = Lane > LastLane;
1575           Value *OpLeft = (LeftToRight) ? OpLastLane : Op;
1576           Value *OpRight = (LeftToRight) ? Op : OpLastLane;
1577           int Score = getLookAheadScore(OpLeft, OpRight, MainAltOps, Lane,
1578                                         OpIdx, Idx, IsUsed);
1579           if (Score > static_cast<int>(BestOp.Score)) {
1580             BestOp.Idx = Idx;
1581             BestOp.Score = Score;
1582             BestScoresPerLanes[std::make_pair(OpIdx, Lane)] = Score;
1583           }
1584           break;
1585         }
1586         case ReorderingMode::Splat:
1587           if (Op == OpLastLane)
1588             BestOp.Idx = Idx;
1589           break;
1590         case ReorderingMode::Failed:
1591           llvm_unreachable("Not expected Failed reordering mode.");
1592         }
1593       }
1594 
1595       if (BestOp.Idx) {
1596         getData(BestOp.Idx.getValue(), Lane).IsUsed = IsUsed;
1597         return BestOp.Idx;
1598       }
1599       // If we could not find a good match return None.
1600       return None;
1601     }
1602 
1603     /// Helper for reorderOperandVecs.
1604     /// \returns the lane that we should start reordering from. This is the one
1605     /// which has the least number of operands that can freely move about or
1606     /// less profitable because it already has the most optimal set of operands.
1607     unsigned getBestLaneToStartReordering() const {
1608       unsigned Min = UINT_MAX;
1609       unsigned SameOpNumber = 0;
1610       // std::pair<unsigned, unsigned> is used to implement a simple voting
1611       // algorithm and choose the lane with the least number of operands that
1612       // can freely move about or less profitable because it already has the
1613       // most optimal set of operands. The first unsigned is a counter for
1614       // voting, the second unsigned is the counter of lanes with instructions
1615       // with same/alternate opcodes and same parent basic block.
1616       MapVector<unsigned, std::pair<unsigned, unsigned>> HashMap;
1617       // Try to be closer to the original results, if we have multiple lanes
1618       // with same cost. If 2 lanes have the same cost, use the one with the
1619       // lowest index.
1620       for (int I = getNumLanes(); I > 0; --I) {
1621         unsigned Lane = I - 1;
1622         OperandsOrderData NumFreeOpsHash =
1623             getMaxNumOperandsThatCanBeReordered(Lane);
1624         // Compare the number of operands that can move and choose the one with
1625         // the least number.
1626         if (NumFreeOpsHash.NumOfAPOs < Min) {
1627           Min = NumFreeOpsHash.NumOfAPOs;
1628           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1629           HashMap.clear();
1630           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1631         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1632                    NumFreeOpsHash.NumOpsWithSameOpcodeParent < SameOpNumber) {
1633           // Select the most optimal lane in terms of number of operands that
1634           // should be moved around.
1635           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1636           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1637         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1638                    NumFreeOpsHash.NumOpsWithSameOpcodeParent == SameOpNumber) {
1639           auto It = HashMap.find(NumFreeOpsHash.Hash);
1640           if (It == HashMap.end())
1641             HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1642           else
1643             ++It->second.first;
1644         }
1645       }
1646       // Select the lane with the minimum counter.
1647       unsigned BestLane = 0;
1648       unsigned CntMin = UINT_MAX;
1649       for (const auto &Data : reverse(HashMap)) {
1650         if (Data.second.first < CntMin) {
1651           CntMin = Data.second.first;
1652           BestLane = Data.second.second;
1653         }
1654       }
1655       return BestLane;
1656     }
1657 
1658     /// Data structure that helps to reorder operands.
1659     struct OperandsOrderData {
1660       /// The best number of operands with the same APOs, which can be
1661       /// reordered.
1662       unsigned NumOfAPOs = UINT_MAX;
1663       /// Number of operands with the same/alternate instruction opcode and
1664       /// parent.
1665       unsigned NumOpsWithSameOpcodeParent = 0;
1666       /// Hash for the actual operands ordering.
1667       /// Used to count operands, actually their position id and opcode
1668       /// value. It is used in the voting mechanism to find the lane with the
1669       /// least number of operands that can freely move about or less profitable
1670       /// because it already has the most optimal set of operands. Can be
1671       /// replaced with SmallVector<unsigned> instead but hash code is faster
1672       /// and requires less memory.
1673       unsigned Hash = 0;
1674     };
1675     /// \returns the maximum number of operands that are allowed to be reordered
1676     /// for \p Lane and the number of compatible instructions(with the same
1677     /// parent/opcode). This is used as a heuristic for selecting the first lane
1678     /// to start operand reordering.
1679     OperandsOrderData getMaxNumOperandsThatCanBeReordered(unsigned Lane) const {
1680       unsigned CntTrue = 0;
1681       unsigned NumOperands = getNumOperands();
1682       // Operands with the same APO can be reordered. We therefore need to count
1683       // how many of them we have for each APO, like this: Cnt[APO] = x.
1684       // Since we only have two APOs, namely true and false, we can avoid using
1685       // a map. Instead we can simply count the number of operands that
1686       // correspond to one of them (in this case the 'true' APO), and calculate
1687       // the other by subtracting it from the total number of operands.
1688       // Operands with the same instruction opcode and parent are more
1689       // profitable since we don't need to move them in many cases, with a high
1690       // probability such lane already can be vectorized effectively.
1691       bool AllUndefs = true;
1692       unsigned NumOpsWithSameOpcodeParent = 0;
1693       Instruction *OpcodeI = nullptr;
1694       BasicBlock *Parent = nullptr;
1695       unsigned Hash = 0;
1696       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1697         const OperandData &OpData = getData(OpIdx, Lane);
1698         if (OpData.APO)
1699           ++CntTrue;
1700         // Use Boyer-Moore majority voting for finding the majority opcode and
1701         // the number of times it occurs.
1702         if (auto *I = dyn_cast<Instruction>(OpData.V)) {
1703           if (!OpcodeI || !getSameOpcode({OpcodeI, I}).getOpcode() ||
1704               I->getParent() != Parent) {
1705             if (NumOpsWithSameOpcodeParent == 0) {
1706               NumOpsWithSameOpcodeParent = 1;
1707               OpcodeI = I;
1708               Parent = I->getParent();
1709             } else {
1710               --NumOpsWithSameOpcodeParent;
1711             }
1712           } else {
1713             ++NumOpsWithSameOpcodeParent;
1714           }
1715         }
1716         Hash = hash_combine(
1717             Hash, hash_value((OpIdx + 1) * (OpData.V->getValueID() + 1)));
1718         AllUndefs = AllUndefs && isa<UndefValue>(OpData.V);
1719       }
1720       if (AllUndefs)
1721         return {};
1722       OperandsOrderData Data;
1723       Data.NumOfAPOs = std::max(CntTrue, NumOperands - CntTrue);
1724       Data.NumOpsWithSameOpcodeParent = NumOpsWithSameOpcodeParent;
1725       Data.Hash = Hash;
1726       return Data;
1727     }
1728 
1729     /// Go through the instructions in VL and append their operands.
1730     void appendOperandsOfVL(ArrayRef<Value *> VL) {
1731       assert(!VL.empty() && "Bad VL");
1732       assert((empty() || VL.size() == getNumLanes()) &&
1733              "Expected same number of lanes");
1734       assert(isa<Instruction>(VL[0]) && "Expected instruction");
1735       unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands();
1736       OpsVec.resize(NumOperands);
1737       unsigned NumLanes = VL.size();
1738       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1739         OpsVec[OpIdx].resize(NumLanes);
1740         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1741           assert(isa<Instruction>(VL[Lane]) && "Expected instruction");
1742           // Our tree has just 3 nodes: the root and two operands.
1743           // It is therefore trivial to get the APO. We only need to check the
1744           // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or
1745           // RHS operand. The LHS operand of both add and sub is never attached
1746           // to an inversese operation in the linearized form, therefore its APO
1747           // is false. The RHS is true only if VL[Lane] is an inverse operation.
1748 
1749           // Since operand reordering is performed on groups of commutative
1750           // operations or alternating sequences (e.g., +, -), we can safely
1751           // tell the inverse operations by checking commutativity.
1752           bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane]));
1753           bool APO = (OpIdx == 0) ? false : IsInverseOperation;
1754           OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx),
1755                                  APO, false};
1756         }
1757       }
1758     }
1759 
1760     /// \returns the number of operands.
1761     unsigned getNumOperands() const { return OpsVec.size(); }
1762 
1763     /// \returns the number of lanes.
1764     unsigned getNumLanes() const { return OpsVec[0].size(); }
1765 
1766     /// \returns the operand value at \p OpIdx and \p Lane.
1767     Value *getValue(unsigned OpIdx, unsigned Lane) const {
1768       return getData(OpIdx, Lane).V;
1769     }
1770 
1771     /// \returns true if the data structure is empty.
1772     bool empty() const { return OpsVec.empty(); }
1773 
1774     /// Clears the data.
1775     void clear() { OpsVec.clear(); }
1776 
1777     /// \Returns true if there are enough operands identical to \p Op to fill
1778     /// the whole vector.
1779     /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow.
1780     bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) {
1781       bool OpAPO = getData(OpIdx, Lane).APO;
1782       for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) {
1783         if (Ln == Lane)
1784           continue;
1785         // This is set to true if we found a candidate for broadcast at Lane.
1786         bool FoundCandidate = false;
1787         for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) {
1788           OperandData &Data = getData(OpI, Ln);
1789           if (Data.APO != OpAPO || Data.IsUsed)
1790             continue;
1791           if (Data.V == Op) {
1792             FoundCandidate = true;
1793             Data.IsUsed = true;
1794             break;
1795           }
1796         }
1797         if (!FoundCandidate)
1798           return false;
1799       }
1800       return true;
1801     }
1802 
1803   public:
1804     /// Initialize with all the operands of the instruction vector \p RootVL.
1805     VLOperands(ArrayRef<Value *> RootVL, const DataLayout &DL,
1806                ScalarEvolution &SE, const BoUpSLP &R)
1807         : DL(DL), SE(SE), R(R) {
1808       // Append all the operands of RootVL.
1809       appendOperandsOfVL(RootVL);
1810     }
1811 
1812     /// \Returns a value vector with the operands across all lanes for the
1813     /// opearnd at \p OpIdx.
1814     ValueList getVL(unsigned OpIdx) const {
1815       ValueList OpVL(OpsVec[OpIdx].size());
1816       assert(OpsVec[OpIdx].size() == getNumLanes() &&
1817              "Expected same num of lanes across all operands");
1818       for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane)
1819         OpVL[Lane] = OpsVec[OpIdx][Lane].V;
1820       return OpVL;
1821     }
1822 
1823     // Performs operand reordering for 2 or more operands.
1824     // The original operands are in OrigOps[OpIdx][Lane].
1825     // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'.
1826     void reorder() {
1827       unsigned NumOperands = getNumOperands();
1828       unsigned NumLanes = getNumLanes();
1829       // Each operand has its own mode. We are using this mode to help us select
1830       // the instructions for each lane, so that they match best with the ones
1831       // we have selected so far.
1832       SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands);
1833 
1834       // This is a greedy single-pass algorithm. We are going over each lane
1835       // once and deciding on the best order right away with no back-tracking.
1836       // However, in order to increase its effectiveness, we start with the lane
1837       // that has operands that can move the least. For example, given the
1838       // following lanes:
1839       //  Lane 0 : A[0] = B[0] + C[0]   // Visited 3rd
1840       //  Lane 1 : A[1] = C[1] - B[1]   // Visited 1st
1841       //  Lane 2 : A[2] = B[2] + C[2]   // Visited 2nd
1842       //  Lane 3 : A[3] = C[3] - B[3]   // Visited 4th
1843       // we will start at Lane 1, since the operands of the subtraction cannot
1844       // be reordered. Then we will visit the rest of the lanes in a circular
1845       // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3.
1846 
1847       // Find the first lane that we will start our search from.
1848       unsigned FirstLane = getBestLaneToStartReordering();
1849 
1850       // Initialize the modes.
1851       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1852         Value *OpLane0 = getValue(OpIdx, FirstLane);
1853         // Keep track if we have instructions with all the same opcode on one
1854         // side.
1855         if (isa<LoadInst>(OpLane0))
1856           ReorderingModes[OpIdx] = ReorderingMode::Load;
1857         else if (isa<Instruction>(OpLane0)) {
1858           // Check if OpLane0 should be broadcast.
1859           if (shouldBroadcast(OpLane0, OpIdx, FirstLane))
1860             ReorderingModes[OpIdx] = ReorderingMode::Splat;
1861           else
1862             ReorderingModes[OpIdx] = ReorderingMode::Opcode;
1863         }
1864         else if (isa<Constant>(OpLane0))
1865           ReorderingModes[OpIdx] = ReorderingMode::Constant;
1866         else if (isa<Argument>(OpLane0))
1867           // Our best hope is a Splat. It may save some cost in some cases.
1868           ReorderingModes[OpIdx] = ReorderingMode::Splat;
1869         else
1870           // NOTE: This should be unreachable.
1871           ReorderingModes[OpIdx] = ReorderingMode::Failed;
1872       }
1873 
1874       // Check that we don't have same operands. No need to reorder if operands
1875       // are just perfect diamond or shuffled diamond match. Do not do it only
1876       // for possible broadcasts or non-power of 2 number of scalars (just for
1877       // now).
1878       auto &&SkipReordering = [this]() {
1879         SmallPtrSet<Value *, 4> UniqueValues;
1880         ArrayRef<OperandData> Op0 = OpsVec.front();
1881         for (const OperandData &Data : Op0)
1882           UniqueValues.insert(Data.V);
1883         for (ArrayRef<OperandData> Op : drop_begin(OpsVec, 1)) {
1884           if (any_of(Op, [&UniqueValues](const OperandData &Data) {
1885                 return !UniqueValues.contains(Data.V);
1886               }))
1887             return false;
1888         }
1889         // TODO: Check if we can remove a check for non-power-2 number of
1890         // scalars after full support of non-power-2 vectorization.
1891         return UniqueValues.size() != 2 && isPowerOf2_32(UniqueValues.size());
1892       };
1893 
1894       // If the initial strategy fails for any of the operand indexes, then we
1895       // perform reordering again in a second pass. This helps avoid assigning
1896       // high priority to the failed strategy, and should improve reordering for
1897       // the non-failed operand indexes.
1898       for (int Pass = 0; Pass != 2; ++Pass) {
1899         // Check if no need to reorder operands since they're are perfect or
1900         // shuffled diamond match.
1901         // Need to to do it to avoid extra external use cost counting for
1902         // shuffled matches, which may cause regressions.
1903         if (SkipReordering())
1904           break;
1905         // Skip the second pass if the first pass did not fail.
1906         bool StrategyFailed = false;
1907         // Mark all operand data as free to use.
1908         clearUsed();
1909         // We keep the original operand order for the FirstLane, so reorder the
1910         // rest of the lanes. We are visiting the nodes in a circular fashion,
1911         // using FirstLane as the center point and increasing the radius
1912         // distance.
1913         SmallVector<SmallVector<Value *, 2>> MainAltOps(NumOperands);
1914         for (unsigned I = 0; I < NumOperands; ++I)
1915           MainAltOps[I].push_back(getData(I, FirstLane).V);
1916 
1917         for (unsigned Distance = 1; Distance != NumLanes; ++Distance) {
1918           // Visit the lane on the right and then the lane on the left.
1919           for (int Direction : {+1, -1}) {
1920             int Lane = FirstLane + Direction * Distance;
1921             if (Lane < 0 || Lane >= (int)NumLanes)
1922               continue;
1923             int LastLane = Lane - Direction;
1924             assert(LastLane >= 0 && LastLane < (int)NumLanes &&
1925                    "Out of bounds");
1926             // Look for a good match for each operand.
1927             for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1928               // Search for the operand that matches SortedOps[OpIdx][Lane-1].
1929               Optional<unsigned> BestIdx = getBestOperand(
1930                   OpIdx, Lane, LastLane, ReorderingModes, MainAltOps[OpIdx]);
1931               // By not selecting a value, we allow the operands that follow to
1932               // select a better matching value. We will get a non-null value in
1933               // the next run of getBestOperand().
1934               if (BestIdx) {
1935                 // Swap the current operand with the one returned by
1936                 // getBestOperand().
1937                 swap(OpIdx, BestIdx.getValue(), Lane);
1938               } else {
1939                 // We failed to find a best operand, set mode to 'Failed'.
1940                 ReorderingModes[OpIdx] = ReorderingMode::Failed;
1941                 // Enable the second pass.
1942                 StrategyFailed = true;
1943               }
1944               // Try to get the alternate opcode and follow it during analysis.
1945               if (MainAltOps[OpIdx].size() != 2) {
1946                 OperandData &AltOp = getData(OpIdx, Lane);
1947                 InstructionsState OpS =
1948                     getSameOpcode({MainAltOps[OpIdx].front(), AltOp.V});
1949                 if (OpS.getOpcode() && OpS.isAltShuffle())
1950                   MainAltOps[OpIdx].push_back(AltOp.V);
1951               }
1952             }
1953           }
1954         }
1955         // Skip second pass if the strategy did not fail.
1956         if (!StrategyFailed)
1957           break;
1958       }
1959     }
1960 
1961 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1962     LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) {
1963       switch (RMode) {
1964       case ReorderingMode::Load:
1965         return "Load";
1966       case ReorderingMode::Opcode:
1967         return "Opcode";
1968       case ReorderingMode::Constant:
1969         return "Constant";
1970       case ReorderingMode::Splat:
1971         return "Splat";
1972       case ReorderingMode::Failed:
1973         return "Failed";
1974       }
1975       llvm_unreachable("Unimplemented Reordering Type");
1976     }
1977 
1978     LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode,
1979                                                    raw_ostream &OS) {
1980       return OS << getModeStr(RMode);
1981     }
1982 
1983     /// Debug print.
1984     LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) {
1985       printMode(RMode, dbgs());
1986     }
1987 
1988     friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) {
1989       return printMode(RMode, OS);
1990     }
1991 
1992     LLVM_DUMP_METHOD raw_ostream &print(raw_ostream &OS) const {
1993       const unsigned Indent = 2;
1994       unsigned Cnt = 0;
1995       for (const OperandDataVec &OpDataVec : OpsVec) {
1996         OS << "Operand " << Cnt++ << "\n";
1997         for (const OperandData &OpData : OpDataVec) {
1998           OS.indent(Indent) << "{";
1999           if (Value *V = OpData.V)
2000             OS << *V;
2001           else
2002             OS << "null";
2003           OS << ", APO:" << OpData.APO << "}\n";
2004         }
2005         OS << "\n";
2006       }
2007       return OS;
2008     }
2009 
2010     /// Debug print.
2011     LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
2012 #endif
2013   };
2014 
2015   /// Evaluate each pair in \p Candidates and return index into \p Candidates
2016   /// for a pair which have highest score deemed to have best chance to form
2017   /// root of profitable tree to vectorize. Return None if no candidate scored
2018   /// above the LookAheadHeuristics::ScoreFail.
2019   /// \param Limit Lower limit of the cost, considered to be good enough score.
2020   Optional<int>
2021   findBestRootPair(ArrayRef<std::pair<Value *, Value *>> Candidates,
2022                    int Limit = LookAheadHeuristics::ScoreFail) {
2023     LookAheadHeuristics LookAhead(*DL, *SE, *this, /*NumLanes=*/2,
2024                                   RootLookAheadMaxDepth);
2025     int BestScore = Limit;
2026     Optional<int> Index = None;
2027     for (int I : seq<int>(0, Candidates.size())) {
2028       int Score = LookAhead.getScoreAtLevelRec(Candidates[I].first,
2029                                                Candidates[I].second,
2030                                                /*U1=*/nullptr, /*U2=*/nullptr,
2031                                                /*Level=*/1, None);
2032       if (Score > BestScore) {
2033         BestScore = Score;
2034         Index = I;
2035       }
2036     }
2037     return Index;
2038   }
2039 
2040   /// Checks if the instruction is marked for deletion.
2041   bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); }
2042 
2043   /// Removes an instruction from its block and eventually deletes it.
2044   /// It's like Instruction::eraseFromParent() except that the actual deletion
2045   /// is delayed until BoUpSLP is destructed.
2046   void eraseInstruction(Instruction *I) {
2047     DeletedInstructions.insert(I);
2048   }
2049 
2050   /// Checks if the instruction was already analyzed for being possible
2051   /// reduction root.
2052   bool isAnalyzedReductionRoot(Instruction *I) const {
2053     return AnalyzedReductionsRoots.count(I);
2054   }
2055   /// Register given instruction as already analyzed for being possible
2056   /// reduction root.
2057   void analyzedReductionRoot(Instruction *I) {
2058     AnalyzedReductionsRoots.insert(I);
2059   }
2060   /// Checks if the provided list of reduced values was checked already for
2061   /// vectorization.
2062   bool areAnalyzedReductionVals(ArrayRef<Value *> VL) {
2063     return AnalyzedReductionVals.contains(hash_value(VL));
2064   }
2065   /// Adds the list of reduced values to list of already checked values for the
2066   /// vectorization.
2067   void analyzedReductionVals(ArrayRef<Value *> VL) {
2068     AnalyzedReductionVals.insert(hash_value(VL));
2069   }
2070   /// Clear the list of the analyzed reduction root instructions.
2071   void clearReductionData() {
2072     AnalyzedReductionsRoots.clear();
2073     AnalyzedReductionVals.clear();
2074   }
2075   /// Checks if the given value is gathered in one of the nodes.
2076   bool isGathered(Value *V) const {
2077     return MustGather.contains(V);
2078   }
2079 
2080   ~BoUpSLP();
2081 
2082 private:
2083   /// Check if the operands on the edges \p Edges of the \p UserTE allows
2084   /// reordering (i.e. the operands can be reordered because they have only one
2085   /// user and reordarable).
2086   /// \param ReorderableGathers List of all gather nodes that require reordering
2087   /// (e.g., gather of extractlements or partially vectorizable loads).
2088   /// \param GatherOps List of gather operand nodes for \p UserTE that require
2089   /// reordering, subset of \p NonVectorized.
2090   bool
2091   canReorderOperands(TreeEntry *UserTE,
2092                      SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
2093                      ArrayRef<TreeEntry *> ReorderableGathers,
2094                      SmallVectorImpl<TreeEntry *> &GatherOps);
2095 
2096   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
2097   /// if any. If it is not vectorized (gather node), returns nullptr.
2098   TreeEntry *getVectorizedOperand(TreeEntry *UserTE, unsigned OpIdx) {
2099     ArrayRef<Value *> VL = UserTE->getOperand(OpIdx);
2100     TreeEntry *TE = nullptr;
2101     const auto *It = find_if(VL, [this, &TE](Value *V) {
2102       TE = getTreeEntry(V);
2103       return TE;
2104     });
2105     if (It != VL.end() && TE->isSame(VL))
2106       return TE;
2107     return nullptr;
2108   }
2109 
2110   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
2111   /// if any. If it is not vectorized (gather node), returns nullptr.
2112   const TreeEntry *getVectorizedOperand(const TreeEntry *UserTE,
2113                                         unsigned OpIdx) const {
2114     return const_cast<BoUpSLP *>(this)->getVectorizedOperand(
2115         const_cast<TreeEntry *>(UserTE), OpIdx);
2116   }
2117 
2118   /// Checks if all users of \p I are the part of the vectorization tree.
2119   bool areAllUsersVectorized(Instruction *I,
2120                              ArrayRef<Value *> VectorizedVals) const;
2121 
2122   /// \returns the cost of the vectorizable entry.
2123   InstructionCost getEntryCost(const TreeEntry *E,
2124                                ArrayRef<Value *> VectorizedVals);
2125 
2126   /// This is the recursive part of buildTree.
2127   void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth,
2128                      const EdgeInfo &EI);
2129 
2130   /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
2131   /// be vectorized to use the original vector (or aggregate "bitcast" to a
2132   /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
2133   /// returns false, setting \p CurrentOrder to either an empty vector or a
2134   /// non-identity permutation that allows to reuse extract instructions.
2135   bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
2136                        SmallVectorImpl<unsigned> &CurrentOrder) const;
2137 
2138   /// Vectorize a single entry in the tree.
2139   Value *vectorizeTree(TreeEntry *E);
2140 
2141   /// Vectorize a single entry in the tree, starting in \p VL.
2142   Value *vectorizeTree(ArrayRef<Value *> VL);
2143 
2144   /// Create a new vector from a list of scalar values.  Produces a sequence
2145   /// which exploits values reused across lanes, and arranges the inserts
2146   /// for ease of later optimization.
2147   Value *createBuildVector(ArrayRef<Value *> VL);
2148 
2149   /// \returns the scalarization cost for this type. Scalarization in this
2150   /// context means the creation of vectors from a group of scalars. If \p
2151   /// NeedToShuffle is true, need to add a cost of reshuffling some of the
2152   /// vector elements.
2153   InstructionCost getGatherCost(FixedVectorType *Ty,
2154                                 const APInt &ShuffledIndices,
2155                                 bool NeedToShuffle) const;
2156 
2157   /// Checks if the gathered \p VL can be represented as shuffle(s) of previous
2158   /// tree entries.
2159   /// \returns ShuffleKind, if gathered values can be represented as shuffles of
2160   /// previous tree entries. \p Mask is filled with the shuffle mask.
2161   Optional<TargetTransformInfo::ShuffleKind>
2162   isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
2163                         SmallVectorImpl<const TreeEntry *> &Entries);
2164 
2165   /// \returns the scalarization cost for this list of values. Assuming that
2166   /// this subtree gets vectorized, we may need to extract the values from the
2167   /// roots. This method calculates the cost of extracting the values.
2168   InstructionCost getGatherCost(ArrayRef<Value *> VL) const;
2169 
2170   /// Set the Builder insert point to one after the last instruction in
2171   /// the bundle
2172   void setInsertPointAfterBundle(const TreeEntry *E);
2173 
2174   /// \returns a vector from a collection of scalars in \p VL.
2175   Value *gather(ArrayRef<Value *> VL);
2176 
2177   /// \returns whether the VectorizableTree is fully vectorizable and will
2178   /// be beneficial even the tree height is tiny.
2179   bool isFullyVectorizableTinyTree(bool ForReduction) const;
2180 
2181   /// Reorder commutative or alt operands to get better probability of
2182   /// generating vectorized code.
2183   static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
2184                                              SmallVectorImpl<Value *> &Left,
2185                                              SmallVectorImpl<Value *> &Right,
2186                                              const DataLayout &DL,
2187                                              ScalarEvolution &SE,
2188                                              const BoUpSLP &R);
2189 
2190   /// Helper for `findExternalStoreUsersReorderIndices()`. It iterates over the
2191   /// users of \p TE and collects the stores. It returns the map from the store
2192   /// pointers to the collected stores.
2193   DenseMap<Value *, SmallVector<StoreInst *, 4>>
2194   collectUserStores(const BoUpSLP::TreeEntry *TE) const;
2195 
2196   /// Helper for `findExternalStoreUsersReorderIndices()`. It checks if the
2197   /// stores in \p StoresVec can for a vector instruction. If so it returns true
2198   /// and populates \p ReorderIndices with the shuffle indices of the the stores
2199   /// when compared to the sorted vector.
2200   bool CanFormVector(const SmallVector<StoreInst *, 4> &StoresVec,
2201                      OrdersType &ReorderIndices) const;
2202 
2203   /// Iterates through the users of \p TE, looking for scalar stores that can be
2204   /// potentially vectorized in a future SLP-tree. If found, it keeps track of
2205   /// their order and builds an order index vector for each store bundle. It
2206   /// returns all these order vectors found.
2207   /// We run this after the tree has formed, otherwise we may come across user
2208   /// instructions that are not yet in the tree.
2209   SmallVector<OrdersType, 1>
2210   findExternalStoreUsersReorderIndices(TreeEntry *TE) const;
2211 
2212   struct TreeEntry {
2213     using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>;
2214     TreeEntry(VecTreeTy &Container) : Container(Container) {}
2215 
2216     /// \returns true if the scalars in VL are equal to this entry.
2217     bool isSame(ArrayRef<Value *> VL) const {
2218       auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) {
2219         if (Mask.size() != VL.size() && VL.size() == Scalars.size())
2220           return std::equal(VL.begin(), VL.end(), Scalars.begin());
2221         return VL.size() == Mask.size() &&
2222                std::equal(VL.begin(), VL.end(), Mask.begin(),
2223                           [Scalars](Value *V, int Idx) {
2224                             return (isa<UndefValue>(V) &&
2225                                     Idx == UndefMaskElem) ||
2226                                    (Idx != UndefMaskElem && V == Scalars[Idx]);
2227                           });
2228       };
2229       if (!ReorderIndices.empty()) {
2230         // TODO: implement matching if the nodes are just reordered, still can
2231         // treat the vector as the same if the list of scalars matches VL
2232         // directly, without reordering.
2233         SmallVector<int> Mask;
2234         inversePermutation(ReorderIndices, Mask);
2235         if (VL.size() == Scalars.size())
2236           return IsSame(Scalars, Mask);
2237         if (VL.size() == ReuseShuffleIndices.size()) {
2238           ::addMask(Mask, ReuseShuffleIndices);
2239           return IsSame(Scalars, Mask);
2240         }
2241         return false;
2242       }
2243       return IsSame(Scalars, ReuseShuffleIndices);
2244     }
2245 
2246     /// \returns true if current entry has same operands as \p TE.
2247     bool hasEqualOperands(const TreeEntry &TE) const {
2248       if (TE.getNumOperands() != getNumOperands())
2249         return false;
2250       SmallBitVector Used(getNumOperands());
2251       for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
2252         unsigned PrevCount = Used.count();
2253         for (unsigned K = 0; K < E; ++K) {
2254           if (Used.test(K))
2255             continue;
2256           if (getOperand(K) == TE.getOperand(I)) {
2257             Used.set(K);
2258             break;
2259           }
2260         }
2261         // Check if we actually found the matching operand.
2262         if (PrevCount == Used.count())
2263           return false;
2264       }
2265       return true;
2266     }
2267 
2268     /// \return Final vectorization factor for the node. Defined by the total
2269     /// number of vectorized scalars, including those, used several times in the
2270     /// entry and counted in the \a ReuseShuffleIndices, if any.
2271     unsigned getVectorFactor() const {
2272       if (!ReuseShuffleIndices.empty())
2273         return ReuseShuffleIndices.size();
2274       return Scalars.size();
2275     };
2276 
2277     /// A vector of scalars.
2278     ValueList Scalars;
2279 
2280     /// The Scalars are vectorized into this value. It is initialized to Null.
2281     Value *VectorizedValue = nullptr;
2282 
2283     /// Do we need to gather this sequence or vectorize it
2284     /// (either with vector instruction or with scatter/gather
2285     /// intrinsics for store/load)?
2286     enum EntryState { Vectorize, ScatterVectorize, NeedToGather };
2287     EntryState State;
2288 
2289     /// Does this sequence require some shuffling?
2290     SmallVector<int, 4> ReuseShuffleIndices;
2291 
2292     /// Does this entry require reordering?
2293     SmallVector<unsigned, 4> ReorderIndices;
2294 
2295     /// Points back to the VectorizableTree.
2296     ///
2297     /// Only used for Graphviz right now.  Unfortunately GraphTrait::NodeRef has
2298     /// to be a pointer and needs to be able to initialize the child iterator.
2299     /// Thus we need a reference back to the container to translate the indices
2300     /// to entries.
2301     VecTreeTy &Container;
2302 
2303     /// The TreeEntry index containing the user of this entry.  We can actually
2304     /// have multiple users so the data structure is not truly a tree.
2305     SmallVector<EdgeInfo, 1> UserTreeIndices;
2306 
2307     /// The index of this treeEntry in VectorizableTree.
2308     int Idx = -1;
2309 
2310   private:
2311     /// The operands of each instruction in each lane Operands[op_index][lane].
2312     /// Note: This helps avoid the replication of the code that performs the
2313     /// reordering of operands during buildTree_rec() and vectorizeTree().
2314     SmallVector<ValueList, 2> Operands;
2315 
2316     /// The main/alternate instruction.
2317     Instruction *MainOp = nullptr;
2318     Instruction *AltOp = nullptr;
2319 
2320   public:
2321     /// Set this bundle's \p OpIdx'th operand to \p OpVL.
2322     void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) {
2323       if (Operands.size() < OpIdx + 1)
2324         Operands.resize(OpIdx + 1);
2325       assert(Operands[OpIdx].empty() && "Already resized?");
2326       assert(OpVL.size() <= Scalars.size() &&
2327              "Number of operands is greater than the number of scalars.");
2328       Operands[OpIdx].resize(OpVL.size());
2329       copy(OpVL, Operands[OpIdx].begin());
2330     }
2331 
2332     /// Set the operands of this bundle in their original order.
2333     void setOperandsInOrder() {
2334       assert(Operands.empty() && "Already initialized?");
2335       auto *I0 = cast<Instruction>(Scalars[0]);
2336       Operands.resize(I0->getNumOperands());
2337       unsigned NumLanes = Scalars.size();
2338       for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands();
2339            OpIdx != NumOperands; ++OpIdx) {
2340         Operands[OpIdx].resize(NumLanes);
2341         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
2342           auto *I = cast<Instruction>(Scalars[Lane]);
2343           assert(I->getNumOperands() == NumOperands &&
2344                  "Expected same number of operands");
2345           Operands[OpIdx][Lane] = I->getOperand(OpIdx);
2346         }
2347       }
2348     }
2349 
2350     /// Reorders operands of the node to the given mask \p Mask.
2351     void reorderOperands(ArrayRef<int> Mask) {
2352       for (ValueList &Operand : Operands)
2353         reorderScalars(Operand, Mask);
2354     }
2355 
2356     /// \returns the \p OpIdx operand of this TreeEntry.
2357     ValueList &getOperand(unsigned OpIdx) {
2358       assert(OpIdx < Operands.size() && "Off bounds");
2359       return Operands[OpIdx];
2360     }
2361 
2362     /// \returns the \p OpIdx operand of this TreeEntry.
2363     ArrayRef<Value *> getOperand(unsigned OpIdx) const {
2364       assert(OpIdx < Operands.size() && "Off bounds");
2365       return Operands[OpIdx];
2366     }
2367 
2368     /// \returns the number of operands.
2369     unsigned getNumOperands() const { return Operands.size(); }
2370 
2371     /// \return the single \p OpIdx operand.
2372     Value *getSingleOperand(unsigned OpIdx) const {
2373       assert(OpIdx < Operands.size() && "Off bounds");
2374       assert(!Operands[OpIdx].empty() && "No operand available");
2375       return Operands[OpIdx][0];
2376     }
2377 
2378     /// Some of the instructions in the list have alternate opcodes.
2379     bool isAltShuffle() const { return MainOp != AltOp; }
2380 
2381     bool isOpcodeOrAlt(Instruction *I) const {
2382       unsigned CheckedOpcode = I->getOpcode();
2383       return (getOpcode() == CheckedOpcode ||
2384               getAltOpcode() == CheckedOpcode);
2385     }
2386 
2387     /// Chooses the correct key for scheduling data. If \p Op has the same (or
2388     /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is
2389     /// \p OpValue.
2390     Value *isOneOf(Value *Op) const {
2391       auto *I = dyn_cast<Instruction>(Op);
2392       if (I && isOpcodeOrAlt(I))
2393         return Op;
2394       return MainOp;
2395     }
2396 
2397     void setOperations(const InstructionsState &S) {
2398       MainOp = S.MainOp;
2399       AltOp = S.AltOp;
2400     }
2401 
2402     Instruction *getMainOp() const {
2403       return MainOp;
2404     }
2405 
2406     Instruction *getAltOp() const {
2407       return AltOp;
2408     }
2409 
2410     /// The main/alternate opcodes for the list of instructions.
2411     unsigned getOpcode() const {
2412       return MainOp ? MainOp->getOpcode() : 0;
2413     }
2414 
2415     unsigned getAltOpcode() const {
2416       return AltOp ? AltOp->getOpcode() : 0;
2417     }
2418 
2419     /// When ReuseReorderShuffleIndices is empty it just returns position of \p
2420     /// V within vector of Scalars. Otherwise, try to remap on its reuse index.
2421     int findLaneForValue(Value *V) const {
2422       unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V));
2423       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2424       if (!ReorderIndices.empty())
2425         FoundLane = ReorderIndices[FoundLane];
2426       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2427       if (!ReuseShuffleIndices.empty()) {
2428         FoundLane = std::distance(ReuseShuffleIndices.begin(),
2429                                   find(ReuseShuffleIndices, FoundLane));
2430       }
2431       return FoundLane;
2432     }
2433 
2434 #ifndef NDEBUG
2435     /// Debug printer.
2436     LLVM_DUMP_METHOD void dump() const {
2437       dbgs() << Idx << ".\n";
2438       for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) {
2439         dbgs() << "Operand " << OpI << ":\n";
2440         for (const Value *V : Operands[OpI])
2441           dbgs().indent(2) << *V << "\n";
2442       }
2443       dbgs() << "Scalars: \n";
2444       for (Value *V : Scalars)
2445         dbgs().indent(2) << *V << "\n";
2446       dbgs() << "State: ";
2447       switch (State) {
2448       case Vectorize:
2449         dbgs() << "Vectorize\n";
2450         break;
2451       case ScatterVectorize:
2452         dbgs() << "ScatterVectorize\n";
2453         break;
2454       case NeedToGather:
2455         dbgs() << "NeedToGather\n";
2456         break;
2457       }
2458       dbgs() << "MainOp: ";
2459       if (MainOp)
2460         dbgs() << *MainOp << "\n";
2461       else
2462         dbgs() << "NULL\n";
2463       dbgs() << "AltOp: ";
2464       if (AltOp)
2465         dbgs() << *AltOp << "\n";
2466       else
2467         dbgs() << "NULL\n";
2468       dbgs() << "VectorizedValue: ";
2469       if (VectorizedValue)
2470         dbgs() << *VectorizedValue << "\n";
2471       else
2472         dbgs() << "NULL\n";
2473       dbgs() << "ReuseShuffleIndices: ";
2474       if (ReuseShuffleIndices.empty())
2475         dbgs() << "Empty";
2476       else
2477         for (int ReuseIdx : ReuseShuffleIndices)
2478           dbgs() << ReuseIdx << ", ";
2479       dbgs() << "\n";
2480       dbgs() << "ReorderIndices: ";
2481       for (unsigned ReorderIdx : ReorderIndices)
2482         dbgs() << ReorderIdx << ", ";
2483       dbgs() << "\n";
2484       dbgs() << "UserTreeIndices: ";
2485       for (const auto &EInfo : UserTreeIndices)
2486         dbgs() << EInfo << ", ";
2487       dbgs() << "\n";
2488     }
2489 #endif
2490   };
2491 
2492 #ifndef NDEBUG
2493   void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost,
2494                      InstructionCost VecCost,
2495                      InstructionCost ScalarCost) const {
2496     dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump();
2497     dbgs() << "SLP: Costs:\n";
2498     dbgs() << "SLP:     ReuseShuffleCost = " << ReuseShuffleCost << "\n";
2499     dbgs() << "SLP:     VectorCost = " << VecCost << "\n";
2500     dbgs() << "SLP:     ScalarCost = " << ScalarCost << "\n";
2501     dbgs() << "SLP:     ReuseShuffleCost + VecCost - ScalarCost = " <<
2502                ReuseShuffleCost + VecCost - ScalarCost << "\n";
2503   }
2504 #endif
2505 
2506   /// Create a new VectorizableTree entry.
2507   TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle,
2508                           const InstructionsState &S,
2509                           const EdgeInfo &UserTreeIdx,
2510                           ArrayRef<int> ReuseShuffleIndices = None,
2511                           ArrayRef<unsigned> ReorderIndices = None) {
2512     TreeEntry::EntryState EntryState =
2513         Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather;
2514     return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx,
2515                         ReuseShuffleIndices, ReorderIndices);
2516   }
2517 
2518   TreeEntry *newTreeEntry(ArrayRef<Value *> VL,
2519                           TreeEntry::EntryState EntryState,
2520                           Optional<ScheduleData *> Bundle,
2521                           const InstructionsState &S,
2522                           const EdgeInfo &UserTreeIdx,
2523                           ArrayRef<int> ReuseShuffleIndices = None,
2524                           ArrayRef<unsigned> ReorderIndices = None) {
2525     assert(((!Bundle && EntryState == TreeEntry::NeedToGather) ||
2526             (Bundle && EntryState != TreeEntry::NeedToGather)) &&
2527            "Need to vectorize gather entry?");
2528     VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree));
2529     TreeEntry *Last = VectorizableTree.back().get();
2530     Last->Idx = VectorizableTree.size() - 1;
2531     Last->State = EntryState;
2532     Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
2533                                      ReuseShuffleIndices.end());
2534     if (ReorderIndices.empty()) {
2535       Last->Scalars.assign(VL.begin(), VL.end());
2536       Last->setOperations(S);
2537     } else {
2538       // Reorder scalars and build final mask.
2539       Last->Scalars.assign(VL.size(), nullptr);
2540       transform(ReorderIndices, Last->Scalars.begin(),
2541                 [VL](unsigned Idx) -> Value * {
2542                   if (Idx >= VL.size())
2543                     return UndefValue::get(VL.front()->getType());
2544                   return VL[Idx];
2545                 });
2546       InstructionsState S = getSameOpcode(Last->Scalars);
2547       Last->setOperations(S);
2548       Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end());
2549     }
2550     if (Last->State != TreeEntry::NeedToGather) {
2551       for (Value *V : VL) {
2552         assert(!getTreeEntry(V) && "Scalar already in tree!");
2553         ScalarToTreeEntry[V] = Last;
2554       }
2555       // Update the scheduler bundle to point to this TreeEntry.
2556       ScheduleData *BundleMember = Bundle.getValue();
2557       assert((BundleMember || isa<PHINode>(S.MainOp) ||
2558               isVectorLikeInstWithConstOps(S.MainOp) ||
2559               doesNotNeedToSchedule(VL)) &&
2560              "Bundle and VL out of sync");
2561       if (BundleMember) {
2562         for (Value *V : VL) {
2563           if (doesNotNeedToBeScheduled(V))
2564             continue;
2565           assert(BundleMember && "Unexpected end of bundle.");
2566           BundleMember->TE = Last;
2567           BundleMember = BundleMember->NextInBundle;
2568         }
2569       }
2570       assert(!BundleMember && "Bundle and VL out of sync");
2571     } else {
2572       MustGather.insert(VL.begin(), VL.end());
2573     }
2574 
2575     if (UserTreeIdx.UserTE)
2576       Last->UserTreeIndices.push_back(UserTreeIdx);
2577 
2578     return Last;
2579   }
2580 
2581   /// -- Vectorization State --
2582   /// Holds all of the tree entries.
2583   TreeEntry::VecTreeTy VectorizableTree;
2584 
2585 #ifndef NDEBUG
2586   /// Debug printer.
2587   LLVM_DUMP_METHOD void dumpVectorizableTree() const {
2588     for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) {
2589       VectorizableTree[Id]->dump();
2590       dbgs() << "\n";
2591     }
2592   }
2593 #endif
2594 
2595   TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); }
2596 
2597   const TreeEntry *getTreeEntry(Value *V) const {
2598     return ScalarToTreeEntry.lookup(V);
2599   }
2600 
2601   /// Maps a specific scalar to its tree entry.
2602   SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry;
2603 
2604   /// Maps a value to the proposed vectorizable size.
2605   SmallDenseMap<Value *, unsigned> InstrElementSize;
2606 
2607   /// A list of scalars that we found that we need to keep as scalars.
2608   ValueSet MustGather;
2609 
2610   /// This POD struct describes one external user in the vectorized tree.
2611   struct ExternalUser {
2612     ExternalUser(Value *S, llvm::User *U, int L)
2613         : Scalar(S), User(U), Lane(L) {}
2614 
2615     // Which scalar in our function.
2616     Value *Scalar;
2617 
2618     // Which user that uses the scalar.
2619     llvm::User *User;
2620 
2621     // Which lane does the scalar belong to.
2622     int Lane;
2623   };
2624   using UserList = SmallVector<ExternalUser, 16>;
2625 
2626   /// Checks if two instructions may access the same memory.
2627   ///
2628   /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
2629   /// is invariant in the calling loop.
2630   bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
2631                  Instruction *Inst2) {
2632     // First check if the result is already in the cache.
2633     AliasCacheKey key = std::make_pair(Inst1, Inst2);
2634     Optional<bool> &result = AliasCache[key];
2635     if (result.hasValue()) {
2636       return result.getValue();
2637     }
2638     bool aliased = true;
2639     if (Loc1.Ptr && isSimple(Inst1))
2640       aliased = isModOrRefSet(BatchAA.getModRefInfo(Inst2, Loc1));
2641     // Store the result in the cache.
2642     result = aliased;
2643     return aliased;
2644   }
2645 
2646   using AliasCacheKey = std::pair<Instruction *, Instruction *>;
2647 
2648   /// Cache for alias results.
2649   /// TODO: consider moving this to the AliasAnalysis itself.
2650   DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
2651 
2652   // Cache for pointerMayBeCaptured calls inside AA.  This is preserved
2653   // globally through SLP because we don't perform any action which
2654   // invalidates capture results.
2655   BatchAAResults BatchAA;
2656 
2657   /// Temporary store for deleted instructions. Instructions will be deleted
2658   /// eventually when the BoUpSLP is destructed.  The deferral is required to
2659   /// ensure that there are no incorrect collisions in the AliasCache, which
2660   /// can happen if a new instruction is allocated at the same address as a
2661   /// previously deleted instruction.
2662   DenseSet<Instruction *> DeletedInstructions;
2663 
2664   /// Set of the instruction, being analyzed already for reductions.
2665   SmallPtrSet<Instruction *, 16> AnalyzedReductionsRoots;
2666 
2667   /// Set of hashes for the list of reduction values already being analyzed.
2668   DenseSet<size_t> AnalyzedReductionVals;
2669 
2670   /// A list of values that need to extracted out of the tree.
2671   /// This list holds pairs of (Internal Scalar : External User). External User
2672   /// can be nullptr, it means that this Internal Scalar will be used later,
2673   /// after vectorization.
2674   UserList ExternalUses;
2675 
2676   /// Values used only by @llvm.assume calls.
2677   SmallPtrSet<const Value *, 32> EphValues;
2678 
2679   /// Holds all of the instructions that we gathered.
2680   SetVector<Instruction *> GatherShuffleSeq;
2681 
2682   /// A list of blocks that we are going to CSE.
2683   SetVector<BasicBlock *> CSEBlocks;
2684 
2685   /// Contains all scheduling relevant data for an instruction.
2686   /// A ScheduleData either represents a single instruction or a member of an
2687   /// instruction bundle (= a group of instructions which is combined into a
2688   /// vector instruction).
2689   struct ScheduleData {
2690     // The initial value for the dependency counters. It means that the
2691     // dependencies are not calculated yet.
2692     enum { InvalidDeps = -1 };
2693 
2694     ScheduleData() = default;
2695 
2696     void init(int BlockSchedulingRegionID, Value *OpVal) {
2697       FirstInBundle = this;
2698       NextInBundle = nullptr;
2699       NextLoadStore = nullptr;
2700       IsScheduled = false;
2701       SchedulingRegionID = BlockSchedulingRegionID;
2702       clearDependencies();
2703       OpValue = OpVal;
2704       TE = nullptr;
2705     }
2706 
2707     /// Verify basic self consistency properties
2708     void verify() {
2709       if (hasValidDependencies()) {
2710         assert(UnscheduledDeps <= Dependencies && "invariant");
2711       } else {
2712         assert(UnscheduledDeps == Dependencies && "invariant");
2713       }
2714 
2715       if (IsScheduled) {
2716         assert(isSchedulingEntity() &&
2717                 "unexpected scheduled state");
2718         for (const ScheduleData *BundleMember = this; BundleMember;
2719              BundleMember = BundleMember->NextInBundle) {
2720           assert(BundleMember->hasValidDependencies() &&
2721                  BundleMember->UnscheduledDeps == 0 &&
2722                  "unexpected scheduled state");
2723           assert((BundleMember == this || !BundleMember->IsScheduled) &&
2724                  "only bundle is marked scheduled");
2725         }
2726       }
2727 
2728       assert(Inst->getParent() == FirstInBundle->Inst->getParent() &&
2729              "all bundle members must be in same basic block");
2730     }
2731 
2732     /// Returns true if the dependency information has been calculated.
2733     /// Note that depenendency validity can vary between instructions within
2734     /// a single bundle.
2735     bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
2736 
2737     /// Returns true for single instructions and for bundle representatives
2738     /// (= the head of a bundle).
2739     bool isSchedulingEntity() const { return FirstInBundle == this; }
2740 
2741     /// Returns true if it represents an instruction bundle and not only a
2742     /// single instruction.
2743     bool isPartOfBundle() const {
2744       return NextInBundle != nullptr || FirstInBundle != this || TE;
2745     }
2746 
2747     /// Returns true if it is ready for scheduling, i.e. it has no more
2748     /// unscheduled depending instructions/bundles.
2749     bool isReady() const {
2750       assert(isSchedulingEntity() &&
2751              "can't consider non-scheduling entity for ready list");
2752       return unscheduledDepsInBundle() == 0 && !IsScheduled;
2753     }
2754 
2755     /// Modifies the number of unscheduled dependencies for this instruction,
2756     /// and returns the number of remaining dependencies for the containing
2757     /// bundle.
2758     int incrementUnscheduledDeps(int Incr) {
2759       assert(hasValidDependencies() &&
2760              "increment of unscheduled deps would be meaningless");
2761       UnscheduledDeps += Incr;
2762       return FirstInBundle->unscheduledDepsInBundle();
2763     }
2764 
2765     /// Sets the number of unscheduled dependencies to the number of
2766     /// dependencies.
2767     void resetUnscheduledDeps() {
2768       UnscheduledDeps = Dependencies;
2769     }
2770 
2771     /// Clears all dependency information.
2772     void clearDependencies() {
2773       Dependencies = InvalidDeps;
2774       resetUnscheduledDeps();
2775       MemoryDependencies.clear();
2776       ControlDependencies.clear();
2777     }
2778 
2779     int unscheduledDepsInBundle() const {
2780       assert(isSchedulingEntity() && "only meaningful on the bundle");
2781       int Sum = 0;
2782       for (const ScheduleData *BundleMember = this; BundleMember;
2783            BundleMember = BundleMember->NextInBundle) {
2784         if (BundleMember->UnscheduledDeps == InvalidDeps)
2785           return InvalidDeps;
2786         Sum += BundleMember->UnscheduledDeps;
2787       }
2788       return Sum;
2789     }
2790 
2791     void dump(raw_ostream &os) const {
2792       if (!isSchedulingEntity()) {
2793         os << "/ " << *Inst;
2794       } else if (NextInBundle) {
2795         os << '[' << *Inst;
2796         ScheduleData *SD = NextInBundle;
2797         while (SD) {
2798           os << ';' << *SD->Inst;
2799           SD = SD->NextInBundle;
2800         }
2801         os << ']';
2802       } else {
2803         os << *Inst;
2804       }
2805     }
2806 
2807     Instruction *Inst = nullptr;
2808 
2809     /// Opcode of the current instruction in the schedule data.
2810     Value *OpValue = nullptr;
2811 
2812     /// The TreeEntry that this instruction corresponds to.
2813     TreeEntry *TE = nullptr;
2814 
2815     /// Points to the head in an instruction bundle (and always to this for
2816     /// single instructions).
2817     ScheduleData *FirstInBundle = nullptr;
2818 
2819     /// Single linked list of all instructions in a bundle. Null if it is a
2820     /// single instruction.
2821     ScheduleData *NextInBundle = nullptr;
2822 
2823     /// Single linked list of all memory instructions (e.g. load, store, call)
2824     /// in the block - until the end of the scheduling region.
2825     ScheduleData *NextLoadStore = nullptr;
2826 
2827     /// The dependent memory instructions.
2828     /// This list is derived on demand in calculateDependencies().
2829     SmallVector<ScheduleData *, 4> MemoryDependencies;
2830 
2831     /// List of instructions which this instruction could be control dependent
2832     /// on.  Allowing such nodes to be scheduled below this one could introduce
2833     /// a runtime fault which didn't exist in the original program.
2834     /// ex: this is a load or udiv following a readonly call which inf loops
2835     SmallVector<ScheduleData *, 4> ControlDependencies;
2836 
2837     /// This ScheduleData is in the current scheduling region if this matches
2838     /// the current SchedulingRegionID of BlockScheduling.
2839     int SchedulingRegionID = 0;
2840 
2841     /// Used for getting a "good" final ordering of instructions.
2842     int SchedulingPriority = 0;
2843 
2844     /// The number of dependencies. Constitutes of the number of users of the
2845     /// instruction plus the number of dependent memory instructions (if any).
2846     /// This value is calculated on demand.
2847     /// If InvalidDeps, the number of dependencies is not calculated yet.
2848     int Dependencies = InvalidDeps;
2849 
2850     /// The number of dependencies minus the number of dependencies of scheduled
2851     /// instructions. As soon as this is zero, the instruction/bundle gets ready
2852     /// for scheduling.
2853     /// Note that this is negative as long as Dependencies is not calculated.
2854     int UnscheduledDeps = InvalidDeps;
2855 
2856     /// True if this instruction is scheduled (or considered as scheduled in the
2857     /// dry-run).
2858     bool IsScheduled = false;
2859   };
2860 
2861 #ifndef NDEBUG
2862   friend inline raw_ostream &operator<<(raw_ostream &os,
2863                                         const BoUpSLP::ScheduleData &SD) {
2864     SD.dump(os);
2865     return os;
2866   }
2867 #endif
2868 
2869   friend struct GraphTraits<BoUpSLP *>;
2870   friend struct DOTGraphTraits<BoUpSLP *>;
2871 
2872   /// Contains all scheduling data for a basic block.
2873   /// It does not schedules instructions, which are not memory read/write
2874   /// instructions and their operands are either constants, or arguments, or
2875   /// phis, or instructions from others blocks, or their users are phis or from
2876   /// the other blocks. The resulting vector instructions can be placed at the
2877   /// beginning of the basic block without scheduling (if operands does not need
2878   /// to be scheduled) or at the end of the block (if users are outside of the
2879   /// block). It allows to save some compile time and memory used by the
2880   /// compiler.
2881   /// ScheduleData is assigned for each instruction in between the boundaries of
2882   /// the tree entry, even for those, which are not part of the graph. It is
2883   /// required to correctly follow the dependencies between the instructions and
2884   /// their correct scheduling. The ScheduleData is not allocated for the
2885   /// instructions, which do not require scheduling, like phis, nodes with
2886   /// extractelements/insertelements only or nodes with instructions, with
2887   /// uses/operands outside of the block.
2888   struct BlockScheduling {
2889     BlockScheduling(BasicBlock *BB)
2890         : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
2891 
2892     void clear() {
2893       ReadyInsts.clear();
2894       ScheduleStart = nullptr;
2895       ScheduleEnd = nullptr;
2896       FirstLoadStoreInRegion = nullptr;
2897       LastLoadStoreInRegion = nullptr;
2898       RegionHasStackSave = false;
2899 
2900       // Reduce the maximum schedule region size by the size of the
2901       // previous scheduling run.
2902       ScheduleRegionSizeLimit -= ScheduleRegionSize;
2903       if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
2904         ScheduleRegionSizeLimit = MinScheduleRegionSize;
2905       ScheduleRegionSize = 0;
2906 
2907       // Make a new scheduling region, i.e. all existing ScheduleData is not
2908       // in the new region yet.
2909       ++SchedulingRegionID;
2910     }
2911 
2912     ScheduleData *getScheduleData(Instruction *I) {
2913       if (BB != I->getParent())
2914         // Avoid lookup if can't possibly be in map.
2915         return nullptr;
2916       ScheduleData *SD = ScheduleDataMap.lookup(I);
2917       if (SD && isInSchedulingRegion(SD))
2918         return SD;
2919       return nullptr;
2920     }
2921 
2922     ScheduleData *getScheduleData(Value *V) {
2923       if (auto *I = dyn_cast<Instruction>(V))
2924         return getScheduleData(I);
2925       return nullptr;
2926     }
2927 
2928     ScheduleData *getScheduleData(Value *V, Value *Key) {
2929       if (V == Key)
2930         return getScheduleData(V);
2931       auto I = ExtraScheduleDataMap.find(V);
2932       if (I != ExtraScheduleDataMap.end()) {
2933         ScheduleData *SD = I->second.lookup(Key);
2934         if (SD && isInSchedulingRegion(SD))
2935           return SD;
2936       }
2937       return nullptr;
2938     }
2939 
2940     bool isInSchedulingRegion(ScheduleData *SD) const {
2941       return SD->SchedulingRegionID == SchedulingRegionID;
2942     }
2943 
2944     /// Marks an instruction as scheduled and puts all dependent ready
2945     /// instructions into the ready-list.
2946     template <typename ReadyListType>
2947     void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
2948       SD->IsScheduled = true;
2949       LLVM_DEBUG(dbgs() << "SLP:   schedule " << *SD << "\n");
2950 
2951       for (ScheduleData *BundleMember = SD; BundleMember;
2952            BundleMember = BundleMember->NextInBundle) {
2953         if (BundleMember->Inst != BundleMember->OpValue)
2954           continue;
2955 
2956         // Handle the def-use chain dependencies.
2957 
2958         // Decrement the unscheduled counter and insert to ready list if ready.
2959         auto &&DecrUnsched = [this, &ReadyList](Instruction *I) {
2960           doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
2961             if (OpDef && OpDef->hasValidDependencies() &&
2962                 OpDef->incrementUnscheduledDeps(-1) == 0) {
2963               // There are no more unscheduled dependencies after
2964               // decrementing, so we can put the dependent instruction
2965               // into the ready list.
2966               ScheduleData *DepBundle = OpDef->FirstInBundle;
2967               assert(!DepBundle->IsScheduled &&
2968                      "already scheduled bundle gets ready");
2969               ReadyList.insert(DepBundle);
2970               LLVM_DEBUG(dbgs()
2971                          << "SLP:    gets ready (def): " << *DepBundle << "\n");
2972             }
2973           });
2974         };
2975 
2976         // If BundleMember is a vector bundle, its operands may have been
2977         // reordered during buildTree(). We therefore need to get its operands
2978         // through the TreeEntry.
2979         if (TreeEntry *TE = BundleMember->TE) {
2980           // Need to search for the lane since the tree entry can be reordered.
2981           int Lane = std::distance(TE->Scalars.begin(),
2982                                    find(TE->Scalars, BundleMember->Inst));
2983           assert(Lane >= 0 && "Lane not set");
2984 
2985           // Since vectorization tree is being built recursively this assertion
2986           // ensures that the tree entry has all operands set before reaching
2987           // this code. Couple of exceptions known at the moment are extracts
2988           // where their second (immediate) operand is not added. Since
2989           // immediates do not affect scheduler behavior this is considered
2990           // okay.
2991           auto *In = BundleMember->Inst;
2992           assert(In &&
2993                  (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) ||
2994                   In->getNumOperands() == TE->getNumOperands()) &&
2995                  "Missed TreeEntry operands?");
2996           (void)In; // fake use to avoid build failure when assertions disabled
2997 
2998           for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands();
2999                OpIdx != NumOperands; ++OpIdx)
3000             if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane]))
3001               DecrUnsched(I);
3002         } else {
3003           // If BundleMember is a stand-alone instruction, no operand reordering
3004           // has taken place, so we directly access its operands.
3005           for (Use &U : BundleMember->Inst->operands())
3006             if (auto *I = dyn_cast<Instruction>(U.get()))
3007               DecrUnsched(I);
3008         }
3009         // Handle the memory dependencies.
3010         for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
3011           if (MemoryDepSD->hasValidDependencies() &&
3012               MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
3013             // There are no more unscheduled dependencies after decrementing,
3014             // so we can put the dependent instruction into the ready list.
3015             ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
3016             assert(!DepBundle->IsScheduled &&
3017                    "already scheduled bundle gets ready");
3018             ReadyList.insert(DepBundle);
3019             LLVM_DEBUG(dbgs()
3020                        << "SLP:    gets ready (mem): " << *DepBundle << "\n");
3021           }
3022         }
3023         // Handle the control dependencies.
3024         for (ScheduleData *DepSD : BundleMember->ControlDependencies) {
3025           if (DepSD->incrementUnscheduledDeps(-1) == 0) {
3026             // There are no more unscheduled dependencies after decrementing,
3027             // so we can put the dependent instruction into the ready list.
3028             ScheduleData *DepBundle = DepSD->FirstInBundle;
3029             assert(!DepBundle->IsScheduled &&
3030                    "already scheduled bundle gets ready");
3031             ReadyList.insert(DepBundle);
3032             LLVM_DEBUG(dbgs()
3033                        << "SLP:    gets ready (ctl): " << *DepBundle << "\n");
3034           }
3035         }
3036 
3037       }
3038     }
3039 
3040     /// Verify basic self consistency properties of the data structure.
3041     void verify() {
3042       if (!ScheduleStart)
3043         return;
3044 
3045       assert(ScheduleStart->getParent() == ScheduleEnd->getParent() &&
3046              ScheduleStart->comesBefore(ScheduleEnd) &&
3047              "Not a valid scheduling region?");
3048 
3049       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
3050         auto *SD = getScheduleData(I);
3051         if (!SD)
3052           continue;
3053         assert(isInSchedulingRegion(SD) &&
3054                "primary schedule data not in window?");
3055         assert(isInSchedulingRegion(SD->FirstInBundle) &&
3056                "entire bundle in window!");
3057         (void)SD;
3058         doForAllOpcodes(I, [](ScheduleData *SD) { SD->verify(); });
3059       }
3060 
3061       for (auto *SD : ReadyInsts) {
3062         assert(SD->isSchedulingEntity() && SD->isReady() &&
3063                "item in ready list not ready?");
3064         (void)SD;
3065       }
3066     }
3067 
3068     void doForAllOpcodes(Value *V,
3069                          function_ref<void(ScheduleData *SD)> Action) {
3070       if (ScheduleData *SD = getScheduleData(V))
3071         Action(SD);
3072       auto I = ExtraScheduleDataMap.find(V);
3073       if (I != ExtraScheduleDataMap.end())
3074         for (auto &P : I->second)
3075           if (isInSchedulingRegion(P.second))
3076             Action(P.second);
3077     }
3078 
3079     /// Put all instructions into the ReadyList which are ready for scheduling.
3080     template <typename ReadyListType>
3081     void initialFillReadyList(ReadyListType &ReadyList) {
3082       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
3083         doForAllOpcodes(I, [&](ScheduleData *SD) {
3084           if (SD->isSchedulingEntity() && SD->hasValidDependencies() &&
3085               SD->isReady()) {
3086             ReadyList.insert(SD);
3087             LLVM_DEBUG(dbgs()
3088                        << "SLP:    initially in ready list: " << *SD << "\n");
3089           }
3090         });
3091       }
3092     }
3093 
3094     /// Build a bundle from the ScheduleData nodes corresponding to the
3095     /// scalar instruction for each lane.
3096     ScheduleData *buildBundle(ArrayRef<Value *> VL);
3097 
3098     /// Checks if a bundle of instructions can be scheduled, i.e. has no
3099     /// cyclic dependencies. This is only a dry-run, no instructions are
3100     /// actually moved at this stage.
3101     /// \returns the scheduling bundle. The returned Optional value is non-None
3102     /// if \p VL is allowed to be scheduled.
3103     Optional<ScheduleData *>
3104     tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
3105                       const InstructionsState &S);
3106 
3107     /// Un-bundles a group of instructions.
3108     void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
3109 
3110     /// Allocates schedule data chunk.
3111     ScheduleData *allocateScheduleDataChunks();
3112 
3113     /// Extends the scheduling region so that V is inside the region.
3114     /// \returns true if the region size is within the limit.
3115     bool extendSchedulingRegion(Value *V, const InstructionsState &S);
3116 
3117     /// Initialize the ScheduleData structures for new instructions in the
3118     /// scheduling region.
3119     void initScheduleData(Instruction *FromI, Instruction *ToI,
3120                           ScheduleData *PrevLoadStore,
3121                           ScheduleData *NextLoadStore);
3122 
3123     /// Updates the dependency information of a bundle and of all instructions/
3124     /// bundles which depend on the original bundle.
3125     void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
3126                                BoUpSLP *SLP);
3127 
3128     /// Sets all instruction in the scheduling region to un-scheduled.
3129     void resetSchedule();
3130 
3131     BasicBlock *BB;
3132 
3133     /// Simple memory allocation for ScheduleData.
3134     std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
3135 
3136     /// The size of a ScheduleData array in ScheduleDataChunks.
3137     int ChunkSize;
3138 
3139     /// The allocator position in the current chunk, which is the last entry
3140     /// of ScheduleDataChunks.
3141     int ChunkPos;
3142 
3143     /// Attaches ScheduleData to Instruction.
3144     /// Note that the mapping survives during all vectorization iterations, i.e.
3145     /// ScheduleData structures are recycled.
3146     DenseMap<Instruction *, ScheduleData *> ScheduleDataMap;
3147 
3148     /// Attaches ScheduleData to Instruction with the leading key.
3149     DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
3150         ExtraScheduleDataMap;
3151 
3152     /// The ready-list for scheduling (only used for the dry-run).
3153     SetVector<ScheduleData *> ReadyInsts;
3154 
3155     /// The first instruction of the scheduling region.
3156     Instruction *ScheduleStart = nullptr;
3157 
3158     /// The first instruction _after_ the scheduling region.
3159     Instruction *ScheduleEnd = nullptr;
3160 
3161     /// The first memory accessing instruction in the scheduling region
3162     /// (can be null).
3163     ScheduleData *FirstLoadStoreInRegion = nullptr;
3164 
3165     /// The last memory accessing instruction in the scheduling region
3166     /// (can be null).
3167     ScheduleData *LastLoadStoreInRegion = nullptr;
3168 
3169     /// Is there an llvm.stacksave or llvm.stackrestore in the scheduling
3170     /// region?  Used to optimize the dependence calculation for the
3171     /// common case where there isn't.
3172     bool RegionHasStackSave = false;
3173 
3174     /// The current size of the scheduling region.
3175     int ScheduleRegionSize = 0;
3176 
3177     /// The maximum size allowed for the scheduling region.
3178     int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
3179 
3180     /// The ID of the scheduling region. For a new vectorization iteration this
3181     /// is incremented which "removes" all ScheduleData from the region.
3182     /// Make sure that the initial SchedulingRegionID is greater than the
3183     /// initial SchedulingRegionID in ScheduleData (which is 0).
3184     int SchedulingRegionID = 1;
3185   };
3186 
3187   /// Attaches the BlockScheduling structures to basic blocks.
3188   MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
3189 
3190   /// Performs the "real" scheduling. Done before vectorization is actually
3191   /// performed in a basic block.
3192   void scheduleBlock(BlockScheduling *BS);
3193 
3194   /// List of users to ignore during scheduling and that don't need extracting.
3195   ArrayRef<Value *> UserIgnoreList;
3196 
3197   /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
3198   /// sorted SmallVectors of unsigned.
3199   struct OrdersTypeDenseMapInfo {
3200     static OrdersType getEmptyKey() {
3201       OrdersType V;
3202       V.push_back(~1U);
3203       return V;
3204     }
3205 
3206     static OrdersType getTombstoneKey() {
3207       OrdersType V;
3208       V.push_back(~2U);
3209       return V;
3210     }
3211 
3212     static unsigned getHashValue(const OrdersType &V) {
3213       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
3214     }
3215 
3216     static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
3217       return LHS == RHS;
3218     }
3219   };
3220 
3221   // Analysis and block reference.
3222   Function *F;
3223   ScalarEvolution *SE;
3224   TargetTransformInfo *TTI;
3225   TargetLibraryInfo *TLI;
3226   LoopInfo *LI;
3227   DominatorTree *DT;
3228   AssumptionCache *AC;
3229   DemandedBits *DB;
3230   const DataLayout *DL;
3231   OptimizationRemarkEmitter *ORE;
3232 
3233   unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
3234   unsigned MinVecRegSize; // Set by cl::opt (default: 128).
3235 
3236   /// Instruction builder to construct the vectorized tree.
3237   IRBuilder<> Builder;
3238 
3239   /// A map of scalar integer values to the smallest bit width with which they
3240   /// can legally be represented. The values map to (width, signed) pairs,
3241   /// where "width" indicates the minimum bit width and "signed" is True if the
3242   /// value must be signed-extended, rather than zero-extended, back to its
3243   /// original width.
3244   MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
3245 };
3246 
3247 } // end namespace slpvectorizer
3248 
3249 template <> struct GraphTraits<BoUpSLP *> {
3250   using TreeEntry = BoUpSLP::TreeEntry;
3251 
3252   /// NodeRef has to be a pointer per the GraphWriter.
3253   using NodeRef = TreeEntry *;
3254 
3255   using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy;
3256 
3257   /// Add the VectorizableTree to the index iterator to be able to return
3258   /// TreeEntry pointers.
3259   struct ChildIteratorType
3260       : public iterator_adaptor_base<
3261             ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
3262     ContainerTy &VectorizableTree;
3263 
3264     ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W,
3265                       ContainerTy &VT)
3266         : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
3267 
3268     NodeRef operator*() { return I->UserTE; }
3269   };
3270 
3271   static NodeRef getEntryNode(BoUpSLP &R) {
3272     return R.VectorizableTree[0].get();
3273   }
3274 
3275   static ChildIteratorType child_begin(NodeRef N) {
3276     return {N->UserTreeIndices.begin(), N->Container};
3277   }
3278 
3279   static ChildIteratorType child_end(NodeRef N) {
3280     return {N->UserTreeIndices.end(), N->Container};
3281   }
3282 
3283   /// For the node iterator we just need to turn the TreeEntry iterator into a
3284   /// TreeEntry* iterator so that it dereferences to NodeRef.
3285   class nodes_iterator {
3286     using ItTy = ContainerTy::iterator;
3287     ItTy It;
3288 
3289   public:
3290     nodes_iterator(const ItTy &It2) : It(It2) {}
3291     NodeRef operator*() { return It->get(); }
3292     nodes_iterator operator++() {
3293       ++It;
3294       return *this;
3295     }
3296     bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
3297   };
3298 
3299   static nodes_iterator nodes_begin(BoUpSLP *R) {
3300     return nodes_iterator(R->VectorizableTree.begin());
3301   }
3302 
3303   static nodes_iterator nodes_end(BoUpSLP *R) {
3304     return nodes_iterator(R->VectorizableTree.end());
3305   }
3306 
3307   static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
3308 };
3309 
3310 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
3311   using TreeEntry = BoUpSLP::TreeEntry;
3312 
3313   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
3314 
3315   std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
3316     std::string Str;
3317     raw_string_ostream OS(Str);
3318     if (isSplat(Entry->Scalars))
3319       OS << "<splat> ";
3320     for (auto V : Entry->Scalars) {
3321       OS << *V;
3322       if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) {
3323             return EU.Scalar == V;
3324           }))
3325         OS << " <extract>";
3326       OS << "\n";
3327     }
3328     return Str;
3329   }
3330 
3331   static std::string getNodeAttributes(const TreeEntry *Entry,
3332                                        const BoUpSLP *) {
3333     if (Entry->State == TreeEntry::NeedToGather)
3334       return "color=red";
3335     return "";
3336   }
3337 };
3338 
3339 } // end namespace llvm
3340 
3341 BoUpSLP::~BoUpSLP() {
3342   SmallVector<WeakTrackingVH> DeadInsts;
3343   for (auto *I : DeletedInstructions) {
3344     for (Use &U : I->operands()) {
3345       auto *Op = dyn_cast<Instruction>(U.get());
3346       if (Op && !DeletedInstructions.count(Op) && Op->hasOneUser() &&
3347           wouldInstructionBeTriviallyDead(Op, TLI))
3348         DeadInsts.emplace_back(Op);
3349     }
3350     I->dropAllReferences();
3351   }
3352   for (auto *I : DeletedInstructions) {
3353     assert(I->use_empty() &&
3354            "trying to erase instruction with users.");
3355     I->eraseFromParent();
3356   }
3357 
3358   // Cleanup any dead scalar code feeding the vectorized instructions
3359   RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI);
3360 
3361 #ifdef EXPENSIVE_CHECKS
3362   // If we could guarantee that this call is not extremely slow, we could
3363   // remove the ifdef limitation (see PR47712).
3364   assert(!verifyFunction(*F, &dbgs()));
3365 #endif
3366 }
3367 
3368 /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses
3369 /// contains original mask for the scalars reused in the node. Procedure
3370 /// transform this mask in accordance with the given \p Mask.
3371 static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) {
3372   assert(!Mask.empty() && Reuses.size() == Mask.size() &&
3373          "Expected non-empty mask.");
3374   SmallVector<int> Prev(Reuses.begin(), Reuses.end());
3375   Prev.swap(Reuses);
3376   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
3377     if (Mask[I] != UndefMaskElem)
3378       Reuses[Mask[I]] = Prev[I];
3379 }
3380 
3381 /// Reorders the given \p Order according to the given \p Mask. \p Order - is
3382 /// the original order of the scalars. Procedure transforms the provided order
3383 /// in accordance with the given \p Mask. If the resulting \p Order is just an
3384 /// identity order, \p Order is cleared.
3385 static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) {
3386   assert(!Mask.empty() && "Expected non-empty mask.");
3387   SmallVector<int> MaskOrder;
3388   if (Order.empty()) {
3389     MaskOrder.resize(Mask.size());
3390     std::iota(MaskOrder.begin(), MaskOrder.end(), 0);
3391   } else {
3392     inversePermutation(Order, MaskOrder);
3393   }
3394   reorderReuses(MaskOrder, Mask);
3395   if (ShuffleVectorInst::isIdentityMask(MaskOrder)) {
3396     Order.clear();
3397     return;
3398   }
3399   Order.assign(Mask.size(), Mask.size());
3400   for (unsigned I = 0, E = Mask.size(); I < E; ++I)
3401     if (MaskOrder[I] != UndefMaskElem)
3402       Order[MaskOrder[I]] = I;
3403   fixupOrderingIndices(Order);
3404 }
3405 
3406 Optional<BoUpSLP::OrdersType>
3407 BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) {
3408   assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
3409   unsigned NumScalars = TE.Scalars.size();
3410   OrdersType CurrentOrder(NumScalars, NumScalars);
3411   SmallVector<int> Positions;
3412   SmallBitVector UsedPositions(NumScalars);
3413   const TreeEntry *STE = nullptr;
3414   // Try to find all gathered scalars that are gets vectorized in other
3415   // vectorize node. Here we can have only one single tree vector node to
3416   // correctly identify order of the gathered scalars.
3417   for (unsigned I = 0; I < NumScalars; ++I) {
3418     Value *V = TE.Scalars[I];
3419     if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V))
3420       continue;
3421     if (const auto *LocalSTE = getTreeEntry(V)) {
3422       if (!STE)
3423         STE = LocalSTE;
3424       else if (STE != LocalSTE)
3425         // Take the order only from the single vector node.
3426         return None;
3427       unsigned Lane =
3428           std::distance(STE->Scalars.begin(), find(STE->Scalars, V));
3429       if (Lane >= NumScalars)
3430         return None;
3431       if (CurrentOrder[Lane] != NumScalars) {
3432         if (Lane != I)
3433           continue;
3434         UsedPositions.reset(CurrentOrder[Lane]);
3435       }
3436       // The partial identity (where only some elements of the gather node are
3437       // in the identity order) is good.
3438       CurrentOrder[Lane] = I;
3439       UsedPositions.set(I);
3440     }
3441   }
3442   // Need to keep the order if we have a vector entry and at least 2 scalars or
3443   // the vectorized entry has just 2 scalars.
3444   if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) {
3445     auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) {
3446       for (unsigned I = 0; I < NumScalars; ++I)
3447         if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars)
3448           return false;
3449       return true;
3450     };
3451     if (IsIdentityOrder(CurrentOrder)) {
3452       CurrentOrder.clear();
3453       return CurrentOrder;
3454     }
3455     auto *It = CurrentOrder.begin();
3456     for (unsigned I = 0; I < NumScalars;) {
3457       if (UsedPositions.test(I)) {
3458         ++I;
3459         continue;
3460       }
3461       if (*It == NumScalars) {
3462         *It = I;
3463         ++I;
3464       }
3465       ++It;
3466     }
3467     return CurrentOrder;
3468   }
3469   return None;
3470 }
3471 
3472 bool clusterSortPtrAccesses(ArrayRef<Value *> VL, Type *ElemTy,
3473                             const DataLayout &DL, ScalarEvolution &SE,
3474                             SmallVectorImpl<unsigned> &SortedIndices) {
3475   assert(llvm::all_of(
3476              VL, [](const Value *V) { return V->getType()->isPointerTy(); }) &&
3477          "Expected list of pointer operands.");
3478   // Map from bases to a vector of (Ptr, Offset, OrigIdx), which we insert each
3479   // Ptr into, sort and return the sorted indices with values next to one
3480   // another.
3481   MapVector<Value *, SmallVector<std::tuple<Value *, int, unsigned>>> Bases;
3482   Bases[VL[0]].push_back(std::make_tuple(VL[0], 0U, 0U));
3483 
3484   unsigned Cnt = 1;
3485   for (Value *Ptr : VL.drop_front()) {
3486     bool Found = any_of(Bases, [&](auto &Base) {
3487       Optional<int> Diff =
3488           getPointersDiff(ElemTy, Base.first, ElemTy, Ptr, DL, SE,
3489                           /*StrictCheck=*/true);
3490       if (!Diff)
3491         return false;
3492 
3493       Base.second.emplace_back(Ptr, *Diff, Cnt++);
3494       return true;
3495     });
3496 
3497     if (!Found) {
3498       // If we haven't found enough to usefully cluster, return early.
3499       if (Bases.size() > VL.size() / 2 - 1)
3500         return false;
3501 
3502       // Not found already - add a new Base
3503       Bases[Ptr].emplace_back(Ptr, 0, Cnt++);
3504     }
3505   }
3506 
3507   // For each of the bases sort the pointers by Offset and check if any of the
3508   // base become consecutively allocated.
3509   bool AnyConsecutive = false;
3510   for (auto &Base : Bases) {
3511     auto &Vec = Base.second;
3512     if (Vec.size() > 1) {
3513       llvm::stable_sort(Vec, [](const std::tuple<Value *, int, unsigned> &X,
3514                                 const std::tuple<Value *, int, unsigned> &Y) {
3515         return std::get<1>(X) < std::get<1>(Y);
3516       });
3517       int InitialOffset = std::get<1>(Vec[0]);
3518       AnyConsecutive |= all_of(enumerate(Vec), [InitialOffset](auto &P) {
3519         return std::get<1>(P.value()) == int(P.index()) + InitialOffset;
3520       });
3521     }
3522   }
3523 
3524   // Fill SortedIndices array only if it looks worth-while to sort the ptrs.
3525   SortedIndices.clear();
3526   if (!AnyConsecutive)
3527     return false;
3528 
3529   for (auto &Base : Bases) {
3530     for (auto &T : Base.second)
3531       SortedIndices.push_back(std::get<2>(T));
3532   }
3533 
3534   assert(SortedIndices.size() == VL.size() &&
3535          "Expected SortedIndices to be the size of VL");
3536   return true;
3537 }
3538 
3539 Optional<BoUpSLP::OrdersType>
3540 BoUpSLP::findPartiallyOrderedLoads(const BoUpSLP::TreeEntry &TE) {
3541   assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
3542   Type *ScalarTy = TE.Scalars[0]->getType();
3543 
3544   SmallVector<Value *> Ptrs;
3545   Ptrs.reserve(TE.Scalars.size());
3546   for (Value *V : TE.Scalars) {
3547     auto *L = dyn_cast<LoadInst>(V);
3548     if (!L || !L->isSimple())
3549       return None;
3550     Ptrs.push_back(L->getPointerOperand());
3551   }
3552 
3553   BoUpSLP::OrdersType Order;
3554   if (clusterSortPtrAccesses(Ptrs, ScalarTy, *DL, *SE, Order))
3555     return Order;
3556   return None;
3557 }
3558 
3559 Optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE,
3560                                                          bool TopToBottom) {
3561   // No need to reorder if need to shuffle reuses, still need to shuffle the
3562   // node.
3563   if (!TE.ReuseShuffleIndices.empty())
3564     return None;
3565   if (TE.State == TreeEntry::Vectorize &&
3566       (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) ||
3567        (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) &&
3568       !TE.isAltShuffle())
3569     return TE.ReorderIndices;
3570   if (TE.State == TreeEntry::NeedToGather) {
3571     // TODO: add analysis of other gather nodes with extractelement
3572     // instructions and other values/instructions, not only undefs.
3573     if (((TE.getOpcode() == Instruction::ExtractElement &&
3574           !TE.isAltShuffle()) ||
3575          (all_of(TE.Scalars,
3576                  [](Value *V) {
3577                    return isa<UndefValue, ExtractElementInst>(V);
3578                  }) &&
3579           any_of(TE.Scalars,
3580                  [](Value *V) { return isa<ExtractElementInst>(V); }))) &&
3581         all_of(TE.Scalars,
3582                [](Value *V) {
3583                  auto *EE = dyn_cast<ExtractElementInst>(V);
3584                  return !EE || isa<FixedVectorType>(EE->getVectorOperandType());
3585                }) &&
3586         allSameType(TE.Scalars)) {
3587       // Check that gather of extractelements can be represented as
3588       // just a shuffle of a single vector.
3589       OrdersType CurrentOrder;
3590       bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder);
3591       if (Reuse || !CurrentOrder.empty()) {
3592         if (!CurrentOrder.empty())
3593           fixupOrderingIndices(CurrentOrder);
3594         return CurrentOrder;
3595       }
3596     }
3597     if (Optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE))
3598       return CurrentOrder;
3599     if (TE.Scalars.size() >= 4)
3600       if (Optional<OrdersType> Order = findPartiallyOrderedLoads(TE))
3601         return Order;
3602   }
3603   return None;
3604 }
3605 
3606 void BoUpSLP::reorderTopToBottom() {
3607   // Maps VF to the graph nodes.
3608   DenseMap<unsigned, SetVector<TreeEntry *>> VFToOrderedEntries;
3609   // ExtractElement gather nodes which can be vectorized and need to handle
3610   // their ordering.
3611   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3612 
3613   // Maps a TreeEntry to the reorder indices of external users.
3614   DenseMap<const TreeEntry *, SmallVector<OrdersType, 1>>
3615       ExternalUserReorderMap;
3616   // Find all reorderable nodes with the given VF.
3617   // Currently the are vectorized stores,loads,extracts + some gathering of
3618   // extracts.
3619   for_each(VectorizableTree, [this, &VFToOrderedEntries, &GathersToOrders,
3620                               &ExternalUserReorderMap](
3621                                  const std::unique_ptr<TreeEntry> &TE) {
3622     // Look for external users that will probably be vectorized.
3623     SmallVector<OrdersType, 1> ExternalUserReorderIndices =
3624         findExternalStoreUsersReorderIndices(TE.get());
3625     if (!ExternalUserReorderIndices.empty()) {
3626       VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
3627       ExternalUserReorderMap.try_emplace(TE.get(),
3628                                          std::move(ExternalUserReorderIndices));
3629     }
3630 
3631     if (Optional<OrdersType> CurrentOrder =
3632             getReorderingData(*TE, /*TopToBottom=*/true)) {
3633       // Do not include ordering for nodes used in the alt opcode vectorization,
3634       // better to reorder them during bottom-to-top stage. If follow the order
3635       // here, it causes reordering of the whole graph though actually it is
3636       // profitable just to reorder the subgraph that starts from the alternate
3637       // opcode vectorization node. Such nodes already end-up with the shuffle
3638       // instruction and it is just enough to change this shuffle rather than
3639       // rotate the scalars for the whole graph.
3640       unsigned Cnt = 0;
3641       const TreeEntry *UserTE = TE.get();
3642       while (UserTE && Cnt < RecursionMaxDepth) {
3643         if (UserTE->UserTreeIndices.size() != 1)
3644           break;
3645         if (all_of(UserTE->UserTreeIndices, [](const EdgeInfo &EI) {
3646               return EI.UserTE->State == TreeEntry::Vectorize &&
3647                      EI.UserTE->isAltShuffle() && EI.UserTE->Idx != 0;
3648             }))
3649           return;
3650         if (UserTE->UserTreeIndices.empty())
3651           UserTE = nullptr;
3652         else
3653           UserTE = UserTE->UserTreeIndices.back().UserTE;
3654         ++Cnt;
3655       }
3656       VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
3657       if (TE->State != TreeEntry::Vectorize)
3658         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3659     }
3660   });
3661 
3662   // Reorder the graph nodes according to their vectorization factor.
3663   for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1;
3664        VF /= 2) {
3665     auto It = VFToOrderedEntries.find(VF);
3666     if (It == VFToOrderedEntries.end())
3667       continue;
3668     // Try to find the most profitable order. We just are looking for the most
3669     // used order and reorder scalar elements in the nodes according to this
3670     // mostly used order.
3671     ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef();
3672     // All operands are reordered and used only in this node - propagate the
3673     // most used order to the user node.
3674     MapVector<OrdersType, unsigned,
3675               DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3676         OrdersUses;
3677     SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3678     for (const TreeEntry *OpTE : OrderedEntries) {
3679       // No need to reorder this nodes, still need to extend and to use shuffle,
3680       // just need to merge reordering shuffle and the reuse shuffle.
3681       if (!OpTE->ReuseShuffleIndices.empty())
3682         continue;
3683       // Count number of orders uses.
3684       const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3685         if (OpTE->State == TreeEntry::NeedToGather) {
3686           auto It = GathersToOrders.find(OpTE);
3687           if (It != GathersToOrders.end())
3688             return It->second;
3689         }
3690         return OpTE->ReorderIndices;
3691       }();
3692       // First consider the order of the external scalar users.
3693       auto It = ExternalUserReorderMap.find(OpTE);
3694       if (It != ExternalUserReorderMap.end()) {
3695         const auto &ExternalUserReorderIndices = It->second;
3696         for (const OrdersType &ExtOrder : ExternalUserReorderIndices)
3697           ++OrdersUses.insert(std::make_pair(ExtOrder, 0)).first->second;
3698         // No other useful reorder data in this entry.
3699         if (Order.empty())
3700           continue;
3701       }
3702       // Stores actually store the mask, not the order, need to invert.
3703       if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3704           OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3705         SmallVector<int> Mask;
3706         inversePermutation(Order, Mask);
3707         unsigned E = Order.size();
3708         OrdersType CurrentOrder(E, E);
3709         transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3710           return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3711         });
3712         fixupOrderingIndices(CurrentOrder);
3713         ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
3714       } else {
3715         ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
3716       }
3717     }
3718     // Set order of the user node.
3719     if (OrdersUses.empty())
3720       continue;
3721     // Choose the most used order.
3722     ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3723     unsigned Cnt = OrdersUses.front().second;
3724     for (const auto &Pair : drop_begin(OrdersUses)) {
3725       if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3726         BestOrder = Pair.first;
3727         Cnt = Pair.second;
3728       }
3729     }
3730     // Set order of the user node.
3731     if (BestOrder.empty())
3732       continue;
3733     SmallVector<int> Mask;
3734     inversePermutation(BestOrder, Mask);
3735     SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3736     unsigned E = BestOrder.size();
3737     transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3738       return I < E ? static_cast<int>(I) : UndefMaskElem;
3739     });
3740     // Do an actual reordering, if profitable.
3741     for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
3742       // Just do the reordering for the nodes with the given VF.
3743       if (TE->Scalars.size() != VF) {
3744         if (TE->ReuseShuffleIndices.size() == VF) {
3745           // Need to reorder the reuses masks of the operands with smaller VF to
3746           // be able to find the match between the graph nodes and scalar
3747           // operands of the given node during vectorization/cost estimation.
3748           assert(all_of(TE->UserTreeIndices,
3749                         [VF, &TE](const EdgeInfo &EI) {
3750                           return EI.UserTE->Scalars.size() == VF ||
3751                                  EI.UserTE->Scalars.size() ==
3752                                      TE->Scalars.size();
3753                         }) &&
3754                  "All users must be of VF size.");
3755           // Update ordering of the operands with the smaller VF than the given
3756           // one.
3757           reorderReuses(TE->ReuseShuffleIndices, Mask);
3758         }
3759         continue;
3760       }
3761       if (TE->State == TreeEntry::Vectorize &&
3762           isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst,
3763               InsertElementInst>(TE->getMainOp()) &&
3764           !TE->isAltShuffle()) {
3765         // Build correct orders for extract{element,value}, loads and
3766         // stores.
3767         reorderOrder(TE->ReorderIndices, Mask);
3768         if (isa<InsertElementInst, StoreInst>(TE->getMainOp()))
3769           TE->reorderOperands(Mask);
3770       } else {
3771         // Reorder the node and its operands.
3772         TE->reorderOperands(Mask);
3773         assert(TE->ReorderIndices.empty() &&
3774                "Expected empty reorder sequence.");
3775         reorderScalars(TE->Scalars, Mask);
3776       }
3777       if (!TE->ReuseShuffleIndices.empty()) {
3778         // Apply reversed order to keep the original ordering of the reused
3779         // elements to avoid extra reorder indices shuffling.
3780         OrdersType CurrentOrder;
3781         reorderOrder(CurrentOrder, MaskOrder);
3782         SmallVector<int> NewReuses;
3783         inversePermutation(CurrentOrder, NewReuses);
3784         addMask(NewReuses, TE->ReuseShuffleIndices);
3785         TE->ReuseShuffleIndices.swap(NewReuses);
3786       }
3787     }
3788   }
3789 }
3790 
3791 bool BoUpSLP::canReorderOperands(
3792     TreeEntry *UserTE, SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
3793     ArrayRef<TreeEntry *> ReorderableGathers,
3794     SmallVectorImpl<TreeEntry *> &GatherOps) {
3795   for (unsigned I = 0, E = UserTE->getNumOperands(); I < E; ++I) {
3796     if (any_of(Edges, [I](const std::pair<unsigned, TreeEntry *> &OpData) {
3797           return OpData.first == I &&
3798                  OpData.second->State == TreeEntry::Vectorize;
3799         }))
3800       continue;
3801     if (TreeEntry *TE = getVectorizedOperand(UserTE, I)) {
3802       // Do not reorder if operand node is used by many user nodes.
3803       if (any_of(TE->UserTreeIndices,
3804                  [UserTE](const EdgeInfo &EI) { return EI.UserTE != UserTE; }))
3805         return false;
3806       // Add the node to the list of the ordered nodes with the identity
3807       // order.
3808       Edges.emplace_back(I, TE);
3809       continue;
3810     }
3811     ArrayRef<Value *> VL = UserTE->getOperand(I);
3812     TreeEntry *Gather = nullptr;
3813     if (count_if(ReorderableGathers, [VL, &Gather](TreeEntry *TE) {
3814           assert(TE->State != TreeEntry::Vectorize &&
3815                  "Only non-vectorized nodes are expected.");
3816           if (TE->isSame(VL)) {
3817             Gather = TE;
3818             return true;
3819           }
3820           return false;
3821         }) > 1)
3822       return false;
3823     if (Gather)
3824       GatherOps.push_back(Gather);
3825   }
3826   return true;
3827 }
3828 
3829 void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) {
3830   SetVector<TreeEntry *> OrderedEntries;
3831   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3832   // Find all reorderable leaf nodes with the given VF.
3833   // Currently the are vectorized loads,extracts without alternate operands +
3834   // some gathering of extracts.
3835   SmallVector<TreeEntry *> NonVectorized;
3836   for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders,
3837                               &NonVectorized](
3838                                  const std::unique_ptr<TreeEntry> &TE) {
3839     if (TE->State != TreeEntry::Vectorize)
3840       NonVectorized.push_back(TE.get());
3841     if (Optional<OrdersType> CurrentOrder =
3842             getReorderingData(*TE, /*TopToBottom=*/false)) {
3843       OrderedEntries.insert(TE.get());
3844       if (TE->State != TreeEntry::Vectorize)
3845         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3846     }
3847   });
3848 
3849   // 1. Propagate order to the graph nodes, which use only reordered nodes.
3850   // I.e., if the node has operands, that are reordered, try to make at least
3851   // one operand order in the natural order and reorder others + reorder the
3852   // user node itself.
3853   SmallPtrSet<const TreeEntry *, 4> Visited;
3854   while (!OrderedEntries.empty()) {
3855     // 1. Filter out only reordered nodes.
3856     // 2. If the entry has multiple uses - skip it and jump to the next node.
3857     MapVector<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users;
3858     SmallVector<TreeEntry *> Filtered;
3859     for (TreeEntry *TE : OrderedEntries) {
3860       if (!(TE->State == TreeEntry::Vectorize ||
3861             (TE->State == TreeEntry::NeedToGather &&
3862              GathersToOrders.count(TE))) ||
3863           TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3864           !all_of(drop_begin(TE->UserTreeIndices),
3865                   [TE](const EdgeInfo &EI) {
3866                     return EI.UserTE == TE->UserTreeIndices.front().UserTE;
3867                   }) ||
3868           !Visited.insert(TE).second) {
3869         Filtered.push_back(TE);
3870         continue;
3871       }
3872       // Build a map between user nodes and their operands order to speedup
3873       // search. The graph currently does not provide this dependency directly.
3874       for (EdgeInfo &EI : TE->UserTreeIndices) {
3875         TreeEntry *UserTE = EI.UserTE;
3876         auto It = Users.find(UserTE);
3877         if (It == Users.end())
3878           It = Users.insert({UserTE, {}}).first;
3879         It->second.emplace_back(EI.EdgeIdx, TE);
3880       }
3881     }
3882     // Erase filtered entries.
3883     for_each(Filtered,
3884              [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); });
3885     for (auto &Data : Users) {
3886       // Check that operands are used only in the User node.
3887       SmallVector<TreeEntry *> GatherOps;
3888       if (!canReorderOperands(Data.first, Data.second, NonVectorized,
3889                               GatherOps)) {
3890         for_each(Data.second,
3891                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3892                    OrderedEntries.remove(Op.second);
3893                  });
3894         continue;
3895       }
3896       // All operands are reordered and used only in this node - propagate the
3897       // most used order to the user node.
3898       MapVector<OrdersType, unsigned,
3899                 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3900           OrdersUses;
3901       // Do the analysis for each tree entry only once, otherwise the order of
3902       // the same node my be considered several times, though might be not
3903       // profitable.
3904       SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3905       SmallPtrSet<const TreeEntry *, 4> VisitedUsers;
3906       for (const auto &Op : Data.second) {
3907         TreeEntry *OpTE = Op.second;
3908         if (!VisitedOps.insert(OpTE).second)
3909           continue;
3910         if (!OpTE->ReuseShuffleIndices.empty() ||
3911             (IgnoreReorder && OpTE == VectorizableTree.front().get()))
3912           continue;
3913         const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3914           if (OpTE->State == TreeEntry::NeedToGather)
3915             return GathersToOrders.find(OpTE)->second;
3916           return OpTE->ReorderIndices;
3917         }();
3918         unsigned NumOps = count_if(
3919             Data.second, [OpTE](const std::pair<unsigned, TreeEntry *> &P) {
3920               return P.second == OpTE;
3921             });
3922         // Stores actually store the mask, not the order, need to invert.
3923         if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3924             OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3925           SmallVector<int> Mask;
3926           inversePermutation(Order, Mask);
3927           unsigned E = Order.size();
3928           OrdersType CurrentOrder(E, E);
3929           transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3930             return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3931           });
3932           fixupOrderingIndices(CurrentOrder);
3933           OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second +=
3934               NumOps;
3935         } else {
3936           OrdersUses.insert(std::make_pair(Order, 0)).first->second += NumOps;
3937         }
3938         auto Res = OrdersUses.insert(std::make_pair(OrdersType(), 0));
3939         const auto &&AllowsReordering = [IgnoreReorder, &GathersToOrders](
3940                                             const TreeEntry *TE) {
3941           if (!TE->ReorderIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3942               (TE->State == TreeEntry::Vectorize && TE->isAltShuffle()) ||
3943               (IgnoreReorder && TE->Idx == 0))
3944             return true;
3945           if (TE->State == TreeEntry::NeedToGather) {
3946             auto It = GathersToOrders.find(TE);
3947             if (It != GathersToOrders.end())
3948               return !It->second.empty();
3949             return true;
3950           }
3951           return false;
3952         };
3953         for (const EdgeInfo &EI : OpTE->UserTreeIndices) {
3954           TreeEntry *UserTE = EI.UserTE;
3955           if (!VisitedUsers.insert(UserTE).second)
3956             continue;
3957           // May reorder user node if it requires reordering, has reused
3958           // scalars, is an alternate op vectorize node or its op nodes require
3959           // reordering.
3960           if (AllowsReordering(UserTE))
3961             continue;
3962           // Check if users allow reordering.
3963           // Currently look up just 1 level of operands to avoid increase of
3964           // the compile time.
3965           // Profitable to reorder if definitely more operands allow
3966           // reordering rather than those with natural order.
3967           ArrayRef<std::pair<unsigned, TreeEntry *>> Ops = Users[UserTE];
3968           if (static_cast<unsigned>(count_if(
3969                   Ops, [UserTE, &AllowsReordering](
3970                            const std::pair<unsigned, TreeEntry *> &Op) {
3971                     return AllowsReordering(Op.second) &&
3972                            all_of(Op.second->UserTreeIndices,
3973                                   [UserTE](const EdgeInfo &EI) {
3974                                     return EI.UserTE == UserTE;
3975                                   });
3976                   })) <= Ops.size() / 2)
3977             ++Res.first->second;
3978         }
3979       }
3980       // If no orders - skip current nodes and jump to the next one, if any.
3981       if (OrdersUses.empty()) {
3982         for_each(Data.second,
3983                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3984                    OrderedEntries.remove(Op.second);
3985                  });
3986         continue;
3987       }
3988       // Choose the best order.
3989       ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3990       unsigned Cnt = OrdersUses.front().second;
3991       for (const auto &Pair : drop_begin(OrdersUses)) {
3992         if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3993           BestOrder = Pair.first;
3994           Cnt = Pair.second;
3995         }
3996       }
3997       // Set order of the user node (reordering of operands and user nodes).
3998       if (BestOrder.empty()) {
3999         for_each(Data.second,
4000                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
4001                    OrderedEntries.remove(Op.second);
4002                  });
4003         continue;
4004       }
4005       // Erase operands from OrderedEntries list and adjust their orders.
4006       VisitedOps.clear();
4007       SmallVector<int> Mask;
4008       inversePermutation(BestOrder, Mask);
4009       SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
4010       unsigned E = BestOrder.size();
4011       transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
4012         return I < E ? static_cast<int>(I) : UndefMaskElem;
4013       });
4014       for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) {
4015         TreeEntry *TE = Op.second;
4016         OrderedEntries.remove(TE);
4017         if (!VisitedOps.insert(TE).second)
4018           continue;
4019         if (TE->ReuseShuffleIndices.size() == BestOrder.size()) {
4020           // Just reorder reuses indices.
4021           reorderReuses(TE->ReuseShuffleIndices, Mask);
4022           continue;
4023         }
4024         // Gathers are processed separately.
4025         if (TE->State != TreeEntry::Vectorize)
4026           continue;
4027         assert((BestOrder.size() == TE->ReorderIndices.size() ||
4028                 TE->ReorderIndices.empty()) &&
4029                "Non-matching sizes of user/operand entries.");
4030         reorderOrder(TE->ReorderIndices, Mask);
4031       }
4032       // For gathers just need to reorder its scalars.
4033       for (TreeEntry *Gather : GatherOps) {
4034         assert(Gather->ReorderIndices.empty() &&
4035                "Unexpected reordering of gathers.");
4036         if (!Gather->ReuseShuffleIndices.empty()) {
4037           // Just reorder reuses indices.
4038           reorderReuses(Gather->ReuseShuffleIndices, Mask);
4039           continue;
4040         }
4041         reorderScalars(Gather->Scalars, Mask);
4042         OrderedEntries.remove(Gather);
4043       }
4044       // Reorder operands of the user node and set the ordering for the user
4045       // node itself.
4046       if (Data.first->State != TreeEntry::Vectorize ||
4047           !isa<ExtractElementInst, ExtractValueInst, LoadInst>(
4048               Data.first->getMainOp()) ||
4049           Data.first->isAltShuffle())
4050         Data.first->reorderOperands(Mask);
4051       if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) ||
4052           Data.first->isAltShuffle()) {
4053         reorderScalars(Data.first->Scalars, Mask);
4054         reorderOrder(Data.first->ReorderIndices, MaskOrder);
4055         if (Data.first->ReuseShuffleIndices.empty() &&
4056             !Data.first->ReorderIndices.empty() &&
4057             !Data.first->isAltShuffle()) {
4058           // Insert user node to the list to try to sink reordering deeper in
4059           // the graph.
4060           OrderedEntries.insert(Data.first);
4061         }
4062       } else {
4063         reorderOrder(Data.first->ReorderIndices, Mask);
4064       }
4065     }
4066   }
4067   // If the reordering is unnecessary, just remove the reorder.
4068   if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() &&
4069       VectorizableTree.front()->ReuseShuffleIndices.empty())
4070     VectorizableTree.front()->ReorderIndices.clear();
4071 }
4072 
4073 void BoUpSLP::buildExternalUses(
4074     const ExtraValueToDebugLocsMap &ExternallyUsedValues) {
4075   // Collect the values that we need to extract from the tree.
4076   for (auto &TEPtr : VectorizableTree) {
4077     TreeEntry *Entry = TEPtr.get();
4078 
4079     // No need to handle users of gathered values.
4080     if (Entry->State == TreeEntry::NeedToGather)
4081       continue;
4082 
4083     // For each lane:
4084     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
4085       Value *Scalar = Entry->Scalars[Lane];
4086       int FoundLane = Entry->findLaneForValue(Scalar);
4087 
4088       // Check if the scalar is externally used as an extra arg.
4089       auto ExtI = ExternallyUsedValues.find(Scalar);
4090       if (ExtI != ExternallyUsedValues.end()) {
4091         LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
4092                           << Lane << " from " << *Scalar << ".\n");
4093         ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
4094       }
4095       for (User *U : Scalar->users()) {
4096         LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
4097 
4098         Instruction *UserInst = dyn_cast<Instruction>(U);
4099         if (!UserInst)
4100           continue;
4101 
4102         if (isDeleted(UserInst))
4103           continue;
4104 
4105         // Skip in-tree scalars that become vectors
4106         if (TreeEntry *UseEntry = getTreeEntry(U)) {
4107           Value *UseScalar = UseEntry->Scalars[0];
4108           // Some in-tree scalars will remain as scalar in vectorized
4109           // instructions. If that is the case, the one in Lane 0 will
4110           // be used.
4111           if (UseScalar != U ||
4112               UseEntry->State == TreeEntry::ScatterVectorize ||
4113               !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
4114             LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
4115                               << ".\n");
4116             assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state");
4117             continue;
4118           }
4119         }
4120 
4121         // Ignore users in the user ignore list.
4122         if (is_contained(UserIgnoreList, UserInst))
4123           continue;
4124 
4125         LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
4126                           << Lane << " from " << *Scalar << ".\n");
4127         ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
4128       }
4129     }
4130   }
4131 }
4132 
4133 DenseMap<Value *, SmallVector<StoreInst *, 4>>
4134 BoUpSLP::collectUserStores(const BoUpSLP::TreeEntry *TE) const {
4135   DenseMap<Value *, SmallVector<StoreInst *, 4>> PtrToStoresMap;
4136   for (unsigned Lane : seq<unsigned>(0, TE->Scalars.size())) {
4137     Value *V = TE->Scalars[Lane];
4138     // To save compilation time we don't visit if we have too many users.
4139     static constexpr unsigned UsersLimit = 4;
4140     if (V->hasNUsesOrMore(UsersLimit))
4141       break;
4142 
4143     // Collect stores per pointer object.
4144     for (User *U : V->users()) {
4145       auto *SI = dyn_cast<StoreInst>(U);
4146       if (SI == nullptr || !SI->isSimple() ||
4147           !isValidElementType(SI->getValueOperand()->getType()))
4148         continue;
4149       // Skip entry if already
4150       if (getTreeEntry(U))
4151         continue;
4152 
4153       Value *Ptr = getUnderlyingObject(SI->getPointerOperand());
4154       auto &StoresVec = PtrToStoresMap[Ptr];
4155       // For now just keep one store per pointer object per lane.
4156       // TODO: Extend this to support multiple stores per pointer per lane
4157       if (StoresVec.size() > Lane)
4158         continue;
4159       // Skip if in different BBs.
4160       if (!StoresVec.empty() &&
4161           SI->getParent() != StoresVec.back()->getParent())
4162         continue;
4163       // Make sure that the stores are of the same type.
4164       if (!StoresVec.empty() &&
4165           SI->getValueOperand()->getType() !=
4166               StoresVec.back()->getValueOperand()->getType())
4167         continue;
4168       StoresVec.push_back(SI);
4169     }
4170   }
4171   return PtrToStoresMap;
4172 }
4173 
4174 bool BoUpSLP::CanFormVector(const SmallVector<StoreInst *, 4> &StoresVec,
4175                             OrdersType &ReorderIndices) const {
4176   // We check whether the stores in StoreVec can form a vector by sorting them
4177   // and checking whether they are consecutive.
4178 
4179   // To avoid calling getPointersDiff() while sorting we create a vector of
4180   // pairs {store, offset from first} and sort this instead.
4181   SmallVector<std::pair<StoreInst *, int>, 4> StoreOffsetVec(StoresVec.size());
4182   StoreInst *S0 = StoresVec[0];
4183   StoreOffsetVec[0] = {S0, 0};
4184   Type *S0Ty = S0->getValueOperand()->getType();
4185   Value *S0Ptr = S0->getPointerOperand();
4186   for (unsigned Idx : seq<unsigned>(1, StoresVec.size())) {
4187     StoreInst *SI = StoresVec[Idx];
4188     Optional<int> Diff =
4189         getPointersDiff(S0Ty, S0Ptr, SI->getValueOperand()->getType(),
4190                         SI->getPointerOperand(), *DL, *SE,
4191                         /*StrictCheck=*/true);
4192     // We failed to compare the pointers so just abandon this StoresVec.
4193     if (!Diff)
4194       return false;
4195     StoreOffsetVec[Idx] = {StoresVec[Idx], *Diff};
4196   }
4197 
4198   // Sort the vector based on the pointers. We create a copy because we may
4199   // need the original later for calculating the reorder (shuffle) indices.
4200   stable_sort(StoreOffsetVec, [](const std::pair<StoreInst *, int> &Pair1,
4201                                  const std::pair<StoreInst *, int> &Pair2) {
4202     int Offset1 = Pair1.second;
4203     int Offset2 = Pair2.second;
4204     return Offset1 < Offset2;
4205   });
4206 
4207   // Check if the stores are consecutive by checking if their difference is 1.
4208   for (unsigned Idx : seq<unsigned>(1, StoreOffsetVec.size()))
4209     if (StoreOffsetVec[Idx].second != StoreOffsetVec[Idx-1].second + 1)
4210       return false;
4211 
4212   // Calculate the shuffle indices according to their offset against the sorted
4213   // StoreOffsetVec.
4214   ReorderIndices.reserve(StoresVec.size());
4215   for (StoreInst *SI : StoresVec) {
4216     unsigned Idx = find_if(StoreOffsetVec,
4217                            [SI](const std::pair<StoreInst *, int> &Pair) {
4218                              return Pair.first == SI;
4219                            }) -
4220                    StoreOffsetVec.begin();
4221     ReorderIndices.push_back(Idx);
4222   }
4223   // Identity order (e.g., {0,1,2,3}) is modeled as an empty OrdersType in
4224   // reorderTopToBottom() and reorderBottomToTop(), so we are following the
4225   // same convention here.
4226   auto IsIdentityOrder = [](const OrdersType &Order) {
4227     for (unsigned Idx : seq<unsigned>(0, Order.size()))
4228       if (Idx != Order[Idx])
4229         return false;
4230     return true;
4231   };
4232   if (IsIdentityOrder(ReorderIndices))
4233     ReorderIndices.clear();
4234 
4235   return true;
4236 }
4237 
4238 #ifndef NDEBUG
4239 LLVM_DUMP_METHOD static void dumpOrder(const BoUpSLP::OrdersType &Order) {
4240   for (unsigned Idx : Order)
4241     dbgs() << Idx << ", ";
4242   dbgs() << "\n";
4243 }
4244 #endif
4245 
4246 SmallVector<BoUpSLP::OrdersType, 1>
4247 BoUpSLP::findExternalStoreUsersReorderIndices(TreeEntry *TE) const {
4248   unsigned NumLanes = TE->Scalars.size();
4249 
4250   DenseMap<Value *, SmallVector<StoreInst *, 4>> PtrToStoresMap =
4251       collectUserStores(TE);
4252 
4253   // Holds the reorder indices for each candidate store vector that is a user of
4254   // the current TreeEntry.
4255   SmallVector<OrdersType, 1> ExternalReorderIndices;
4256 
4257   // Now inspect the stores collected per pointer and look for vectorization
4258   // candidates. For each candidate calculate the reorder index vector and push
4259   // it into `ExternalReorderIndices`
4260   for (const auto &Pair : PtrToStoresMap) {
4261     auto &StoresVec = Pair.second;
4262     // If we have fewer than NumLanes stores, then we can't form a vector.
4263     if (StoresVec.size() != NumLanes)
4264       continue;
4265 
4266     // If the stores are not consecutive then abandon this StoresVec.
4267     OrdersType ReorderIndices;
4268     if (!CanFormVector(StoresVec, ReorderIndices))
4269       continue;
4270 
4271     // We now know that the scalars in StoresVec can form a vector instruction,
4272     // so set the reorder indices.
4273     ExternalReorderIndices.push_back(ReorderIndices);
4274   }
4275   return ExternalReorderIndices;
4276 }
4277 
4278 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
4279                         ArrayRef<Value *> UserIgnoreLst) {
4280   deleteTree();
4281   UserIgnoreList = UserIgnoreLst;
4282   if (!allSameType(Roots))
4283     return;
4284   buildTree_rec(Roots, 0, EdgeInfo());
4285 }
4286 
4287 namespace {
4288 /// Tracks the state we can represent the loads in the given sequence.
4289 enum class LoadsState { Gather, Vectorize, ScatterVectorize };
4290 } // anonymous namespace
4291 
4292 /// Checks if the given array of loads can be represented as a vectorized,
4293 /// scatter or just simple gather.
4294 static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0,
4295                                     const TargetTransformInfo &TTI,
4296                                     const DataLayout &DL, ScalarEvolution &SE,
4297                                     SmallVectorImpl<unsigned> &Order,
4298                                     SmallVectorImpl<Value *> &PointerOps) {
4299   // Check that a vectorized load would load the same memory as a scalar
4300   // load. For example, we don't want to vectorize loads that are smaller
4301   // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
4302   // treats loading/storing it as an i8 struct. If we vectorize loads/stores
4303   // from such a struct, we read/write packed bits disagreeing with the
4304   // unvectorized version.
4305   Type *ScalarTy = VL0->getType();
4306 
4307   if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy))
4308     return LoadsState::Gather;
4309 
4310   // Make sure all loads in the bundle are simple - we can't vectorize
4311   // atomic or volatile loads.
4312   PointerOps.clear();
4313   PointerOps.resize(VL.size());
4314   auto *POIter = PointerOps.begin();
4315   for (Value *V : VL) {
4316     auto *L = cast<LoadInst>(V);
4317     if (!L->isSimple())
4318       return LoadsState::Gather;
4319     *POIter = L->getPointerOperand();
4320     ++POIter;
4321   }
4322 
4323   Order.clear();
4324   // Check the order of pointer operands.
4325   if (llvm::sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order)) {
4326     Value *Ptr0;
4327     Value *PtrN;
4328     if (Order.empty()) {
4329       Ptr0 = PointerOps.front();
4330       PtrN = PointerOps.back();
4331     } else {
4332       Ptr0 = PointerOps[Order.front()];
4333       PtrN = PointerOps[Order.back()];
4334     }
4335     Optional<int> Diff =
4336         getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE);
4337     // Check that the sorted loads are consecutive.
4338     if (static_cast<unsigned>(*Diff) == VL.size() - 1)
4339       return LoadsState::Vectorize;
4340     Align CommonAlignment = cast<LoadInst>(VL0)->getAlign();
4341     for (Value *V : VL)
4342       CommonAlignment =
4343           commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
4344     if (TTI.isLegalMaskedGather(FixedVectorType::get(ScalarTy, VL.size()),
4345                                 CommonAlignment))
4346       return LoadsState::ScatterVectorize;
4347   }
4348 
4349   return LoadsState::Gather;
4350 }
4351 
4352 /// \return true if the specified list of values has only one instruction that
4353 /// requires scheduling, false otherwise.
4354 #ifndef NDEBUG
4355 static bool needToScheduleSingleInstruction(ArrayRef<Value *> VL) {
4356   Value *NeedsScheduling = nullptr;
4357   for (Value *V : VL) {
4358     if (doesNotNeedToBeScheduled(V))
4359       continue;
4360     if (!NeedsScheduling) {
4361       NeedsScheduling = V;
4362       continue;
4363     }
4364     return false;
4365   }
4366   return NeedsScheduling;
4367 }
4368 #endif
4369 
4370 /// Generates key/subkey pair for the given value to provide effective sorting
4371 /// of the values and better detection of the vectorizable values sequences. The
4372 /// keys/subkeys can be used for better sorting of the values themselves (keys)
4373 /// and in values subgroups (subkeys).
4374 static std::pair<size_t, size_t> generateKeySubkey(
4375     Value *V, const TargetLibraryInfo *TLI,
4376     function_ref<hash_code(size_t, LoadInst *)> LoadsSubkeyGenerator,
4377     bool AllowAlternate) {
4378   hash_code Key = hash_value(V->getValueID() + 2);
4379   hash_code SubKey = hash_value(0);
4380   // Sort the loads by the distance between the pointers.
4381   if (auto *LI = dyn_cast<LoadInst>(V)) {
4382     Key = hash_combine(hash_value(Instruction::Load), Key);
4383     if (LI->isSimple())
4384       SubKey = hash_value(LoadsSubkeyGenerator(Key, LI));
4385     else
4386       SubKey = hash_value(LI);
4387   } else if (isVectorLikeInstWithConstOps(V)) {
4388     // Sort extracts by the vector operands.
4389     if (isa<ExtractElementInst, UndefValue>(V))
4390       Key = hash_value(Value::UndefValueVal + 1);
4391     if (auto *EI = dyn_cast<ExtractElementInst>(V)) {
4392       if (!isUndefVector(EI->getVectorOperand()) &&
4393           !isa<UndefValue>(EI->getIndexOperand()))
4394         SubKey = hash_value(EI->getVectorOperand());
4395     }
4396   } else if (auto *I = dyn_cast<Instruction>(V)) {
4397     // Sort other instructions just by the opcodes except for CMPInst.
4398     // For CMP also sort by the predicate kind.
4399     if ((isa<BinaryOperator>(I) || isa<CastInst>(I)) &&
4400         isValidForAlternation(I->getOpcode())) {
4401       if (AllowAlternate)
4402         Key = hash_value(isa<BinaryOperator>(I) ? 1 : 0);
4403       else
4404         Key = hash_combine(hash_value(I->getOpcode()), Key);
4405       SubKey = hash_combine(
4406           hash_value(I->getOpcode()), hash_value(I->getType()),
4407           hash_value(isa<BinaryOperator>(I)
4408                          ? I->getType()
4409                          : cast<CastInst>(I)->getOperand(0)->getType()));
4410     } else if (auto *CI = dyn_cast<CmpInst>(I)) {
4411       CmpInst::Predicate Pred = CI->getPredicate();
4412       if (CI->isCommutative())
4413         Pred = std::min(Pred, CmpInst::getInversePredicate(Pred));
4414       CmpInst::Predicate SwapPred = CmpInst::getSwappedPredicate(Pred);
4415       SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(Pred),
4416                             hash_value(SwapPred),
4417                             hash_value(CI->getOperand(0)->getType()));
4418     } else if (auto *Call = dyn_cast<CallInst>(I)) {
4419       Intrinsic::ID ID = getVectorIntrinsicIDForCall(Call, TLI);
4420       if (isTriviallyVectorizable(ID))
4421         SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(ID));
4422       else if (!VFDatabase(*Call).getMappings(*Call).empty())
4423         SubKey = hash_combine(hash_value(I->getOpcode()),
4424                               hash_value(Call->getCalledFunction()));
4425       else
4426         SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(Call));
4427       for (const CallBase::BundleOpInfo &Op : Call->bundle_op_infos())
4428         SubKey = hash_combine(hash_value(Op.Begin), hash_value(Op.End),
4429                               hash_value(Op.Tag), SubKey);
4430     } else if (auto *Gep = dyn_cast<GetElementPtrInst>(I)) {
4431       if (Gep->getNumOperands() == 2 && isa<ConstantInt>(Gep->getOperand(1)))
4432         SubKey = hash_value(Gep->getPointerOperand());
4433       else
4434         SubKey = hash_value(Gep);
4435     } else if (BinaryOperator::isIntDivRem(I->getOpcode()) &&
4436                !isa<ConstantInt>(I->getOperand(1))) {
4437       // Do not try to vectorize instructions with potentially high cost.
4438       SubKey = hash_value(I);
4439     } else {
4440       SubKey = hash_value(I->getOpcode());
4441     }
4442     Key = hash_combine(hash_value(I->getParent()), Key);
4443   }
4444   return std::make_pair(Key, SubKey);
4445 }
4446 
4447 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
4448                             const EdgeInfo &UserTreeIdx) {
4449   assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
4450 
4451   SmallVector<int> ReuseShuffleIndicies;
4452   SmallVector<Value *> UniqueValues;
4453   auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues,
4454                                 &UserTreeIdx,
4455                                 this](const InstructionsState &S) {
4456     // Check that every instruction appears once in this bundle.
4457     DenseMap<Value *, unsigned> UniquePositions;
4458     for (Value *V : VL) {
4459       if (isConstant(V)) {
4460         ReuseShuffleIndicies.emplace_back(
4461             isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size());
4462         UniqueValues.emplace_back(V);
4463         continue;
4464       }
4465       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
4466       ReuseShuffleIndicies.emplace_back(Res.first->second);
4467       if (Res.second)
4468         UniqueValues.emplace_back(V);
4469     }
4470     size_t NumUniqueScalarValues = UniqueValues.size();
4471     if (NumUniqueScalarValues == VL.size()) {
4472       ReuseShuffleIndicies.clear();
4473     } else {
4474       LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
4475       if (NumUniqueScalarValues <= 1 ||
4476           (UniquePositions.size() == 1 && all_of(UniqueValues,
4477                                                  [](Value *V) {
4478                                                    return isa<UndefValue>(V) ||
4479                                                           !isConstant(V);
4480                                                  })) ||
4481           !llvm::isPowerOf2_32(NumUniqueScalarValues)) {
4482         LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
4483         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4484         return false;
4485       }
4486       VL = UniqueValues;
4487     }
4488     return true;
4489   };
4490 
4491   InstructionsState S = getSameOpcode(VL);
4492   if (Depth == RecursionMaxDepth) {
4493     LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
4494     if (TryToFindDuplicates(S))
4495       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4496                    ReuseShuffleIndicies);
4497     return;
4498   }
4499 
4500   // Don't handle scalable vectors
4501   if (S.getOpcode() == Instruction::ExtractElement &&
4502       isa<ScalableVectorType>(
4503           cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) {
4504     LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n");
4505     if (TryToFindDuplicates(S))
4506       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4507                    ReuseShuffleIndicies);
4508     return;
4509   }
4510 
4511   // Don't handle vectors.
4512   if (S.OpValue->getType()->isVectorTy() &&
4513       !isa<InsertElementInst>(S.OpValue)) {
4514     LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
4515     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4516     return;
4517   }
4518 
4519   if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
4520     if (SI->getValueOperand()->getType()->isVectorTy()) {
4521       LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
4522       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4523       return;
4524     }
4525 
4526   // If all of the operands are identical or constant we have a simple solution.
4527   // If we deal with insert/extract instructions, they all must have constant
4528   // indices, otherwise we should gather them, not try to vectorize.
4529   // If alternate op node with 2 elements with gathered operands - do not
4530   // vectorize.
4531   auto &&NotProfitableForVectorization = [&S, this,
4532                                           Depth](ArrayRef<Value *> VL) {
4533     if (!S.getOpcode() || !S.isAltShuffle() || VL.size() > 2)
4534       return false;
4535     if (VectorizableTree.size() < MinTreeSize)
4536       return false;
4537     if (Depth >= RecursionMaxDepth - 1)
4538       return true;
4539     // Check if all operands are extracts, part of vector node or can build a
4540     // regular vectorize node.
4541     SmallVector<unsigned, 2> InstsCount(VL.size(), 0);
4542     for (Value *V : VL) {
4543       auto *I = cast<Instruction>(V);
4544       InstsCount.push_back(count_if(I->operand_values(), [](Value *Op) {
4545         return isa<Instruction>(Op) || isVectorLikeInstWithConstOps(Op);
4546       }));
4547     }
4548     bool IsCommutative = isCommutative(S.MainOp) || isCommutative(S.AltOp);
4549     if ((IsCommutative &&
4550          std::accumulate(InstsCount.begin(), InstsCount.end(), 0) < 2) ||
4551         (!IsCommutative &&
4552          all_of(InstsCount, [](unsigned ICnt) { return ICnt < 2; })))
4553       return true;
4554     assert(VL.size() == 2 && "Expected only 2 alternate op instructions.");
4555     SmallVector<SmallVector<std::pair<Value *, Value *>>> Candidates;
4556     auto *I1 = cast<Instruction>(VL.front());
4557     auto *I2 = cast<Instruction>(VL.back());
4558     for (int Op = 0, E = S.MainOp->getNumOperands(); Op < E; ++Op)
4559       Candidates.emplace_back().emplace_back(I1->getOperand(Op),
4560                                              I2->getOperand(Op));
4561     if (count_if(
4562             Candidates, [this](ArrayRef<std::pair<Value *, Value *>> Cand) {
4563               return findBestRootPair(Cand, LookAheadHeuristics::ScoreSplat);
4564             }) >= S.MainOp->getNumOperands() / 2)
4565       return false;
4566     if (S.MainOp->getNumOperands() > 2)
4567       return true;
4568     if (IsCommutative) {
4569       // Check permuted operands.
4570       Candidates.clear();
4571       for (int Op = 0, E = S.MainOp->getNumOperands(); Op < E; ++Op)
4572         Candidates.emplace_back().emplace_back(I1->getOperand(Op),
4573                                                I2->getOperand((Op + 1) % E));
4574       if (any_of(
4575               Candidates, [this](ArrayRef<std::pair<Value *, Value *>> Cand) {
4576                 return findBestRootPair(Cand, LookAheadHeuristics::ScoreSplat);
4577               }))
4578         return false;
4579     }
4580     return true;
4581   };
4582   if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode() ||
4583       (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(S.MainOp) &&
4584        !all_of(VL, isVectorLikeInstWithConstOps)) ||
4585       NotProfitableForVectorization(VL)) {
4586     LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O, small shuffle. \n");
4587     if (TryToFindDuplicates(S))
4588       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4589                    ReuseShuffleIndicies);
4590     return;
4591   }
4592 
4593   // We now know that this is a vector of instructions of the same type from
4594   // the same block.
4595 
4596   // Don't vectorize ephemeral values.
4597   for (Value *V : VL) {
4598     if (EphValues.count(V)) {
4599       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
4600                         << ") is ephemeral.\n");
4601       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4602       return;
4603     }
4604   }
4605 
4606   // Check if this is a duplicate of another entry.
4607   if (TreeEntry *E = getTreeEntry(S.OpValue)) {
4608     LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n");
4609     if (!E->isSame(VL)) {
4610       LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
4611       if (TryToFindDuplicates(S))
4612         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4613                      ReuseShuffleIndicies);
4614       return;
4615     }
4616     // Record the reuse of the tree node.  FIXME, currently this is only used to
4617     // properly draw the graph rather than for the actual vectorization.
4618     E->UserTreeIndices.push_back(UserTreeIdx);
4619     LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue
4620                       << ".\n");
4621     return;
4622   }
4623 
4624   // Check that none of the instructions in the bundle are already in the tree.
4625   for (Value *V : VL) {
4626     auto *I = dyn_cast<Instruction>(V);
4627     if (!I)
4628       continue;
4629     if (getTreeEntry(I)) {
4630       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
4631                         << ") is already in tree.\n");
4632       if (TryToFindDuplicates(S))
4633         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4634                      ReuseShuffleIndicies);
4635       return;
4636     }
4637   }
4638 
4639   // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
4640   for (Value *V : VL) {
4641     if (is_contained(UserIgnoreList, V)) {
4642       LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
4643       if (TryToFindDuplicates(S))
4644         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4645                      ReuseShuffleIndicies);
4646       return;
4647     }
4648   }
4649 
4650   // Check that all of the users of the scalars that we want to vectorize are
4651   // schedulable.
4652   auto *VL0 = cast<Instruction>(S.OpValue);
4653   BasicBlock *BB = VL0->getParent();
4654 
4655   if (!DT->isReachableFromEntry(BB)) {
4656     // Don't go into unreachable blocks. They may contain instructions with
4657     // dependency cycles which confuse the final scheduling.
4658     LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
4659     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4660     return;
4661   }
4662 
4663   // Check that every instruction appears once in this bundle.
4664   if (!TryToFindDuplicates(S))
4665     return;
4666 
4667   auto &BSRef = BlocksSchedules[BB];
4668   if (!BSRef)
4669     BSRef = std::make_unique<BlockScheduling>(BB);
4670 
4671   BlockScheduling &BS = *BSRef;
4672 
4673   Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S);
4674 #ifdef EXPENSIVE_CHECKS
4675   // Make sure we didn't break any internal invariants
4676   BS.verify();
4677 #endif
4678   if (!Bundle) {
4679     LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
4680     assert((!BS.getScheduleData(VL0) ||
4681             !BS.getScheduleData(VL0)->isPartOfBundle()) &&
4682            "tryScheduleBundle should cancelScheduling on failure");
4683     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4684                  ReuseShuffleIndicies);
4685     return;
4686   }
4687   LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
4688 
4689   unsigned ShuffleOrOp = S.isAltShuffle() ?
4690                 (unsigned) Instruction::ShuffleVector : S.getOpcode();
4691   switch (ShuffleOrOp) {
4692     case Instruction::PHI: {
4693       auto *PH = cast<PHINode>(VL0);
4694 
4695       // Check for terminator values (e.g. invoke).
4696       for (Value *V : VL)
4697         for (Value *Incoming : cast<PHINode>(V)->incoming_values()) {
4698           Instruction *Term = dyn_cast<Instruction>(Incoming);
4699           if (Term && Term->isTerminator()) {
4700             LLVM_DEBUG(dbgs()
4701                        << "SLP: Need to swizzle PHINodes (terminator use).\n");
4702             BS.cancelScheduling(VL, VL0);
4703             newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4704                          ReuseShuffleIndicies);
4705             return;
4706           }
4707         }
4708 
4709       TreeEntry *TE =
4710           newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies);
4711       LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
4712 
4713       // Keeps the reordered operands to avoid code duplication.
4714       SmallVector<ValueList, 2> OperandsVec;
4715       for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
4716         if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) {
4717           ValueList Operands(VL.size(), PoisonValue::get(PH->getType()));
4718           TE->setOperand(I, Operands);
4719           OperandsVec.push_back(Operands);
4720           continue;
4721         }
4722         ValueList Operands;
4723         // Prepare the operand vector.
4724         for (Value *V : VL)
4725           Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(
4726               PH->getIncomingBlock(I)));
4727         TE->setOperand(I, Operands);
4728         OperandsVec.push_back(Operands);
4729       }
4730       for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx)
4731         buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx});
4732       return;
4733     }
4734     case Instruction::ExtractValue:
4735     case Instruction::ExtractElement: {
4736       OrdersType CurrentOrder;
4737       bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
4738       if (Reuse) {
4739         LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
4740         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4741                      ReuseShuffleIndicies);
4742         // This is a special case, as it does not gather, but at the same time
4743         // we are not extending buildTree_rec() towards the operands.
4744         ValueList Op0;
4745         Op0.assign(VL.size(), VL0->getOperand(0));
4746         VectorizableTree.back()->setOperand(0, Op0);
4747         return;
4748       }
4749       if (!CurrentOrder.empty()) {
4750         LLVM_DEBUG({
4751           dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
4752                     "with order";
4753           for (unsigned Idx : CurrentOrder)
4754             dbgs() << " " << Idx;
4755           dbgs() << "\n";
4756         });
4757         fixupOrderingIndices(CurrentOrder);
4758         // Insert new order with initial value 0, if it does not exist,
4759         // otherwise return the iterator to the existing one.
4760         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4761                      ReuseShuffleIndicies, CurrentOrder);
4762         // This is a special case, as it does not gather, but at the same time
4763         // we are not extending buildTree_rec() towards the operands.
4764         ValueList Op0;
4765         Op0.assign(VL.size(), VL0->getOperand(0));
4766         VectorizableTree.back()->setOperand(0, Op0);
4767         return;
4768       }
4769       LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
4770       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4771                    ReuseShuffleIndicies);
4772       BS.cancelScheduling(VL, VL0);
4773       return;
4774     }
4775     case Instruction::InsertElement: {
4776       assert(ReuseShuffleIndicies.empty() && "All inserts should be unique");
4777 
4778       // Check that we have a buildvector and not a shuffle of 2 or more
4779       // different vectors.
4780       ValueSet SourceVectors;
4781       for (Value *V : VL) {
4782         SourceVectors.insert(cast<Instruction>(V)->getOperand(0));
4783         assert(getInsertIndex(V) != None && "Non-constant or undef index?");
4784       }
4785 
4786       if (count_if(VL, [&SourceVectors](Value *V) {
4787             return !SourceVectors.contains(V);
4788           }) >= 2) {
4789         // Found 2nd source vector - cancel.
4790         LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with "
4791                              "different source vectors.\n");
4792         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4793         BS.cancelScheduling(VL, VL0);
4794         return;
4795       }
4796 
4797       auto OrdCompare = [](const std::pair<int, int> &P1,
4798                            const std::pair<int, int> &P2) {
4799         return P1.first > P2.first;
4800       };
4801       PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>,
4802                     decltype(OrdCompare)>
4803           Indices(OrdCompare);
4804       for (int I = 0, E = VL.size(); I < E; ++I) {
4805         unsigned Idx = *getInsertIndex(VL[I]);
4806         Indices.emplace(Idx, I);
4807       }
4808       OrdersType CurrentOrder(VL.size(), VL.size());
4809       bool IsIdentity = true;
4810       for (int I = 0, E = VL.size(); I < E; ++I) {
4811         CurrentOrder[Indices.top().second] = I;
4812         IsIdentity &= Indices.top().second == I;
4813         Indices.pop();
4814       }
4815       if (IsIdentity)
4816         CurrentOrder.clear();
4817       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4818                                    None, CurrentOrder);
4819       LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n");
4820 
4821       constexpr int NumOps = 2;
4822       ValueList VectorOperands[NumOps];
4823       for (int I = 0; I < NumOps; ++I) {
4824         for (Value *V : VL)
4825           VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I));
4826 
4827         TE->setOperand(I, VectorOperands[I]);
4828       }
4829       buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1});
4830       return;
4831     }
4832     case Instruction::Load: {
4833       // Check that a vectorized load would load the same memory as a scalar
4834       // load. For example, we don't want to vectorize loads that are smaller
4835       // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
4836       // treats loading/storing it as an i8 struct. If we vectorize loads/stores
4837       // from such a struct, we read/write packed bits disagreeing with the
4838       // unvectorized version.
4839       SmallVector<Value *> PointerOps;
4840       OrdersType CurrentOrder;
4841       TreeEntry *TE = nullptr;
4842       switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, CurrentOrder,
4843                                 PointerOps)) {
4844       case LoadsState::Vectorize:
4845         if (CurrentOrder.empty()) {
4846           // Original loads are consecutive and does not require reordering.
4847           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4848                             ReuseShuffleIndicies);
4849           LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
4850         } else {
4851           fixupOrderingIndices(CurrentOrder);
4852           // Need to reorder.
4853           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4854                             ReuseShuffleIndicies, CurrentOrder);
4855           LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
4856         }
4857         TE->setOperandsInOrder();
4858         break;
4859       case LoadsState::ScatterVectorize:
4860         // Vectorizing non-consecutive loads with `llvm.masked.gather`.
4861         TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S,
4862                           UserTreeIdx, ReuseShuffleIndicies);
4863         TE->setOperandsInOrder();
4864         buildTree_rec(PointerOps, Depth + 1, {TE, 0});
4865         LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n");
4866         break;
4867       case LoadsState::Gather:
4868         BS.cancelScheduling(VL, VL0);
4869         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4870                      ReuseShuffleIndicies);
4871 #ifndef NDEBUG
4872         Type *ScalarTy = VL0->getType();
4873         if (DL->getTypeSizeInBits(ScalarTy) !=
4874             DL->getTypeAllocSizeInBits(ScalarTy))
4875           LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
4876         else if (any_of(VL, [](Value *V) {
4877                    return !cast<LoadInst>(V)->isSimple();
4878                  }))
4879           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
4880         else
4881           LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
4882 #endif // NDEBUG
4883         break;
4884       }
4885       return;
4886     }
4887     case Instruction::ZExt:
4888     case Instruction::SExt:
4889     case Instruction::FPToUI:
4890     case Instruction::FPToSI:
4891     case Instruction::FPExt:
4892     case Instruction::PtrToInt:
4893     case Instruction::IntToPtr:
4894     case Instruction::SIToFP:
4895     case Instruction::UIToFP:
4896     case Instruction::Trunc:
4897     case Instruction::FPTrunc:
4898     case Instruction::BitCast: {
4899       Type *SrcTy = VL0->getOperand(0)->getType();
4900       for (Value *V : VL) {
4901         Type *Ty = cast<Instruction>(V)->getOperand(0)->getType();
4902         if (Ty != SrcTy || !isValidElementType(Ty)) {
4903           BS.cancelScheduling(VL, VL0);
4904           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4905                        ReuseShuffleIndicies);
4906           LLVM_DEBUG(dbgs()
4907                      << "SLP: Gathering casts with different src types.\n");
4908           return;
4909         }
4910       }
4911       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4912                                    ReuseShuffleIndicies);
4913       LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
4914 
4915       TE->setOperandsInOrder();
4916       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4917         ValueList Operands;
4918         // Prepare the operand vector.
4919         for (Value *V : VL)
4920           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4921 
4922         buildTree_rec(Operands, Depth + 1, {TE, i});
4923       }
4924       return;
4925     }
4926     case Instruction::ICmp:
4927     case Instruction::FCmp: {
4928       // Check that all of the compares have the same predicate.
4929       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
4930       CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0);
4931       Type *ComparedTy = VL0->getOperand(0)->getType();
4932       for (Value *V : VL) {
4933         CmpInst *Cmp = cast<CmpInst>(V);
4934         if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) ||
4935             Cmp->getOperand(0)->getType() != ComparedTy) {
4936           BS.cancelScheduling(VL, VL0);
4937           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4938                        ReuseShuffleIndicies);
4939           LLVM_DEBUG(dbgs()
4940                      << "SLP: Gathering cmp with different predicate.\n");
4941           return;
4942         }
4943       }
4944 
4945       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4946                                    ReuseShuffleIndicies);
4947       LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
4948 
4949       ValueList Left, Right;
4950       if (cast<CmpInst>(VL0)->isCommutative()) {
4951         // Commutative predicate - collect + sort operands of the instructions
4952         // so that each side is more likely to have the same opcode.
4953         assert(P0 == SwapP0 && "Commutative Predicate mismatch");
4954         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4955       } else {
4956         // Collect operands - commute if it uses the swapped predicate.
4957         for (Value *V : VL) {
4958           auto *Cmp = cast<CmpInst>(V);
4959           Value *LHS = Cmp->getOperand(0);
4960           Value *RHS = Cmp->getOperand(1);
4961           if (Cmp->getPredicate() != P0)
4962             std::swap(LHS, RHS);
4963           Left.push_back(LHS);
4964           Right.push_back(RHS);
4965         }
4966       }
4967       TE->setOperand(0, Left);
4968       TE->setOperand(1, Right);
4969       buildTree_rec(Left, Depth + 1, {TE, 0});
4970       buildTree_rec(Right, Depth + 1, {TE, 1});
4971       return;
4972     }
4973     case Instruction::Select:
4974     case Instruction::FNeg:
4975     case Instruction::Add:
4976     case Instruction::FAdd:
4977     case Instruction::Sub:
4978     case Instruction::FSub:
4979     case Instruction::Mul:
4980     case Instruction::FMul:
4981     case Instruction::UDiv:
4982     case Instruction::SDiv:
4983     case Instruction::FDiv:
4984     case Instruction::URem:
4985     case Instruction::SRem:
4986     case Instruction::FRem:
4987     case Instruction::Shl:
4988     case Instruction::LShr:
4989     case Instruction::AShr:
4990     case Instruction::And:
4991     case Instruction::Or:
4992     case Instruction::Xor: {
4993       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4994                                    ReuseShuffleIndicies);
4995       LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n");
4996 
4997       // Sort operands of the instructions so that each side is more likely to
4998       // have the same opcode.
4999       if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
5000         ValueList Left, Right;
5001         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
5002         TE->setOperand(0, Left);
5003         TE->setOperand(1, Right);
5004         buildTree_rec(Left, Depth + 1, {TE, 0});
5005         buildTree_rec(Right, Depth + 1, {TE, 1});
5006         return;
5007       }
5008 
5009       TE->setOperandsInOrder();
5010       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
5011         ValueList Operands;
5012         // Prepare the operand vector.
5013         for (Value *V : VL)
5014           Operands.push_back(cast<Instruction>(V)->getOperand(i));
5015 
5016         buildTree_rec(Operands, Depth + 1, {TE, i});
5017       }
5018       return;
5019     }
5020     case Instruction::GetElementPtr: {
5021       // We don't combine GEPs with complicated (nested) indexing.
5022       for (Value *V : VL) {
5023         if (cast<Instruction>(V)->getNumOperands() != 2) {
5024           LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
5025           BS.cancelScheduling(VL, VL0);
5026           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5027                        ReuseShuffleIndicies);
5028           return;
5029         }
5030       }
5031 
5032       // We can't combine several GEPs into one vector if they operate on
5033       // different types.
5034       Type *Ty0 = cast<GEPOperator>(VL0)->getSourceElementType();
5035       for (Value *V : VL) {
5036         Type *CurTy = cast<GEPOperator>(V)->getSourceElementType();
5037         if (Ty0 != CurTy) {
5038           LLVM_DEBUG(dbgs()
5039                      << "SLP: not-vectorizable GEP (different types).\n");
5040           BS.cancelScheduling(VL, VL0);
5041           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5042                        ReuseShuffleIndicies);
5043           return;
5044         }
5045       }
5046 
5047       // We don't combine GEPs with non-constant indexes.
5048       Type *Ty1 = VL0->getOperand(1)->getType();
5049       for (Value *V : VL) {
5050         auto Op = cast<Instruction>(V)->getOperand(1);
5051         if (!isa<ConstantInt>(Op) ||
5052             (Op->getType() != Ty1 &&
5053              Op->getType()->getScalarSizeInBits() >
5054                  DL->getIndexSizeInBits(
5055                      V->getType()->getPointerAddressSpace()))) {
5056           LLVM_DEBUG(dbgs()
5057                      << "SLP: not-vectorizable GEP (non-constant indexes).\n");
5058           BS.cancelScheduling(VL, VL0);
5059           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5060                        ReuseShuffleIndicies);
5061           return;
5062         }
5063       }
5064 
5065       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
5066                                    ReuseShuffleIndicies);
5067       LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
5068       SmallVector<ValueList, 2> Operands(2);
5069       // Prepare the operand vector for pointer operands.
5070       for (Value *V : VL)
5071         Operands.front().push_back(
5072             cast<GetElementPtrInst>(V)->getPointerOperand());
5073       TE->setOperand(0, Operands.front());
5074       // Need to cast all indices to the same type before vectorization to
5075       // avoid crash.
5076       // Required to be able to find correct matches between different gather
5077       // nodes and reuse the vectorized values rather than trying to gather them
5078       // again.
5079       int IndexIdx = 1;
5080       Type *VL0Ty = VL0->getOperand(IndexIdx)->getType();
5081       Type *Ty = all_of(VL,
5082                         [VL0Ty, IndexIdx](Value *V) {
5083                           return VL0Ty == cast<GetElementPtrInst>(V)
5084                                               ->getOperand(IndexIdx)
5085                                               ->getType();
5086                         })
5087                      ? VL0Ty
5088                      : DL->getIndexType(cast<GetElementPtrInst>(VL0)
5089                                             ->getPointerOperandType()
5090                                             ->getScalarType());
5091       // Prepare the operand vector.
5092       for (Value *V : VL) {
5093         auto *Op = cast<Instruction>(V)->getOperand(IndexIdx);
5094         auto *CI = cast<ConstantInt>(Op);
5095         Operands.back().push_back(ConstantExpr::getIntegerCast(
5096             CI, Ty, CI->getValue().isSignBitSet()));
5097       }
5098       TE->setOperand(IndexIdx, Operands.back());
5099 
5100       for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I)
5101         buildTree_rec(Operands[I], Depth + 1, {TE, I});
5102       return;
5103     }
5104     case Instruction::Store: {
5105       // Check if the stores are consecutive or if we need to swizzle them.
5106       llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType();
5107       // Avoid types that are padded when being allocated as scalars, while
5108       // being packed together in a vector (such as i1).
5109       if (DL->getTypeSizeInBits(ScalarTy) !=
5110           DL->getTypeAllocSizeInBits(ScalarTy)) {
5111         BS.cancelScheduling(VL, VL0);
5112         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5113                      ReuseShuffleIndicies);
5114         LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n");
5115         return;
5116       }
5117       // Make sure all stores in the bundle are simple - we can't vectorize
5118       // atomic or volatile stores.
5119       SmallVector<Value *, 4> PointerOps(VL.size());
5120       ValueList Operands(VL.size());
5121       auto POIter = PointerOps.begin();
5122       auto OIter = Operands.begin();
5123       for (Value *V : VL) {
5124         auto *SI = cast<StoreInst>(V);
5125         if (!SI->isSimple()) {
5126           BS.cancelScheduling(VL, VL0);
5127           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5128                        ReuseShuffleIndicies);
5129           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n");
5130           return;
5131         }
5132         *POIter = SI->getPointerOperand();
5133         *OIter = SI->getValueOperand();
5134         ++POIter;
5135         ++OIter;
5136       }
5137 
5138       OrdersType CurrentOrder;
5139       // Check the order of pointer operands.
5140       if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) {
5141         Value *Ptr0;
5142         Value *PtrN;
5143         if (CurrentOrder.empty()) {
5144           Ptr0 = PointerOps.front();
5145           PtrN = PointerOps.back();
5146         } else {
5147           Ptr0 = PointerOps[CurrentOrder.front()];
5148           PtrN = PointerOps[CurrentOrder.back()];
5149         }
5150         Optional<int> Dist =
5151             getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE);
5152         // Check that the sorted pointer operands are consecutive.
5153         if (static_cast<unsigned>(*Dist) == VL.size() - 1) {
5154           if (CurrentOrder.empty()) {
5155             // Original stores are consecutive and does not require reordering.
5156             TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
5157                                          UserTreeIdx, ReuseShuffleIndicies);
5158             TE->setOperandsInOrder();
5159             buildTree_rec(Operands, Depth + 1, {TE, 0});
5160             LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
5161           } else {
5162             fixupOrderingIndices(CurrentOrder);
5163             TreeEntry *TE =
5164                 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
5165                              ReuseShuffleIndicies, CurrentOrder);
5166             TE->setOperandsInOrder();
5167             buildTree_rec(Operands, Depth + 1, {TE, 0});
5168             LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n");
5169           }
5170           return;
5171         }
5172       }
5173 
5174       BS.cancelScheduling(VL, VL0);
5175       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5176                    ReuseShuffleIndicies);
5177       LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
5178       return;
5179     }
5180     case Instruction::Call: {
5181       // Check if the calls are all to the same vectorizable intrinsic or
5182       // library function.
5183       CallInst *CI = cast<CallInst>(VL0);
5184       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5185 
5186       VFShape Shape = VFShape::get(
5187           *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())),
5188           false /*HasGlobalPred*/);
5189       Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
5190 
5191       if (!VecFunc && !isTriviallyVectorizable(ID)) {
5192         BS.cancelScheduling(VL, VL0);
5193         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5194                      ReuseShuffleIndicies);
5195         LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
5196         return;
5197       }
5198       Function *F = CI->getCalledFunction();
5199       unsigned NumArgs = CI->arg_size();
5200       SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr);
5201       for (unsigned j = 0; j != NumArgs; ++j)
5202         if (isVectorIntrinsicWithScalarOpAtArg(ID, j))
5203           ScalarArgs[j] = CI->getArgOperand(j);
5204       for (Value *V : VL) {
5205         CallInst *CI2 = dyn_cast<CallInst>(V);
5206         if (!CI2 || CI2->getCalledFunction() != F ||
5207             getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
5208             (VecFunc &&
5209              VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) ||
5210             !CI->hasIdenticalOperandBundleSchema(*CI2)) {
5211           BS.cancelScheduling(VL, VL0);
5212           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5213                        ReuseShuffleIndicies);
5214           LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V
5215                             << "\n");
5216           return;
5217         }
5218         // Some intrinsics have scalar arguments and should be same in order for
5219         // them to be vectorized.
5220         for (unsigned j = 0; j != NumArgs; ++j) {
5221           if (isVectorIntrinsicWithScalarOpAtArg(ID, j)) {
5222             Value *A1J = CI2->getArgOperand(j);
5223             if (ScalarArgs[j] != A1J) {
5224               BS.cancelScheduling(VL, VL0);
5225               newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5226                            ReuseShuffleIndicies);
5227               LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
5228                                 << " argument " << ScalarArgs[j] << "!=" << A1J
5229                                 << "\n");
5230               return;
5231             }
5232           }
5233         }
5234         // Verify that the bundle operands are identical between the two calls.
5235         if (CI->hasOperandBundles() &&
5236             !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
5237                         CI->op_begin() + CI->getBundleOperandsEndIndex(),
5238                         CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
5239           BS.cancelScheduling(VL, VL0);
5240           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5241                        ReuseShuffleIndicies);
5242           LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
5243                             << *CI << "!=" << *V << '\n');
5244           return;
5245         }
5246       }
5247 
5248       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
5249                                    ReuseShuffleIndicies);
5250       TE->setOperandsInOrder();
5251       for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
5252         // For scalar operands no need to to create an entry since no need to
5253         // vectorize it.
5254         if (isVectorIntrinsicWithScalarOpAtArg(ID, i))
5255           continue;
5256         ValueList Operands;
5257         // Prepare the operand vector.
5258         for (Value *V : VL) {
5259           auto *CI2 = cast<CallInst>(V);
5260           Operands.push_back(CI2->getArgOperand(i));
5261         }
5262         buildTree_rec(Operands, Depth + 1, {TE, i});
5263       }
5264       return;
5265     }
5266     case Instruction::ShuffleVector: {
5267       // If this is not an alternate sequence of opcode like add-sub
5268       // then do not vectorize this instruction.
5269       if (!S.isAltShuffle()) {
5270         BS.cancelScheduling(VL, VL0);
5271         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5272                      ReuseShuffleIndicies);
5273         LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
5274         return;
5275       }
5276       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
5277                                    ReuseShuffleIndicies);
5278       LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
5279 
5280       // Reorder operands if reordering would enable vectorization.
5281       auto *CI = dyn_cast<CmpInst>(VL0);
5282       if (isa<BinaryOperator>(VL0) || CI) {
5283         ValueList Left, Right;
5284         if (!CI || all_of(VL, [](Value *V) {
5285               return cast<CmpInst>(V)->isCommutative();
5286             })) {
5287           reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
5288         } else {
5289           CmpInst::Predicate P0 = CI->getPredicate();
5290           CmpInst::Predicate AltP0 = cast<CmpInst>(S.AltOp)->getPredicate();
5291           assert(P0 != AltP0 &&
5292                  "Expected different main/alternate predicates.");
5293           CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
5294           Value *BaseOp0 = VL0->getOperand(0);
5295           Value *BaseOp1 = VL0->getOperand(1);
5296           // Collect operands - commute if it uses the swapped predicate or
5297           // alternate operation.
5298           for (Value *V : VL) {
5299             auto *Cmp = cast<CmpInst>(V);
5300             Value *LHS = Cmp->getOperand(0);
5301             Value *RHS = Cmp->getOperand(1);
5302             CmpInst::Predicate CurrentPred = Cmp->getPredicate();
5303             if (P0 == AltP0Swapped) {
5304               if (CI != Cmp && S.AltOp != Cmp &&
5305                   ((P0 == CurrentPred &&
5306                     !areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)) ||
5307                    (AltP0 == CurrentPred &&
5308                     areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS))))
5309                 std::swap(LHS, RHS);
5310             } else if (P0 != CurrentPred && AltP0 != CurrentPred) {
5311               std::swap(LHS, RHS);
5312             }
5313             Left.push_back(LHS);
5314             Right.push_back(RHS);
5315           }
5316         }
5317         TE->setOperand(0, Left);
5318         TE->setOperand(1, Right);
5319         buildTree_rec(Left, Depth + 1, {TE, 0});
5320         buildTree_rec(Right, Depth + 1, {TE, 1});
5321         return;
5322       }
5323 
5324       TE->setOperandsInOrder();
5325       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
5326         ValueList Operands;
5327         // Prepare the operand vector.
5328         for (Value *V : VL)
5329           Operands.push_back(cast<Instruction>(V)->getOperand(i));
5330 
5331         buildTree_rec(Operands, Depth + 1, {TE, i});
5332       }
5333       return;
5334     }
5335     default:
5336       BS.cancelScheduling(VL, VL0);
5337       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5338                    ReuseShuffleIndicies);
5339       LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
5340       return;
5341   }
5342 }
5343 
5344 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
5345   unsigned N = 1;
5346   Type *EltTy = T;
5347 
5348   while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) ||
5349          isa<VectorType>(EltTy)) {
5350     if (auto *ST = dyn_cast<StructType>(EltTy)) {
5351       // Check that struct is homogeneous.
5352       for (const auto *Ty : ST->elements())
5353         if (Ty != *ST->element_begin())
5354           return 0;
5355       N *= ST->getNumElements();
5356       EltTy = *ST->element_begin();
5357     } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) {
5358       N *= AT->getNumElements();
5359       EltTy = AT->getElementType();
5360     } else {
5361       auto *VT = cast<FixedVectorType>(EltTy);
5362       N *= VT->getNumElements();
5363       EltTy = VT->getElementType();
5364     }
5365   }
5366 
5367   if (!isValidElementType(EltTy))
5368     return 0;
5369   uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N));
5370   if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
5371     return 0;
5372   return N;
5373 }
5374 
5375 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
5376                               SmallVectorImpl<unsigned> &CurrentOrder) const {
5377   const auto *It = find_if(VL, [](Value *V) {
5378     return isa<ExtractElementInst, ExtractValueInst>(V);
5379   });
5380   assert(It != VL.end() && "Expected at least one extract instruction.");
5381   auto *E0 = cast<Instruction>(*It);
5382   assert(all_of(VL,
5383                 [](Value *V) {
5384                   return isa<UndefValue, ExtractElementInst, ExtractValueInst>(
5385                       V);
5386                 }) &&
5387          "Invalid opcode");
5388   // Check if all of the extracts come from the same vector and from the
5389   // correct offset.
5390   Value *Vec = E0->getOperand(0);
5391 
5392   CurrentOrder.clear();
5393 
5394   // We have to extract from a vector/aggregate with the same number of elements.
5395   unsigned NElts;
5396   if (E0->getOpcode() == Instruction::ExtractValue) {
5397     const DataLayout &DL = E0->getModule()->getDataLayout();
5398     NElts = canMapToVector(Vec->getType(), DL);
5399     if (!NElts)
5400       return false;
5401     // Check if load can be rewritten as load of vector.
5402     LoadInst *LI = dyn_cast<LoadInst>(Vec);
5403     if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
5404       return false;
5405   } else {
5406     NElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
5407   }
5408 
5409   if (NElts != VL.size())
5410     return false;
5411 
5412   // Check that all of the indices extract from the correct offset.
5413   bool ShouldKeepOrder = true;
5414   unsigned E = VL.size();
5415   // Assign to all items the initial value E + 1 so we can check if the extract
5416   // instruction index was used already.
5417   // Also, later we can check that all the indices are used and we have a
5418   // consecutive access in the extract instructions, by checking that no
5419   // element of CurrentOrder still has value E + 1.
5420   CurrentOrder.assign(E, E);
5421   unsigned I = 0;
5422   for (; I < E; ++I) {
5423     auto *Inst = dyn_cast<Instruction>(VL[I]);
5424     if (!Inst)
5425       continue;
5426     if (Inst->getOperand(0) != Vec)
5427       break;
5428     if (auto *EE = dyn_cast<ExtractElementInst>(Inst))
5429       if (isa<UndefValue>(EE->getIndexOperand()))
5430         continue;
5431     Optional<unsigned> Idx = getExtractIndex(Inst);
5432     if (!Idx)
5433       break;
5434     const unsigned ExtIdx = *Idx;
5435     if (ExtIdx != I) {
5436       if (ExtIdx >= E || CurrentOrder[ExtIdx] != E)
5437         break;
5438       ShouldKeepOrder = false;
5439       CurrentOrder[ExtIdx] = I;
5440     } else {
5441       if (CurrentOrder[I] != E)
5442         break;
5443       CurrentOrder[I] = I;
5444     }
5445   }
5446   if (I < E) {
5447     CurrentOrder.clear();
5448     return false;
5449   }
5450   if (ShouldKeepOrder)
5451     CurrentOrder.clear();
5452 
5453   return ShouldKeepOrder;
5454 }
5455 
5456 bool BoUpSLP::areAllUsersVectorized(Instruction *I,
5457                                     ArrayRef<Value *> VectorizedVals) const {
5458   return (I->hasOneUse() && is_contained(VectorizedVals, I)) ||
5459          all_of(I->users(), [this](User *U) {
5460            return ScalarToTreeEntry.count(U) > 0 ||
5461                   isVectorLikeInstWithConstOps(U) ||
5462                   (isa<ExtractElementInst>(U) && MustGather.contains(U));
5463          });
5464 }
5465 
5466 static std::pair<InstructionCost, InstructionCost>
5467 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy,
5468                    TargetTransformInfo *TTI, TargetLibraryInfo *TLI) {
5469   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5470 
5471   // Calculate the cost of the scalar and vector calls.
5472   SmallVector<Type *, 4> VecTys;
5473   for (Use &Arg : CI->args())
5474     VecTys.push_back(
5475         FixedVectorType::get(Arg->getType(), VecTy->getNumElements()));
5476   FastMathFlags FMF;
5477   if (auto *FPCI = dyn_cast<FPMathOperator>(CI))
5478     FMF = FPCI->getFastMathFlags();
5479   SmallVector<const Value *> Arguments(CI->args());
5480   IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF,
5481                                     dyn_cast<IntrinsicInst>(CI));
5482   auto IntrinsicCost =
5483     TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput);
5484 
5485   auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
5486                                      VecTy->getNumElements())),
5487                             false /*HasGlobalPred*/);
5488   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
5489   auto LibCost = IntrinsicCost;
5490   if (!CI->isNoBuiltin() && VecFunc) {
5491     // Calculate the cost of the vector library call.
5492     // If the corresponding vector call is cheaper, return its cost.
5493     LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys,
5494                                     TTI::TCK_RecipThroughput);
5495   }
5496   return {IntrinsicCost, LibCost};
5497 }
5498 
5499 /// Compute the cost of creating a vector of type \p VecTy containing the
5500 /// extracted values from \p VL.
5501 static InstructionCost
5502 computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy,
5503                    TargetTransformInfo::ShuffleKind ShuffleKind,
5504                    ArrayRef<int> Mask, TargetTransformInfo &TTI) {
5505   unsigned NumOfParts = TTI.getNumberOfParts(VecTy);
5506 
5507   if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts ||
5508       VecTy->getNumElements() < NumOfParts)
5509     return TTI.getShuffleCost(ShuffleKind, VecTy, Mask);
5510 
5511   bool AllConsecutive = true;
5512   unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts;
5513   unsigned Idx = -1;
5514   InstructionCost Cost = 0;
5515 
5516   // Process extracts in blocks of EltsPerVector to check if the source vector
5517   // operand can be re-used directly. If not, add the cost of creating a shuffle
5518   // to extract the values into a vector register.
5519   SmallVector<int> RegMask(EltsPerVector, UndefMaskElem);
5520   for (auto *V : VL) {
5521     ++Idx;
5522 
5523     // Need to exclude undefs from analysis.
5524     if (isa<UndefValue>(V) || Mask[Idx] == UndefMaskElem)
5525       continue;
5526 
5527     // Reached the start of a new vector registers.
5528     if (Idx % EltsPerVector == 0) {
5529       RegMask.assign(EltsPerVector, UndefMaskElem);
5530       AllConsecutive = true;
5531       continue;
5532     }
5533 
5534     // Check all extracts for a vector register on the target directly
5535     // extract values in order.
5536     unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V));
5537     if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != UndefMaskElem) {
5538       unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1]));
5539       AllConsecutive &= PrevIdx + 1 == CurrentIdx &&
5540                         CurrentIdx % EltsPerVector == Idx % EltsPerVector;
5541       RegMask[Idx % EltsPerVector] = CurrentIdx % EltsPerVector;
5542     }
5543 
5544     if (AllConsecutive)
5545       continue;
5546 
5547     // Skip all indices, except for the last index per vector block.
5548     if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size())
5549       continue;
5550 
5551     // If we have a series of extracts which are not consecutive and hence
5552     // cannot re-use the source vector register directly, compute the shuffle
5553     // cost to extract the vector with EltsPerVector elements.
5554     Cost += TTI.getShuffleCost(
5555         TargetTransformInfo::SK_PermuteSingleSrc,
5556         FixedVectorType::get(VecTy->getElementType(), EltsPerVector), RegMask);
5557   }
5558   return Cost;
5559 }
5560 
5561 /// Build shuffle mask for shuffle graph entries and lists of main and alternate
5562 /// operations operands.
5563 static void
5564 buildShuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices,
5565                       ArrayRef<int> ReusesIndices,
5566                       const function_ref<bool(Instruction *)> IsAltOp,
5567                       SmallVectorImpl<int> &Mask,
5568                       SmallVectorImpl<Value *> *OpScalars = nullptr,
5569                       SmallVectorImpl<Value *> *AltScalars = nullptr) {
5570   unsigned Sz = VL.size();
5571   Mask.assign(Sz, UndefMaskElem);
5572   SmallVector<int> OrderMask;
5573   if (!ReorderIndices.empty())
5574     inversePermutation(ReorderIndices, OrderMask);
5575   for (unsigned I = 0; I < Sz; ++I) {
5576     unsigned Idx = I;
5577     if (!ReorderIndices.empty())
5578       Idx = OrderMask[I];
5579     auto *OpInst = cast<Instruction>(VL[Idx]);
5580     if (IsAltOp(OpInst)) {
5581       Mask[I] = Sz + Idx;
5582       if (AltScalars)
5583         AltScalars->push_back(OpInst);
5584     } else {
5585       Mask[I] = Idx;
5586       if (OpScalars)
5587         OpScalars->push_back(OpInst);
5588     }
5589   }
5590   if (!ReusesIndices.empty()) {
5591     SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem);
5592     transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) {
5593       return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem;
5594     });
5595     Mask.swap(NewMask);
5596   }
5597 }
5598 
5599 /// Checks if the specified instruction \p I is an alternate operation for the
5600 /// given \p MainOp and \p AltOp instructions.
5601 static bool isAlternateInstruction(const Instruction *I,
5602                                    const Instruction *MainOp,
5603                                    const Instruction *AltOp) {
5604   if (auto *CI0 = dyn_cast<CmpInst>(MainOp)) {
5605     auto *AltCI0 = cast<CmpInst>(AltOp);
5606     auto *CI = cast<CmpInst>(I);
5607     CmpInst::Predicate P0 = CI0->getPredicate();
5608     CmpInst::Predicate AltP0 = AltCI0->getPredicate();
5609     assert(P0 != AltP0 && "Expected different main/alternate predicates.");
5610     CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
5611     CmpInst::Predicate CurrentPred = CI->getPredicate();
5612     if (P0 == AltP0Swapped)
5613       return I == AltCI0 ||
5614              (I != MainOp &&
5615               !areCompatibleCmpOps(CI0->getOperand(0), CI0->getOperand(1),
5616                                    CI->getOperand(0), CI->getOperand(1)));
5617     return AltP0 == CurrentPred || AltP0Swapped == CurrentPred;
5618   }
5619   return I->getOpcode() == AltOp->getOpcode();
5620 }
5621 
5622 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E,
5623                                       ArrayRef<Value *> VectorizedVals) {
5624   ArrayRef<Value*> VL = E->Scalars;
5625 
5626   Type *ScalarTy = VL[0]->getType();
5627   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
5628     ScalarTy = SI->getValueOperand()->getType();
5629   else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
5630     ScalarTy = CI->getOperand(0)->getType();
5631   else if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
5632     ScalarTy = IE->getOperand(1)->getType();
5633   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
5634   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
5635 
5636   // If we have computed a smaller type for the expression, update VecTy so
5637   // that the costs will be accurate.
5638   if (MinBWs.count(VL[0]))
5639     VecTy = FixedVectorType::get(
5640         IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
5641   unsigned EntryVF = E->getVectorFactor();
5642   auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF);
5643 
5644   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
5645   // FIXME: it tries to fix a problem with MSVC buildbots.
5646   TargetTransformInfo &TTIRef = *TTI;
5647   auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy,
5648                                VectorizedVals, E](InstructionCost &Cost) {
5649     DenseMap<Value *, int> ExtractVectorsTys;
5650     SmallPtrSet<Value *, 4> CheckedExtracts;
5651     for (auto *V : VL) {
5652       if (isa<UndefValue>(V))
5653         continue;
5654       // If all users of instruction are going to be vectorized and this
5655       // instruction itself is not going to be vectorized, consider this
5656       // instruction as dead and remove its cost from the final cost of the
5657       // vectorized tree.
5658       // Also, avoid adjusting the cost for extractelements with multiple uses
5659       // in different graph entries.
5660       const TreeEntry *VE = getTreeEntry(V);
5661       if (!CheckedExtracts.insert(V).second ||
5662           !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) ||
5663           (VE && VE != E))
5664         continue;
5665       auto *EE = cast<ExtractElementInst>(V);
5666       Optional<unsigned> EEIdx = getExtractIndex(EE);
5667       if (!EEIdx)
5668         continue;
5669       unsigned Idx = *EEIdx;
5670       if (TTIRef.getNumberOfParts(VecTy) !=
5671           TTIRef.getNumberOfParts(EE->getVectorOperandType())) {
5672         auto It =
5673             ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first;
5674         It->getSecond() = std::min<int>(It->second, Idx);
5675       }
5676       // Take credit for instruction that will become dead.
5677       if (EE->hasOneUse()) {
5678         Instruction *Ext = EE->user_back();
5679         if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5680             all_of(Ext->users(),
5681                    [](User *U) { return isa<GetElementPtrInst>(U); })) {
5682           // Use getExtractWithExtendCost() to calculate the cost of
5683           // extractelement/ext pair.
5684           Cost -=
5685               TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(),
5686                                               EE->getVectorOperandType(), Idx);
5687           // Add back the cost of s|zext which is subtracted separately.
5688           Cost += TTIRef.getCastInstrCost(
5689               Ext->getOpcode(), Ext->getType(), EE->getType(),
5690               TTI::getCastContextHint(Ext), CostKind, Ext);
5691           continue;
5692         }
5693       }
5694       Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement,
5695                                         EE->getVectorOperandType(), Idx);
5696     }
5697     // Add a cost for subvector extracts/inserts if required.
5698     for (const auto &Data : ExtractVectorsTys) {
5699       auto *EEVTy = cast<FixedVectorType>(Data.first->getType());
5700       unsigned NumElts = VecTy->getNumElements();
5701       if (Data.second % NumElts == 0)
5702         continue;
5703       if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) {
5704         unsigned Idx = (Data.second / NumElts) * NumElts;
5705         unsigned EENumElts = EEVTy->getNumElements();
5706         if (Idx + NumElts <= EENumElts) {
5707           Cost +=
5708               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5709                                     EEVTy, None, Idx, VecTy);
5710         } else {
5711           // Need to round up the subvector type vectorization factor to avoid a
5712           // crash in cost model functions. Make SubVT so that Idx + VF of SubVT
5713           // <= EENumElts.
5714           auto *SubVT =
5715               FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx);
5716           Cost +=
5717               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5718                                     EEVTy, None, Idx, SubVT);
5719         }
5720       } else {
5721         Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector,
5722                                       VecTy, None, 0, EEVTy);
5723       }
5724     }
5725   };
5726   if (E->State == TreeEntry::NeedToGather) {
5727     if (allConstant(VL))
5728       return 0;
5729     if (isa<InsertElementInst>(VL[0]))
5730       return InstructionCost::getInvalid();
5731     SmallVector<int> Mask;
5732     SmallVector<const TreeEntry *> Entries;
5733     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
5734         isGatherShuffledEntry(E, Mask, Entries);
5735     if (Shuffle.hasValue()) {
5736       InstructionCost GatherCost = 0;
5737       if (ShuffleVectorInst::isIdentityMask(Mask)) {
5738         // Perfect match in the graph, will reuse the previously vectorized
5739         // node. Cost is 0.
5740         LLVM_DEBUG(
5741             dbgs()
5742             << "SLP: perfect diamond match for gather bundle that starts with "
5743             << *VL.front() << ".\n");
5744         if (NeedToShuffleReuses)
5745           GatherCost =
5746               TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5747                                   FinalVecTy, E->ReuseShuffleIndices);
5748       } else {
5749         LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size()
5750                           << " entries for bundle that starts with "
5751                           << *VL.front() << ".\n");
5752         // Detected that instead of gather we can emit a shuffle of single/two
5753         // previously vectorized nodes. Add the cost of the permutation rather
5754         // than gather.
5755         ::addMask(Mask, E->ReuseShuffleIndices);
5756         GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask);
5757       }
5758       return GatherCost;
5759     }
5760     if ((E->getOpcode() == Instruction::ExtractElement ||
5761          all_of(E->Scalars,
5762                 [](Value *V) {
5763                   return isa<ExtractElementInst, UndefValue>(V);
5764                 })) &&
5765         allSameType(VL)) {
5766       // Check that gather of extractelements can be represented as just a
5767       // shuffle of a single/two vectors the scalars are extracted from.
5768       SmallVector<int> Mask;
5769       Optional<TargetTransformInfo::ShuffleKind> ShuffleKind =
5770           isFixedVectorShuffle(VL, Mask);
5771       if (ShuffleKind.hasValue()) {
5772         // Found the bunch of extractelement instructions that must be gathered
5773         // into a vector and can be represented as a permutation elements in a
5774         // single input vector or of 2 input vectors.
5775         InstructionCost Cost =
5776             computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI);
5777         AdjustExtractsCost(Cost);
5778         if (NeedToShuffleReuses)
5779           Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5780                                       FinalVecTy, E->ReuseShuffleIndices);
5781         return Cost;
5782       }
5783     }
5784     if (isSplat(VL)) {
5785       // Found the broadcasting of the single scalar, calculate the cost as the
5786       // broadcast.
5787       assert(VecTy == FinalVecTy &&
5788              "No reused scalars expected for broadcast.");
5789       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy,
5790                                  /*Mask=*/None, /*Index=*/0,
5791                                  /*SubTp=*/nullptr, /*Args=*/VL[0]);
5792     }
5793     InstructionCost ReuseShuffleCost = 0;
5794     if (NeedToShuffleReuses)
5795       ReuseShuffleCost = TTI->getShuffleCost(
5796           TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices);
5797     // Improve gather cost for gather of loads, if we can group some of the
5798     // loads into vector loads.
5799     if (VL.size() > 2 && E->getOpcode() == Instruction::Load &&
5800         !E->isAltShuffle()) {
5801       BoUpSLP::ValueSet VectorizedLoads;
5802       unsigned StartIdx = 0;
5803       unsigned VF = VL.size() / 2;
5804       unsigned VectorizedCnt = 0;
5805       unsigned ScatterVectorizeCnt = 0;
5806       const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType());
5807       for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) {
5808         for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End;
5809              Cnt += VF) {
5810           ArrayRef<Value *> Slice = VL.slice(Cnt, VF);
5811           if (!VectorizedLoads.count(Slice.front()) &&
5812               !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) {
5813             SmallVector<Value *> PointerOps;
5814             OrdersType CurrentOrder;
5815             LoadsState LS = canVectorizeLoads(Slice, Slice.front(), *TTI, *DL,
5816                                               *SE, CurrentOrder, PointerOps);
5817             switch (LS) {
5818             case LoadsState::Vectorize:
5819             case LoadsState::ScatterVectorize:
5820               // Mark the vectorized loads so that we don't vectorize them
5821               // again.
5822               if (LS == LoadsState::Vectorize)
5823                 ++VectorizedCnt;
5824               else
5825                 ++ScatterVectorizeCnt;
5826               VectorizedLoads.insert(Slice.begin(), Slice.end());
5827               // If we vectorized initial block, no need to try to vectorize it
5828               // again.
5829               if (Cnt == StartIdx)
5830                 StartIdx += VF;
5831               break;
5832             case LoadsState::Gather:
5833               break;
5834             }
5835           }
5836         }
5837         // Check if the whole array was vectorized already - exit.
5838         if (StartIdx >= VL.size())
5839           break;
5840         // Found vectorizable parts - exit.
5841         if (!VectorizedLoads.empty())
5842           break;
5843       }
5844       if (!VectorizedLoads.empty()) {
5845         InstructionCost GatherCost = 0;
5846         unsigned NumParts = TTI->getNumberOfParts(VecTy);
5847         bool NeedInsertSubvectorAnalysis =
5848             !NumParts || (VL.size() / VF) > NumParts;
5849         // Get the cost for gathered loads.
5850         for (unsigned I = 0, End = VL.size(); I < End; I += VF) {
5851           if (VectorizedLoads.contains(VL[I]))
5852             continue;
5853           GatherCost += getGatherCost(VL.slice(I, VF));
5854         }
5855         // The cost for vectorized loads.
5856         InstructionCost ScalarsCost = 0;
5857         for (Value *V : VectorizedLoads) {
5858           auto *LI = cast<LoadInst>(V);
5859           ScalarsCost += TTI->getMemoryOpCost(
5860               Instruction::Load, LI->getType(), LI->getAlign(),
5861               LI->getPointerAddressSpace(), CostKind, LI);
5862         }
5863         auto *LI = cast<LoadInst>(E->getMainOp());
5864         auto *LoadTy = FixedVectorType::get(LI->getType(), VF);
5865         Align Alignment = LI->getAlign();
5866         GatherCost +=
5867             VectorizedCnt *
5868             TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment,
5869                                  LI->getPointerAddressSpace(), CostKind, LI);
5870         GatherCost += ScatterVectorizeCnt *
5871                       TTI->getGatherScatterOpCost(
5872                           Instruction::Load, LoadTy, LI->getPointerOperand(),
5873                           /*VariableMask=*/false, Alignment, CostKind, LI);
5874         if (NeedInsertSubvectorAnalysis) {
5875           // Add the cost for the subvectors insert.
5876           for (int I = VF, E = VL.size(); I < E; I += VF)
5877             GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy,
5878                                               None, I, LoadTy);
5879         }
5880         return ReuseShuffleCost + GatherCost - ScalarsCost;
5881       }
5882     }
5883     return ReuseShuffleCost + getGatherCost(VL);
5884   }
5885   InstructionCost CommonCost = 0;
5886   SmallVector<int> Mask;
5887   if (!E->ReorderIndices.empty()) {
5888     SmallVector<int> NewMask;
5889     if (E->getOpcode() == Instruction::Store) {
5890       // For stores the order is actually a mask.
5891       NewMask.resize(E->ReorderIndices.size());
5892       copy(E->ReorderIndices, NewMask.begin());
5893     } else {
5894       inversePermutation(E->ReorderIndices, NewMask);
5895     }
5896     ::addMask(Mask, NewMask);
5897   }
5898   if (NeedToShuffleReuses)
5899     ::addMask(Mask, E->ReuseShuffleIndices);
5900   if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask))
5901     CommonCost =
5902         TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask);
5903   assert((E->State == TreeEntry::Vectorize ||
5904           E->State == TreeEntry::ScatterVectorize) &&
5905          "Unhandled state");
5906   assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
5907   Instruction *VL0 = E->getMainOp();
5908   unsigned ShuffleOrOp =
5909       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
5910   switch (ShuffleOrOp) {
5911     case Instruction::PHI:
5912       return 0;
5913 
5914     case Instruction::ExtractValue:
5915     case Instruction::ExtractElement: {
5916       // The common cost of removal ExtractElement/ExtractValue instructions +
5917       // the cost of shuffles, if required to resuffle the original vector.
5918       if (NeedToShuffleReuses) {
5919         unsigned Idx = 0;
5920         for (unsigned I : E->ReuseShuffleIndices) {
5921           if (ShuffleOrOp == Instruction::ExtractElement) {
5922             auto *EE = cast<ExtractElementInst>(VL[I]);
5923             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5924                                                   EE->getVectorOperandType(),
5925                                                   *getExtractIndex(EE));
5926           } else {
5927             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5928                                                   VecTy, Idx);
5929             ++Idx;
5930           }
5931         }
5932         Idx = EntryVF;
5933         for (Value *V : VL) {
5934           if (ShuffleOrOp == Instruction::ExtractElement) {
5935             auto *EE = cast<ExtractElementInst>(V);
5936             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5937                                                   EE->getVectorOperandType(),
5938                                                   *getExtractIndex(EE));
5939           } else {
5940             --Idx;
5941             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5942                                                   VecTy, Idx);
5943           }
5944         }
5945       }
5946       if (ShuffleOrOp == Instruction::ExtractValue) {
5947         for (unsigned I = 0, E = VL.size(); I < E; ++I) {
5948           auto *EI = cast<Instruction>(VL[I]);
5949           // Take credit for instruction that will become dead.
5950           if (EI->hasOneUse()) {
5951             Instruction *Ext = EI->user_back();
5952             if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5953                 all_of(Ext->users(),
5954                        [](User *U) { return isa<GetElementPtrInst>(U); })) {
5955               // Use getExtractWithExtendCost() to calculate the cost of
5956               // extractelement/ext pair.
5957               CommonCost -= TTI->getExtractWithExtendCost(
5958                   Ext->getOpcode(), Ext->getType(), VecTy, I);
5959               // Add back the cost of s|zext which is subtracted separately.
5960               CommonCost += TTI->getCastInstrCost(
5961                   Ext->getOpcode(), Ext->getType(), EI->getType(),
5962                   TTI::getCastContextHint(Ext), CostKind, Ext);
5963               continue;
5964             }
5965           }
5966           CommonCost -=
5967               TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I);
5968         }
5969       } else {
5970         AdjustExtractsCost(CommonCost);
5971       }
5972       return CommonCost;
5973     }
5974     case Instruction::InsertElement: {
5975       assert(E->ReuseShuffleIndices.empty() &&
5976              "Unique insertelements only are expected.");
5977       auto *SrcVecTy = cast<FixedVectorType>(VL0->getType());
5978 
5979       unsigned const NumElts = SrcVecTy->getNumElements();
5980       unsigned const NumScalars = VL.size();
5981       APInt DemandedElts = APInt::getZero(NumElts);
5982       // TODO: Add support for Instruction::InsertValue.
5983       SmallVector<int> Mask;
5984       if (!E->ReorderIndices.empty()) {
5985         inversePermutation(E->ReorderIndices, Mask);
5986         Mask.append(NumElts - NumScalars, UndefMaskElem);
5987       } else {
5988         Mask.assign(NumElts, UndefMaskElem);
5989         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
5990       }
5991       unsigned Offset = *getInsertIndex(VL0);
5992       bool IsIdentity = true;
5993       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
5994       Mask.swap(PrevMask);
5995       for (unsigned I = 0; I < NumScalars; ++I) {
5996         unsigned InsertIdx = *getInsertIndex(VL[PrevMask[I]]);
5997         DemandedElts.setBit(InsertIdx);
5998         IsIdentity &= InsertIdx - Offset == I;
5999         Mask[InsertIdx - Offset] = I;
6000       }
6001       assert(Offset < NumElts && "Failed to find vector index offset");
6002 
6003       InstructionCost Cost = 0;
6004       Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts,
6005                                             /*Insert*/ true, /*Extract*/ false);
6006 
6007       if (IsIdentity && NumElts != NumScalars && Offset % NumScalars != 0) {
6008         // FIXME: Replace with SK_InsertSubvector once it is properly supported.
6009         unsigned Sz = PowerOf2Ceil(Offset + NumScalars);
6010         Cost += TTI->getShuffleCost(
6011             TargetTransformInfo::SK_PermuteSingleSrc,
6012             FixedVectorType::get(SrcVecTy->getElementType(), Sz));
6013       } else if (!IsIdentity) {
6014         auto *FirstInsert =
6015             cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
6016               return !is_contained(E->Scalars,
6017                                    cast<Instruction>(V)->getOperand(0));
6018             }));
6019         if (isUndefVector(FirstInsert->getOperand(0))) {
6020           Cost += TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, SrcVecTy, Mask);
6021         } else {
6022           SmallVector<int> InsertMask(NumElts);
6023           std::iota(InsertMask.begin(), InsertMask.end(), 0);
6024           for (unsigned I = 0; I < NumElts; I++) {
6025             if (Mask[I] != UndefMaskElem)
6026               InsertMask[Offset + I] = NumElts + I;
6027           }
6028           Cost +=
6029               TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVecTy, InsertMask);
6030         }
6031       }
6032 
6033       return Cost;
6034     }
6035     case Instruction::ZExt:
6036     case Instruction::SExt:
6037     case Instruction::FPToUI:
6038     case Instruction::FPToSI:
6039     case Instruction::FPExt:
6040     case Instruction::PtrToInt:
6041     case Instruction::IntToPtr:
6042     case Instruction::SIToFP:
6043     case Instruction::UIToFP:
6044     case Instruction::Trunc:
6045     case Instruction::FPTrunc:
6046     case Instruction::BitCast: {
6047       Type *SrcTy = VL0->getOperand(0)->getType();
6048       InstructionCost ScalarEltCost =
6049           TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy,
6050                                 TTI::getCastContextHint(VL0), CostKind, VL0);
6051       if (NeedToShuffleReuses) {
6052         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
6053       }
6054 
6055       // Calculate the cost of this instruction.
6056       InstructionCost ScalarCost = VL.size() * ScalarEltCost;
6057 
6058       auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size());
6059       InstructionCost VecCost = 0;
6060       // Check if the values are candidates to demote.
6061       if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
6062         VecCost = CommonCost + TTI->getCastInstrCost(
6063                                    E->getOpcode(), VecTy, SrcVecTy,
6064                                    TTI::getCastContextHint(VL0), CostKind, VL0);
6065       }
6066       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
6067       return VecCost - ScalarCost;
6068     }
6069     case Instruction::FCmp:
6070     case Instruction::ICmp:
6071     case Instruction::Select: {
6072       // Calculate the cost of this instruction.
6073       InstructionCost ScalarEltCost =
6074           TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
6075                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0);
6076       if (NeedToShuffleReuses) {
6077         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
6078       }
6079       auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size());
6080       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
6081 
6082       // Check if all entries in VL are either compares or selects with compares
6083       // as condition that have the same predicates.
6084       CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE;
6085       bool First = true;
6086       for (auto *V : VL) {
6087         CmpInst::Predicate CurrentPred;
6088         auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value());
6089         if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) &&
6090              !match(V, MatchCmp)) ||
6091             (!First && VecPred != CurrentPred)) {
6092           VecPred = CmpInst::BAD_ICMP_PREDICATE;
6093           break;
6094         }
6095         First = false;
6096         VecPred = CurrentPred;
6097       }
6098 
6099       InstructionCost VecCost = TTI->getCmpSelInstrCost(
6100           E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0);
6101       // Check if it is possible and profitable to use min/max for selects in
6102       // VL.
6103       //
6104       auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL);
6105       if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) {
6106         IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy,
6107                                           {VecTy, VecTy});
6108         InstructionCost IntrinsicCost =
6109             TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
6110         // If the selects are the only uses of the compares, they will be dead
6111         // and we can adjust the cost by removing their cost.
6112         if (IntrinsicAndUse.second)
6113           IntrinsicCost -= TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy,
6114                                                    MaskTy, VecPred, CostKind);
6115         VecCost = std::min(VecCost, IntrinsicCost);
6116       }
6117       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
6118       return CommonCost + VecCost - ScalarCost;
6119     }
6120     case Instruction::FNeg:
6121     case Instruction::Add:
6122     case Instruction::FAdd:
6123     case Instruction::Sub:
6124     case Instruction::FSub:
6125     case Instruction::Mul:
6126     case Instruction::FMul:
6127     case Instruction::UDiv:
6128     case Instruction::SDiv:
6129     case Instruction::FDiv:
6130     case Instruction::URem:
6131     case Instruction::SRem:
6132     case Instruction::FRem:
6133     case Instruction::Shl:
6134     case Instruction::LShr:
6135     case Instruction::AShr:
6136     case Instruction::And:
6137     case Instruction::Or:
6138     case Instruction::Xor: {
6139       // Certain instructions can be cheaper to vectorize if they have a
6140       // constant second vector operand.
6141       TargetTransformInfo::OperandValueKind Op1VK =
6142           TargetTransformInfo::OK_AnyValue;
6143       TargetTransformInfo::OperandValueKind Op2VK =
6144           TargetTransformInfo::OK_UniformConstantValue;
6145       TargetTransformInfo::OperandValueProperties Op1VP =
6146           TargetTransformInfo::OP_None;
6147       TargetTransformInfo::OperandValueProperties Op2VP =
6148           TargetTransformInfo::OP_PowerOf2;
6149 
6150       // If all operands are exactly the same ConstantInt then set the
6151       // operand kind to OK_UniformConstantValue.
6152       // If instead not all operands are constants, then set the operand kind
6153       // to OK_AnyValue. If all operands are constants but not the same,
6154       // then set the operand kind to OK_NonUniformConstantValue.
6155       ConstantInt *CInt0 = nullptr;
6156       for (unsigned i = 0, e = VL.size(); i < e; ++i) {
6157         const Instruction *I = cast<Instruction>(VL[i]);
6158         unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0;
6159         ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx));
6160         if (!CInt) {
6161           Op2VK = TargetTransformInfo::OK_AnyValue;
6162           Op2VP = TargetTransformInfo::OP_None;
6163           break;
6164         }
6165         if (Op2VP == TargetTransformInfo::OP_PowerOf2 &&
6166             !CInt->getValue().isPowerOf2())
6167           Op2VP = TargetTransformInfo::OP_None;
6168         if (i == 0) {
6169           CInt0 = CInt;
6170           continue;
6171         }
6172         if (CInt0 != CInt)
6173           Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
6174       }
6175 
6176       SmallVector<const Value *, 4> Operands(VL0->operand_values());
6177       InstructionCost ScalarEltCost =
6178           TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK,
6179                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
6180       if (NeedToShuffleReuses) {
6181         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
6182       }
6183       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
6184       InstructionCost VecCost =
6185           TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK,
6186                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
6187       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
6188       return CommonCost + VecCost - ScalarCost;
6189     }
6190     case Instruction::GetElementPtr: {
6191       TargetTransformInfo::OperandValueKind Op1VK =
6192           TargetTransformInfo::OK_AnyValue;
6193       TargetTransformInfo::OperandValueKind Op2VK =
6194           TargetTransformInfo::OK_UniformConstantValue;
6195 
6196       InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost(
6197           Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK);
6198       if (NeedToShuffleReuses) {
6199         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
6200       }
6201       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
6202       InstructionCost VecCost = TTI->getArithmeticInstrCost(
6203           Instruction::Add, VecTy, CostKind, Op1VK, Op2VK);
6204       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
6205       return CommonCost + VecCost - ScalarCost;
6206     }
6207     case Instruction::Load: {
6208       // Cost of wide load - cost of scalar loads.
6209       Align Alignment = cast<LoadInst>(VL0)->getAlign();
6210       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
6211           Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0);
6212       if (NeedToShuffleReuses) {
6213         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
6214       }
6215       InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost;
6216       InstructionCost VecLdCost;
6217       if (E->State == TreeEntry::Vectorize) {
6218         VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0,
6219                                          CostKind, VL0);
6220       } else {
6221         assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState");
6222         Align CommonAlignment = Alignment;
6223         for (Value *V : VL)
6224           CommonAlignment =
6225               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
6226         VecLdCost = TTI->getGatherScatterOpCost(
6227             Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(),
6228             /*VariableMask=*/false, CommonAlignment, CostKind, VL0);
6229       }
6230       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost));
6231       return CommonCost + VecLdCost - ScalarLdCost;
6232     }
6233     case Instruction::Store: {
6234       // We know that we can merge the stores. Calculate the cost.
6235       bool IsReorder = !E->ReorderIndices.empty();
6236       auto *SI =
6237           cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0);
6238       Align Alignment = SI->getAlign();
6239       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
6240           Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0);
6241       InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost;
6242       InstructionCost VecStCost = TTI->getMemoryOpCost(
6243           Instruction::Store, VecTy, Alignment, 0, CostKind, VL0);
6244       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost));
6245       return CommonCost + VecStCost - ScalarStCost;
6246     }
6247     case Instruction::Call: {
6248       CallInst *CI = cast<CallInst>(VL0);
6249       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
6250 
6251       // Calculate the cost of the scalar and vector calls.
6252       IntrinsicCostAttributes CostAttrs(ID, *CI, 1);
6253       InstructionCost ScalarEltCost =
6254           TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
6255       if (NeedToShuffleReuses) {
6256         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
6257       }
6258       InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
6259 
6260       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
6261       InstructionCost VecCallCost =
6262           std::min(VecCallCosts.first, VecCallCosts.second);
6263 
6264       LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
6265                         << " (" << VecCallCost << "-" << ScalarCallCost << ")"
6266                         << " for " << *CI << "\n");
6267 
6268       return CommonCost + VecCallCost - ScalarCallCost;
6269     }
6270     case Instruction::ShuffleVector: {
6271       assert(E->isAltShuffle() &&
6272              ((Instruction::isBinaryOp(E->getOpcode()) &&
6273                Instruction::isBinaryOp(E->getAltOpcode())) ||
6274               (Instruction::isCast(E->getOpcode()) &&
6275                Instruction::isCast(E->getAltOpcode())) ||
6276               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
6277              "Invalid Shuffle Vector Operand");
6278       InstructionCost ScalarCost = 0;
6279       if (NeedToShuffleReuses) {
6280         for (unsigned Idx : E->ReuseShuffleIndices) {
6281           Instruction *I = cast<Instruction>(VL[Idx]);
6282           CommonCost -= TTI->getInstructionCost(I, CostKind);
6283         }
6284         for (Value *V : VL) {
6285           Instruction *I = cast<Instruction>(V);
6286           CommonCost += TTI->getInstructionCost(I, CostKind);
6287         }
6288       }
6289       for (Value *V : VL) {
6290         Instruction *I = cast<Instruction>(V);
6291         assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
6292         ScalarCost += TTI->getInstructionCost(I, CostKind);
6293       }
6294       // VecCost is equal to sum of the cost of creating 2 vectors
6295       // and the cost of creating shuffle.
6296       InstructionCost VecCost = 0;
6297       // Try to find the previous shuffle node with the same operands and same
6298       // main/alternate ops.
6299       auto &&TryFindNodeWithEqualOperands = [this, E]() {
6300         for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
6301           if (TE.get() == E)
6302             break;
6303           if (TE->isAltShuffle() &&
6304               ((TE->getOpcode() == E->getOpcode() &&
6305                 TE->getAltOpcode() == E->getAltOpcode()) ||
6306                (TE->getOpcode() == E->getAltOpcode() &&
6307                 TE->getAltOpcode() == E->getOpcode())) &&
6308               TE->hasEqualOperands(*E))
6309             return true;
6310         }
6311         return false;
6312       };
6313       if (TryFindNodeWithEqualOperands()) {
6314         LLVM_DEBUG({
6315           dbgs() << "SLP: diamond match for alternate node found.\n";
6316           E->dump();
6317         });
6318         // No need to add new vector costs here since we're going to reuse
6319         // same main/alternate vector ops, just do different shuffling.
6320       } else if (Instruction::isBinaryOp(E->getOpcode())) {
6321         VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind);
6322         VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy,
6323                                                CostKind);
6324       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
6325         VecCost = TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy,
6326                                           Builder.getInt1Ty(),
6327                                           CI0->getPredicate(), CostKind, VL0);
6328         VecCost += TTI->getCmpSelInstrCost(
6329             E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
6330             cast<CmpInst>(E->getAltOp())->getPredicate(), CostKind,
6331             E->getAltOp());
6332       } else {
6333         Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
6334         Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
6335         auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size());
6336         auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size());
6337         VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty,
6338                                         TTI::CastContextHint::None, CostKind);
6339         VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty,
6340                                          TTI::CastContextHint::None, CostKind);
6341       }
6342 
6343       if (E->ReuseShuffleIndices.empty()) {
6344         CommonCost =
6345             TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy);
6346       } else {
6347         SmallVector<int> Mask;
6348         buildShuffleEntryMask(
6349             E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
6350             [E](Instruction *I) {
6351               assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
6352               return I->getOpcode() == E->getAltOpcode();
6353             },
6354             Mask);
6355         CommonCost = TTI->getShuffleCost(TargetTransformInfo::SK_PermuteTwoSrc,
6356                                          FinalVecTy, Mask);
6357       }
6358       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
6359       return CommonCost + VecCost - ScalarCost;
6360     }
6361     default:
6362       llvm_unreachable("Unknown instruction");
6363   }
6364 }
6365 
6366 bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const {
6367   LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
6368                     << VectorizableTree.size() << " is fully vectorizable .\n");
6369 
6370   auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) {
6371     SmallVector<int> Mask;
6372     return TE->State == TreeEntry::NeedToGather &&
6373            !any_of(TE->Scalars,
6374                    [this](Value *V) { return EphValues.contains(V); }) &&
6375            (allConstant(TE->Scalars) || isSplat(TE->Scalars) ||
6376             TE->Scalars.size() < Limit ||
6377             ((TE->getOpcode() == Instruction::ExtractElement ||
6378               all_of(TE->Scalars,
6379                      [](Value *V) {
6380                        return isa<ExtractElementInst, UndefValue>(V);
6381                      })) &&
6382              isFixedVectorShuffle(TE->Scalars, Mask)) ||
6383             (TE->State == TreeEntry::NeedToGather &&
6384              TE->getOpcode() == Instruction::Load && !TE->isAltShuffle()));
6385   };
6386 
6387   // We only handle trees of heights 1 and 2.
6388   if (VectorizableTree.size() == 1 &&
6389       (VectorizableTree[0]->State == TreeEntry::Vectorize ||
6390        (ForReduction &&
6391         AreVectorizableGathers(VectorizableTree[0].get(),
6392                                VectorizableTree[0]->Scalars.size()) &&
6393         VectorizableTree[0]->getVectorFactor() > 2)))
6394     return true;
6395 
6396   if (VectorizableTree.size() != 2)
6397     return false;
6398 
6399   // Handle splat and all-constants stores. Also try to vectorize tiny trees
6400   // with the second gather nodes if they have less scalar operands rather than
6401   // the initial tree element (may be profitable to shuffle the second gather)
6402   // or they are extractelements, which form shuffle.
6403   SmallVector<int> Mask;
6404   if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
6405       AreVectorizableGathers(VectorizableTree[1].get(),
6406                              VectorizableTree[0]->Scalars.size()))
6407     return true;
6408 
6409   // Gathering cost would be too much for tiny trees.
6410   if (VectorizableTree[0]->State == TreeEntry::NeedToGather ||
6411       (VectorizableTree[1]->State == TreeEntry::NeedToGather &&
6412        VectorizableTree[0]->State != TreeEntry::ScatterVectorize))
6413     return false;
6414 
6415   return true;
6416 }
6417 
6418 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts,
6419                                        TargetTransformInfo *TTI,
6420                                        bool MustMatchOrInst) {
6421   // Look past the root to find a source value. Arbitrarily follow the
6422   // path through operand 0 of any 'or'. Also, peek through optional
6423   // shift-left-by-multiple-of-8-bits.
6424   Value *ZextLoad = Root;
6425   const APInt *ShAmtC;
6426   bool FoundOr = false;
6427   while (!isa<ConstantExpr>(ZextLoad) &&
6428          (match(ZextLoad, m_Or(m_Value(), m_Value())) ||
6429           (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) &&
6430            ShAmtC->urem(8) == 0))) {
6431     auto *BinOp = cast<BinaryOperator>(ZextLoad);
6432     ZextLoad = BinOp->getOperand(0);
6433     if (BinOp->getOpcode() == Instruction::Or)
6434       FoundOr = true;
6435   }
6436   // Check if the input is an extended load of the required or/shift expression.
6437   Value *Load;
6438   if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root ||
6439       !match(ZextLoad, m_ZExt(m_Value(Load))) || !isa<LoadInst>(Load))
6440     return false;
6441 
6442   // Require that the total load bit width is a legal integer type.
6443   // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
6444   // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
6445   Type *SrcTy = Load->getType();
6446   unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts;
6447   if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth)))
6448     return false;
6449 
6450   // Everything matched - assume that we can fold the whole sequence using
6451   // load combining.
6452   LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "
6453              << *(cast<Instruction>(Root)) << "\n");
6454 
6455   return true;
6456 }
6457 
6458 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const {
6459   if (RdxKind != RecurKind::Or)
6460     return false;
6461 
6462   unsigned NumElts = VectorizableTree[0]->Scalars.size();
6463   Value *FirstReduced = VectorizableTree[0]->Scalars[0];
6464   return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI,
6465                                     /* MatchOr */ false);
6466 }
6467 
6468 bool BoUpSLP::isLoadCombineCandidate() const {
6469   // Peek through a final sequence of stores and check if all operations are
6470   // likely to be load-combined.
6471   unsigned NumElts = VectorizableTree[0]->Scalars.size();
6472   for (Value *Scalar : VectorizableTree[0]->Scalars) {
6473     Value *X;
6474     if (!match(Scalar, m_Store(m_Value(X), m_Value())) ||
6475         !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true))
6476       return false;
6477   }
6478   return true;
6479 }
6480 
6481 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const {
6482   // No need to vectorize inserts of gathered values.
6483   if (VectorizableTree.size() == 2 &&
6484       isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) &&
6485       VectorizableTree[1]->State == TreeEntry::NeedToGather)
6486     return true;
6487 
6488   // We can vectorize the tree if its size is greater than or equal to the
6489   // minimum size specified by the MinTreeSize command line option.
6490   if (VectorizableTree.size() >= MinTreeSize)
6491     return false;
6492 
6493   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
6494   // can vectorize it if we can prove it fully vectorizable.
6495   if (isFullyVectorizableTinyTree(ForReduction))
6496     return false;
6497 
6498   assert(VectorizableTree.empty()
6499              ? ExternalUses.empty()
6500              : true && "We shouldn't have any external users");
6501 
6502   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
6503   // vectorizable.
6504   return true;
6505 }
6506 
6507 InstructionCost BoUpSLP::getSpillCost() const {
6508   // Walk from the bottom of the tree to the top, tracking which values are
6509   // live. When we see a call instruction that is not part of our tree,
6510   // query TTI to see if there is a cost to keeping values live over it
6511   // (for example, if spills and fills are required).
6512   unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
6513   InstructionCost Cost = 0;
6514 
6515   SmallPtrSet<Instruction*, 4> LiveValues;
6516   Instruction *PrevInst = nullptr;
6517 
6518   // The entries in VectorizableTree are not necessarily ordered by their
6519   // position in basic blocks. Collect them and order them by dominance so later
6520   // instructions are guaranteed to be visited first. For instructions in
6521   // different basic blocks, we only scan to the beginning of the block, so
6522   // their order does not matter, as long as all instructions in a basic block
6523   // are grouped together. Using dominance ensures a deterministic order.
6524   SmallVector<Instruction *, 16> OrderedScalars;
6525   for (const auto &TEPtr : VectorizableTree) {
6526     Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
6527     if (!Inst)
6528       continue;
6529     OrderedScalars.push_back(Inst);
6530   }
6531   llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) {
6532     auto *NodeA = DT->getNode(A->getParent());
6533     auto *NodeB = DT->getNode(B->getParent());
6534     assert(NodeA && "Should only process reachable instructions");
6535     assert(NodeB && "Should only process reachable instructions");
6536     assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
6537            "Different nodes should have different DFS numbers");
6538     if (NodeA != NodeB)
6539       return NodeA->getDFSNumIn() < NodeB->getDFSNumIn();
6540     return B->comesBefore(A);
6541   });
6542 
6543   for (Instruction *Inst : OrderedScalars) {
6544     if (!PrevInst) {
6545       PrevInst = Inst;
6546       continue;
6547     }
6548 
6549     // Update LiveValues.
6550     LiveValues.erase(PrevInst);
6551     for (auto &J : PrevInst->operands()) {
6552       if (isa<Instruction>(&*J) && getTreeEntry(&*J))
6553         LiveValues.insert(cast<Instruction>(&*J));
6554     }
6555 
6556     LLVM_DEBUG({
6557       dbgs() << "SLP: #LV: " << LiveValues.size();
6558       for (auto *X : LiveValues)
6559         dbgs() << " " << X->getName();
6560       dbgs() << ", Looking at ";
6561       Inst->dump();
6562     });
6563 
6564     // Now find the sequence of instructions between PrevInst and Inst.
6565     unsigned NumCalls = 0;
6566     BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
6567                                  PrevInstIt =
6568                                      PrevInst->getIterator().getReverse();
6569     while (InstIt != PrevInstIt) {
6570       if (PrevInstIt == PrevInst->getParent()->rend()) {
6571         PrevInstIt = Inst->getParent()->rbegin();
6572         continue;
6573       }
6574 
6575       // Debug information does not impact spill cost.
6576       if ((isa<CallInst>(&*PrevInstIt) &&
6577            !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
6578           &*PrevInstIt != PrevInst)
6579         NumCalls++;
6580 
6581       ++PrevInstIt;
6582     }
6583 
6584     if (NumCalls) {
6585       SmallVector<Type*, 4> V;
6586       for (auto *II : LiveValues) {
6587         auto *ScalarTy = II->getType();
6588         if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy))
6589           ScalarTy = VectorTy->getElementType();
6590         V.push_back(FixedVectorType::get(ScalarTy, BundleWidth));
6591       }
6592       Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
6593     }
6594 
6595     PrevInst = Inst;
6596   }
6597 
6598   return Cost;
6599 }
6600 
6601 /// Check if two insertelement instructions are from the same buildvector.
6602 static bool areTwoInsertFromSameBuildVector(InsertElementInst *VU,
6603                                             InsertElementInst *V) {
6604   // Instructions must be from the same basic blocks.
6605   if (VU->getParent() != V->getParent())
6606     return false;
6607   // Checks if 2 insertelements are from the same buildvector.
6608   if (VU->getType() != V->getType())
6609     return false;
6610   // Multiple used inserts are separate nodes.
6611   if (!VU->hasOneUse() && !V->hasOneUse())
6612     return false;
6613   auto *IE1 = VU;
6614   auto *IE2 = V;
6615   unsigned Idx1 = *getInsertIndex(IE1);
6616   unsigned Idx2 = *getInsertIndex(IE2);
6617   // Go through the vector operand of insertelement instructions trying to find
6618   // either VU as the original vector for IE2 or V as the original vector for
6619   // IE1.
6620   do {
6621     if (IE2 == VU)
6622       return VU->hasOneUse();
6623     if (IE1 == V)
6624       return V->hasOneUse();
6625     if (IE1) {
6626       if ((IE1 != VU && !IE1->hasOneUse()) ||
6627           getInsertIndex(IE1).getValueOr(Idx2) == Idx2)
6628         IE1 = nullptr;
6629       else
6630         IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0));
6631     }
6632     if (IE2) {
6633       if ((IE2 != V && !IE2->hasOneUse()) ||
6634           getInsertIndex(IE2).getValueOr(Idx1) == Idx1)
6635         IE2 = nullptr;
6636       else
6637         IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0));
6638     }
6639   } while (IE1 || IE2);
6640   return false;
6641 }
6642 
6643 /// Checks if the \p IE1 instructions is followed by \p IE2 instruction in the
6644 /// buildvector sequence.
6645 static bool isFirstInsertElement(const InsertElementInst *IE1,
6646                                  const InsertElementInst *IE2) {
6647   const auto *I1 = IE1;
6648   const auto *I2 = IE2;
6649   const InsertElementInst *PrevI1;
6650   const InsertElementInst *PrevI2;
6651   unsigned Idx1 = *getInsertIndex(IE1);
6652   unsigned Idx2 = *getInsertIndex(IE2);
6653   do {
6654     if (I2 == IE1)
6655       return true;
6656     if (I1 == IE2)
6657       return false;
6658     PrevI1 = I1;
6659     PrevI2 = I2;
6660     if (I1 && (I1 == IE1 || I1->hasOneUse()) &&
6661         getInsertIndex(I1).getValueOr(Idx2) != Idx2)
6662       I1 = dyn_cast<InsertElementInst>(I1->getOperand(0));
6663     if (I2 && ((I2 == IE2 || I2->hasOneUse())) &&
6664         getInsertIndex(I2).getValueOr(Idx1) != Idx1)
6665       I2 = dyn_cast<InsertElementInst>(I2->getOperand(0));
6666   } while ((I1 && PrevI1 != I1) || (I2 && PrevI2 != I2));
6667   llvm_unreachable("Two different buildvectors not expected.");
6668 }
6669 
6670 /// Does the analysis of the provided shuffle masks and performs the requested
6671 /// actions on the vectors with the given shuffle masks. It tries to do it in
6672 /// several steps.
6673 /// 1. If the Base vector is not undef vector, resizing the very first mask to
6674 /// have common VF and perform action for 2 input vectors (including non-undef
6675 /// Base). Other shuffle masks are combined with the resulting after the 1 stage
6676 /// and processed as a shuffle of 2 elements.
6677 /// 2. If the Base is undef vector and have only 1 shuffle mask, perform the
6678 /// action only for 1 vector with the given mask, if it is not the identity
6679 /// mask.
6680 /// 3. If > 2 masks are used, perform the remaining shuffle actions for 2
6681 /// vectors, combing the masks properly between the steps.
6682 template <typename T>
6683 static T *performExtractsShuffleAction(
6684     MutableArrayRef<std::pair<T *, SmallVector<int>>> ShuffleMask, Value *Base,
6685     function_ref<unsigned(T *)> GetVF,
6686     function_ref<std::pair<T *, bool>(T *, ArrayRef<int>)> ResizeAction,
6687     function_ref<T *(ArrayRef<int>, ArrayRef<T *>)> Action) {
6688   assert(!ShuffleMask.empty() && "Empty list of shuffles for inserts.");
6689   SmallVector<int> Mask(ShuffleMask.begin()->second);
6690   auto VMIt = std::next(ShuffleMask.begin());
6691   T *Prev = nullptr;
6692   bool IsBaseNotUndef = !isUndefVector(Base);
6693   if (IsBaseNotUndef) {
6694     // Base is not undef, need to combine it with the next subvectors.
6695     std::pair<T *, bool> Res = ResizeAction(ShuffleMask.begin()->first, Mask);
6696     for (unsigned Idx = 0, VF = Mask.size(); Idx < VF; ++Idx) {
6697       if (Mask[Idx] == UndefMaskElem)
6698         Mask[Idx] = Idx;
6699       else
6700         Mask[Idx] = (Res.second ? Idx : Mask[Idx]) + VF;
6701     }
6702     Prev = Action(Mask, {nullptr, Res.first});
6703   } else if (ShuffleMask.size() == 1) {
6704     // Base is undef and only 1 vector is shuffled - perform the action only for
6705     // single vector, if the mask is not the identity mask.
6706     std::pair<T *, bool> Res = ResizeAction(ShuffleMask.begin()->first, Mask);
6707     if (Res.second)
6708       // Identity mask is found.
6709       Prev = Res.first;
6710     else
6711       Prev = Action(Mask, {ShuffleMask.begin()->first});
6712   } else {
6713     // Base is undef and at least 2 input vectors shuffled - perform 2 vectors
6714     // shuffles step by step, combining shuffle between the steps.
6715     unsigned Vec1VF = GetVF(ShuffleMask.begin()->first);
6716     unsigned Vec2VF = GetVF(VMIt->first);
6717     if (Vec1VF == Vec2VF) {
6718       // No need to resize the input vectors since they are of the same size, we
6719       // can shuffle them directly.
6720       ArrayRef<int> SecMask = VMIt->second;
6721       for (unsigned I = 0, VF = Mask.size(); I < VF; ++I) {
6722         if (SecMask[I] != UndefMaskElem) {
6723           assert(Mask[I] == UndefMaskElem && "Multiple uses of scalars.");
6724           Mask[I] = SecMask[I] + Vec1VF;
6725         }
6726       }
6727       Prev = Action(Mask, {ShuffleMask.begin()->first, VMIt->first});
6728     } else {
6729       // Vectors of different sizes - resize and reshuffle.
6730       std::pair<T *, bool> Res1 =
6731           ResizeAction(ShuffleMask.begin()->first, Mask);
6732       std::pair<T *, bool> Res2 = ResizeAction(VMIt->first, VMIt->second);
6733       ArrayRef<int> SecMask = VMIt->second;
6734       for (unsigned I = 0, VF = Mask.size(); I < VF; ++I) {
6735         if (Mask[I] != UndefMaskElem) {
6736           assert(SecMask[I] == UndefMaskElem && "Multiple uses of scalars.");
6737           if (Res1.second)
6738             Mask[I] = I;
6739         } else if (SecMask[I] != UndefMaskElem) {
6740           assert(Mask[I] == UndefMaskElem && "Multiple uses of scalars.");
6741           Mask[I] = (Res2.second ? I : SecMask[I]) + VF;
6742         }
6743       }
6744       Prev = Action(Mask, {Res1.first, Res2.first});
6745     }
6746     VMIt = std::next(VMIt);
6747   }
6748   // Perform requested actions for the remaining masks/vectors.
6749   for (auto E = ShuffleMask.end(); VMIt != E; ++VMIt) {
6750     // Shuffle other input vectors, if any.
6751     std::pair<T *, bool> Res = ResizeAction(VMIt->first, VMIt->second);
6752     ArrayRef<int> SecMask = VMIt->second;
6753     for (unsigned I = 0, VF = Mask.size(); I < VF; ++I) {
6754       if (SecMask[I] != UndefMaskElem) {
6755         assert((Mask[I] == UndefMaskElem || IsBaseNotUndef) &&
6756                "Multiple uses of scalars.");
6757         Mask[I] = (Res.second ? I : SecMask[I]) + VF;
6758       } else if (Mask[I] != UndefMaskElem) {
6759         Mask[I] = I;
6760       }
6761     }
6762     Prev = Action(Mask, {Prev, Res.first});
6763   }
6764   return Prev;
6765 }
6766 
6767 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) {
6768   InstructionCost Cost = 0;
6769   LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
6770                     << VectorizableTree.size() << ".\n");
6771 
6772   unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
6773 
6774   for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
6775     TreeEntry &TE = *VectorizableTree[I];
6776 
6777     InstructionCost C = getEntryCost(&TE, VectorizedVals);
6778     Cost += C;
6779     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6780                       << " for bundle that starts with " << *TE.Scalars[0]
6781                       << ".\n"
6782                       << "SLP: Current total cost = " << Cost << "\n");
6783   }
6784 
6785   SmallPtrSet<Value *, 16> ExtractCostCalculated;
6786   InstructionCost ExtractCost = 0;
6787   SmallVector<MapVector<const TreeEntry *, SmallVector<int>>> ShuffleMasks;
6788   SmallVector<std::pair<Value *, const TreeEntry *>> FirstUsers;
6789   SmallVector<APInt> DemandedElts;
6790   for (ExternalUser &EU : ExternalUses) {
6791     // We only add extract cost once for the same scalar.
6792     if (!isa_and_nonnull<InsertElementInst>(EU.User) &&
6793         !ExtractCostCalculated.insert(EU.Scalar).second)
6794       continue;
6795 
6796     // Uses by ephemeral values are free (because the ephemeral value will be
6797     // removed prior to code generation, and so the extraction will be
6798     // removed as well).
6799     if (EphValues.count(EU.User))
6800       continue;
6801 
6802     // No extract cost for vector "scalar"
6803     if (isa<FixedVectorType>(EU.Scalar->getType()))
6804       continue;
6805 
6806     // Already counted the cost for external uses when tried to adjust the cost
6807     // for extractelements, no need to add it again.
6808     if (isa<ExtractElementInst>(EU.Scalar))
6809       continue;
6810 
6811     // If found user is an insertelement, do not calculate extract cost but try
6812     // to detect it as a final shuffled/identity match.
6813     if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) {
6814       if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) {
6815         Optional<unsigned> InsertIdx = getInsertIndex(VU);
6816         if (InsertIdx) {
6817           const TreeEntry *ScalarTE = getTreeEntry(EU.Scalar);
6818           auto *It =
6819               find_if(FirstUsers,
6820                       [VU](const std::pair<Value *, const TreeEntry *> &Pair) {
6821                         return areTwoInsertFromSameBuildVector(
6822                             VU, cast<InsertElementInst>(Pair.first));
6823                       });
6824           int VecId = -1;
6825           if (It == FirstUsers.end()) {
6826             (void)ShuffleMasks.emplace_back();
6827             SmallVectorImpl<int> &Mask = ShuffleMasks.back()[ScalarTE];
6828             if (Mask.empty())
6829               Mask.assign(FTy->getNumElements(), UndefMaskElem);
6830             // Find the insertvector, vectorized in tree, if any.
6831             Value *Base = VU;
6832             while (auto *IEBase = dyn_cast<InsertElementInst>(Base)) {
6833               if (IEBase != EU.User &&
6834                   (!IEBase->hasOneUse() ||
6835                    getInsertIndex(IEBase).getValueOr(*InsertIdx) == *InsertIdx))
6836                 break;
6837               // Build the mask for the vectorized insertelement instructions.
6838               if (const TreeEntry *E = getTreeEntry(IEBase)) {
6839                 VU = IEBase;
6840                 do {
6841                   IEBase = cast<InsertElementInst>(Base);
6842                   int Idx = *getInsertIndex(IEBase);
6843                   assert(Mask[Idx] == UndefMaskElem &&
6844                          "InsertElementInstruction used already.");
6845                   Mask[Idx] = Idx;
6846                   Base = IEBase->getOperand(0);
6847                 } while (E == getTreeEntry(Base));
6848                 break;
6849               }
6850               Base = cast<InsertElementInst>(Base)->getOperand(0);
6851             }
6852             FirstUsers.emplace_back(VU, ScalarTE);
6853             DemandedElts.push_back(APInt::getZero(FTy->getNumElements()));
6854             VecId = FirstUsers.size() - 1;
6855           } else {
6856             if (isFirstInsertElement(VU, cast<InsertElementInst>(It->first)))
6857               It->first = VU;
6858             VecId = std::distance(FirstUsers.begin(), It);
6859           }
6860           int InIdx = *InsertIdx;
6861           SmallVectorImpl<int> &Mask = ShuffleMasks[VecId][ScalarTE];
6862           if (Mask.empty())
6863             Mask.assign(FTy->getNumElements(), UndefMaskElem);
6864           Mask[InIdx] = EU.Lane;
6865           DemandedElts[VecId].setBit(InIdx);
6866           continue;
6867         }
6868       }
6869     }
6870 
6871     // If we plan to rewrite the tree in a smaller type, we will need to sign
6872     // extend the extracted value back to the original type. Here, we account
6873     // for the extract and the added cost of the sign extend if needed.
6874     auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth);
6875     auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
6876     if (MinBWs.count(ScalarRoot)) {
6877       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
6878       auto Extend =
6879           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
6880       VecTy = FixedVectorType::get(MinTy, BundleWidth);
6881       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
6882                                                    VecTy, EU.Lane);
6883     } else {
6884       ExtractCost +=
6885           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
6886     }
6887   }
6888 
6889   InstructionCost SpillCost = getSpillCost();
6890   Cost += SpillCost + ExtractCost;
6891   auto &&ResizeToVF = [this, &Cost](const TreeEntry *TE, ArrayRef<int> Mask) {
6892     InstructionCost C = 0;
6893     unsigned VF = Mask.size();
6894     unsigned VecVF = TE->getVectorFactor();
6895     if (VF != VecVF &&
6896         (any_of(Mask, [VF](int Idx) { return Idx >= static_cast<int>(VF); }) ||
6897          (all_of(Mask,
6898                  [VF](int Idx) { return Idx < 2 * static_cast<int>(VF); }) &&
6899           !ShuffleVectorInst::isIdentityMask(Mask)))) {
6900       SmallVector<int> OrigMask(VecVF, UndefMaskElem);
6901       std::copy(Mask.begin(), std::next(Mask.begin(), std::min(VF, VecVF)),
6902                 OrigMask.begin());
6903       C = TTI->getShuffleCost(
6904           TTI::SK_PermuteSingleSrc,
6905           FixedVectorType::get(TE->getMainOp()->getType(), VecVF), OrigMask);
6906       LLVM_DEBUG(
6907           dbgs() << "SLP: Adding cost " << C
6908                  << " for final shuffle of insertelement external users.\n";
6909           TE->dump(); dbgs() << "SLP: Current total cost = " << Cost << "\n");
6910       Cost += C;
6911       return std::make_pair(TE, true);
6912     }
6913     return std::make_pair(TE, false);
6914   };
6915   // Calculate the cost of the reshuffled vectors, if any.
6916   for (int I = 0, E = FirstUsers.size(); I < E; ++I) {
6917     Value *Base = cast<Instruction>(FirstUsers[I].first)->getOperand(0);
6918     unsigned VF = ShuffleMasks[I].begin()->second.size();
6919     auto *FTy = FixedVectorType::get(
6920         cast<VectorType>(FirstUsers[I].first->getType())->getElementType(), VF);
6921     auto Vector = ShuffleMasks[I].takeVector();
6922     auto &&EstimateShufflesCost = [this, FTy,
6923                                    &Cost](ArrayRef<int> Mask,
6924                                           ArrayRef<const TreeEntry *> TEs) {
6925       assert((TEs.size() == 1 || TEs.size() == 2) &&
6926              "Expected exactly 1 or 2 tree entries.");
6927       if (TEs.size() == 1) {
6928         int Limit = 2 * Mask.size();
6929         if (!all_of(Mask, [Limit](int Idx) { return Idx < Limit; }) ||
6930             !ShuffleVectorInst::isIdentityMask(Mask)) {
6931           InstructionCost C =
6932               TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FTy, Mask);
6933           LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6934                             << " for final shuffle of insertelement "
6935                                "external users.\n";
6936                      TEs.front()->dump();
6937                      dbgs() << "SLP: Current total cost = " << Cost << "\n");
6938           Cost += C;
6939         }
6940       } else {
6941         InstructionCost C =
6942             TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, FTy, Mask);
6943         LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6944                           << " for final shuffle of vector node and external "
6945                              "insertelement users.\n";
6946                    if (TEs.front()) { TEs.front()->dump(); } TEs.back()->dump();
6947                    dbgs() << "SLP: Current total cost = " << Cost << "\n");
6948         Cost += C;
6949       }
6950       return TEs.back();
6951     };
6952     (void)performExtractsShuffleAction<const TreeEntry>(
6953         makeMutableArrayRef(Vector.data(), Vector.size()), Base,
6954         [](const TreeEntry *E) { return E->getVectorFactor(); }, ResizeToVF,
6955         EstimateShufflesCost);
6956     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6957         cast<FixedVectorType>(FirstUsers[I].first->getType()), DemandedElts[I],
6958         /*Insert*/ true, /*Extract*/ false);
6959     Cost -= InsertCost;
6960   }
6961 
6962 #ifndef NDEBUG
6963   SmallString<256> Str;
6964   {
6965     raw_svector_ostream OS(Str);
6966     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
6967        << "SLP: Extract Cost = " << ExtractCost << ".\n"
6968        << "SLP: Total Cost = " << Cost << ".\n";
6969   }
6970   LLVM_DEBUG(dbgs() << Str);
6971   if (ViewSLPTree)
6972     ViewGraph(this, "SLP" + F->getName(), false, Str);
6973 #endif
6974 
6975   return Cost;
6976 }
6977 
6978 Optional<TargetTransformInfo::ShuffleKind>
6979 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
6980                                SmallVectorImpl<const TreeEntry *> &Entries) {
6981   // TODO: currently checking only for Scalars in the tree entry, need to count
6982   // reused elements too for better cost estimation.
6983   Mask.assign(TE->Scalars.size(), UndefMaskElem);
6984   Entries.clear();
6985   // Build a lists of values to tree entries.
6986   DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs;
6987   for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) {
6988     if (EntryPtr.get() == TE)
6989       break;
6990     if (EntryPtr->State != TreeEntry::NeedToGather)
6991       continue;
6992     for (Value *V : EntryPtr->Scalars)
6993       ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get());
6994   }
6995   // Find all tree entries used by the gathered values. If no common entries
6996   // found - not a shuffle.
6997   // Here we build a set of tree nodes for each gathered value and trying to
6998   // find the intersection between these sets. If we have at least one common
6999   // tree node for each gathered value - we have just a permutation of the
7000   // single vector. If we have 2 different sets, we're in situation where we
7001   // have a permutation of 2 input vectors.
7002   SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs;
7003   DenseMap<Value *, int> UsedValuesEntry;
7004   for (Value *V : TE->Scalars) {
7005     if (isa<UndefValue>(V))
7006       continue;
7007     // Build a list of tree entries where V is used.
7008     SmallPtrSet<const TreeEntry *, 4> VToTEs;
7009     auto It = ValueToTEs.find(V);
7010     if (It != ValueToTEs.end())
7011       VToTEs = It->second;
7012     if (const TreeEntry *VTE = getTreeEntry(V))
7013       VToTEs.insert(VTE);
7014     if (VToTEs.empty())
7015       return None;
7016     if (UsedTEs.empty()) {
7017       // The first iteration, just insert the list of nodes to vector.
7018       UsedTEs.push_back(VToTEs);
7019     } else {
7020       // Need to check if there are any previously used tree nodes which use V.
7021       // If there are no such nodes, consider that we have another one input
7022       // vector.
7023       SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs);
7024       unsigned Idx = 0;
7025       for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) {
7026         // Do we have a non-empty intersection of previously listed tree entries
7027         // and tree entries using current V?
7028         set_intersect(VToTEs, Set);
7029         if (!VToTEs.empty()) {
7030           // Yes, write the new subset and continue analysis for the next
7031           // scalar.
7032           Set.swap(VToTEs);
7033           break;
7034         }
7035         VToTEs = SavedVToTEs;
7036         ++Idx;
7037       }
7038       // No non-empty intersection found - need to add a second set of possible
7039       // source vectors.
7040       if (Idx == UsedTEs.size()) {
7041         // If the number of input vectors is greater than 2 - not a permutation,
7042         // fallback to the regular gather.
7043         if (UsedTEs.size() == 2)
7044           return None;
7045         UsedTEs.push_back(SavedVToTEs);
7046         Idx = UsedTEs.size() - 1;
7047       }
7048       UsedValuesEntry.try_emplace(V, Idx);
7049     }
7050   }
7051 
7052   if (UsedTEs.empty()) {
7053     assert(all_of(TE->Scalars, UndefValue::classof) &&
7054            "Expected vector of undefs only.");
7055     return None;
7056   }
7057 
7058   unsigned VF = 0;
7059   if (UsedTEs.size() == 1) {
7060     // Try to find the perfect match in another gather node at first.
7061     auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) {
7062       return EntryPtr->isSame(TE->Scalars);
7063     });
7064     if (It != UsedTEs.front().end()) {
7065       Entries.push_back(*It);
7066       std::iota(Mask.begin(), Mask.end(), 0);
7067       return TargetTransformInfo::SK_PermuteSingleSrc;
7068     }
7069     // No perfect match, just shuffle, so choose the first tree node.
7070     Entries.push_back(*UsedTEs.front().begin());
7071   } else {
7072     // Try to find nodes with the same vector factor.
7073     assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries.");
7074     DenseMap<int, const TreeEntry *> VFToTE;
7075     for (const TreeEntry *TE : UsedTEs.front())
7076       VFToTE.try_emplace(TE->getVectorFactor(), TE);
7077     for (const TreeEntry *TE : UsedTEs.back()) {
7078       auto It = VFToTE.find(TE->getVectorFactor());
7079       if (It != VFToTE.end()) {
7080         VF = It->first;
7081         Entries.push_back(It->second);
7082         Entries.push_back(TE);
7083         break;
7084       }
7085     }
7086     // No 2 source vectors with the same vector factor - give up and do regular
7087     // gather.
7088     if (Entries.empty())
7089       return None;
7090   }
7091 
7092   // Build a shuffle mask for better cost estimation and vector emission.
7093   for (int I = 0, E = TE->Scalars.size(); I < E; ++I) {
7094     Value *V = TE->Scalars[I];
7095     if (isa<UndefValue>(V))
7096       continue;
7097     unsigned Idx = UsedValuesEntry.lookup(V);
7098     const TreeEntry *VTE = Entries[Idx];
7099     int FoundLane = VTE->findLaneForValue(V);
7100     Mask[I] = Idx * VF + FoundLane;
7101     // Extra check required by isSingleSourceMaskImpl function (called by
7102     // ShuffleVectorInst::isSingleSourceMask).
7103     if (Mask[I] >= 2 * E)
7104       return None;
7105   }
7106   switch (Entries.size()) {
7107   case 1:
7108     return TargetTransformInfo::SK_PermuteSingleSrc;
7109   case 2:
7110     return TargetTransformInfo::SK_PermuteTwoSrc;
7111   default:
7112     break;
7113   }
7114   return None;
7115 }
7116 
7117 InstructionCost BoUpSLP::getGatherCost(FixedVectorType *Ty,
7118                                        const APInt &ShuffledIndices,
7119                                        bool NeedToShuffle) const {
7120   InstructionCost Cost =
7121       TTI->getScalarizationOverhead(Ty, ~ShuffledIndices, /*Insert*/ true,
7122                                     /*Extract*/ false);
7123   if (NeedToShuffle)
7124     Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
7125   return Cost;
7126 }
7127 
7128 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
7129   // Find the type of the operands in VL.
7130   Type *ScalarTy = VL[0]->getType();
7131   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
7132     ScalarTy = SI->getValueOperand()->getType();
7133   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
7134   bool DuplicateNonConst = false;
7135   // Find the cost of inserting/extracting values from the vector.
7136   // Check if the same elements are inserted several times and count them as
7137   // shuffle candidates.
7138   APInt ShuffledElements = APInt::getZero(VL.size());
7139   DenseSet<Value *> UniqueElements;
7140   // Iterate in reverse order to consider insert elements with the high cost.
7141   for (unsigned I = VL.size(); I > 0; --I) {
7142     unsigned Idx = I - 1;
7143     // No need to shuffle duplicates for constants.
7144     if (isConstant(VL[Idx])) {
7145       ShuffledElements.setBit(Idx);
7146       continue;
7147     }
7148     if (!UniqueElements.insert(VL[Idx]).second) {
7149       DuplicateNonConst = true;
7150       ShuffledElements.setBit(Idx);
7151     }
7152   }
7153   return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst);
7154 }
7155 
7156 // Perform operand reordering on the instructions in VL and return the reordered
7157 // operands in Left and Right.
7158 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
7159                                              SmallVectorImpl<Value *> &Left,
7160                                              SmallVectorImpl<Value *> &Right,
7161                                              const DataLayout &DL,
7162                                              ScalarEvolution &SE,
7163                                              const BoUpSLP &R) {
7164   if (VL.empty())
7165     return;
7166   VLOperands Ops(VL, DL, SE, R);
7167   // Reorder the operands in place.
7168   Ops.reorder();
7169   Left = Ops.getVL(0);
7170   Right = Ops.getVL(1);
7171 }
7172 
7173 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) {
7174   // Get the basic block this bundle is in. All instructions in the bundle
7175   // should be in this block.
7176   auto *Front = E->getMainOp();
7177   auto *BB = Front->getParent();
7178   assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool {
7179     auto *I = cast<Instruction>(V);
7180     return !E->isOpcodeOrAlt(I) || I->getParent() == BB;
7181   }));
7182 
7183   auto &&FindLastInst = [E, Front]() {
7184     Instruction *LastInst = Front;
7185     for (Value *V : E->Scalars) {
7186       auto *I = dyn_cast<Instruction>(V);
7187       if (!I)
7188         continue;
7189       if (LastInst->comesBefore(I))
7190         LastInst = I;
7191     }
7192     return LastInst;
7193   };
7194 
7195   auto &&FindFirstInst = [E, Front]() {
7196     Instruction *FirstInst = Front;
7197     for (Value *V : E->Scalars) {
7198       auto *I = dyn_cast<Instruction>(V);
7199       if (!I)
7200         continue;
7201       if (I->comesBefore(FirstInst))
7202         FirstInst = I;
7203     }
7204     return FirstInst;
7205   };
7206 
7207   // Set the insert point to the beginning of the basic block if the entry
7208   // should not be scheduled.
7209   if (E->State != TreeEntry::NeedToGather &&
7210       doesNotNeedToSchedule(E->Scalars)) {
7211     Instruction *InsertInst;
7212     if (all_of(E->Scalars, isUsedOutsideBlock))
7213       InsertInst = FindLastInst();
7214     else
7215       InsertInst = FindFirstInst();
7216     // If the instruction is PHI, set the insert point after all the PHIs.
7217     if (isa<PHINode>(InsertInst))
7218       InsertInst = BB->getFirstNonPHI();
7219     BasicBlock::iterator InsertPt = InsertInst->getIterator();
7220     Builder.SetInsertPoint(BB, InsertPt);
7221     Builder.SetCurrentDebugLocation(Front->getDebugLoc());
7222     return;
7223   }
7224 
7225   // The last instruction in the bundle in program order.
7226   Instruction *LastInst = nullptr;
7227 
7228   // Find the last instruction. The common case should be that BB has been
7229   // scheduled, and the last instruction is VL.back(). So we start with
7230   // VL.back() and iterate over schedule data until we reach the end of the
7231   // bundle. The end of the bundle is marked by null ScheduleData.
7232   if (BlocksSchedules.count(BB)) {
7233     Value *V = E->isOneOf(E->Scalars.back());
7234     if (doesNotNeedToBeScheduled(V))
7235       V = *find_if_not(E->Scalars, doesNotNeedToBeScheduled);
7236     auto *Bundle = BlocksSchedules[BB]->getScheduleData(V);
7237     if (Bundle && Bundle->isPartOfBundle())
7238       for (; Bundle; Bundle = Bundle->NextInBundle)
7239         if (Bundle->OpValue == Bundle->Inst)
7240           LastInst = Bundle->Inst;
7241   }
7242 
7243   // LastInst can still be null at this point if there's either not an entry
7244   // for BB in BlocksSchedules or there's no ScheduleData available for
7245   // VL.back(). This can be the case if buildTree_rec aborts for various
7246   // reasons (e.g., the maximum recursion depth is reached, the maximum region
7247   // size is reached, etc.). ScheduleData is initialized in the scheduling
7248   // "dry-run".
7249   //
7250   // If this happens, we can still find the last instruction by brute force. We
7251   // iterate forwards from Front (inclusive) until we either see all
7252   // instructions in the bundle or reach the end of the block. If Front is the
7253   // last instruction in program order, LastInst will be set to Front, and we
7254   // will visit all the remaining instructions in the block.
7255   //
7256   // One of the reasons we exit early from buildTree_rec is to place an upper
7257   // bound on compile-time. Thus, taking an additional compile-time hit here is
7258   // not ideal. However, this should be exceedingly rare since it requires that
7259   // we both exit early from buildTree_rec and that the bundle be out-of-order
7260   // (causing us to iterate all the way to the end of the block).
7261   if (!LastInst) {
7262     LastInst = FindLastInst();
7263     // If the instruction is PHI, set the insert point after all the PHIs.
7264     if (isa<PHINode>(LastInst))
7265       LastInst = BB->getFirstNonPHI()->getPrevNode();
7266   }
7267   assert(LastInst && "Failed to find last instruction in bundle");
7268 
7269   // Set the insertion point after the last instruction in the bundle. Set the
7270   // debug location to Front.
7271   Builder.SetInsertPoint(BB, std::next(LastInst->getIterator()));
7272   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
7273 }
7274 
7275 Value *BoUpSLP::gather(ArrayRef<Value *> VL) {
7276   // List of instructions/lanes from current block and/or the blocks which are
7277   // part of the current loop. These instructions will be inserted at the end to
7278   // make it possible to optimize loops and hoist invariant instructions out of
7279   // the loops body with better chances for success.
7280   SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts;
7281   SmallSet<int, 4> PostponedIndices;
7282   Loop *L = LI->getLoopFor(Builder.GetInsertBlock());
7283   auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) {
7284     SmallPtrSet<BasicBlock *, 4> Visited;
7285     while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second)
7286       InsertBB = InsertBB->getSinglePredecessor();
7287     return InsertBB && InsertBB == InstBB;
7288   };
7289   for (int I = 0, E = VL.size(); I < E; ++I) {
7290     if (auto *Inst = dyn_cast<Instruction>(VL[I]))
7291       if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) ||
7292            getTreeEntry(Inst) || (L && (L->contains(Inst)))) &&
7293           PostponedIndices.insert(I).second)
7294         PostponedInsts.emplace_back(Inst, I);
7295   }
7296 
7297   auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) {
7298     Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos));
7299     auto *InsElt = dyn_cast<InsertElementInst>(Vec);
7300     if (!InsElt)
7301       return Vec;
7302     GatherShuffleSeq.insert(InsElt);
7303     CSEBlocks.insert(InsElt->getParent());
7304     // Add to our 'need-to-extract' list.
7305     if (TreeEntry *Entry = getTreeEntry(V)) {
7306       // Find which lane we need to extract.
7307       unsigned FoundLane = Entry->findLaneForValue(V);
7308       ExternalUses.emplace_back(V, InsElt, FoundLane);
7309     }
7310     return Vec;
7311   };
7312   Value *Val0 =
7313       isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0];
7314   FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size());
7315   Value *Vec = PoisonValue::get(VecTy);
7316   SmallVector<int> NonConsts;
7317   // Insert constant values at first.
7318   for (int I = 0, E = VL.size(); I < E; ++I) {
7319     if (PostponedIndices.contains(I))
7320       continue;
7321     if (!isConstant(VL[I])) {
7322       NonConsts.push_back(I);
7323       continue;
7324     }
7325     Vec = CreateInsertElement(Vec, VL[I], I);
7326   }
7327   // Insert non-constant values.
7328   for (int I : NonConsts)
7329     Vec = CreateInsertElement(Vec, VL[I], I);
7330   // Append instructions, which are/may be part of the loop, in the end to make
7331   // it possible to hoist non-loop-based instructions.
7332   for (const std::pair<Value *, unsigned> &Pair : PostponedInsts)
7333     Vec = CreateInsertElement(Vec, Pair.first, Pair.second);
7334 
7335   return Vec;
7336 }
7337 
7338 namespace {
7339 /// Merges shuffle masks and emits final shuffle instruction, if required.
7340 class ShuffleInstructionBuilder {
7341   IRBuilderBase &Builder;
7342   const unsigned VF = 0;
7343   bool IsFinalized = false;
7344   SmallVector<int, 4> Mask;
7345   /// Holds all of the instructions that we gathered.
7346   SetVector<Instruction *> &GatherShuffleSeq;
7347   /// A list of blocks that we are going to CSE.
7348   SetVector<BasicBlock *> &CSEBlocks;
7349 
7350 public:
7351   ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF,
7352                             SetVector<Instruction *> &GatherShuffleSeq,
7353                             SetVector<BasicBlock *> &CSEBlocks)
7354       : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq),
7355         CSEBlocks(CSEBlocks) {}
7356 
7357   /// Adds a mask, inverting it before applying.
7358   void addInversedMask(ArrayRef<unsigned> SubMask) {
7359     if (SubMask.empty())
7360       return;
7361     SmallVector<int, 4> NewMask;
7362     inversePermutation(SubMask, NewMask);
7363     addMask(NewMask);
7364   }
7365 
7366   /// Functions adds masks, merging them into  single one.
7367   void addMask(ArrayRef<unsigned> SubMask) {
7368     SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end());
7369     addMask(NewMask);
7370   }
7371 
7372   void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); }
7373 
7374   Value *finalize(Value *V) {
7375     IsFinalized = true;
7376     unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements();
7377     if (VF == ValueVF && Mask.empty())
7378       return V;
7379     SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem);
7380     std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0);
7381     addMask(NormalizedMask);
7382 
7383     if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask))
7384       return V;
7385     Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle");
7386     if (auto *I = dyn_cast<Instruction>(Vec)) {
7387       GatherShuffleSeq.insert(I);
7388       CSEBlocks.insert(I->getParent());
7389     }
7390     return Vec;
7391   }
7392 
7393   ~ShuffleInstructionBuilder() {
7394     assert((IsFinalized || Mask.empty()) &&
7395            "Shuffle construction must be finalized.");
7396   }
7397 };
7398 } // namespace
7399 
7400 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
7401   const unsigned VF = VL.size();
7402   InstructionsState S = getSameOpcode(VL);
7403   if (S.getOpcode()) {
7404     if (TreeEntry *E = getTreeEntry(S.OpValue))
7405       if (E->isSame(VL)) {
7406         Value *V = vectorizeTree(E);
7407         if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) {
7408           if (!E->ReuseShuffleIndices.empty()) {
7409             // Reshuffle to get only unique values.
7410             // If some of the scalars are duplicated in the vectorization tree
7411             // entry, we do not vectorize them but instead generate a mask for
7412             // the reuses. But if there are several users of the same entry,
7413             // they may have different vectorization factors. This is especially
7414             // important for PHI nodes. In this case, we need to adapt the
7415             // resulting instruction for the user vectorization factor and have
7416             // to reshuffle it again to take only unique elements of the vector.
7417             // Without this code the function incorrectly returns reduced vector
7418             // instruction with the same elements, not with the unique ones.
7419 
7420             // block:
7421             // %phi = phi <2 x > { .., %entry} {%shuffle, %block}
7422             // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0>
7423             // ... (use %2)
7424             // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0}
7425             // br %block
7426             SmallVector<int> UniqueIdxs(VF, UndefMaskElem);
7427             SmallSet<int, 4> UsedIdxs;
7428             int Pos = 0;
7429             int Sz = VL.size();
7430             for (int Idx : E->ReuseShuffleIndices) {
7431               if (Idx != Sz && Idx != UndefMaskElem &&
7432                   UsedIdxs.insert(Idx).second)
7433                 UniqueIdxs[Idx] = Pos;
7434               ++Pos;
7435             }
7436             assert(VF >= UsedIdxs.size() && "Expected vectorization factor "
7437                                             "less than original vector size.");
7438             UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem);
7439             V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle");
7440           } else {
7441             assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() &&
7442                    "Expected vectorization factor less "
7443                    "than original vector size.");
7444             SmallVector<int> UniformMask(VF, 0);
7445             std::iota(UniformMask.begin(), UniformMask.end(), 0);
7446             V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle");
7447           }
7448           if (auto *I = dyn_cast<Instruction>(V)) {
7449             GatherShuffleSeq.insert(I);
7450             CSEBlocks.insert(I->getParent());
7451           }
7452         }
7453         return V;
7454       }
7455   }
7456 
7457   // Can't vectorize this, so simply build a new vector with each lane
7458   // corresponding to the requested value.
7459   return createBuildVector(VL);
7460 }
7461 Value *BoUpSLP::createBuildVector(ArrayRef<Value *> VL) {
7462   unsigned VF = VL.size();
7463   // Exploit possible reuse of values across lanes.
7464   SmallVector<int> ReuseShuffleIndicies;
7465   SmallVector<Value *> UniqueValues;
7466   if (VL.size() > 2) {
7467     DenseMap<Value *, unsigned> UniquePositions;
7468     unsigned NumValues =
7469         std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) {
7470                                     return !isa<UndefValue>(V);
7471                                   }).base());
7472     VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues));
7473     int UniqueVals = 0;
7474     for (Value *V : VL.drop_back(VL.size() - VF)) {
7475       if (isa<UndefValue>(V)) {
7476         ReuseShuffleIndicies.emplace_back(UndefMaskElem);
7477         continue;
7478       }
7479       if (isConstant(V)) {
7480         ReuseShuffleIndicies.emplace_back(UniqueValues.size());
7481         UniqueValues.emplace_back(V);
7482         continue;
7483       }
7484       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
7485       ReuseShuffleIndicies.emplace_back(Res.first->second);
7486       if (Res.second) {
7487         UniqueValues.emplace_back(V);
7488         ++UniqueVals;
7489       }
7490     }
7491     if (UniqueVals == 1 && UniqueValues.size() == 1) {
7492       // Emit pure splat vector.
7493       ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(),
7494                                   UndefMaskElem);
7495     } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) {
7496       ReuseShuffleIndicies.clear();
7497       UniqueValues.clear();
7498       UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues));
7499     }
7500     UniqueValues.append(VF - UniqueValues.size(),
7501                         PoisonValue::get(VL[0]->getType()));
7502     VL = UniqueValues;
7503   }
7504 
7505   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
7506                                            CSEBlocks);
7507   Value *Vec = gather(VL);
7508   if (!ReuseShuffleIndicies.empty()) {
7509     ShuffleBuilder.addMask(ReuseShuffleIndicies);
7510     Vec = ShuffleBuilder.finalize(Vec);
7511   }
7512   return Vec;
7513 }
7514 
7515 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
7516   IRBuilder<>::InsertPointGuard Guard(Builder);
7517 
7518   if (E->VectorizedValue) {
7519     LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
7520     return E->VectorizedValue;
7521   }
7522 
7523   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
7524   unsigned VF = E->getVectorFactor();
7525   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
7526                                            CSEBlocks);
7527   if (E->State == TreeEntry::NeedToGather) {
7528     if (E->getMainOp())
7529       setInsertPointAfterBundle(E);
7530     Value *Vec;
7531     SmallVector<int> Mask;
7532     SmallVector<const TreeEntry *> Entries;
7533     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
7534         isGatherShuffledEntry(E, Mask, Entries);
7535     if (Shuffle.hasValue()) {
7536       assert((Entries.size() == 1 || Entries.size() == 2) &&
7537              "Expected shuffle of 1 or 2 entries.");
7538       Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue,
7539                                         Entries.back()->VectorizedValue, Mask);
7540       if (auto *I = dyn_cast<Instruction>(Vec)) {
7541         GatherShuffleSeq.insert(I);
7542         CSEBlocks.insert(I->getParent());
7543       }
7544     } else {
7545       Vec = gather(E->Scalars);
7546     }
7547     if (NeedToShuffleReuses) {
7548       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7549       Vec = ShuffleBuilder.finalize(Vec);
7550     }
7551     E->VectorizedValue = Vec;
7552     return Vec;
7553   }
7554 
7555   assert((E->State == TreeEntry::Vectorize ||
7556           E->State == TreeEntry::ScatterVectorize) &&
7557          "Unhandled state");
7558   unsigned ShuffleOrOp =
7559       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
7560   Instruction *VL0 = E->getMainOp();
7561   Type *ScalarTy = VL0->getType();
7562   if (auto *Store = dyn_cast<StoreInst>(VL0))
7563     ScalarTy = Store->getValueOperand()->getType();
7564   else if (auto *IE = dyn_cast<InsertElementInst>(VL0))
7565     ScalarTy = IE->getOperand(1)->getType();
7566   auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
7567   switch (ShuffleOrOp) {
7568     case Instruction::PHI: {
7569       assert(
7570           (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) &&
7571           "PHI reordering is free.");
7572       auto *PH = cast<PHINode>(VL0);
7573       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
7574       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
7575       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
7576       Value *V = NewPhi;
7577 
7578       // Adjust insertion point once all PHI's have been generated.
7579       Builder.SetInsertPoint(&*PH->getParent()->getFirstInsertionPt());
7580       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
7581 
7582       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7583       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7584       V = ShuffleBuilder.finalize(V);
7585 
7586       E->VectorizedValue = V;
7587 
7588       // PHINodes may have multiple entries from the same block. We want to
7589       // visit every block once.
7590       SmallPtrSet<BasicBlock*, 4> VisitedBBs;
7591 
7592       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
7593         ValueList Operands;
7594         BasicBlock *IBB = PH->getIncomingBlock(i);
7595 
7596         if (!VisitedBBs.insert(IBB).second) {
7597           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
7598           continue;
7599         }
7600 
7601         Builder.SetInsertPoint(IBB->getTerminator());
7602         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
7603         Value *Vec = vectorizeTree(E->getOperand(i));
7604         NewPhi->addIncoming(Vec, IBB);
7605       }
7606 
7607       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
7608              "Invalid number of incoming values");
7609       return V;
7610     }
7611 
7612     case Instruction::ExtractElement: {
7613       Value *V = E->getSingleOperand(0);
7614       Builder.SetInsertPoint(VL0);
7615       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7616       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7617       V = ShuffleBuilder.finalize(V);
7618       E->VectorizedValue = V;
7619       return V;
7620     }
7621     case Instruction::ExtractValue: {
7622       auto *LI = cast<LoadInst>(E->getSingleOperand(0));
7623       Builder.SetInsertPoint(LI);
7624       auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
7625       Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
7626       LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
7627       Value *NewV = propagateMetadata(V, E->Scalars);
7628       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7629       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7630       NewV = ShuffleBuilder.finalize(NewV);
7631       E->VectorizedValue = NewV;
7632       return NewV;
7633     }
7634     case Instruction::InsertElement: {
7635       assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique");
7636       Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back()));
7637       Value *V = vectorizeTree(E->getOperand(1));
7638 
7639       // Create InsertVector shuffle if necessary
7640       auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
7641         return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0));
7642       }));
7643       const unsigned NumElts =
7644           cast<FixedVectorType>(FirstInsert->getType())->getNumElements();
7645       const unsigned NumScalars = E->Scalars.size();
7646 
7647       unsigned Offset = *getInsertIndex(VL0);
7648       assert(Offset < NumElts && "Failed to find vector index offset");
7649 
7650       // Create shuffle to resize vector
7651       SmallVector<int> Mask;
7652       if (!E->ReorderIndices.empty()) {
7653         inversePermutation(E->ReorderIndices, Mask);
7654         Mask.append(NumElts - NumScalars, UndefMaskElem);
7655       } else {
7656         Mask.assign(NumElts, UndefMaskElem);
7657         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
7658       }
7659       // Create InsertVector shuffle if necessary
7660       bool IsIdentity = true;
7661       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
7662       Mask.swap(PrevMask);
7663       for (unsigned I = 0; I < NumScalars; ++I) {
7664         Value *Scalar = E->Scalars[PrevMask[I]];
7665         unsigned InsertIdx = *getInsertIndex(Scalar);
7666         IsIdentity &= InsertIdx - Offset == I;
7667         Mask[InsertIdx - Offset] = I;
7668       }
7669       if (!IsIdentity || NumElts != NumScalars) {
7670         V = Builder.CreateShuffleVector(V, Mask);
7671         if (auto *I = dyn_cast<Instruction>(V)) {
7672           GatherShuffleSeq.insert(I);
7673           CSEBlocks.insert(I->getParent());
7674         }
7675       }
7676 
7677       if ((!IsIdentity || Offset != 0 ||
7678            !isUndefVector(FirstInsert->getOperand(0))) &&
7679           NumElts != NumScalars) {
7680         SmallVector<int> InsertMask(NumElts);
7681         std::iota(InsertMask.begin(), InsertMask.end(), 0);
7682         for (unsigned I = 0; I < NumElts; I++) {
7683           if (Mask[I] != UndefMaskElem)
7684             InsertMask[Offset + I] = NumElts + I;
7685         }
7686 
7687         V = Builder.CreateShuffleVector(
7688             FirstInsert->getOperand(0), V, InsertMask,
7689             cast<Instruction>(E->Scalars.back())->getName());
7690         if (auto *I = dyn_cast<Instruction>(V)) {
7691           GatherShuffleSeq.insert(I);
7692           CSEBlocks.insert(I->getParent());
7693         }
7694       }
7695 
7696       ++NumVectorInstructions;
7697       E->VectorizedValue = V;
7698       return V;
7699     }
7700     case Instruction::ZExt:
7701     case Instruction::SExt:
7702     case Instruction::FPToUI:
7703     case Instruction::FPToSI:
7704     case Instruction::FPExt:
7705     case Instruction::PtrToInt:
7706     case Instruction::IntToPtr:
7707     case Instruction::SIToFP:
7708     case Instruction::UIToFP:
7709     case Instruction::Trunc:
7710     case Instruction::FPTrunc:
7711     case Instruction::BitCast: {
7712       setInsertPointAfterBundle(E);
7713 
7714       Value *InVec = vectorizeTree(E->getOperand(0));
7715 
7716       if (E->VectorizedValue) {
7717         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7718         return E->VectorizedValue;
7719       }
7720 
7721       auto *CI = cast<CastInst>(VL0);
7722       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
7723       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7724       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7725       V = ShuffleBuilder.finalize(V);
7726 
7727       E->VectorizedValue = V;
7728       ++NumVectorInstructions;
7729       return V;
7730     }
7731     case Instruction::FCmp:
7732     case Instruction::ICmp: {
7733       setInsertPointAfterBundle(E);
7734 
7735       Value *L = vectorizeTree(E->getOperand(0));
7736       Value *R = vectorizeTree(E->getOperand(1));
7737 
7738       if (E->VectorizedValue) {
7739         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7740         return E->VectorizedValue;
7741       }
7742 
7743       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
7744       Value *V = Builder.CreateCmp(P0, L, R);
7745       propagateIRFlags(V, E->Scalars, VL0);
7746       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7747       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7748       V = ShuffleBuilder.finalize(V);
7749 
7750       E->VectorizedValue = V;
7751       ++NumVectorInstructions;
7752       return V;
7753     }
7754     case Instruction::Select: {
7755       setInsertPointAfterBundle(E);
7756 
7757       Value *Cond = vectorizeTree(E->getOperand(0));
7758       Value *True = vectorizeTree(E->getOperand(1));
7759       Value *False = vectorizeTree(E->getOperand(2));
7760 
7761       if (E->VectorizedValue) {
7762         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7763         return E->VectorizedValue;
7764       }
7765 
7766       Value *V = Builder.CreateSelect(Cond, True, False);
7767       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7768       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7769       V = ShuffleBuilder.finalize(V);
7770 
7771       E->VectorizedValue = V;
7772       ++NumVectorInstructions;
7773       return V;
7774     }
7775     case Instruction::FNeg: {
7776       setInsertPointAfterBundle(E);
7777 
7778       Value *Op = 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       Value *V = Builder.CreateUnOp(
7786           static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
7787       propagateIRFlags(V, E->Scalars, VL0);
7788       if (auto *I = dyn_cast<Instruction>(V))
7789         V = propagateMetadata(I, E->Scalars);
7790 
7791       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7792       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7793       V = ShuffleBuilder.finalize(V);
7794 
7795       E->VectorizedValue = V;
7796       ++NumVectorInstructions;
7797 
7798       return V;
7799     }
7800     case Instruction::Add:
7801     case Instruction::FAdd:
7802     case Instruction::Sub:
7803     case Instruction::FSub:
7804     case Instruction::Mul:
7805     case Instruction::FMul:
7806     case Instruction::UDiv:
7807     case Instruction::SDiv:
7808     case Instruction::FDiv:
7809     case Instruction::URem:
7810     case Instruction::SRem:
7811     case Instruction::FRem:
7812     case Instruction::Shl:
7813     case Instruction::LShr:
7814     case Instruction::AShr:
7815     case Instruction::And:
7816     case Instruction::Or:
7817     case Instruction::Xor: {
7818       setInsertPointAfterBundle(E);
7819 
7820       Value *LHS = vectorizeTree(E->getOperand(0));
7821       Value *RHS = vectorizeTree(E->getOperand(1));
7822 
7823       if (E->VectorizedValue) {
7824         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7825         return E->VectorizedValue;
7826       }
7827 
7828       Value *V = Builder.CreateBinOp(
7829           static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
7830           RHS);
7831       propagateIRFlags(V, E->Scalars, VL0);
7832       if (auto *I = dyn_cast<Instruction>(V))
7833         V = propagateMetadata(I, E->Scalars);
7834 
7835       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7836       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7837       V = ShuffleBuilder.finalize(V);
7838 
7839       E->VectorizedValue = V;
7840       ++NumVectorInstructions;
7841 
7842       return V;
7843     }
7844     case Instruction::Load: {
7845       // Loads are inserted at the head of the tree because we don't want to
7846       // sink them all the way down past store instructions.
7847       setInsertPointAfterBundle(E);
7848 
7849       LoadInst *LI = cast<LoadInst>(VL0);
7850       Instruction *NewLI;
7851       unsigned AS = LI->getPointerAddressSpace();
7852       Value *PO = LI->getPointerOperand();
7853       if (E->State == TreeEntry::Vectorize) {
7854         Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS));
7855         NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
7856 
7857         // The pointer operand uses an in-tree scalar so we add the new BitCast
7858         // or LoadInst to ExternalUses list to make sure that an extract will
7859         // be generated in the future.
7860         if (TreeEntry *Entry = getTreeEntry(PO)) {
7861           // Find which lane we need to extract.
7862           unsigned FoundLane = Entry->findLaneForValue(PO);
7863           ExternalUses.emplace_back(
7864               PO, PO != VecPtr ? cast<User>(VecPtr) : NewLI, FoundLane);
7865         }
7866       } else {
7867         assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state");
7868         Value *VecPtr = vectorizeTree(E->getOperand(0));
7869         // Use the minimum alignment of the gathered loads.
7870         Align CommonAlignment = LI->getAlign();
7871         for (Value *V : E->Scalars)
7872           CommonAlignment =
7873               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
7874         NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment);
7875       }
7876       Value *V = propagateMetadata(NewLI, E->Scalars);
7877 
7878       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7879       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7880       V = ShuffleBuilder.finalize(V);
7881       E->VectorizedValue = V;
7882       ++NumVectorInstructions;
7883       return V;
7884     }
7885     case Instruction::Store: {
7886       auto *SI = cast<StoreInst>(VL0);
7887       unsigned AS = SI->getPointerAddressSpace();
7888 
7889       setInsertPointAfterBundle(E);
7890 
7891       Value *VecValue = vectorizeTree(E->getOperand(0));
7892       ShuffleBuilder.addMask(E->ReorderIndices);
7893       VecValue = ShuffleBuilder.finalize(VecValue);
7894 
7895       Value *ScalarPtr = SI->getPointerOperand();
7896       Value *VecPtr = Builder.CreateBitCast(
7897           ScalarPtr, VecValue->getType()->getPointerTo(AS));
7898       StoreInst *ST =
7899           Builder.CreateAlignedStore(VecValue, VecPtr, SI->getAlign());
7900 
7901       // The pointer operand uses an in-tree scalar, so add the new BitCast or
7902       // StoreInst to ExternalUses to make sure that an extract will be
7903       // generated in the future.
7904       if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) {
7905         // Find which lane we need to extract.
7906         unsigned FoundLane = Entry->findLaneForValue(ScalarPtr);
7907         ExternalUses.push_back(ExternalUser(
7908             ScalarPtr, ScalarPtr != VecPtr ? cast<User>(VecPtr) : ST,
7909             FoundLane));
7910       }
7911 
7912       Value *V = propagateMetadata(ST, E->Scalars);
7913 
7914       E->VectorizedValue = V;
7915       ++NumVectorInstructions;
7916       return V;
7917     }
7918     case Instruction::GetElementPtr: {
7919       auto *GEP0 = cast<GetElementPtrInst>(VL0);
7920       setInsertPointAfterBundle(E);
7921 
7922       Value *Op0 = vectorizeTree(E->getOperand(0));
7923 
7924       SmallVector<Value *> OpVecs;
7925       for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) {
7926         Value *OpVec = vectorizeTree(E->getOperand(J));
7927         OpVecs.push_back(OpVec);
7928       }
7929 
7930       Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs);
7931       if (Instruction *I = dyn_cast<Instruction>(V))
7932         V = propagateMetadata(I, E->Scalars);
7933 
7934       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7935       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7936       V = ShuffleBuilder.finalize(V);
7937 
7938       E->VectorizedValue = V;
7939       ++NumVectorInstructions;
7940 
7941       return V;
7942     }
7943     case Instruction::Call: {
7944       CallInst *CI = cast<CallInst>(VL0);
7945       setInsertPointAfterBundle(E);
7946 
7947       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
7948       if (Function *FI = CI->getCalledFunction())
7949         IID = FI->getIntrinsicID();
7950 
7951       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
7952 
7953       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
7954       bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
7955                           VecCallCosts.first <= VecCallCosts.second;
7956 
7957       Value *ScalarArg = nullptr;
7958       std::vector<Value *> OpVecs;
7959       SmallVector<Type *, 2> TysForDecl =
7960           {FixedVectorType::get(CI->getType(), E->Scalars.size())};
7961       for (int j = 0, e = CI->arg_size(); j < e; ++j) {
7962         ValueList OpVL;
7963         // Some intrinsics have scalar arguments. This argument should not be
7964         // vectorized.
7965         if (UseIntrinsic && isVectorIntrinsicWithScalarOpAtArg(IID, j)) {
7966           CallInst *CEI = cast<CallInst>(VL0);
7967           ScalarArg = CEI->getArgOperand(j);
7968           OpVecs.push_back(CEI->getArgOperand(j));
7969           if (isVectorIntrinsicWithOverloadTypeAtArg(IID, j))
7970             TysForDecl.push_back(ScalarArg->getType());
7971           continue;
7972         }
7973 
7974         Value *OpVec = vectorizeTree(E->getOperand(j));
7975         LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
7976         OpVecs.push_back(OpVec);
7977         if (isVectorIntrinsicWithOverloadTypeAtArg(IID, j))
7978           TysForDecl.push_back(OpVec->getType());
7979       }
7980 
7981       Function *CF;
7982       if (!UseIntrinsic) {
7983         VFShape Shape =
7984             VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
7985                                   VecTy->getNumElements())),
7986                          false /*HasGlobalPred*/);
7987         CF = VFDatabase(*CI).getVectorizedFunction(Shape);
7988       } else {
7989         CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl);
7990       }
7991 
7992       SmallVector<OperandBundleDef, 1> OpBundles;
7993       CI->getOperandBundlesAsDefs(OpBundles);
7994       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
7995 
7996       // The scalar argument uses an in-tree scalar so we add the new vectorized
7997       // call to ExternalUses list to make sure that an extract will be
7998       // generated in the future.
7999       if (ScalarArg) {
8000         if (TreeEntry *Entry = getTreeEntry(ScalarArg)) {
8001           // Find which lane we need to extract.
8002           unsigned FoundLane = Entry->findLaneForValue(ScalarArg);
8003           ExternalUses.push_back(
8004               ExternalUser(ScalarArg, cast<User>(V), FoundLane));
8005         }
8006       }
8007 
8008       propagateIRFlags(V, E->Scalars, VL0);
8009       ShuffleBuilder.addInversedMask(E->ReorderIndices);
8010       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
8011       V = ShuffleBuilder.finalize(V);
8012 
8013       E->VectorizedValue = V;
8014       ++NumVectorInstructions;
8015       return V;
8016     }
8017     case Instruction::ShuffleVector: {
8018       assert(E->isAltShuffle() &&
8019              ((Instruction::isBinaryOp(E->getOpcode()) &&
8020                Instruction::isBinaryOp(E->getAltOpcode())) ||
8021               (Instruction::isCast(E->getOpcode()) &&
8022                Instruction::isCast(E->getAltOpcode())) ||
8023               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
8024              "Invalid Shuffle Vector Operand");
8025 
8026       Value *LHS = nullptr, *RHS = nullptr;
8027       if (Instruction::isBinaryOp(E->getOpcode()) || isa<CmpInst>(VL0)) {
8028         setInsertPointAfterBundle(E);
8029         LHS = vectorizeTree(E->getOperand(0));
8030         RHS = vectorizeTree(E->getOperand(1));
8031       } else {
8032         setInsertPointAfterBundle(E);
8033         LHS = vectorizeTree(E->getOperand(0));
8034       }
8035 
8036       if (E->VectorizedValue) {
8037         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
8038         return E->VectorizedValue;
8039       }
8040 
8041       Value *V0, *V1;
8042       if (Instruction::isBinaryOp(E->getOpcode())) {
8043         V0 = Builder.CreateBinOp(
8044             static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
8045         V1 = Builder.CreateBinOp(
8046             static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
8047       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
8048         V0 = Builder.CreateCmp(CI0->getPredicate(), LHS, RHS);
8049         auto *AltCI = cast<CmpInst>(E->getAltOp());
8050         CmpInst::Predicate AltPred = AltCI->getPredicate();
8051         V1 = Builder.CreateCmp(AltPred, LHS, RHS);
8052       } else {
8053         V0 = Builder.CreateCast(
8054             static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
8055         V1 = Builder.CreateCast(
8056             static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
8057       }
8058       // Add V0 and V1 to later analysis to try to find and remove matching
8059       // instruction, if any.
8060       for (Value *V : {V0, V1}) {
8061         if (auto *I = dyn_cast<Instruction>(V)) {
8062           GatherShuffleSeq.insert(I);
8063           CSEBlocks.insert(I->getParent());
8064         }
8065       }
8066 
8067       // Create shuffle to take alternate operations from the vector.
8068       // Also, gather up main and alt scalar ops to propagate IR flags to
8069       // each vector operation.
8070       ValueList OpScalars, AltScalars;
8071       SmallVector<int> Mask;
8072       buildShuffleEntryMask(
8073           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
8074           [E](Instruction *I) {
8075             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
8076             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
8077           },
8078           Mask, &OpScalars, &AltScalars);
8079 
8080       propagateIRFlags(V0, OpScalars);
8081       propagateIRFlags(V1, AltScalars);
8082 
8083       Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
8084       if (auto *I = dyn_cast<Instruction>(V)) {
8085         V = propagateMetadata(I, E->Scalars);
8086         GatherShuffleSeq.insert(I);
8087         CSEBlocks.insert(I->getParent());
8088       }
8089       V = ShuffleBuilder.finalize(V);
8090 
8091       E->VectorizedValue = V;
8092       ++NumVectorInstructions;
8093 
8094       return V;
8095     }
8096     default:
8097     llvm_unreachable("unknown inst");
8098   }
8099   return nullptr;
8100 }
8101 
8102 Value *BoUpSLP::vectorizeTree() {
8103   ExtraValueToDebugLocsMap ExternallyUsedValues;
8104   return vectorizeTree(ExternallyUsedValues);
8105 }
8106 
8107 Value *
8108 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
8109   // All blocks must be scheduled before any instructions are inserted.
8110   for (auto &BSIter : BlocksSchedules) {
8111     scheduleBlock(BSIter.second.get());
8112   }
8113 
8114   Builder.SetInsertPoint(&F->getEntryBlock().front());
8115   auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
8116 
8117   // If the vectorized tree can be rewritten in a smaller type, we truncate the
8118   // vectorized root. InstCombine will then rewrite the entire expression. We
8119   // sign extend the extracted values below.
8120   auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
8121   if (MinBWs.count(ScalarRoot)) {
8122     if (auto *I = dyn_cast<Instruction>(VectorRoot)) {
8123       // If current instr is a phi and not the last phi, insert it after the
8124       // last phi node.
8125       if (isa<PHINode>(I))
8126         Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt());
8127       else
8128         Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
8129     }
8130     auto BundleWidth = VectorizableTree[0]->Scalars.size();
8131     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
8132     auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
8133     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
8134     VectorizableTree[0]->VectorizedValue = Trunc;
8135   }
8136 
8137   LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
8138                     << " values .\n");
8139 
8140   // Extract all of the elements with the external uses.
8141   for (const auto &ExternalUse : ExternalUses) {
8142     Value *Scalar = ExternalUse.Scalar;
8143     llvm::User *User = ExternalUse.User;
8144 
8145     // Skip users that we already RAUW. This happens when one instruction
8146     // has multiple uses of the same value.
8147     if (User && !is_contained(Scalar->users(), User))
8148       continue;
8149     TreeEntry *E = getTreeEntry(Scalar);
8150     assert(E && "Invalid scalar");
8151     assert(E->State != TreeEntry::NeedToGather &&
8152            "Extracting from a gather list");
8153 
8154     Value *Vec = E->VectorizedValue;
8155     assert(Vec && "Can't find vectorizable value");
8156 
8157     Value *Lane = Builder.getInt32(ExternalUse.Lane);
8158     auto ExtractAndExtendIfNeeded = [&](Value *Vec) {
8159       if (Scalar->getType() != Vec->getType()) {
8160         Value *Ex;
8161         // "Reuse" the existing extract to improve final codegen.
8162         if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) {
8163           Ex = Builder.CreateExtractElement(ES->getOperand(0),
8164                                             ES->getOperand(1));
8165         } else {
8166           Ex = Builder.CreateExtractElement(Vec, Lane);
8167         }
8168         // If necessary, sign-extend or zero-extend ScalarRoot
8169         // to the larger type.
8170         if (!MinBWs.count(ScalarRoot))
8171           return Ex;
8172         if (MinBWs[ScalarRoot].second)
8173           return Builder.CreateSExt(Ex, Scalar->getType());
8174         return Builder.CreateZExt(Ex, Scalar->getType());
8175       }
8176       assert(isa<FixedVectorType>(Scalar->getType()) &&
8177              isa<InsertElementInst>(Scalar) &&
8178              "In-tree scalar of vector type is not insertelement?");
8179       return Vec;
8180     };
8181     // If User == nullptr, the Scalar is used as extra arg. Generate
8182     // ExtractElement instruction and update the record for this scalar in
8183     // ExternallyUsedValues.
8184     if (!User) {
8185       assert(ExternallyUsedValues.count(Scalar) &&
8186              "Scalar with nullptr as an external user must be registered in "
8187              "ExternallyUsedValues map");
8188       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
8189         Builder.SetInsertPoint(VecI->getParent(),
8190                                std::next(VecI->getIterator()));
8191       } else {
8192         Builder.SetInsertPoint(&F->getEntryBlock().front());
8193       }
8194       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
8195       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
8196       auto &NewInstLocs = ExternallyUsedValues[NewInst];
8197       auto It = ExternallyUsedValues.find(Scalar);
8198       assert(It != ExternallyUsedValues.end() &&
8199              "Externally used scalar is not found in ExternallyUsedValues");
8200       NewInstLocs.append(It->second);
8201       ExternallyUsedValues.erase(Scalar);
8202       // Required to update internally referenced instructions.
8203       Scalar->replaceAllUsesWith(NewInst);
8204       continue;
8205     }
8206 
8207     // Generate extracts for out-of-tree users.
8208     // Find the insertion point for the extractelement lane.
8209     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
8210       if (PHINode *PH = dyn_cast<PHINode>(User)) {
8211         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
8212           if (PH->getIncomingValue(i) == Scalar) {
8213             Instruction *IncomingTerminator =
8214                 PH->getIncomingBlock(i)->getTerminator();
8215             if (isa<CatchSwitchInst>(IncomingTerminator)) {
8216               Builder.SetInsertPoint(VecI->getParent(),
8217                                      std::next(VecI->getIterator()));
8218             } else {
8219               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
8220             }
8221             Value *NewInst = ExtractAndExtendIfNeeded(Vec);
8222             CSEBlocks.insert(PH->getIncomingBlock(i));
8223             PH->setOperand(i, NewInst);
8224           }
8225         }
8226       } else {
8227         Builder.SetInsertPoint(cast<Instruction>(User));
8228         Value *NewInst = ExtractAndExtendIfNeeded(Vec);
8229         CSEBlocks.insert(cast<Instruction>(User)->getParent());
8230         User->replaceUsesOfWith(Scalar, NewInst);
8231       }
8232     } else {
8233       Builder.SetInsertPoint(&F->getEntryBlock().front());
8234       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
8235       CSEBlocks.insert(&F->getEntryBlock());
8236       User->replaceUsesOfWith(Scalar, NewInst);
8237     }
8238 
8239     LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
8240   }
8241 
8242   // For each vectorized value:
8243   for (auto &TEPtr : VectorizableTree) {
8244     TreeEntry *Entry = TEPtr.get();
8245 
8246     // No need to handle users of gathered values.
8247     if (Entry->State == TreeEntry::NeedToGather)
8248       continue;
8249 
8250     assert(Entry->VectorizedValue && "Can't find vectorizable value");
8251 
8252     // For each lane:
8253     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
8254       Value *Scalar = Entry->Scalars[Lane];
8255 
8256 #ifndef NDEBUG
8257       Type *Ty = Scalar->getType();
8258       if (!Ty->isVoidTy()) {
8259         for (User *U : Scalar->users()) {
8260           LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
8261 
8262           // It is legal to delete users in the ignorelist.
8263           assert((getTreeEntry(U) || is_contained(UserIgnoreList, U) ||
8264                   (isa_and_nonnull<Instruction>(U) &&
8265                    isDeleted(cast<Instruction>(U)))) &&
8266                  "Deleting out-of-tree value");
8267         }
8268       }
8269 #endif
8270       LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
8271       eraseInstruction(cast<Instruction>(Scalar));
8272     }
8273   }
8274 
8275   Builder.ClearInsertionPoint();
8276   InstrElementSize.clear();
8277 
8278   return VectorizableTree[0]->VectorizedValue;
8279 }
8280 
8281 void BoUpSLP::optimizeGatherSequence() {
8282   LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleSeq.size()
8283                     << " gather sequences instructions.\n");
8284   // LICM InsertElementInst sequences.
8285   for (Instruction *I : GatherShuffleSeq) {
8286     if (isDeleted(I))
8287       continue;
8288 
8289     // Check if this block is inside a loop.
8290     Loop *L = LI->getLoopFor(I->getParent());
8291     if (!L)
8292       continue;
8293 
8294     // Check if it has a preheader.
8295     BasicBlock *PreHeader = L->getLoopPreheader();
8296     if (!PreHeader)
8297       continue;
8298 
8299     // If the vector or the element that we insert into it are
8300     // instructions that are defined in this basic block then we can't
8301     // hoist this instruction.
8302     if (any_of(I->operands(), [L](Value *V) {
8303           auto *OpI = dyn_cast<Instruction>(V);
8304           return OpI && L->contains(OpI);
8305         }))
8306       continue;
8307 
8308     // We can hoist this instruction. Move it to the pre-header.
8309     I->moveBefore(PreHeader->getTerminator());
8310   }
8311 
8312   // Make a list of all reachable blocks in our CSE queue.
8313   SmallVector<const DomTreeNode *, 8> CSEWorkList;
8314   CSEWorkList.reserve(CSEBlocks.size());
8315   for (BasicBlock *BB : CSEBlocks)
8316     if (DomTreeNode *N = DT->getNode(BB)) {
8317       assert(DT->isReachableFromEntry(N));
8318       CSEWorkList.push_back(N);
8319     }
8320 
8321   // Sort blocks by domination. This ensures we visit a block after all blocks
8322   // dominating it are visited.
8323   llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) {
8324     assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) &&
8325            "Different nodes should have different DFS numbers");
8326     return A->getDFSNumIn() < B->getDFSNumIn();
8327   });
8328 
8329   // Less defined shuffles can be replaced by the more defined copies.
8330   // Between two shuffles one is less defined if it has the same vector operands
8331   // and its mask indeces are the same as in the first one or undefs. E.g.
8332   // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0,
8333   // poison, <0, 0, 0, 0>.
8334   auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2,
8335                                            SmallVectorImpl<int> &NewMask) {
8336     if (I1->getType() != I2->getType())
8337       return false;
8338     auto *SI1 = dyn_cast<ShuffleVectorInst>(I1);
8339     auto *SI2 = dyn_cast<ShuffleVectorInst>(I2);
8340     if (!SI1 || !SI2)
8341       return I1->isIdenticalTo(I2);
8342     if (SI1->isIdenticalTo(SI2))
8343       return true;
8344     for (int I = 0, E = SI1->getNumOperands(); I < E; ++I)
8345       if (SI1->getOperand(I) != SI2->getOperand(I))
8346         return false;
8347     // Check if the second instruction is more defined than the first one.
8348     NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end());
8349     ArrayRef<int> SM1 = SI1->getShuffleMask();
8350     // Count trailing undefs in the mask to check the final number of used
8351     // registers.
8352     unsigned LastUndefsCnt = 0;
8353     for (int I = 0, E = NewMask.size(); I < E; ++I) {
8354       if (SM1[I] == UndefMaskElem)
8355         ++LastUndefsCnt;
8356       else
8357         LastUndefsCnt = 0;
8358       if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem &&
8359           NewMask[I] != SM1[I])
8360         return false;
8361       if (NewMask[I] == UndefMaskElem)
8362         NewMask[I] = SM1[I];
8363     }
8364     // Check if the last undefs actually change the final number of used vector
8365     // registers.
8366     return SM1.size() - LastUndefsCnt > 1 &&
8367            TTI->getNumberOfParts(SI1->getType()) ==
8368                TTI->getNumberOfParts(
8369                    FixedVectorType::get(SI1->getType()->getElementType(),
8370                                         SM1.size() - LastUndefsCnt));
8371   };
8372   // Perform O(N^2) search over the gather/shuffle sequences and merge identical
8373   // instructions. TODO: We can further optimize this scan if we split the
8374   // instructions into different buckets based on the insert lane.
8375   SmallVector<Instruction *, 16> Visited;
8376   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
8377     assert(*I &&
8378            (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
8379            "Worklist not sorted properly!");
8380     BasicBlock *BB = (*I)->getBlock();
8381     // For all instructions in blocks containing gather sequences:
8382     for (Instruction &In : llvm::make_early_inc_range(*BB)) {
8383       if (isDeleted(&In))
8384         continue;
8385       if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) &&
8386           !isa<ShuffleVectorInst>(&In) && !GatherShuffleSeq.contains(&In))
8387         continue;
8388 
8389       // Check if we can replace this instruction with any of the
8390       // visited instructions.
8391       bool Replaced = false;
8392       for (Instruction *&V : Visited) {
8393         SmallVector<int> NewMask;
8394         if (IsIdenticalOrLessDefined(&In, V, NewMask) &&
8395             DT->dominates(V->getParent(), In.getParent())) {
8396           In.replaceAllUsesWith(V);
8397           eraseInstruction(&In);
8398           if (auto *SI = dyn_cast<ShuffleVectorInst>(V))
8399             if (!NewMask.empty())
8400               SI->setShuffleMask(NewMask);
8401           Replaced = true;
8402           break;
8403         }
8404         if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) &&
8405             GatherShuffleSeq.contains(V) &&
8406             IsIdenticalOrLessDefined(V, &In, NewMask) &&
8407             DT->dominates(In.getParent(), V->getParent())) {
8408           In.moveAfter(V);
8409           V->replaceAllUsesWith(&In);
8410           eraseInstruction(V);
8411           if (auto *SI = dyn_cast<ShuffleVectorInst>(&In))
8412             if (!NewMask.empty())
8413               SI->setShuffleMask(NewMask);
8414           V = &In;
8415           Replaced = true;
8416           break;
8417         }
8418       }
8419       if (!Replaced) {
8420         assert(!is_contained(Visited, &In));
8421         Visited.push_back(&In);
8422       }
8423     }
8424   }
8425   CSEBlocks.clear();
8426   GatherShuffleSeq.clear();
8427 }
8428 
8429 BoUpSLP::ScheduleData *
8430 BoUpSLP::BlockScheduling::buildBundle(ArrayRef<Value *> VL) {
8431   ScheduleData *Bundle = nullptr;
8432   ScheduleData *PrevInBundle = nullptr;
8433   for (Value *V : VL) {
8434     if (doesNotNeedToBeScheduled(V))
8435       continue;
8436     ScheduleData *BundleMember = getScheduleData(V);
8437     assert(BundleMember &&
8438            "no ScheduleData for bundle member "
8439            "(maybe not in same basic block)");
8440     assert(BundleMember->isSchedulingEntity() &&
8441            "bundle member already part of other bundle");
8442     if (PrevInBundle) {
8443       PrevInBundle->NextInBundle = BundleMember;
8444     } else {
8445       Bundle = BundleMember;
8446     }
8447 
8448     // Group the instructions to a bundle.
8449     BundleMember->FirstInBundle = Bundle;
8450     PrevInBundle = BundleMember;
8451   }
8452   assert(Bundle && "Failed to find schedule bundle");
8453   return Bundle;
8454 }
8455 
8456 // Groups the instructions to a bundle (which is then a single scheduling entity)
8457 // and schedules instructions until the bundle gets ready.
8458 Optional<BoUpSLP::ScheduleData *>
8459 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
8460                                             const InstructionsState &S) {
8461   // No need to schedule PHIs, insertelement, extractelement and extractvalue
8462   // instructions.
8463   if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue) ||
8464       doesNotNeedToSchedule(VL))
8465     return nullptr;
8466 
8467   // Initialize the instruction bundle.
8468   Instruction *OldScheduleEnd = ScheduleEnd;
8469   LLVM_DEBUG(dbgs() << "SLP:  bundle: " << *S.OpValue << "\n");
8470 
8471   auto TryScheduleBundleImpl = [this, OldScheduleEnd, SLP](bool ReSchedule,
8472                                                          ScheduleData *Bundle) {
8473     // The scheduling region got new instructions at the lower end (or it is a
8474     // new region for the first bundle). This makes it necessary to
8475     // recalculate all dependencies.
8476     // It is seldom that this needs to be done a second time after adding the
8477     // initial bundle to the region.
8478     if (ScheduleEnd != OldScheduleEnd) {
8479       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode())
8480         doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); });
8481       ReSchedule = true;
8482     }
8483     if (Bundle) {
8484       LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle
8485                         << " in block " << BB->getName() << "\n");
8486       calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP);
8487     }
8488 
8489     if (ReSchedule) {
8490       resetSchedule();
8491       initialFillReadyList(ReadyInsts);
8492     }
8493 
8494     // Now try to schedule the new bundle or (if no bundle) just calculate
8495     // dependencies. As soon as the bundle is "ready" it means that there are no
8496     // cyclic dependencies and we can schedule it. Note that's important that we
8497     // don't "schedule" the bundle yet (see cancelScheduling).
8498     while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) &&
8499            !ReadyInsts.empty()) {
8500       ScheduleData *Picked = ReadyInsts.pop_back_val();
8501       assert(Picked->isSchedulingEntity() && Picked->isReady() &&
8502              "must be ready to schedule");
8503       schedule(Picked, ReadyInsts);
8504     }
8505   };
8506 
8507   // Make sure that the scheduling region contains all
8508   // instructions of the bundle.
8509   for (Value *V : VL) {
8510     if (doesNotNeedToBeScheduled(V))
8511       continue;
8512     if (!extendSchedulingRegion(V, S)) {
8513       // If the scheduling region got new instructions at the lower end (or it
8514       // is a new region for the first bundle). This makes it necessary to
8515       // recalculate all dependencies.
8516       // Otherwise the compiler may crash trying to incorrectly calculate
8517       // dependencies and emit instruction in the wrong order at the actual
8518       // scheduling.
8519       TryScheduleBundleImpl(/*ReSchedule=*/false, nullptr);
8520       return None;
8521     }
8522   }
8523 
8524   bool ReSchedule = false;
8525   for (Value *V : VL) {
8526     if (doesNotNeedToBeScheduled(V))
8527       continue;
8528     ScheduleData *BundleMember = getScheduleData(V);
8529     assert(BundleMember &&
8530            "no ScheduleData for bundle member (maybe not in same basic block)");
8531 
8532     // Make sure we don't leave the pieces of the bundle in the ready list when
8533     // whole bundle might not be ready.
8534     ReadyInsts.remove(BundleMember);
8535 
8536     if (!BundleMember->IsScheduled)
8537       continue;
8538     // A bundle member was scheduled as single instruction before and now
8539     // needs to be scheduled as part of the bundle. We just get rid of the
8540     // existing schedule.
8541     LLVM_DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
8542                       << " was already scheduled\n");
8543     ReSchedule = true;
8544   }
8545 
8546   auto *Bundle = buildBundle(VL);
8547   TryScheduleBundleImpl(ReSchedule, Bundle);
8548   if (!Bundle->isReady()) {
8549     cancelScheduling(VL, S.OpValue);
8550     return None;
8551   }
8552   return Bundle;
8553 }
8554 
8555 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
8556                                                 Value *OpValue) {
8557   if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue) ||
8558       doesNotNeedToSchedule(VL))
8559     return;
8560 
8561   if (doesNotNeedToBeScheduled(OpValue))
8562     OpValue = *find_if_not(VL, doesNotNeedToBeScheduled);
8563   ScheduleData *Bundle = getScheduleData(OpValue);
8564   LLVM_DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
8565   assert(!Bundle->IsScheduled &&
8566          "Can't cancel bundle which is already scheduled");
8567   assert(Bundle->isSchedulingEntity() &&
8568          (Bundle->isPartOfBundle() || needToScheduleSingleInstruction(VL)) &&
8569          "tried to unbundle something which is not a bundle");
8570 
8571   // Remove the bundle from the ready list.
8572   if (Bundle->isReady())
8573     ReadyInsts.remove(Bundle);
8574 
8575   // Un-bundle: make single instructions out of the bundle.
8576   ScheduleData *BundleMember = Bundle;
8577   while (BundleMember) {
8578     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
8579     BundleMember->FirstInBundle = BundleMember;
8580     ScheduleData *Next = BundleMember->NextInBundle;
8581     BundleMember->NextInBundle = nullptr;
8582     BundleMember->TE = nullptr;
8583     if (BundleMember->unscheduledDepsInBundle() == 0) {
8584       ReadyInsts.insert(BundleMember);
8585     }
8586     BundleMember = Next;
8587   }
8588 }
8589 
8590 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
8591   // Allocate a new ScheduleData for the instruction.
8592   if (ChunkPos >= ChunkSize) {
8593     ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
8594     ChunkPos = 0;
8595   }
8596   return &(ScheduleDataChunks.back()[ChunkPos++]);
8597 }
8598 
8599 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
8600                                                       const InstructionsState &S) {
8601   if (getScheduleData(V, isOneOf(S, V)))
8602     return true;
8603   Instruction *I = dyn_cast<Instruction>(V);
8604   assert(I && "bundle member must be an instruction");
8605   assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) &&
8606          !doesNotNeedToBeScheduled(I) &&
8607          "phi nodes/insertelements/extractelements/extractvalues don't need to "
8608          "be scheduled");
8609   auto &&CheckScheduleForI = [this, &S](Instruction *I) -> bool {
8610     ScheduleData *ISD = getScheduleData(I);
8611     if (!ISD)
8612       return false;
8613     assert(isInSchedulingRegion(ISD) &&
8614            "ScheduleData not in scheduling region");
8615     ScheduleData *SD = allocateScheduleDataChunks();
8616     SD->Inst = I;
8617     SD->init(SchedulingRegionID, S.OpValue);
8618     ExtraScheduleDataMap[I][S.OpValue] = SD;
8619     return true;
8620   };
8621   if (CheckScheduleForI(I))
8622     return true;
8623   if (!ScheduleStart) {
8624     // It's the first instruction in the new region.
8625     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
8626     ScheduleStart = I;
8627     ScheduleEnd = I->getNextNode();
8628     if (isOneOf(S, I) != I)
8629       CheckScheduleForI(I);
8630     assert(ScheduleEnd && "tried to vectorize a terminator?");
8631     LLVM_DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
8632     return true;
8633   }
8634   // Search up and down at the same time, because we don't know if the new
8635   // instruction is above or below the existing scheduling region.
8636   BasicBlock::reverse_iterator UpIter =
8637       ++ScheduleStart->getIterator().getReverse();
8638   BasicBlock::reverse_iterator UpperEnd = BB->rend();
8639   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
8640   BasicBlock::iterator LowerEnd = BB->end();
8641   while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I &&
8642          &*DownIter != I) {
8643     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
8644       LLVM_DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
8645       return false;
8646     }
8647 
8648     ++UpIter;
8649     ++DownIter;
8650   }
8651   if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) {
8652     assert(I->getParent() == ScheduleStart->getParent() &&
8653            "Instruction is in wrong basic block.");
8654     initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
8655     ScheduleStart = I;
8656     if (isOneOf(S, I) != I)
8657       CheckScheduleForI(I);
8658     LLVM_DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I
8659                       << "\n");
8660     return true;
8661   }
8662   assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) &&
8663          "Expected to reach top of the basic block or instruction down the "
8664          "lower end.");
8665   assert(I->getParent() == ScheduleEnd->getParent() &&
8666          "Instruction is in wrong basic block.");
8667   initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
8668                    nullptr);
8669   ScheduleEnd = I->getNextNode();
8670   if (isOneOf(S, I) != I)
8671     CheckScheduleForI(I);
8672   assert(ScheduleEnd && "tried to vectorize a terminator?");
8673   LLVM_DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
8674   return true;
8675 }
8676 
8677 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
8678                                                 Instruction *ToI,
8679                                                 ScheduleData *PrevLoadStore,
8680                                                 ScheduleData *NextLoadStore) {
8681   ScheduleData *CurrentLoadStore = PrevLoadStore;
8682   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
8683     // No need to allocate data for non-schedulable instructions.
8684     if (doesNotNeedToBeScheduled(I))
8685       continue;
8686     ScheduleData *SD = ScheduleDataMap.lookup(I);
8687     if (!SD) {
8688       SD = allocateScheduleDataChunks();
8689       ScheduleDataMap[I] = SD;
8690       SD->Inst = I;
8691     }
8692     assert(!isInSchedulingRegion(SD) &&
8693            "new ScheduleData already in scheduling region");
8694     SD->init(SchedulingRegionID, I);
8695 
8696     if (I->mayReadOrWriteMemory() &&
8697         (!isa<IntrinsicInst>(I) ||
8698          (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect &&
8699           cast<IntrinsicInst>(I)->getIntrinsicID() !=
8700               Intrinsic::pseudoprobe))) {
8701       // Update the linked list of memory accessing instructions.
8702       if (CurrentLoadStore) {
8703         CurrentLoadStore->NextLoadStore = SD;
8704       } else {
8705         FirstLoadStoreInRegion = SD;
8706       }
8707       CurrentLoadStore = SD;
8708     }
8709 
8710     if (match(I, m_Intrinsic<Intrinsic::stacksave>()) ||
8711         match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8712       RegionHasStackSave = true;
8713   }
8714   if (NextLoadStore) {
8715     if (CurrentLoadStore)
8716       CurrentLoadStore->NextLoadStore = NextLoadStore;
8717   } else {
8718     LastLoadStoreInRegion = CurrentLoadStore;
8719   }
8720 }
8721 
8722 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
8723                                                      bool InsertInReadyList,
8724                                                      BoUpSLP *SLP) {
8725   assert(SD->isSchedulingEntity());
8726 
8727   SmallVector<ScheduleData *, 10> WorkList;
8728   WorkList.push_back(SD);
8729 
8730   while (!WorkList.empty()) {
8731     ScheduleData *SD = WorkList.pop_back_val();
8732     for (ScheduleData *BundleMember = SD; BundleMember;
8733          BundleMember = BundleMember->NextInBundle) {
8734       assert(isInSchedulingRegion(BundleMember));
8735       if (BundleMember->hasValidDependencies())
8736         continue;
8737 
8738       LLVM_DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember
8739                  << "\n");
8740       BundleMember->Dependencies = 0;
8741       BundleMember->resetUnscheduledDeps();
8742 
8743       // Handle def-use chain dependencies.
8744       if (BundleMember->OpValue != BundleMember->Inst) {
8745         if (ScheduleData *UseSD = getScheduleData(BundleMember->Inst)) {
8746           BundleMember->Dependencies++;
8747           ScheduleData *DestBundle = UseSD->FirstInBundle;
8748           if (!DestBundle->IsScheduled)
8749             BundleMember->incrementUnscheduledDeps(1);
8750           if (!DestBundle->hasValidDependencies())
8751             WorkList.push_back(DestBundle);
8752         }
8753       } else {
8754         for (User *U : BundleMember->Inst->users()) {
8755           if (ScheduleData *UseSD = getScheduleData(cast<Instruction>(U))) {
8756             BundleMember->Dependencies++;
8757             ScheduleData *DestBundle = UseSD->FirstInBundle;
8758             if (!DestBundle->IsScheduled)
8759               BundleMember->incrementUnscheduledDeps(1);
8760             if (!DestBundle->hasValidDependencies())
8761               WorkList.push_back(DestBundle);
8762           }
8763         }
8764       }
8765 
8766       auto makeControlDependent = [&](Instruction *I) {
8767         auto *DepDest = getScheduleData(I);
8768         assert(DepDest && "must be in schedule window");
8769         DepDest->ControlDependencies.push_back(BundleMember);
8770         BundleMember->Dependencies++;
8771         ScheduleData *DestBundle = DepDest->FirstInBundle;
8772         if (!DestBundle->IsScheduled)
8773           BundleMember->incrementUnscheduledDeps(1);
8774         if (!DestBundle->hasValidDependencies())
8775           WorkList.push_back(DestBundle);
8776       };
8777 
8778       // Any instruction which isn't safe to speculate at the begining of the
8779       // block is control dependend on any early exit or non-willreturn call
8780       // which proceeds it.
8781       if (!isGuaranteedToTransferExecutionToSuccessor(BundleMember->Inst)) {
8782         for (Instruction *I = BundleMember->Inst->getNextNode();
8783              I != ScheduleEnd; I = I->getNextNode()) {
8784           if (isSafeToSpeculativelyExecute(I, &*BB->begin()))
8785             continue;
8786 
8787           // Add the dependency
8788           makeControlDependent(I);
8789 
8790           if (!isGuaranteedToTransferExecutionToSuccessor(I))
8791             // Everything past here must be control dependent on I.
8792             break;
8793         }
8794       }
8795 
8796       if (RegionHasStackSave) {
8797         // If we have an inalloc alloca instruction, it needs to be scheduled
8798         // after any preceeding stacksave.  We also need to prevent any alloca
8799         // from reordering above a preceeding stackrestore.
8800         if (match(BundleMember->Inst, m_Intrinsic<Intrinsic::stacksave>()) ||
8801             match(BundleMember->Inst, m_Intrinsic<Intrinsic::stackrestore>())) {
8802           for (Instruction *I = BundleMember->Inst->getNextNode();
8803                I != ScheduleEnd; I = I->getNextNode()) {
8804             if (match(I, m_Intrinsic<Intrinsic::stacksave>()) ||
8805                 match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8806               // Any allocas past here must be control dependent on I, and I
8807               // must be memory dependend on BundleMember->Inst.
8808               break;
8809 
8810             if (!isa<AllocaInst>(I))
8811               continue;
8812 
8813             // Add the dependency
8814             makeControlDependent(I);
8815           }
8816         }
8817 
8818         // In addition to the cases handle just above, we need to prevent
8819         // allocas from moving below a stacksave.  The stackrestore case
8820         // is currently thought to be conservatism.
8821         if (isa<AllocaInst>(BundleMember->Inst)) {
8822           for (Instruction *I = BundleMember->Inst->getNextNode();
8823                I != ScheduleEnd; I = I->getNextNode()) {
8824             if (!match(I, m_Intrinsic<Intrinsic::stacksave>()) &&
8825                 !match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8826               continue;
8827 
8828             // Add the dependency
8829             makeControlDependent(I);
8830             break;
8831           }
8832         }
8833       }
8834 
8835       // Handle the memory dependencies (if any).
8836       ScheduleData *DepDest = BundleMember->NextLoadStore;
8837       if (!DepDest)
8838         continue;
8839       Instruction *SrcInst = BundleMember->Inst;
8840       assert(SrcInst->mayReadOrWriteMemory() &&
8841              "NextLoadStore list for non memory effecting bundle?");
8842       MemoryLocation SrcLoc = getLocation(SrcInst);
8843       bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
8844       unsigned numAliased = 0;
8845       unsigned DistToSrc = 1;
8846 
8847       for ( ; DepDest; DepDest = DepDest->NextLoadStore) {
8848         assert(isInSchedulingRegion(DepDest));
8849 
8850         // We have two limits to reduce the complexity:
8851         // 1) AliasedCheckLimit: It's a small limit to reduce calls to
8852         //    SLP->isAliased (which is the expensive part in this loop).
8853         // 2) MaxMemDepDistance: It's for very large blocks and it aborts
8854         //    the whole loop (even if the loop is fast, it's quadratic).
8855         //    It's important for the loop break condition (see below) to
8856         //    check this limit even between two read-only instructions.
8857         if (DistToSrc >= MaxMemDepDistance ||
8858             ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
8859              (numAliased >= AliasedCheckLimit ||
8860               SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
8861 
8862           // We increment the counter only if the locations are aliased
8863           // (instead of counting all alias checks). This gives a better
8864           // balance between reduced runtime and accurate dependencies.
8865           numAliased++;
8866 
8867           DepDest->MemoryDependencies.push_back(BundleMember);
8868           BundleMember->Dependencies++;
8869           ScheduleData *DestBundle = DepDest->FirstInBundle;
8870           if (!DestBundle->IsScheduled) {
8871             BundleMember->incrementUnscheduledDeps(1);
8872           }
8873           if (!DestBundle->hasValidDependencies()) {
8874             WorkList.push_back(DestBundle);
8875           }
8876         }
8877 
8878         // Example, explaining the loop break condition: Let's assume our
8879         // starting instruction is i0 and MaxMemDepDistance = 3.
8880         //
8881         //                      +--------v--v--v
8882         //             i0,i1,i2,i3,i4,i5,i6,i7,i8
8883         //             +--------^--^--^
8884         //
8885         // MaxMemDepDistance let us stop alias-checking at i3 and we add
8886         // dependencies from i0 to i3,i4,.. (even if they are not aliased).
8887         // Previously we already added dependencies from i3 to i6,i7,i8
8888         // (because of MaxMemDepDistance). As we added a dependency from
8889         // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
8890         // and we can abort this loop at i6.
8891         if (DistToSrc >= 2 * MaxMemDepDistance)
8892           break;
8893         DistToSrc++;
8894       }
8895     }
8896     if (InsertInReadyList && SD->isReady()) {
8897       ReadyInsts.insert(SD);
8898       LLVM_DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst
8899                         << "\n");
8900     }
8901   }
8902 }
8903 
8904 void BoUpSLP::BlockScheduling::resetSchedule() {
8905   assert(ScheduleStart &&
8906          "tried to reset schedule on block which has not been scheduled");
8907   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
8908     doForAllOpcodes(I, [&](ScheduleData *SD) {
8909       assert(isInSchedulingRegion(SD) &&
8910              "ScheduleData not in scheduling region");
8911       SD->IsScheduled = false;
8912       SD->resetUnscheduledDeps();
8913     });
8914   }
8915   ReadyInsts.clear();
8916 }
8917 
8918 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
8919   if (!BS->ScheduleStart)
8920     return;
8921 
8922   LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
8923 
8924   // A key point - if we got here, pre-scheduling was able to find a valid
8925   // scheduling of the sub-graph of the scheduling window which consists
8926   // of all vector bundles and their transitive users.  As such, we do not
8927   // need to reschedule anything *outside of* that subgraph.
8928 
8929   BS->resetSchedule();
8930 
8931   // For the real scheduling we use a more sophisticated ready-list: it is
8932   // sorted by the original instruction location. This lets the final schedule
8933   // be as  close as possible to the original instruction order.
8934   // WARNING: If changing this order causes a correctness issue, that means
8935   // there is some missing dependence edge in the schedule data graph.
8936   struct ScheduleDataCompare {
8937     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
8938       return SD2->SchedulingPriority < SD1->SchedulingPriority;
8939     }
8940   };
8941   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
8942 
8943   // Ensure that all dependency data is updated (for nodes in the sub-graph)
8944   // and fill the ready-list with initial instructions.
8945   int Idx = 0;
8946   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
8947        I = I->getNextNode()) {
8948     BS->doForAllOpcodes(I, [this, &Idx, BS](ScheduleData *SD) {
8949       TreeEntry *SDTE = getTreeEntry(SD->Inst);
8950       (void)SDTE;
8951       assert((isVectorLikeInstWithConstOps(SD->Inst) ||
8952               SD->isPartOfBundle() ==
8953                   (SDTE && !doesNotNeedToSchedule(SDTE->Scalars))) &&
8954              "scheduler and vectorizer bundle mismatch");
8955       SD->FirstInBundle->SchedulingPriority = Idx++;
8956 
8957       if (SD->isSchedulingEntity() && SD->isPartOfBundle())
8958         BS->calculateDependencies(SD, false, this);
8959     });
8960   }
8961   BS->initialFillReadyList(ReadyInsts);
8962 
8963   Instruction *LastScheduledInst = BS->ScheduleEnd;
8964 
8965   // Do the "real" scheduling.
8966   while (!ReadyInsts.empty()) {
8967     ScheduleData *picked = *ReadyInsts.begin();
8968     ReadyInsts.erase(ReadyInsts.begin());
8969 
8970     // Move the scheduled instruction(s) to their dedicated places, if not
8971     // there yet.
8972     for (ScheduleData *BundleMember = picked; BundleMember;
8973          BundleMember = BundleMember->NextInBundle) {
8974       Instruction *pickedInst = BundleMember->Inst;
8975       if (pickedInst->getNextNode() != LastScheduledInst)
8976         pickedInst->moveBefore(LastScheduledInst);
8977       LastScheduledInst = pickedInst;
8978     }
8979 
8980     BS->schedule(picked, ReadyInsts);
8981   }
8982 
8983   // Check that we didn't break any of our invariants.
8984 #ifdef EXPENSIVE_CHECKS
8985   BS->verify();
8986 #endif
8987 
8988 #if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS)
8989   // Check that all schedulable entities got scheduled
8990   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; I = I->getNextNode()) {
8991     BS->doForAllOpcodes(I, [&](ScheduleData *SD) {
8992       if (SD->isSchedulingEntity() && SD->hasValidDependencies()) {
8993         assert(SD->IsScheduled && "must be scheduled at this point");
8994       }
8995     });
8996   }
8997 #endif
8998 
8999   // Avoid duplicate scheduling of the block.
9000   BS->ScheduleStart = nullptr;
9001 }
9002 
9003 unsigned BoUpSLP::getVectorElementSize(Value *V) {
9004   // If V is a store, just return the width of the stored value (or value
9005   // truncated just before storing) without traversing the expression tree.
9006   // This is the common case.
9007   if (auto *Store = dyn_cast<StoreInst>(V))
9008     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
9009 
9010   if (auto *IEI = dyn_cast<InsertElementInst>(V))
9011     return getVectorElementSize(IEI->getOperand(1));
9012 
9013   auto E = InstrElementSize.find(V);
9014   if (E != InstrElementSize.end())
9015     return E->second;
9016 
9017   // If V is not a store, we can traverse the expression tree to find loads
9018   // that feed it. The type of the loaded value may indicate a more suitable
9019   // width than V's type. We want to base the vector element size on the width
9020   // of memory operations where possible.
9021   SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist;
9022   SmallPtrSet<Instruction *, 16> Visited;
9023   if (auto *I = dyn_cast<Instruction>(V)) {
9024     Worklist.emplace_back(I, I->getParent());
9025     Visited.insert(I);
9026   }
9027 
9028   // Traverse the expression tree in bottom-up order looking for loads. If we
9029   // encounter an instruction we don't yet handle, we give up.
9030   auto Width = 0u;
9031   while (!Worklist.empty()) {
9032     Instruction *I;
9033     BasicBlock *Parent;
9034     std::tie(I, Parent) = Worklist.pop_back_val();
9035 
9036     // We should only be looking at scalar instructions here. If the current
9037     // instruction has a vector type, skip.
9038     auto *Ty = I->getType();
9039     if (isa<VectorType>(Ty))
9040       continue;
9041 
9042     // If the current instruction is a load, update MaxWidth to reflect the
9043     // width of the loaded value.
9044     if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) ||
9045         isa<ExtractValueInst>(I))
9046       Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty));
9047 
9048     // Otherwise, we need to visit the operands of the instruction. We only
9049     // handle the interesting cases from buildTree here. If an operand is an
9050     // instruction we haven't yet visited and from the same basic block as the
9051     // user or the use is a PHI node, we add it to the worklist.
9052     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
9053              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) ||
9054              isa<UnaryOperator>(I)) {
9055       for (Use &U : I->operands())
9056         if (auto *J = dyn_cast<Instruction>(U.get()))
9057           if (Visited.insert(J).second &&
9058               (isa<PHINode>(I) || J->getParent() == Parent))
9059             Worklist.emplace_back(J, J->getParent());
9060     } else {
9061       break;
9062     }
9063   }
9064 
9065   // If we didn't encounter a memory access in the expression tree, or if we
9066   // gave up for some reason, just return the width of V. Otherwise, return the
9067   // maximum width we found.
9068   if (!Width) {
9069     if (auto *CI = dyn_cast<CmpInst>(V))
9070       V = CI->getOperand(0);
9071     Width = DL->getTypeSizeInBits(V->getType());
9072   }
9073 
9074   for (Instruction *I : Visited)
9075     InstrElementSize[I] = Width;
9076 
9077   return Width;
9078 }
9079 
9080 // Determine if a value V in a vectorizable expression Expr can be demoted to a
9081 // smaller type with a truncation. We collect the values that will be demoted
9082 // in ToDemote and additional roots that require investigating in Roots.
9083 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
9084                                   SmallVectorImpl<Value *> &ToDemote,
9085                                   SmallVectorImpl<Value *> &Roots) {
9086   // We can always demote constants.
9087   if (isa<Constant>(V)) {
9088     ToDemote.push_back(V);
9089     return true;
9090   }
9091 
9092   // If the value is not an instruction in the expression with only one use, it
9093   // cannot be demoted.
9094   auto *I = dyn_cast<Instruction>(V);
9095   if (!I || !I->hasOneUse() || !Expr.count(I))
9096     return false;
9097 
9098   switch (I->getOpcode()) {
9099 
9100   // We can always demote truncations and extensions. Since truncations can
9101   // seed additional demotion, we save the truncated value.
9102   case Instruction::Trunc:
9103     Roots.push_back(I->getOperand(0));
9104     break;
9105   case Instruction::ZExt:
9106   case Instruction::SExt:
9107     if (isa<ExtractElementInst>(I->getOperand(0)) ||
9108         isa<InsertElementInst>(I->getOperand(0)))
9109       return false;
9110     break;
9111 
9112   // We can demote certain binary operations if we can demote both of their
9113   // operands.
9114   case Instruction::Add:
9115   case Instruction::Sub:
9116   case Instruction::Mul:
9117   case Instruction::And:
9118   case Instruction::Or:
9119   case Instruction::Xor:
9120     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
9121         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
9122       return false;
9123     break;
9124 
9125   // We can demote selects if we can demote their true and false values.
9126   case Instruction::Select: {
9127     SelectInst *SI = cast<SelectInst>(I);
9128     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
9129         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
9130       return false;
9131     break;
9132   }
9133 
9134   // We can demote phis if we can demote all their incoming operands. Note that
9135   // we don't need to worry about cycles since we ensure single use above.
9136   case Instruction::PHI: {
9137     PHINode *PN = cast<PHINode>(I);
9138     for (Value *IncValue : PN->incoming_values())
9139       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
9140         return false;
9141     break;
9142   }
9143 
9144   // Otherwise, conservatively give up.
9145   default:
9146     return false;
9147   }
9148 
9149   // Record the value that we can demote.
9150   ToDemote.push_back(V);
9151   return true;
9152 }
9153 
9154 void BoUpSLP::computeMinimumValueSizes() {
9155   // If there are no external uses, the expression tree must be rooted by a
9156   // store. We can't demote in-memory values, so there is nothing to do here.
9157   if (ExternalUses.empty())
9158     return;
9159 
9160   // We only attempt to truncate integer expressions.
9161   auto &TreeRoot = VectorizableTree[0]->Scalars;
9162   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
9163   if (!TreeRootIT)
9164     return;
9165 
9166   // If the expression is not rooted by a store, these roots should have
9167   // external uses. We will rely on InstCombine to rewrite the expression in
9168   // the narrower type. However, InstCombine only rewrites single-use values.
9169   // This means that if a tree entry other than a root is used externally, it
9170   // must have multiple uses and InstCombine will not rewrite it. The code
9171   // below ensures that only the roots are used externally.
9172   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
9173   for (auto &EU : ExternalUses)
9174     if (!Expr.erase(EU.Scalar))
9175       return;
9176   if (!Expr.empty())
9177     return;
9178 
9179   // Collect the scalar values of the vectorizable expression. We will use this
9180   // context to determine which values can be demoted. If we see a truncation,
9181   // we mark it as seeding another demotion.
9182   for (auto &EntryPtr : VectorizableTree)
9183     Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
9184 
9185   // Ensure the roots of the vectorizable tree don't form a cycle. They must
9186   // have a single external user that is not in the vectorizable tree.
9187   for (auto *Root : TreeRoot)
9188     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
9189       return;
9190 
9191   // Conservatively determine if we can actually truncate the roots of the
9192   // expression. Collect the values that can be demoted in ToDemote and
9193   // additional roots that require investigating in Roots.
9194   SmallVector<Value *, 32> ToDemote;
9195   SmallVector<Value *, 4> Roots;
9196   for (auto *Root : TreeRoot)
9197     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
9198       return;
9199 
9200   // The maximum bit width required to represent all the values that can be
9201   // demoted without loss of precision. It would be safe to truncate the roots
9202   // of the expression to this width.
9203   auto MaxBitWidth = 8u;
9204 
9205   // We first check if all the bits of the roots are demanded. If they're not,
9206   // we can truncate the roots to this narrower type.
9207   for (auto *Root : TreeRoot) {
9208     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
9209     MaxBitWidth = std::max<unsigned>(
9210         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
9211   }
9212 
9213   // True if the roots can be zero-extended back to their original type, rather
9214   // than sign-extended. We know that if the leading bits are not demanded, we
9215   // can safely zero-extend. So we initialize IsKnownPositive to True.
9216   bool IsKnownPositive = true;
9217 
9218   // If all the bits of the roots are demanded, we can try a little harder to
9219   // compute a narrower type. This can happen, for example, if the roots are
9220   // getelementptr indices. InstCombine promotes these indices to the pointer
9221   // width. Thus, all their bits are technically demanded even though the
9222   // address computation might be vectorized in a smaller type.
9223   //
9224   // We start by looking at each entry that can be demoted. We compute the
9225   // maximum bit width required to store the scalar by using ValueTracking to
9226   // compute the number of high-order bits we can truncate.
9227   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
9228       llvm::all_of(TreeRoot, [](Value *R) {
9229         assert(R->hasOneUse() && "Root should have only one use!");
9230         return isa<GetElementPtrInst>(R->user_back());
9231       })) {
9232     MaxBitWidth = 8u;
9233 
9234     // Determine if the sign bit of all the roots is known to be zero. If not,
9235     // IsKnownPositive is set to False.
9236     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
9237       KnownBits Known = computeKnownBits(R, *DL);
9238       return Known.isNonNegative();
9239     });
9240 
9241     // Determine the maximum number of bits required to store the scalar
9242     // values.
9243     for (auto *Scalar : ToDemote) {
9244       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
9245       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
9246       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
9247     }
9248 
9249     // If we can't prove that the sign bit is zero, we must add one to the
9250     // maximum bit width to account for the unknown sign bit. This preserves
9251     // the existing sign bit so we can safely sign-extend the root back to the
9252     // original type. Otherwise, if we know the sign bit is zero, we will
9253     // zero-extend the root instead.
9254     //
9255     // FIXME: This is somewhat suboptimal, as there will be cases where adding
9256     //        one to the maximum bit width will yield a larger-than-necessary
9257     //        type. In general, we need to add an extra bit only if we can't
9258     //        prove that the upper bit of the original type is equal to the
9259     //        upper bit of the proposed smaller type. If these two bits are the
9260     //        same (either zero or one) we know that sign-extending from the
9261     //        smaller type will result in the same value. Here, since we can't
9262     //        yet prove this, we are just making the proposed smaller type
9263     //        larger to ensure correctness.
9264     if (!IsKnownPositive)
9265       ++MaxBitWidth;
9266   }
9267 
9268   // Round MaxBitWidth up to the next power-of-two.
9269   if (!isPowerOf2_64(MaxBitWidth))
9270     MaxBitWidth = NextPowerOf2(MaxBitWidth);
9271 
9272   // If the maximum bit width we compute is less than the with of the roots'
9273   // type, we can proceed with the narrowing. Otherwise, do nothing.
9274   if (MaxBitWidth >= TreeRootIT->getBitWidth())
9275     return;
9276 
9277   // If we can truncate the root, we must collect additional values that might
9278   // be demoted as a result. That is, those seeded by truncations we will
9279   // modify.
9280   while (!Roots.empty())
9281     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
9282 
9283   // Finally, map the values we can demote to the maximum bit with we computed.
9284   for (auto *Scalar : ToDemote)
9285     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
9286 }
9287 
9288 namespace {
9289 
9290 /// The SLPVectorizer Pass.
9291 struct SLPVectorizer : public FunctionPass {
9292   SLPVectorizerPass Impl;
9293 
9294   /// Pass identification, replacement for typeid
9295   static char ID;
9296 
9297   explicit SLPVectorizer() : FunctionPass(ID) {
9298     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
9299   }
9300 
9301   bool doInitialization(Module &M) override { return false; }
9302 
9303   bool runOnFunction(Function &F) override {
9304     if (skipFunction(F))
9305       return false;
9306 
9307     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
9308     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
9309     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
9310     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
9311     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
9312     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
9313     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
9314     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
9315     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
9316     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
9317 
9318     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
9319   }
9320 
9321   void getAnalysisUsage(AnalysisUsage &AU) const override {
9322     FunctionPass::getAnalysisUsage(AU);
9323     AU.addRequired<AssumptionCacheTracker>();
9324     AU.addRequired<ScalarEvolutionWrapperPass>();
9325     AU.addRequired<AAResultsWrapperPass>();
9326     AU.addRequired<TargetTransformInfoWrapperPass>();
9327     AU.addRequired<LoopInfoWrapperPass>();
9328     AU.addRequired<DominatorTreeWrapperPass>();
9329     AU.addRequired<DemandedBitsWrapperPass>();
9330     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
9331     AU.addRequired<InjectTLIMappingsLegacy>();
9332     AU.addPreserved<LoopInfoWrapperPass>();
9333     AU.addPreserved<DominatorTreeWrapperPass>();
9334     AU.addPreserved<AAResultsWrapperPass>();
9335     AU.addPreserved<GlobalsAAWrapperPass>();
9336     AU.setPreservesCFG();
9337   }
9338 };
9339 
9340 } // end anonymous namespace
9341 
9342 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
9343   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
9344   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
9345   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
9346   auto *AA = &AM.getResult<AAManager>(F);
9347   auto *LI = &AM.getResult<LoopAnalysis>(F);
9348   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
9349   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
9350   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
9351   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
9352 
9353   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
9354   if (!Changed)
9355     return PreservedAnalyses::all();
9356 
9357   PreservedAnalyses PA;
9358   PA.preserveSet<CFGAnalyses>();
9359   return PA;
9360 }
9361 
9362 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
9363                                 TargetTransformInfo *TTI_,
9364                                 TargetLibraryInfo *TLI_, AAResults *AA_,
9365                                 LoopInfo *LI_, DominatorTree *DT_,
9366                                 AssumptionCache *AC_, DemandedBits *DB_,
9367                                 OptimizationRemarkEmitter *ORE_) {
9368   if (!RunSLPVectorization)
9369     return false;
9370   SE = SE_;
9371   TTI = TTI_;
9372   TLI = TLI_;
9373   AA = AA_;
9374   LI = LI_;
9375   DT = DT_;
9376   AC = AC_;
9377   DB = DB_;
9378   DL = &F.getParent()->getDataLayout();
9379 
9380   Stores.clear();
9381   GEPs.clear();
9382   bool Changed = false;
9383 
9384   // If the target claims to have no vector registers don't attempt
9385   // vectorization.
9386   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true))) {
9387     LLVM_DEBUG(
9388         dbgs() << "SLP: Didn't find any vector registers for target, abort.\n");
9389     return false;
9390   }
9391 
9392   // Don't vectorize when the attribute NoImplicitFloat is used.
9393   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
9394     return false;
9395 
9396   LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
9397 
9398   // Use the bottom up slp vectorizer to construct chains that start with
9399   // store instructions.
9400   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
9401 
9402   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
9403   // delete instructions.
9404 
9405   // Update DFS numbers now so that we can use them for ordering.
9406   DT->updateDFSNumbers();
9407 
9408   // Scan the blocks in the function in post order.
9409   for (auto BB : post_order(&F.getEntryBlock())) {
9410     // Start new block - clear the list of reduction roots.
9411     R.clearReductionData();
9412     collectSeedInstructions(BB);
9413 
9414     // Vectorize trees that end at stores.
9415     if (!Stores.empty()) {
9416       LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
9417                         << " underlying objects.\n");
9418       Changed |= vectorizeStoreChains(R);
9419     }
9420 
9421     // Vectorize trees that end at reductions.
9422     Changed |= vectorizeChainsInBlock(BB, R);
9423 
9424     // Vectorize the index computations of getelementptr instructions. This
9425     // is primarily intended to catch gather-like idioms ending at
9426     // non-consecutive loads.
9427     if (!GEPs.empty()) {
9428       LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
9429                         << " underlying objects.\n");
9430       Changed |= vectorizeGEPIndices(BB, R);
9431     }
9432   }
9433 
9434   if (Changed) {
9435     R.optimizeGatherSequence();
9436     LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
9437   }
9438   return Changed;
9439 }
9440 
9441 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
9442                                             unsigned Idx, unsigned MinVF) {
9443   LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()
9444                     << "\n");
9445   const unsigned Sz = R.getVectorElementSize(Chain[0]);
9446   unsigned VF = Chain.size();
9447 
9448   if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
9449     return false;
9450 
9451   LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx
9452                     << "\n");
9453 
9454   R.buildTree(Chain);
9455   if (R.isTreeTinyAndNotFullyVectorizable())
9456     return false;
9457   if (R.isLoadCombineCandidate())
9458     return false;
9459   R.reorderTopToBottom();
9460   R.reorderBottomToTop();
9461   R.buildExternalUses();
9462 
9463   R.computeMinimumValueSizes();
9464 
9465   InstructionCost Cost = R.getTreeCost();
9466 
9467   LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n");
9468   if (Cost < -SLPCostThreshold) {
9469     LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n");
9470 
9471     using namespace ore;
9472 
9473     R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
9474                                         cast<StoreInst>(Chain[0]))
9475                      << "Stores SLP vectorized with cost " << NV("Cost", Cost)
9476                      << " and with tree size "
9477                      << NV("TreeSize", R.getTreeSize()));
9478 
9479     R.vectorizeTree();
9480     return true;
9481   }
9482 
9483   return false;
9484 }
9485 
9486 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
9487                                         BoUpSLP &R) {
9488   // We may run into multiple chains that merge into a single chain. We mark the
9489   // stores that we vectorized so that we don't visit the same store twice.
9490   BoUpSLP::ValueSet VectorizedStores;
9491   bool Changed = false;
9492 
9493   int E = Stores.size();
9494   SmallBitVector Tails(E, false);
9495   int MaxIter = MaxStoreLookup.getValue();
9496   SmallVector<std::pair<int, int>, 16> ConsecutiveChain(
9497       E, std::make_pair(E, INT_MAX));
9498   SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false));
9499   int IterCnt;
9500   auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
9501                                   &CheckedPairs,
9502                                   &ConsecutiveChain](int K, int Idx) {
9503     if (IterCnt >= MaxIter)
9504       return true;
9505     if (CheckedPairs[Idx].test(K))
9506       return ConsecutiveChain[K].second == 1 &&
9507              ConsecutiveChain[K].first == Idx;
9508     ++IterCnt;
9509     CheckedPairs[Idx].set(K);
9510     CheckedPairs[K].set(Idx);
9511     Optional<int> Diff = getPointersDiff(
9512         Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(),
9513         Stores[Idx]->getValueOperand()->getType(),
9514         Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true);
9515     if (!Diff || *Diff == 0)
9516       return false;
9517     int Val = *Diff;
9518     if (Val < 0) {
9519       if (ConsecutiveChain[Idx].second > -Val) {
9520         Tails.set(K);
9521         ConsecutiveChain[Idx] = std::make_pair(K, -Val);
9522       }
9523       return false;
9524     }
9525     if (ConsecutiveChain[K].second <= Val)
9526       return false;
9527 
9528     Tails.set(Idx);
9529     ConsecutiveChain[K] = std::make_pair(Idx, Val);
9530     return Val == 1;
9531   };
9532   // Do a quadratic search on all of the given stores in reverse order and find
9533   // all of the pairs of stores that follow each other.
9534   for (int Idx = E - 1; Idx >= 0; --Idx) {
9535     // If a store has multiple consecutive store candidates, search according
9536     // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
9537     // This is because usually pairing with immediate succeeding or preceding
9538     // candidate create the best chance to find slp vectorization opportunity.
9539     const int MaxLookDepth = std::max(E - Idx, Idx + 1);
9540     IterCnt = 0;
9541     for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
9542       if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
9543           (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
9544         break;
9545   }
9546 
9547   // Tracks if we tried to vectorize stores starting from the given tail
9548   // already.
9549   SmallBitVector TriedTails(E, false);
9550   // For stores that start but don't end a link in the chain:
9551   for (int Cnt = E; Cnt > 0; --Cnt) {
9552     int I = Cnt - 1;
9553     if (ConsecutiveChain[I].first == E || Tails.test(I))
9554       continue;
9555     // We found a store instr that starts a chain. Now follow the chain and try
9556     // to vectorize it.
9557     BoUpSLP::ValueList Operands;
9558     // Collect the chain into a list.
9559     while (I != E && !VectorizedStores.count(Stores[I])) {
9560       Operands.push_back(Stores[I]);
9561       Tails.set(I);
9562       if (ConsecutiveChain[I].second != 1) {
9563         // Mark the new end in the chain and go back, if required. It might be
9564         // required if the original stores come in reversed order, for example.
9565         if (ConsecutiveChain[I].first != E &&
9566             Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) &&
9567             !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) {
9568           TriedTails.set(I);
9569           Tails.reset(ConsecutiveChain[I].first);
9570           if (Cnt < ConsecutiveChain[I].first + 2)
9571             Cnt = ConsecutiveChain[I].first + 2;
9572         }
9573         break;
9574       }
9575       // Move to the next value in the chain.
9576       I = ConsecutiveChain[I].first;
9577     }
9578     assert(!Operands.empty() && "Expected non-empty list of stores.");
9579 
9580     unsigned MaxVecRegSize = R.getMaxVecRegSize();
9581     unsigned EltSize = R.getVectorElementSize(Operands[0]);
9582     unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize);
9583 
9584     unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store),
9585                               MaxElts);
9586     auto *Store = cast<StoreInst>(Operands[0]);
9587     Type *StoreTy = Store->getValueOperand()->getType();
9588     Type *ValueTy = StoreTy;
9589     if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand()))
9590       ValueTy = Trunc->getSrcTy();
9591     unsigned MinVF = TTI->getStoreMinimumVF(
9592         R.getMinVF(DL->getTypeSizeInBits(ValueTy)), StoreTy, ValueTy);
9593 
9594     // FIXME: Is division-by-2 the correct step? Should we assert that the
9595     // register size is a power-of-2?
9596     unsigned StartIdx = 0;
9597     for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) {
9598       for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
9599         ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size);
9600         if (!VectorizedStores.count(Slice.front()) &&
9601             !VectorizedStores.count(Slice.back()) &&
9602             vectorizeStoreChain(Slice, R, Cnt, MinVF)) {
9603           // Mark the vectorized stores so that we don't vectorize them again.
9604           VectorizedStores.insert(Slice.begin(), Slice.end());
9605           Changed = true;
9606           // If we vectorized initial block, no need to try to vectorize it
9607           // again.
9608           if (Cnt == StartIdx)
9609             StartIdx += Size;
9610           Cnt += Size;
9611           continue;
9612         }
9613         ++Cnt;
9614       }
9615       // Check if the whole array was vectorized already - exit.
9616       if (StartIdx >= Operands.size())
9617         break;
9618     }
9619   }
9620 
9621   return Changed;
9622 }
9623 
9624 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
9625   // Initialize the collections. We will make a single pass over the block.
9626   Stores.clear();
9627   GEPs.clear();
9628 
9629   // Visit the store and getelementptr instructions in BB and organize them in
9630   // Stores and GEPs according to the underlying objects of their pointer
9631   // operands.
9632   for (Instruction &I : *BB) {
9633     // Ignore store instructions that are volatile or have a pointer operand
9634     // that doesn't point to a scalar type.
9635     if (auto *SI = dyn_cast<StoreInst>(&I)) {
9636       if (!SI->isSimple())
9637         continue;
9638       if (!isValidElementType(SI->getValueOperand()->getType()))
9639         continue;
9640       Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI);
9641     }
9642 
9643     // Ignore getelementptr instructions that have more than one index, a
9644     // constant index, or a pointer operand that doesn't point to a scalar
9645     // type.
9646     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
9647       auto Idx = GEP->idx_begin()->get();
9648       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
9649         continue;
9650       if (!isValidElementType(Idx->getType()))
9651         continue;
9652       if (GEP->getType()->isVectorTy())
9653         continue;
9654       GEPs[GEP->getPointerOperand()].push_back(GEP);
9655     }
9656   }
9657 }
9658 
9659 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
9660   if (!A || !B)
9661     return false;
9662   if (isa<InsertElementInst>(A) || isa<InsertElementInst>(B))
9663     return false;
9664   Value *VL[] = {A, B};
9665   return tryToVectorizeList(VL, R);
9666 }
9667 
9668 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
9669                                            bool LimitForRegisterSize) {
9670   if (VL.size() < 2)
9671     return false;
9672 
9673   LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
9674                     << VL.size() << ".\n");
9675 
9676   // Check that all of the parts are instructions of the same type,
9677   // we permit an alternate opcode via InstructionsState.
9678   InstructionsState S = getSameOpcode(VL);
9679   if (!S.getOpcode())
9680     return false;
9681 
9682   Instruction *I0 = cast<Instruction>(S.OpValue);
9683   // Make sure invalid types (including vector type) are rejected before
9684   // determining vectorization factor for scalar instructions.
9685   for (Value *V : VL) {
9686     Type *Ty = V->getType();
9687     if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) {
9688       // NOTE: the following will give user internal llvm type name, which may
9689       // not be useful.
9690       R.getORE()->emit([&]() {
9691         std::string type_str;
9692         llvm::raw_string_ostream rso(type_str);
9693         Ty->print(rso);
9694         return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
9695                << "Cannot SLP vectorize list: type "
9696                << rso.str() + " is unsupported by vectorizer";
9697       });
9698       return false;
9699     }
9700   }
9701 
9702   unsigned Sz = R.getVectorElementSize(I0);
9703   unsigned MinVF = R.getMinVF(Sz);
9704   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
9705   MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF);
9706   if (MaxVF < 2) {
9707     R.getORE()->emit([&]() {
9708       return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
9709              << "Cannot SLP vectorize list: vectorization factor "
9710              << "less than 2 is not supported";
9711     });
9712     return false;
9713   }
9714 
9715   bool Changed = false;
9716   bool CandidateFound = false;
9717   InstructionCost MinCost = SLPCostThreshold.getValue();
9718   Type *ScalarTy = VL[0]->getType();
9719   if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
9720     ScalarTy = IE->getOperand(1)->getType();
9721 
9722   unsigned NextInst = 0, MaxInst = VL.size();
9723   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
9724     // No actual vectorization should happen, if number of parts is the same as
9725     // provided vectorization factor (i.e. the scalar type is used for vector
9726     // code during codegen).
9727     auto *VecTy = FixedVectorType::get(ScalarTy, VF);
9728     if (TTI->getNumberOfParts(VecTy) == VF)
9729       continue;
9730     for (unsigned I = NextInst; I < MaxInst; ++I) {
9731       unsigned OpsWidth = 0;
9732 
9733       if (I + VF > MaxInst)
9734         OpsWidth = MaxInst - I;
9735       else
9736         OpsWidth = VF;
9737 
9738       if (!isPowerOf2_32(OpsWidth))
9739         continue;
9740 
9741       if ((LimitForRegisterSize && OpsWidth < MaxVF) ||
9742           (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2))
9743         break;
9744 
9745       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
9746       // Check that a previous iteration of this loop did not delete the Value.
9747       if (llvm::any_of(Ops, [&R](Value *V) {
9748             auto *I = dyn_cast<Instruction>(V);
9749             return I && R.isDeleted(I);
9750           }))
9751         continue;
9752 
9753       LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
9754                         << "\n");
9755 
9756       R.buildTree(Ops);
9757       if (R.isTreeTinyAndNotFullyVectorizable())
9758         continue;
9759       R.reorderTopToBottom();
9760       R.reorderBottomToTop(!isa<InsertElementInst>(Ops.front()));
9761       R.buildExternalUses();
9762 
9763       R.computeMinimumValueSizes();
9764       InstructionCost Cost = R.getTreeCost();
9765       CandidateFound = true;
9766       MinCost = std::min(MinCost, Cost);
9767 
9768       if (Cost < -SLPCostThreshold) {
9769         LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
9770         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
9771                                                     cast<Instruction>(Ops[0]))
9772                                  << "SLP vectorized with cost " << ore::NV("Cost", Cost)
9773                                  << " and with tree size "
9774                                  << ore::NV("TreeSize", R.getTreeSize()));
9775 
9776         R.vectorizeTree();
9777         // Move to the next bundle.
9778         I += VF - 1;
9779         NextInst = I + 1;
9780         Changed = true;
9781       }
9782     }
9783   }
9784 
9785   if (!Changed && CandidateFound) {
9786     R.getORE()->emit([&]() {
9787       return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
9788              << "List vectorization was possible but not beneficial with cost "
9789              << ore::NV("Cost", MinCost) << " >= "
9790              << ore::NV("Treshold", -SLPCostThreshold);
9791     });
9792   } else if (!Changed) {
9793     R.getORE()->emit([&]() {
9794       return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
9795              << "Cannot SLP vectorize list: vectorization was impossible"
9796              << " with available vectorization factors";
9797     });
9798   }
9799   return Changed;
9800 }
9801 
9802 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
9803   if (!I)
9804     return false;
9805 
9806   if ((!isa<BinaryOperator>(I) && !isa<CmpInst>(I)) ||
9807       isa<VectorType>(I->getType()))
9808     return false;
9809 
9810   Value *P = I->getParent();
9811 
9812   // Vectorize in current basic block only.
9813   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
9814   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
9815   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
9816     return false;
9817 
9818   // First collect all possible candidates
9819   SmallVector<std::pair<Value *, Value *>, 4> Candidates;
9820   Candidates.emplace_back(Op0, Op1);
9821 
9822   auto *A = dyn_cast<BinaryOperator>(Op0);
9823   auto *B = dyn_cast<BinaryOperator>(Op1);
9824   // Try to skip B.
9825   if (A && B && B->hasOneUse()) {
9826     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
9827     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
9828     if (B0 && B0->getParent() == P)
9829       Candidates.emplace_back(A, B0);
9830     if (B1 && B1->getParent() == P)
9831       Candidates.emplace_back(A, B1);
9832   }
9833   // Try to skip A.
9834   if (B && A && A->hasOneUse()) {
9835     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
9836     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
9837     if (A0 && A0->getParent() == P)
9838       Candidates.emplace_back(A0, B);
9839     if (A1 && A1->getParent() == P)
9840       Candidates.emplace_back(A1, B);
9841   }
9842 
9843   if (Candidates.size() == 1)
9844     return tryToVectorizePair(Op0, Op1, R);
9845 
9846   // We have multiple options. Try to pick the single best.
9847   Optional<int> BestCandidate = R.findBestRootPair(Candidates);
9848   if (!BestCandidate)
9849     return false;
9850   return tryToVectorizePair(Candidates[*BestCandidate].first,
9851                             Candidates[*BestCandidate].second, R);
9852 }
9853 
9854 namespace {
9855 
9856 /// Model horizontal reductions.
9857 ///
9858 /// A horizontal reduction is a tree of reduction instructions that has values
9859 /// that can be put into a vector as its leaves. For example:
9860 ///
9861 /// mul mul mul mul
9862 ///  \  /    \  /
9863 ///   +       +
9864 ///    \     /
9865 ///       +
9866 /// This tree has "mul" as its leaf values and "+" as its reduction
9867 /// instructions. A reduction can feed into a store or a binary operation
9868 /// feeding a phi.
9869 ///    ...
9870 ///    \  /
9871 ///     +
9872 ///     |
9873 ///  phi +=
9874 ///
9875 ///  Or:
9876 ///    ...
9877 ///    \  /
9878 ///     +
9879 ///     |
9880 ///   *p =
9881 ///
9882 class HorizontalReduction {
9883   using ReductionOpsType = SmallVector<Value *, 16>;
9884   using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
9885   ReductionOpsListType ReductionOps;
9886   /// List of possibly reduced values.
9887   SmallVector<SmallVector<Value *>> ReducedVals;
9888   /// Maps reduced value to the corresponding reduction operation.
9889   DenseMap<Value *, SmallVector<Instruction *>> ReducedValsToOps;
9890   // Use map vector to make stable output.
9891   MapVector<Instruction *, Value *> ExtraArgs;
9892   WeakTrackingVH ReductionRoot;
9893   /// The type of reduction operation.
9894   RecurKind RdxKind;
9895 
9896   static bool isCmpSelMinMax(Instruction *I) {
9897     return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) &&
9898            RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I));
9899   }
9900 
9901   // And/or are potentially poison-safe logical patterns like:
9902   // select x, y, false
9903   // select x, true, y
9904   static bool isBoolLogicOp(Instruction *I) {
9905     return match(I, m_LogicalAnd(m_Value(), m_Value())) ||
9906            match(I, m_LogicalOr(m_Value(), m_Value()));
9907   }
9908 
9909   /// Checks if instruction is associative and can be vectorized.
9910   static bool isVectorizable(RecurKind Kind, Instruction *I) {
9911     if (Kind == RecurKind::None)
9912       return false;
9913 
9914     // Integer ops that map to select instructions or intrinsics are fine.
9915     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) ||
9916         isBoolLogicOp(I))
9917       return true;
9918 
9919     if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) {
9920       // FP min/max are associative except for NaN and -0.0. We do not
9921       // have to rule out -0.0 here because the intrinsic semantics do not
9922       // specify a fixed result for it.
9923       return I->getFastMathFlags().noNaNs();
9924     }
9925 
9926     return I->isAssociative();
9927   }
9928 
9929   static Value *getRdxOperand(Instruction *I, unsigned Index) {
9930     // Poison-safe 'or' takes the form: select X, true, Y
9931     // To make that work with the normal operand processing, we skip the
9932     // true value operand.
9933     // TODO: Change the code and data structures to handle this without a hack.
9934     if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1)
9935       return I->getOperand(2);
9936     return I->getOperand(Index);
9937   }
9938 
9939   /// Creates reduction operation with the current opcode.
9940   static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS,
9941                          Value *RHS, const Twine &Name, bool UseSelect) {
9942     unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind);
9943     switch (Kind) {
9944     case RecurKind::Or:
9945       if (UseSelect &&
9946           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9947         return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name);
9948       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9949                                  Name);
9950     case RecurKind::And:
9951       if (UseSelect &&
9952           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9953         return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name);
9954       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9955                                  Name);
9956     case RecurKind::Add:
9957     case RecurKind::Mul:
9958     case RecurKind::Xor:
9959     case RecurKind::FAdd:
9960     case RecurKind::FMul:
9961       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9962                                  Name);
9963     case RecurKind::FMax:
9964       return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS);
9965     case RecurKind::FMin:
9966       return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS);
9967     case RecurKind::SMax:
9968       if (UseSelect) {
9969         Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name);
9970         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9971       }
9972       return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS);
9973     case RecurKind::SMin:
9974       if (UseSelect) {
9975         Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name);
9976         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9977       }
9978       return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS);
9979     case RecurKind::UMax:
9980       if (UseSelect) {
9981         Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name);
9982         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9983       }
9984       return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS);
9985     case RecurKind::UMin:
9986       if (UseSelect) {
9987         Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name);
9988         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9989       }
9990       return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS);
9991     default:
9992       llvm_unreachable("Unknown reduction operation.");
9993     }
9994   }
9995 
9996   /// Creates reduction operation with the current opcode with the IR flags
9997   /// from \p ReductionOps.
9998   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9999                          Value *RHS, const Twine &Name,
10000                          const ReductionOpsListType &ReductionOps) {
10001     bool UseSelect = ReductionOps.size() == 2 ||
10002                      // Logical or/and.
10003                      (ReductionOps.size() == 1 &&
10004                       isa<SelectInst>(ReductionOps.front().front()));
10005     assert((!UseSelect || ReductionOps.size() != 2 ||
10006             isa<SelectInst>(ReductionOps[1][0])) &&
10007            "Expected cmp + select pairs for reduction");
10008     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect);
10009     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
10010       if (auto *Sel = dyn_cast<SelectInst>(Op)) {
10011         propagateIRFlags(Sel->getCondition(), ReductionOps[0]);
10012         propagateIRFlags(Op, ReductionOps[1]);
10013         return Op;
10014       }
10015     }
10016     propagateIRFlags(Op, ReductionOps[0]);
10017     return Op;
10018   }
10019 
10020   /// Creates reduction operation with the current opcode with the IR flags
10021   /// from \p I.
10022   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
10023                          Value *RHS, const Twine &Name, Value *I) {
10024     auto *SelI = dyn_cast<SelectInst>(I);
10025     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, SelI != nullptr);
10026     if (SelI && RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
10027       if (auto *Sel = dyn_cast<SelectInst>(Op))
10028         propagateIRFlags(Sel->getCondition(), SelI->getCondition());
10029     }
10030     propagateIRFlags(Op, I);
10031     return Op;
10032   }
10033 
10034   static RecurKind getRdxKind(Value *V) {
10035     auto *I = dyn_cast<Instruction>(V);
10036     if (!I)
10037       return RecurKind::None;
10038     if (match(I, m_Add(m_Value(), m_Value())))
10039       return RecurKind::Add;
10040     if (match(I, m_Mul(m_Value(), m_Value())))
10041       return RecurKind::Mul;
10042     if (match(I, m_And(m_Value(), m_Value())) ||
10043         match(I, m_LogicalAnd(m_Value(), m_Value())))
10044       return RecurKind::And;
10045     if (match(I, m_Or(m_Value(), m_Value())) ||
10046         match(I, m_LogicalOr(m_Value(), m_Value())))
10047       return RecurKind::Or;
10048     if (match(I, m_Xor(m_Value(), m_Value())))
10049       return RecurKind::Xor;
10050     if (match(I, m_FAdd(m_Value(), m_Value())))
10051       return RecurKind::FAdd;
10052     if (match(I, m_FMul(m_Value(), m_Value())))
10053       return RecurKind::FMul;
10054 
10055     if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value())))
10056       return RecurKind::FMax;
10057     if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value())))
10058       return RecurKind::FMin;
10059 
10060     // This matches either cmp+select or intrinsics. SLP is expected to handle
10061     // either form.
10062     // TODO: If we are canonicalizing to intrinsics, we can remove several
10063     //       special-case paths that deal with selects.
10064     if (match(I, m_SMax(m_Value(), m_Value())))
10065       return RecurKind::SMax;
10066     if (match(I, m_SMin(m_Value(), m_Value())))
10067       return RecurKind::SMin;
10068     if (match(I, m_UMax(m_Value(), m_Value())))
10069       return RecurKind::UMax;
10070     if (match(I, m_UMin(m_Value(), m_Value())))
10071       return RecurKind::UMin;
10072 
10073     if (auto *Select = dyn_cast<SelectInst>(I)) {
10074       // Try harder: look for min/max pattern based on instructions producing
10075       // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
10076       // During the intermediate stages of SLP, it's very common to have
10077       // pattern like this (since optimizeGatherSequence is run only once
10078       // at the end):
10079       // %1 = extractelement <2 x i32> %a, i32 0
10080       // %2 = extractelement <2 x i32> %a, i32 1
10081       // %cond = icmp sgt i32 %1, %2
10082       // %3 = extractelement <2 x i32> %a, i32 0
10083       // %4 = extractelement <2 x i32> %a, i32 1
10084       // %select = select i1 %cond, i32 %3, i32 %4
10085       CmpInst::Predicate Pred;
10086       Instruction *L1;
10087       Instruction *L2;
10088 
10089       Value *LHS = Select->getTrueValue();
10090       Value *RHS = Select->getFalseValue();
10091       Value *Cond = Select->getCondition();
10092 
10093       // TODO: Support inverse predicates.
10094       if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
10095         if (!isa<ExtractElementInst>(RHS) ||
10096             !L2->isIdenticalTo(cast<Instruction>(RHS)))
10097           return RecurKind::None;
10098       } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
10099         if (!isa<ExtractElementInst>(LHS) ||
10100             !L1->isIdenticalTo(cast<Instruction>(LHS)))
10101           return RecurKind::None;
10102       } else {
10103         if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
10104           return RecurKind::None;
10105         if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
10106             !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
10107             !L2->isIdenticalTo(cast<Instruction>(RHS)))
10108           return RecurKind::None;
10109       }
10110 
10111       switch (Pred) {
10112       default:
10113         return RecurKind::None;
10114       case CmpInst::ICMP_SGT:
10115       case CmpInst::ICMP_SGE:
10116         return RecurKind::SMax;
10117       case CmpInst::ICMP_SLT:
10118       case CmpInst::ICMP_SLE:
10119         return RecurKind::SMin;
10120       case CmpInst::ICMP_UGT:
10121       case CmpInst::ICMP_UGE:
10122         return RecurKind::UMax;
10123       case CmpInst::ICMP_ULT:
10124       case CmpInst::ICMP_ULE:
10125         return RecurKind::UMin;
10126       }
10127     }
10128     return RecurKind::None;
10129   }
10130 
10131   /// Get the index of the first operand.
10132   static unsigned getFirstOperandIndex(Instruction *I) {
10133     return isCmpSelMinMax(I) ? 1 : 0;
10134   }
10135 
10136   /// Total number of operands in the reduction operation.
10137   static unsigned getNumberOfOperands(Instruction *I) {
10138     return isCmpSelMinMax(I) ? 3 : 2;
10139   }
10140 
10141   /// Checks if the instruction is in basic block \p BB.
10142   /// For a cmp+sel min/max reduction check that both ops are in \p BB.
10143   static bool hasSameParent(Instruction *I, BasicBlock *BB) {
10144     if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) {
10145       auto *Sel = cast<SelectInst>(I);
10146       auto *Cmp = dyn_cast<Instruction>(Sel->getCondition());
10147       return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB;
10148     }
10149     return I->getParent() == BB;
10150   }
10151 
10152   /// Expected number of uses for reduction operations/reduced values.
10153   static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) {
10154     if (IsCmpSelMinMax) {
10155       // SelectInst must be used twice while the condition op must have single
10156       // use only.
10157       if (auto *Sel = dyn_cast<SelectInst>(I))
10158         return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse();
10159       return I->hasNUses(2);
10160     }
10161 
10162     // Arithmetic reduction operation must be used once only.
10163     return I->hasOneUse();
10164   }
10165 
10166   /// Initializes the list of reduction operations.
10167   void initReductionOps(Instruction *I) {
10168     if (isCmpSelMinMax(I))
10169       ReductionOps.assign(2, ReductionOpsType());
10170     else
10171       ReductionOps.assign(1, ReductionOpsType());
10172   }
10173 
10174   /// Add all reduction operations for the reduction instruction \p I.
10175   void addReductionOps(Instruction *I) {
10176     if (isCmpSelMinMax(I)) {
10177       ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
10178       ReductionOps[1].emplace_back(I);
10179     } else {
10180       ReductionOps[0].emplace_back(I);
10181     }
10182   }
10183 
10184   static Value *getLHS(RecurKind Kind, Instruction *I) {
10185     if (Kind == RecurKind::None)
10186       return nullptr;
10187     return I->getOperand(getFirstOperandIndex(I));
10188   }
10189   static Value *getRHS(RecurKind Kind, Instruction *I) {
10190     if (Kind == RecurKind::None)
10191       return nullptr;
10192     return I->getOperand(getFirstOperandIndex(I) + 1);
10193   }
10194 
10195 public:
10196   HorizontalReduction() = default;
10197 
10198   /// Try to find a reduction tree.
10199   bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst,
10200                                  ScalarEvolution &SE, const DataLayout &DL,
10201                                  const TargetLibraryInfo &TLI) {
10202     assert((!Phi || is_contained(Phi->operands(), Inst)) &&
10203            "Phi needs to use the binary operator");
10204     assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) ||
10205             isa<IntrinsicInst>(Inst)) &&
10206            "Expected binop, select, or intrinsic for reduction matching");
10207     RdxKind = getRdxKind(Inst);
10208 
10209     // We could have a initial reductions that is not an add.
10210     //  r *= v1 + v2 + v3 + v4
10211     // In such a case start looking for a tree rooted in the first '+'.
10212     if (Phi) {
10213       if (getLHS(RdxKind, Inst) == Phi) {
10214         Phi = nullptr;
10215         Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst));
10216         if (!Inst)
10217           return false;
10218         RdxKind = getRdxKind(Inst);
10219       } else if (getRHS(RdxKind, Inst) == Phi) {
10220         Phi = nullptr;
10221         Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst));
10222         if (!Inst)
10223           return false;
10224         RdxKind = getRdxKind(Inst);
10225       }
10226     }
10227 
10228     if (!isVectorizable(RdxKind, Inst))
10229       return false;
10230 
10231     // Analyze "regular" integer/FP types for reductions - no target-specific
10232     // types or pointers.
10233     Type *Ty = Inst->getType();
10234     if (!isValidElementType(Ty) || Ty->isPointerTy())
10235       return false;
10236 
10237     // Though the ultimate reduction may have multiple uses, its condition must
10238     // have only single use.
10239     if (auto *Sel = dyn_cast<SelectInst>(Inst))
10240       if (!Sel->getCondition()->hasOneUse())
10241         return false;
10242 
10243     ReductionRoot = Inst;
10244 
10245     // Iterate through all the operands of the possible reduction tree and
10246     // gather all the reduced values, sorting them by their value id.
10247     BasicBlock *BB = Inst->getParent();
10248     bool IsCmpSelMinMax = isCmpSelMinMax(Inst);
10249     SmallVector<Instruction *> Worklist(1, Inst);
10250     // Checks if the operands of the \p TreeN instruction are also reduction
10251     // operations or should be treated as reduced values or an extra argument,
10252     // which is not part of the reduction.
10253     auto &&CheckOperands = [this, IsCmpSelMinMax,
10254                             BB](Instruction *TreeN,
10255                                 SmallVectorImpl<Value *> &ExtraArgs,
10256                                 SmallVectorImpl<Value *> &PossibleReducedVals,
10257                                 SmallVectorImpl<Instruction *> &ReductionOps) {
10258       for (int I = getFirstOperandIndex(TreeN),
10259                End = getNumberOfOperands(TreeN);
10260            I < End; ++I) {
10261         Value *EdgeVal = getRdxOperand(TreeN, I);
10262         ReducedValsToOps[EdgeVal].push_back(TreeN);
10263         auto *EdgeInst = dyn_cast<Instruction>(EdgeVal);
10264         // Edge has wrong parent - mark as an extra argument.
10265         if (EdgeInst && !isVectorLikeInstWithConstOps(EdgeInst) &&
10266             !hasSameParent(EdgeInst, BB)) {
10267           ExtraArgs.push_back(EdgeVal);
10268           continue;
10269         }
10270         // If the edge is not an instruction, or it is different from the main
10271         // reduction opcode or has too many uses - possible reduced value.
10272         if (!EdgeInst || getRdxKind(EdgeInst) != RdxKind ||
10273             IsCmpSelMinMax != isCmpSelMinMax(EdgeInst) ||
10274             !hasRequiredNumberOfUses(IsCmpSelMinMax, EdgeInst) ||
10275             !isVectorizable(getRdxKind(EdgeInst), EdgeInst)) {
10276           PossibleReducedVals.push_back(EdgeVal);
10277           continue;
10278         }
10279         ReductionOps.push_back(EdgeInst);
10280       }
10281     };
10282     // Try to regroup reduced values so that it gets more profitable to try to
10283     // reduce them. Values are grouped by their value ids, instructions - by
10284     // instruction op id and/or alternate op id, plus do extra analysis for
10285     // loads (grouping them by the distabce between pointers) and cmp
10286     // instructions (grouping them by the predicate).
10287     MapVector<size_t, MapVector<size_t, MapVector<Value *, unsigned>>>
10288         PossibleReducedVals;
10289     initReductionOps(Inst);
10290     while (!Worklist.empty()) {
10291       Instruction *TreeN = Worklist.pop_back_val();
10292       SmallVector<Value *> Args;
10293       SmallVector<Value *> PossibleRedVals;
10294       SmallVector<Instruction *> PossibleReductionOps;
10295       CheckOperands(TreeN, Args, PossibleRedVals, PossibleReductionOps);
10296       // If too many extra args - mark the instruction itself as a reduction
10297       // value, not a reduction operation.
10298       if (Args.size() < 2) {
10299         addReductionOps(TreeN);
10300         // Add extra args.
10301         if (!Args.empty()) {
10302           assert(Args.size() == 1 && "Expected only single argument.");
10303           ExtraArgs[TreeN] = Args.front();
10304         }
10305         // Add reduction values. The values are sorted for better vectorization
10306         // results.
10307         for (Value *V : PossibleRedVals) {
10308           size_t Key, Idx;
10309           std::tie(Key, Idx) = generateKeySubkey(
10310               V, &TLI,
10311               [&PossibleReducedVals, &DL, &SE](size_t Key, LoadInst *LI) {
10312                 for (const auto &LoadData : PossibleReducedVals[Key]) {
10313                   auto *RLI = cast<LoadInst>(LoadData.second.front().first);
10314                   if (getPointersDiff(RLI->getType(), RLI->getPointerOperand(),
10315                                       LI->getType(), LI->getPointerOperand(),
10316                                       DL, SE, /*StrictCheck=*/true))
10317                     return hash_value(RLI->getPointerOperand());
10318                 }
10319                 return hash_value(LI->getPointerOperand());
10320               },
10321               /*AllowAlternate=*/false);
10322           ++PossibleReducedVals[Key][Idx]
10323                 .insert(std::make_pair(V, 0))
10324                 .first->second;
10325         }
10326         Worklist.append(PossibleReductionOps.rbegin(),
10327                         PossibleReductionOps.rend());
10328       } else {
10329         size_t Key, Idx;
10330         std::tie(Key, Idx) = generateKeySubkey(
10331             TreeN, &TLI,
10332             [&PossibleReducedVals, &DL, &SE](size_t Key, LoadInst *LI) {
10333               for (const auto &LoadData : PossibleReducedVals[Key]) {
10334                 auto *RLI = cast<LoadInst>(LoadData.second.front().first);
10335                 if (getPointersDiff(RLI->getType(), RLI->getPointerOperand(),
10336                                     LI->getType(), LI->getPointerOperand(), DL,
10337                                     SE, /*StrictCheck=*/true))
10338                   return hash_value(RLI->getPointerOperand());
10339               }
10340               return hash_value(LI->getPointerOperand());
10341             },
10342             /*AllowAlternate=*/false);
10343         ++PossibleReducedVals[Key][Idx]
10344               .insert(std::make_pair(TreeN, 0))
10345               .first->second;
10346       }
10347     }
10348     auto PossibleReducedValsVect = PossibleReducedVals.takeVector();
10349     // Sort values by the total number of values kinds to start the reduction
10350     // from the longest possible reduced values sequences.
10351     for (auto &PossibleReducedVals : PossibleReducedValsVect) {
10352       auto PossibleRedVals = PossibleReducedVals.second.takeVector();
10353       SmallVector<SmallVector<Value *>> PossibleRedValsVect;
10354       for (auto It = PossibleRedVals.begin(), E = PossibleRedVals.end();
10355            It != E; ++It) {
10356         PossibleRedValsVect.emplace_back();
10357         auto RedValsVect = It->second.takeVector();
10358         stable_sort(RedValsVect, [](const auto &P1, const auto &P2) {
10359           return P1.second < P2.second;
10360         });
10361         for (const std::pair<Value *, unsigned> &Data : RedValsVect)
10362           PossibleRedValsVect.back().append(Data.second, Data.first);
10363       }
10364       stable_sort(PossibleRedValsVect, [](const auto &P1, const auto &P2) {
10365         return P1.size() > P2.size();
10366       });
10367       ReducedVals.emplace_back();
10368       for (ArrayRef<Value *> Data : PossibleRedValsVect)
10369         ReducedVals.back().append(Data.rbegin(), Data.rend());
10370     }
10371     // Sort the reduced values by number of same/alternate opcode and/or pointer
10372     // operand.
10373     stable_sort(ReducedVals, [](ArrayRef<Value *> P1, ArrayRef<Value *> P2) {
10374       return P1.size() > P2.size();
10375     });
10376     return true;
10377   }
10378 
10379   /// Attempt to vectorize the tree found by matchAssociativeReduction.
10380   Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
10381     constexpr int ReductionLimit = 4;
10382     // If there are a sufficient number of reduction values, reduce
10383     // to a nearby power-of-2. We can safely generate oversized
10384     // vectors and rely on the backend to split them to legal sizes.
10385     unsigned NumReducedVals = std::accumulate(
10386         ReducedVals.begin(), ReducedVals.end(), 0,
10387         [](int Num, ArrayRef<Value *> Vals) { return Num + Vals.size(); });
10388     if (NumReducedVals < ReductionLimit)
10389       return nullptr;
10390 
10391     IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
10392 
10393     // Track the reduced values in case if they are replaced by extractelement
10394     // because of the vectorization.
10395     DenseMap<Value *, WeakTrackingVH> TrackedVals;
10396     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
10397     // The same extra argument may be used several times, so log each attempt
10398     // to use it.
10399     for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) {
10400       assert(Pair.first && "DebugLoc must be set.");
10401       ExternallyUsedValues[Pair.second].push_back(Pair.first);
10402       TrackedVals.try_emplace(Pair.second, Pair.second);
10403     }
10404 
10405     // The compare instruction of a min/max is the insertion point for new
10406     // instructions and may be replaced with a new compare instruction.
10407     auto &&GetCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
10408       assert(isa<SelectInst>(RdxRootInst) &&
10409              "Expected min/max reduction to have select root instruction");
10410       Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
10411       assert(isa<Instruction>(ScalarCond) &&
10412              "Expected min/max reduction to have compare condition");
10413       return cast<Instruction>(ScalarCond);
10414     };
10415 
10416     // The reduction root is used as the insertion point for new instructions,
10417     // so set it as externally used to prevent it from being deleted.
10418     ExternallyUsedValues[ReductionRoot];
10419     SmallVector<Value *> IgnoreList;
10420     for (ReductionOpsType &RdxOps : ReductionOps)
10421       for (Value *RdxOp : RdxOps) {
10422         if (!RdxOp)
10423           continue;
10424         IgnoreList.push_back(RdxOp);
10425       }
10426     bool IsCmpSelMinMax = isCmpSelMinMax(cast<Instruction>(ReductionRoot));
10427 
10428     // Need to track reduced vals, they may be changed during vectorization of
10429     // subvectors.
10430     for (ArrayRef<Value *> Candidates : ReducedVals)
10431       for (Value *V : Candidates)
10432         TrackedVals.try_emplace(V, V);
10433 
10434     DenseMap<Value *, unsigned> VectorizedVals;
10435     Value *VectorizedTree = nullptr;
10436     bool CheckForReusedReductionOps = false;
10437     // Try to vectorize elements based on their type.
10438     for (unsigned I = 0, E = ReducedVals.size(); I < E; ++I) {
10439       ArrayRef<Value *> OrigReducedVals = ReducedVals[I];
10440       InstructionsState S = getSameOpcode(OrigReducedVals);
10441       SmallVector<Value *> Candidates;
10442       DenseMap<Value *, Value *> TrackedToOrig;
10443       for (unsigned Cnt = 0, Sz = OrigReducedVals.size(); Cnt < Sz; ++Cnt) {
10444         Value *RdxVal = TrackedVals.find(OrigReducedVals[Cnt])->second;
10445         // Check if the reduction value was not overriden by the extractelement
10446         // instruction because of the vectorization and exclude it, if it is not
10447         // compatible with other values.
10448         if (auto *Inst = dyn_cast<Instruction>(RdxVal))
10449           if (isVectorLikeInstWithConstOps(Inst) &&
10450               (!S.getOpcode() || !S.isOpcodeOrAlt(Inst)))
10451             continue;
10452         Candidates.push_back(RdxVal);
10453         TrackedToOrig.try_emplace(RdxVal, OrigReducedVals[Cnt]);
10454       }
10455       bool ShuffledExtracts = false;
10456       // Try to handle shuffled extractelements.
10457       if (S.getOpcode() == Instruction::ExtractElement && !S.isAltShuffle() &&
10458           I + 1 < E) {
10459         InstructionsState NextS = getSameOpcode(ReducedVals[I + 1]);
10460         if (NextS.getOpcode() == Instruction::ExtractElement &&
10461             !NextS.isAltShuffle()) {
10462           SmallVector<Value *> CommonCandidates(Candidates);
10463           for (Value *RV : ReducedVals[I + 1]) {
10464             Value *RdxVal = TrackedVals.find(RV)->second;
10465             // Check if the reduction value was not overriden by the
10466             // extractelement instruction because of the vectorization and
10467             // exclude it, if it is not compatible with other values.
10468             if (auto *Inst = dyn_cast<Instruction>(RdxVal))
10469               if (!NextS.getOpcode() || !NextS.isOpcodeOrAlt(Inst))
10470                 continue;
10471             CommonCandidates.push_back(RdxVal);
10472             TrackedToOrig.try_emplace(RdxVal, RV);
10473           }
10474           SmallVector<int> Mask;
10475           if (isFixedVectorShuffle(CommonCandidates, Mask)) {
10476             ++I;
10477             Candidates.swap(CommonCandidates);
10478             ShuffledExtracts = true;
10479           }
10480         }
10481       }
10482       unsigned NumReducedVals = Candidates.size();
10483       if (NumReducedVals < ReductionLimit)
10484         continue;
10485 
10486       unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
10487       unsigned Start = 0;
10488       unsigned Pos = Start;
10489       // Restarts vectorization attempt with lower vector factor.
10490       unsigned PrevReduxWidth = ReduxWidth;
10491       bool CheckForReusedReductionOpsLocal = false;
10492       auto &&AdjustReducedVals = [&Pos, &Start, &ReduxWidth, NumReducedVals,
10493                                   &CheckForReusedReductionOpsLocal,
10494                                   &PrevReduxWidth, &V,
10495                                   &IgnoreList](bool IgnoreVL = false) {
10496         bool IsAnyRedOpGathered =
10497             !IgnoreVL && any_of(IgnoreList, [&V](Value *RedOp) {
10498               return V.isGathered(RedOp);
10499             });
10500         if (!CheckForReusedReductionOpsLocal && PrevReduxWidth == ReduxWidth) {
10501           // Check if any of the reduction ops are gathered. If so, worth
10502           // trying again with less number of reduction ops.
10503           CheckForReusedReductionOpsLocal |= IsAnyRedOpGathered;
10504         }
10505         ++Pos;
10506         if (Pos < NumReducedVals - ReduxWidth + 1)
10507           return IsAnyRedOpGathered;
10508         Pos = Start;
10509         ReduxWidth /= 2;
10510         return IsAnyRedOpGathered;
10511       };
10512       while (Pos < NumReducedVals - ReduxWidth + 1 &&
10513              ReduxWidth >= ReductionLimit) {
10514         // Dependency in tree of the reduction ops - drop this attempt, try
10515         // later.
10516         if (CheckForReusedReductionOpsLocal && PrevReduxWidth != ReduxWidth &&
10517             Start == 0) {
10518           CheckForReusedReductionOps = true;
10519           break;
10520         }
10521         PrevReduxWidth = ReduxWidth;
10522         ArrayRef<Value *> VL(std::next(Candidates.begin(), Pos), ReduxWidth);
10523         // Beeing analyzed already - skip.
10524         if (V.areAnalyzedReductionVals(VL)) {
10525           (void)AdjustReducedVals(/*IgnoreVL=*/true);
10526           continue;
10527         }
10528         // Early exit if any of the reduction values were deleted during
10529         // previous vectorization attempts.
10530         if (any_of(VL, [&V](Value *RedVal) {
10531               auto *RedValI = dyn_cast<Instruction>(RedVal);
10532               if (!RedValI)
10533                 return false;
10534               return V.isDeleted(RedValI);
10535             }))
10536           break;
10537         V.buildTree(VL, IgnoreList);
10538         if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true)) {
10539           if (!AdjustReducedVals())
10540             V.analyzedReductionVals(VL);
10541           continue;
10542         }
10543         if (V.isLoadCombineReductionCandidate(RdxKind)) {
10544           if (!AdjustReducedVals())
10545             V.analyzedReductionVals(VL);
10546           continue;
10547         }
10548         V.reorderTopToBottom();
10549         // No need to reorder the root node at all.
10550         V.reorderBottomToTop(/*IgnoreReorder=*/true);
10551         // Keep extracted other reduction values, if they are used in the
10552         // vectorization trees.
10553         BoUpSLP::ExtraValueToDebugLocsMap LocalExternallyUsedValues(
10554             ExternallyUsedValues);
10555         for (unsigned Cnt = 0, Sz = ReducedVals.size(); Cnt < Sz; ++Cnt) {
10556           if (Cnt == I || (ShuffledExtracts && Cnt == I - 1))
10557             continue;
10558           for_each(ReducedVals[Cnt],
10559                    [&LocalExternallyUsedValues, &TrackedVals](Value *V) {
10560                      if (isa<Instruction>(V))
10561                        LocalExternallyUsedValues[TrackedVals[V]];
10562                    });
10563         }
10564         for (unsigned Cnt = 0; Cnt < NumReducedVals; ++Cnt) {
10565           if (Cnt >= Pos && Cnt < Pos + ReduxWidth)
10566             continue;
10567           unsigned NumOps = VectorizedVals.lookup(Candidates[Cnt]) +
10568                             std::count(VL.begin(), VL.end(), Candidates[Cnt]);
10569           if (NumOps != ReducedValsToOps.find(Candidates[Cnt])->second.size())
10570             LocalExternallyUsedValues[Candidates[Cnt]];
10571         }
10572         V.buildExternalUses(LocalExternallyUsedValues);
10573 
10574         V.computeMinimumValueSizes();
10575 
10576         // Intersect the fast-math-flags from all reduction operations.
10577         FastMathFlags RdxFMF;
10578         RdxFMF.set();
10579         for (Value *U : IgnoreList)
10580           if (auto *FPMO = dyn_cast<FPMathOperator>(U))
10581             RdxFMF &= FPMO->getFastMathFlags();
10582         // Estimate cost.
10583         InstructionCost TreeCost = V.getTreeCost(VL);
10584         InstructionCost ReductionCost =
10585             getReductionCost(TTI, VL, ReduxWidth, RdxFMF);
10586         InstructionCost Cost = TreeCost + ReductionCost;
10587         if (!Cost.isValid()) {
10588           LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n");
10589           return nullptr;
10590         }
10591         if (Cost >= -SLPCostThreshold) {
10592           V.getORE()->emit([&]() {
10593             return OptimizationRemarkMissed(
10594                        SV_NAME, "HorSLPNotBeneficial",
10595                        ReducedValsToOps.find(VL[0])->second.front())
10596                    << "Vectorizing horizontal reduction is possible"
10597                    << "but not beneficial with cost " << ore::NV("Cost", Cost)
10598                    << " and threshold "
10599                    << ore::NV("Threshold", -SLPCostThreshold);
10600           });
10601           if (!AdjustReducedVals())
10602             V.analyzedReductionVals(VL);
10603           continue;
10604         }
10605 
10606         LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
10607                           << Cost << ". (HorRdx)\n");
10608         V.getORE()->emit([&]() {
10609           return OptimizationRemark(
10610                      SV_NAME, "VectorizedHorizontalReduction",
10611                      ReducedValsToOps.find(VL[0])->second.front())
10612                  << "Vectorized horizontal reduction with cost "
10613                  << ore::NV("Cost", Cost) << " and with tree size "
10614                  << ore::NV("TreeSize", V.getTreeSize());
10615         });
10616 
10617         Builder.setFastMathFlags(RdxFMF);
10618 
10619         // Vectorize a tree.
10620         Value *VectorizedRoot = V.vectorizeTree(LocalExternallyUsedValues);
10621 
10622         // Emit a reduction. If the root is a select (min/max idiom), the insert
10623         // point is the compare condition of that select.
10624         Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
10625         if (IsCmpSelMinMax)
10626           Builder.SetInsertPoint(GetCmpForMinMaxReduction(RdxRootInst));
10627         else
10628           Builder.SetInsertPoint(RdxRootInst);
10629 
10630         // To prevent poison from leaking across what used to be sequential,
10631         // safe, scalar boolean logic operations, the reduction operand must be
10632         // frozen.
10633         if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst))
10634           VectorizedRoot = Builder.CreateFreeze(VectorizedRoot);
10635 
10636         Value *ReducedSubTree =
10637             emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
10638 
10639         if (!VectorizedTree) {
10640           // Initialize the final value in the reduction.
10641           VectorizedTree = ReducedSubTree;
10642         } else {
10643           // Update the final value in the reduction.
10644           Builder.SetCurrentDebugLocation(
10645               cast<Instruction>(ReductionOps.front().front())->getDebugLoc());
10646           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
10647                                     ReducedSubTree, "op.rdx", ReductionOps);
10648         }
10649         // Count vectorized reduced values to exclude them from final reduction.
10650         for (Value *V : VL)
10651           ++VectorizedVals.try_emplace(TrackedToOrig.find(V)->second, 0)
10652                 .first->getSecond();
10653         Pos += ReduxWidth;
10654         Start = Pos;
10655         ReduxWidth = PowerOf2Floor(NumReducedVals - Pos);
10656       }
10657     }
10658     if (VectorizedTree) {
10659       // Finish the reduction.
10660       // Need to add extra arguments and not vectorized possible reduction
10661       // values.
10662       // Try to avoid dependencies between the scalar remainders after
10663       // reductions.
10664       auto &&FinalGen =
10665           [this, &Builder,
10666            &TrackedVals](ArrayRef<std::pair<Instruction *, Value *>> InstVals) {
10667             unsigned Sz = InstVals.size();
10668             SmallVector<std::pair<Instruction *, Value *>> ExtraReds(Sz / 2 +
10669                                                                      Sz % 2);
10670             for (unsigned I = 0, E = (Sz / 2) * 2; I < E; I += 2) {
10671               Instruction *RedOp = InstVals[I + 1].first;
10672               Builder.SetCurrentDebugLocation(RedOp->getDebugLoc());
10673               ReductionOpsListType Ops;
10674               if (auto *Sel = dyn_cast<SelectInst>(RedOp))
10675                 Ops.emplace_back().push_back(Sel->getCondition());
10676               Ops.emplace_back().push_back(RedOp);
10677               Value *RdxVal1 = InstVals[I].second;
10678               Value *StableRdxVal1 = RdxVal1;
10679               auto It1 = TrackedVals.find(RdxVal1);
10680               if (It1 != TrackedVals.end())
10681                 StableRdxVal1 = It1->second;
10682               Value *RdxVal2 = InstVals[I + 1].second;
10683               Value *StableRdxVal2 = RdxVal2;
10684               auto It2 = TrackedVals.find(RdxVal2);
10685               if (It2 != TrackedVals.end())
10686                 StableRdxVal2 = It2->second;
10687               Value *ExtraRed = createOp(Builder, RdxKind, StableRdxVal1,
10688                                          StableRdxVal2, "op.rdx", Ops);
10689               ExtraReds[I / 2] = std::make_pair(InstVals[I].first, ExtraRed);
10690             }
10691             if (Sz % 2 == 1)
10692               ExtraReds[Sz / 2] = InstVals.back();
10693             return ExtraReds;
10694           };
10695       SmallVector<std::pair<Instruction *, Value *>> ExtraReductions;
10696       SmallPtrSet<Value *, 8> Visited;
10697       for (ArrayRef<Value *> Candidates : ReducedVals) {
10698         for (Value *RdxVal : Candidates) {
10699           if (!Visited.insert(RdxVal).second)
10700             continue;
10701           unsigned NumOps = VectorizedVals.lookup(RdxVal);
10702           for (Instruction *RedOp :
10703                makeArrayRef(ReducedValsToOps.find(RdxVal)->second)
10704                    .drop_back(NumOps))
10705             ExtraReductions.emplace_back(RedOp, RdxVal);
10706         }
10707       }
10708       for (auto &Pair : ExternallyUsedValues) {
10709         // Add each externally used value to the final reduction.
10710         for (auto *I : Pair.second)
10711           ExtraReductions.emplace_back(I, Pair.first);
10712       }
10713       // Iterate through all not-vectorized reduction values/extra arguments.
10714       while (ExtraReductions.size() > 1) {
10715         SmallVector<std::pair<Instruction *, Value *>> NewReds =
10716             FinalGen(ExtraReductions);
10717         ExtraReductions.swap(NewReds);
10718       }
10719       // Final reduction.
10720       if (ExtraReductions.size() == 1) {
10721         Instruction *RedOp = ExtraReductions.back().first;
10722         Builder.SetCurrentDebugLocation(RedOp->getDebugLoc());
10723         ReductionOpsListType Ops;
10724         if (auto *Sel = dyn_cast<SelectInst>(RedOp))
10725           Ops.emplace_back().push_back(Sel->getCondition());
10726         Ops.emplace_back().push_back(RedOp);
10727         Value *RdxVal = ExtraReductions.back().second;
10728         Value *StableRdxVal = RdxVal;
10729         auto It = TrackedVals.find(RdxVal);
10730         if (It != TrackedVals.end())
10731           StableRdxVal = It->second;
10732         VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
10733                                   StableRdxVal, "op.rdx", Ops);
10734       }
10735 
10736       ReductionRoot->replaceAllUsesWith(VectorizedTree);
10737 
10738       // The original scalar reduction is expected to have no remaining
10739       // uses outside the reduction tree itself.  Assert that we got this
10740       // correct, replace internal uses with undef, and mark for eventual
10741       // deletion.
10742 #ifndef NDEBUG
10743       SmallSet<Value *, 4> IgnoreSet;
10744       for (ArrayRef<Value *> RdxOps : ReductionOps)
10745         IgnoreSet.insert(RdxOps.begin(), RdxOps.end());
10746 #endif
10747       for (ArrayRef<Value *> RdxOps : ReductionOps) {
10748         for (Value *Ignore : RdxOps) {
10749           if (!Ignore)
10750             continue;
10751 #ifndef NDEBUG
10752           for (auto *U : Ignore->users()) {
10753             assert(IgnoreSet.count(U) &&
10754                    "All users must be either in the reduction ops list.");
10755           }
10756 #endif
10757           if (!Ignore->use_empty()) {
10758             Value *Undef = UndefValue::get(Ignore->getType());
10759             Ignore->replaceAllUsesWith(Undef);
10760           }
10761           V.eraseInstruction(cast<Instruction>(Ignore));
10762         }
10763       }
10764     } else if (!CheckForReusedReductionOps) {
10765       for (ReductionOpsType &RdxOps : ReductionOps)
10766         for (Value *RdxOp : RdxOps)
10767           V.analyzedReductionRoot(cast<Instruction>(RdxOp));
10768     }
10769     return VectorizedTree;
10770   }
10771 
10772 private:
10773   /// Calculate the cost of a reduction.
10774   InstructionCost getReductionCost(TargetTransformInfo *TTI,
10775                                    ArrayRef<Value *> ReducedVals,
10776                                    unsigned ReduxWidth, FastMathFlags FMF) {
10777     TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
10778     Value *FirstReducedVal = ReducedVals.front();
10779     Type *ScalarTy = FirstReducedVal->getType();
10780     FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth);
10781     InstructionCost VectorCost = 0, ScalarCost;
10782     // If all of the reduced values are constant, the vector cost is 0, since
10783     // the reduction value can be calculated at the compile time.
10784     bool AllConsts = all_of(ReducedVals, isConstant);
10785     switch (RdxKind) {
10786     case RecurKind::Add:
10787     case RecurKind::Mul:
10788     case RecurKind::Or:
10789     case RecurKind::And:
10790     case RecurKind::Xor:
10791     case RecurKind::FAdd:
10792     case RecurKind::FMul: {
10793       unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind);
10794       if (!AllConsts)
10795         VectorCost =
10796             TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind);
10797       ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind);
10798       break;
10799     }
10800     case RecurKind::FMax:
10801     case RecurKind::FMin: {
10802       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
10803       if (!AllConsts) {
10804         auto *VecCondTy =
10805             cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
10806         VectorCost =
10807             TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
10808                                         /*IsUnsigned=*/false, CostKind);
10809       }
10810       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
10811       ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy,
10812                                            SclCondTy, RdxPred, CostKind) +
10813                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
10814                                            SclCondTy, RdxPred, CostKind);
10815       break;
10816     }
10817     case RecurKind::SMax:
10818     case RecurKind::SMin:
10819     case RecurKind::UMax:
10820     case RecurKind::UMin: {
10821       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
10822       if (!AllConsts) {
10823         auto *VecCondTy =
10824             cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
10825         bool IsUnsigned =
10826             RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin;
10827         VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
10828                                                  IsUnsigned, CostKind);
10829       }
10830       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
10831       ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
10832                                            SclCondTy, RdxPred, CostKind) +
10833                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
10834                                            SclCondTy, RdxPred, CostKind);
10835       break;
10836     }
10837     default:
10838       llvm_unreachable("Expected arithmetic or min/max reduction operation");
10839     }
10840 
10841     // Scalar cost is repeated for N-1 elements.
10842     ScalarCost *= (ReduxWidth - 1);
10843     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost
10844                       << " for reduction that starts with " << *FirstReducedVal
10845                       << " (It is a splitting reduction)\n");
10846     return VectorCost - ScalarCost;
10847   }
10848 
10849   /// Emit a horizontal reduction of the vectorized value.
10850   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
10851                        unsigned ReduxWidth, const TargetTransformInfo *TTI) {
10852     assert(VectorizedValue && "Need to have a vectorized tree node");
10853     assert(isPowerOf2_32(ReduxWidth) &&
10854            "We only handle power-of-two reductions for now");
10855     assert(RdxKind != RecurKind::FMulAdd &&
10856            "A call to the llvm.fmuladd intrinsic is not handled yet");
10857 
10858     ++NumVectorInstructions;
10859     return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind);
10860   }
10861 };
10862 
10863 } // end anonymous namespace
10864 
10865 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) {
10866   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
10867     return cast<FixedVectorType>(IE->getType())->getNumElements();
10868 
10869   unsigned AggregateSize = 1;
10870   auto *IV = cast<InsertValueInst>(InsertInst);
10871   Type *CurrentType = IV->getType();
10872   do {
10873     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
10874       for (auto *Elt : ST->elements())
10875         if (Elt != ST->getElementType(0)) // check homogeneity
10876           return None;
10877       AggregateSize *= ST->getNumElements();
10878       CurrentType = ST->getElementType(0);
10879     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
10880       AggregateSize *= AT->getNumElements();
10881       CurrentType = AT->getElementType();
10882     } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
10883       AggregateSize *= VT->getNumElements();
10884       return AggregateSize;
10885     } else if (CurrentType->isSingleValueType()) {
10886       return AggregateSize;
10887     } else {
10888       return None;
10889     }
10890   } while (true);
10891 }
10892 
10893 static void findBuildAggregate_rec(Instruction *LastInsertInst,
10894                                    TargetTransformInfo *TTI,
10895                                    SmallVectorImpl<Value *> &BuildVectorOpds,
10896                                    SmallVectorImpl<Value *> &InsertElts,
10897                                    unsigned OperandOffset) {
10898   do {
10899     Value *InsertedOperand = LastInsertInst->getOperand(1);
10900     Optional<unsigned> OperandIndex =
10901         getInsertIndex(LastInsertInst, OperandOffset);
10902     if (!OperandIndex)
10903       return;
10904     if (isa<InsertElementInst>(InsertedOperand) ||
10905         isa<InsertValueInst>(InsertedOperand)) {
10906       findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI,
10907                              BuildVectorOpds, InsertElts, *OperandIndex);
10908 
10909     } else {
10910       BuildVectorOpds[*OperandIndex] = InsertedOperand;
10911       InsertElts[*OperandIndex] = LastInsertInst;
10912     }
10913     LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0));
10914   } while (LastInsertInst != nullptr &&
10915            (isa<InsertValueInst>(LastInsertInst) ||
10916             isa<InsertElementInst>(LastInsertInst)) &&
10917            LastInsertInst->hasOneUse());
10918 }
10919 
10920 /// Recognize construction of vectors like
10921 ///  %ra = insertelement <4 x float> poison, float %s0, i32 0
10922 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
10923 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
10924 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
10925 ///  starting from the last insertelement or insertvalue instruction.
10926 ///
10927 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>},
10928 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
10929 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
10930 ///
10931 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
10932 ///
10933 /// \return true if it matches.
10934 static bool findBuildAggregate(Instruction *LastInsertInst,
10935                                TargetTransformInfo *TTI,
10936                                SmallVectorImpl<Value *> &BuildVectorOpds,
10937                                SmallVectorImpl<Value *> &InsertElts) {
10938 
10939   assert((isa<InsertElementInst>(LastInsertInst) ||
10940           isa<InsertValueInst>(LastInsertInst)) &&
10941          "Expected insertelement or insertvalue instruction!");
10942 
10943   assert((BuildVectorOpds.empty() && InsertElts.empty()) &&
10944          "Expected empty result vectors!");
10945 
10946   Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst);
10947   if (!AggregateSize)
10948     return false;
10949   BuildVectorOpds.resize(*AggregateSize);
10950   InsertElts.resize(*AggregateSize);
10951 
10952   findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts, 0);
10953   llvm::erase_value(BuildVectorOpds, nullptr);
10954   llvm::erase_value(InsertElts, nullptr);
10955   if (BuildVectorOpds.size() >= 2)
10956     return true;
10957 
10958   return false;
10959 }
10960 
10961 /// Try and get a reduction value from a phi node.
10962 ///
10963 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
10964 /// if they come from either \p ParentBB or a containing loop latch.
10965 ///
10966 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
10967 /// if not possible.
10968 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
10969                                 BasicBlock *ParentBB, LoopInfo *LI) {
10970   // There are situations where the reduction value is not dominated by the
10971   // reduction phi. Vectorizing such cases has been reported to cause
10972   // miscompiles. See PR25787.
10973   auto DominatedReduxValue = [&](Value *R) {
10974     return isa<Instruction>(R) &&
10975            DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
10976   };
10977 
10978   Value *Rdx = nullptr;
10979 
10980   // Return the incoming value if it comes from the same BB as the phi node.
10981   if (P->getIncomingBlock(0) == ParentBB) {
10982     Rdx = P->getIncomingValue(0);
10983   } else if (P->getIncomingBlock(1) == ParentBB) {
10984     Rdx = P->getIncomingValue(1);
10985   }
10986 
10987   if (Rdx && DominatedReduxValue(Rdx))
10988     return Rdx;
10989 
10990   // Otherwise, check whether we have a loop latch to look at.
10991   Loop *BBL = LI->getLoopFor(ParentBB);
10992   if (!BBL)
10993     return nullptr;
10994   BasicBlock *BBLatch = BBL->getLoopLatch();
10995   if (!BBLatch)
10996     return nullptr;
10997 
10998   // There is a loop latch, return the incoming value if it comes from
10999   // that. This reduction pattern occasionally turns up.
11000   if (P->getIncomingBlock(0) == BBLatch) {
11001     Rdx = P->getIncomingValue(0);
11002   } else if (P->getIncomingBlock(1) == BBLatch) {
11003     Rdx = P->getIncomingValue(1);
11004   }
11005 
11006   if (Rdx && DominatedReduxValue(Rdx))
11007     return Rdx;
11008 
11009   return nullptr;
11010 }
11011 
11012 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) {
11013   if (match(I, m_BinOp(m_Value(V0), m_Value(V1))))
11014     return true;
11015   if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1))))
11016     return true;
11017   if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1))))
11018     return true;
11019   if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1))))
11020     return true;
11021   if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1))))
11022     return true;
11023   if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1))))
11024     return true;
11025   if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1))))
11026     return true;
11027   return false;
11028 }
11029 
11030 /// Attempt to reduce a horizontal reduction.
11031 /// If it is legal to match a horizontal reduction feeding the phi node \a P
11032 /// with reduction operators \a Root (or one of its operands) in a basic block
11033 /// \a BB, then check if it can be done. If horizontal reduction is not found
11034 /// and root instruction is a binary operation, vectorization of the operands is
11035 /// attempted.
11036 /// \returns true if a horizontal reduction was matched and reduced or operands
11037 /// of one of the binary instruction were vectorized.
11038 /// \returns false if a horizontal reduction was not matched (or not possible)
11039 /// or no vectorization of any binary operation feeding \a Root instruction was
11040 /// performed.
11041 static bool tryToVectorizeHorReductionOrInstOperands(
11042     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
11043     TargetTransformInfo *TTI, ScalarEvolution &SE, const DataLayout &DL,
11044     const TargetLibraryInfo &TLI,
11045     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
11046   if (!ShouldVectorizeHor)
11047     return false;
11048 
11049   if (!Root)
11050     return false;
11051 
11052   if (Root->getParent() != BB || isa<PHINode>(Root))
11053     return false;
11054   // Start analysis starting from Root instruction. If horizontal reduction is
11055   // found, try to vectorize it. If it is not a horizontal reduction or
11056   // vectorization is not possible or not effective, and currently analyzed
11057   // instruction is a binary operation, try to vectorize the operands, using
11058   // pre-order DFS traversal order. If the operands were not vectorized, repeat
11059   // the same procedure considering each operand as a possible root of the
11060   // horizontal reduction.
11061   // Interrupt the process if the Root instruction itself was vectorized or all
11062   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
11063   // Skip the analysis of CmpInsts. Compiler implements postanalysis of the
11064   // CmpInsts so we can skip extra attempts in
11065   // tryToVectorizeHorReductionOrInstOperands and save compile time.
11066   std::queue<std::pair<Instruction *, unsigned>> Stack;
11067   Stack.emplace(Root, 0);
11068   SmallPtrSet<Value *, 8> VisitedInstrs;
11069   SmallVector<WeakTrackingVH> PostponedInsts;
11070   bool Res = false;
11071   auto &&TryToReduce = [TTI, &SE, &DL, &P, &R, &TLI](Instruction *Inst,
11072                                                      Value *&B0,
11073                                                      Value *&B1) -> Value * {
11074     if (R.isAnalyzedReductionRoot(Inst))
11075       return nullptr;
11076     bool IsBinop = matchRdxBop(Inst, B0, B1);
11077     bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value()));
11078     if (IsBinop || IsSelect) {
11079       HorizontalReduction HorRdx;
11080       if (HorRdx.matchAssociativeReduction(P, Inst, SE, DL, TLI))
11081         return HorRdx.tryToReduce(R, TTI);
11082     }
11083     return nullptr;
11084   };
11085   while (!Stack.empty()) {
11086     Instruction *Inst;
11087     unsigned Level;
11088     std::tie(Inst, Level) = Stack.front();
11089     Stack.pop();
11090     // Do not try to analyze instruction that has already been vectorized.
11091     // This may happen when we vectorize instruction operands on a previous
11092     // iteration while stack was populated before that happened.
11093     if (R.isDeleted(Inst))
11094       continue;
11095     Value *B0 = nullptr, *B1 = nullptr;
11096     if (Value *V = TryToReduce(Inst, B0, B1)) {
11097       Res = true;
11098       // Set P to nullptr to avoid re-analysis of phi node in
11099       // matchAssociativeReduction function unless this is the root node.
11100       P = nullptr;
11101       if (auto *I = dyn_cast<Instruction>(V)) {
11102         // Try to find another reduction.
11103         Stack.emplace(I, Level);
11104         continue;
11105       }
11106     } else {
11107       bool IsBinop = B0 && B1;
11108       if (P && IsBinop) {
11109         Inst = dyn_cast<Instruction>(B0);
11110         if (Inst == P)
11111           Inst = dyn_cast<Instruction>(B1);
11112         if (!Inst) {
11113           // Set P to nullptr to avoid re-analysis of phi node in
11114           // matchAssociativeReduction function unless this is the root node.
11115           P = nullptr;
11116           continue;
11117         }
11118       }
11119       // Set P to nullptr to avoid re-analysis of phi node in
11120       // matchAssociativeReduction function unless this is the root node.
11121       P = nullptr;
11122       // Do not try to vectorize CmpInst operands, this is done separately.
11123       // Final attempt for binop args vectorization should happen after the loop
11124       // to try to find reductions.
11125       if (!isa<CmpInst, InsertElementInst, InsertValueInst>(Inst))
11126         PostponedInsts.push_back(Inst);
11127     }
11128 
11129     // Try to vectorize operands.
11130     // Continue analysis for the instruction from the same basic block only to
11131     // save compile time.
11132     if (++Level < RecursionMaxDepth)
11133       for (auto *Op : Inst->operand_values())
11134         if (VisitedInstrs.insert(Op).second)
11135           if (auto *I = dyn_cast<Instruction>(Op))
11136             // Do not try to vectorize CmpInst operands,  this is done
11137             // separately.
11138             if (!isa<PHINode, CmpInst, InsertElementInst, InsertValueInst>(I) &&
11139                 !R.isDeleted(I) && I->getParent() == BB)
11140               Stack.emplace(I, Level);
11141   }
11142   // Try to vectorized binops where reductions were not found.
11143   for (Value *V : PostponedInsts)
11144     if (auto *Inst = dyn_cast<Instruction>(V))
11145       if (!R.isDeleted(Inst))
11146         Res |= Vectorize(Inst, R);
11147   return Res;
11148 }
11149 
11150 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
11151                                                  BasicBlock *BB, BoUpSLP &R,
11152                                                  TargetTransformInfo *TTI) {
11153   auto *I = dyn_cast_or_null<Instruction>(V);
11154   if (!I)
11155     return false;
11156 
11157   if (!isa<BinaryOperator>(I))
11158     P = nullptr;
11159   // Try to match and vectorize a horizontal reduction.
11160   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
11161     return tryToVectorize(I, R);
11162   };
11163   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI, *SE, *DL,
11164                                                   *TLI, ExtraVectorization);
11165 }
11166 
11167 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
11168                                                  BasicBlock *BB, BoUpSLP &R) {
11169   const DataLayout &DL = BB->getModule()->getDataLayout();
11170   if (!R.canMapToVector(IVI->getType(), DL))
11171     return false;
11172 
11173   SmallVector<Value *, 16> BuildVectorOpds;
11174   SmallVector<Value *, 16> BuildVectorInsts;
11175   if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts))
11176     return false;
11177 
11178   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
11179   // Aggregate value is unlikely to be processed in vector register.
11180   return tryToVectorizeList(BuildVectorOpds, R);
11181 }
11182 
11183 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
11184                                                    BasicBlock *BB, BoUpSLP &R) {
11185   SmallVector<Value *, 16> BuildVectorInsts;
11186   SmallVector<Value *, 16> BuildVectorOpds;
11187   SmallVector<int> Mask;
11188   if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
11189       (llvm::all_of(
11190            BuildVectorOpds,
11191            [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) &&
11192        isFixedVectorShuffle(BuildVectorOpds, Mask)))
11193     return false;
11194 
11195   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n");
11196   return tryToVectorizeList(BuildVectorInsts, R);
11197 }
11198 
11199 template <typename T>
11200 static bool
11201 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming,
11202                        function_ref<unsigned(T *)> Limit,
11203                        function_ref<bool(T *, T *)> Comparator,
11204                        function_ref<bool(T *, T *)> AreCompatible,
11205                        function_ref<bool(ArrayRef<T *>, bool)> TryToVectorizeHelper,
11206                        bool LimitForRegisterSize) {
11207   bool Changed = false;
11208   // Sort by type, parent, operands.
11209   stable_sort(Incoming, Comparator);
11210 
11211   // Try to vectorize elements base on their type.
11212   SmallVector<T *> Candidates;
11213   for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) {
11214     // Look for the next elements with the same type, parent and operand
11215     // kinds.
11216     auto *SameTypeIt = IncIt;
11217     while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt))
11218       ++SameTypeIt;
11219 
11220     // Try to vectorize them.
11221     unsigned NumElts = (SameTypeIt - IncIt);
11222     LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes ("
11223                       << NumElts << ")\n");
11224     // The vectorization is a 3-state attempt:
11225     // 1. Try to vectorize instructions with the same/alternate opcodes with the
11226     // size of maximal register at first.
11227     // 2. Try to vectorize remaining instructions with the same type, if
11228     // possible. This may result in the better vectorization results rather than
11229     // if we try just to vectorize instructions with the same/alternate opcodes.
11230     // 3. Final attempt to try to vectorize all instructions with the
11231     // same/alternate ops only, this may result in some extra final
11232     // vectorization.
11233     if (NumElts > 1 &&
11234         TryToVectorizeHelper(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) {
11235       // Success start over because instructions might have been changed.
11236       Changed = true;
11237     } else if (NumElts < Limit(*IncIt) &&
11238                (Candidates.empty() ||
11239                 Candidates.front()->getType() == (*IncIt)->getType())) {
11240       Candidates.append(IncIt, std::next(IncIt, NumElts));
11241     }
11242     // Final attempt to vectorize instructions with the same types.
11243     if (Candidates.size() > 1 &&
11244         (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) {
11245       if (TryToVectorizeHelper(Candidates, /*LimitForRegisterSize=*/false)) {
11246         // Success start over because instructions might have been changed.
11247         Changed = true;
11248       } else if (LimitForRegisterSize) {
11249         // Try to vectorize using small vectors.
11250         for (auto *It = Candidates.begin(), *End = Candidates.end();
11251              It != End;) {
11252           auto *SameTypeIt = It;
11253           while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It))
11254             ++SameTypeIt;
11255           unsigned NumElts = (SameTypeIt - It);
11256           if (NumElts > 1 && TryToVectorizeHelper(makeArrayRef(It, NumElts),
11257                                             /*LimitForRegisterSize=*/false))
11258             Changed = true;
11259           It = SameTypeIt;
11260         }
11261       }
11262       Candidates.clear();
11263     }
11264 
11265     // Start over at the next instruction of a different type (or the end).
11266     IncIt = SameTypeIt;
11267   }
11268   return Changed;
11269 }
11270 
11271 /// Compare two cmp instructions. If IsCompatibility is true, function returns
11272 /// true if 2 cmps have same/swapped predicates and mos compatible corresponding
11273 /// operands. If IsCompatibility is false, function implements strict weak
11274 /// ordering relation between two cmp instructions, returning true if the first
11275 /// instruction is "less" than the second, i.e. its predicate is less than the
11276 /// predicate of the second or the operands IDs are less than the operands IDs
11277 /// of the second cmp instruction.
11278 template <bool IsCompatibility>
11279 static bool compareCmp(Value *V, Value *V2,
11280                        function_ref<bool(Instruction *)> IsDeleted) {
11281   auto *CI1 = cast<CmpInst>(V);
11282   auto *CI2 = cast<CmpInst>(V2);
11283   if (IsDeleted(CI2) || !isValidElementType(CI2->getType()))
11284     return false;
11285   if (CI1->getOperand(0)->getType()->getTypeID() <
11286       CI2->getOperand(0)->getType()->getTypeID())
11287     return !IsCompatibility;
11288   if (CI1->getOperand(0)->getType()->getTypeID() >
11289       CI2->getOperand(0)->getType()->getTypeID())
11290     return false;
11291   CmpInst::Predicate Pred1 = CI1->getPredicate();
11292   CmpInst::Predicate Pred2 = CI2->getPredicate();
11293   CmpInst::Predicate SwapPred1 = CmpInst::getSwappedPredicate(Pred1);
11294   CmpInst::Predicate SwapPred2 = CmpInst::getSwappedPredicate(Pred2);
11295   CmpInst::Predicate BasePred1 = std::min(Pred1, SwapPred1);
11296   CmpInst::Predicate BasePred2 = std::min(Pred2, SwapPred2);
11297   if (BasePred1 < BasePred2)
11298     return !IsCompatibility;
11299   if (BasePred1 > BasePred2)
11300     return false;
11301   // Compare operands.
11302   bool LEPreds = Pred1 <= Pred2;
11303   bool GEPreds = Pred1 >= Pred2;
11304   for (int I = 0, E = CI1->getNumOperands(); I < E; ++I) {
11305     auto *Op1 = CI1->getOperand(LEPreds ? I : E - I - 1);
11306     auto *Op2 = CI2->getOperand(GEPreds ? I : E - I - 1);
11307     if (Op1->getValueID() < Op2->getValueID())
11308       return !IsCompatibility;
11309     if (Op1->getValueID() > Op2->getValueID())
11310       return false;
11311     if (auto *I1 = dyn_cast<Instruction>(Op1))
11312       if (auto *I2 = dyn_cast<Instruction>(Op2)) {
11313         if (I1->getParent() != I2->getParent())
11314           return false;
11315         InstructionsState S = getSameOpcode({I1, I2});
11316         if (S.getOpcode())
11317           continue;
11318         return false;
11319       }
11320   }
11321   return IsCompatibility;
11322 }
11323 
11324 bool SLPVectorizerPass::vectorizeSimpleInstructions(
11325     SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R,
11326     bool AtTerminator) {
11327   bool OpsChanged = false;
11328   SmallVector<Instruction *, 4> PostponedCmps;
11329   for (auto *I : reverse(Instructions)) {
11330     if (R.isDeleted(I))
11331       continue;
11332     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I)) {
11333       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
11334     } else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I)) {
11335       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
11336     } else if (isa<CmpInst>(I)) {
11337       PostponedCmps.push_back(I);
11338       continue;
11339     }
11340     // Try to find reductions in buildvector sequnces.
11341     OpsChanged |= vectorizeRootInstruction(nullptr, I, BB, R, TTI);
11342   }
11343   if (AtTerminator) {
11344     // Try to find reductions first.
11345     for (Instruction *I : PostponedCmps) {
11346       if (R.isDeleted(I))
11347         continue;
11348       for (Value *Op : I->operands())
11349         OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI);
11350     }
11351     // Try to vectorize operands as vector bundles.
11352     for (Instruction *I : PostponedCmps) {
11353       if (R.isDeleted(I))
11354         continue;
11355       OpsChanged |= tryToVectorize(I, R);
11356     }
11357     // Try to vectorize list of compares.
11358     // Sort by type, compare predicate, etc.
11359     auto &&CompareSorter = [&R](Value *V, Value *V2) {
11360       return compareCmp<false>(V, V2,
11361                                [&R](Instruction *I) { return R.isDeleted(I); });
11362     };
11363 
11364     auto &&AreCompatibleCompares = [&R](Value *V1, Value *V2) {
11365       if (V1 == V2)
11366         return true;
11367       return compareCmp<true>(V1, V2,
11368                               [&R](Instruction *I) { return R.isDeleted(I); });
11369     };
11370     auto Limit = [&R](Value *V) {
11371       unsigned EltSize = R.getVectorElementSize(V);
11372       return std::max(2U, R.getMaxVecRegSize() / EltSize);
11373     };
11374 
11375     SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end());
11376     OpsChanged |= tryToVectorizeSequence<Value>(
11377         Vals, Limit, CompareSorter, AreCompatibleCompares,
11378         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
11379           // Exclude possible reductions from other blocks.
11380           bool ArePossiblyReducedInOtherBlock =
11381               any_of(Candidates, [](Value *V) {
11382                 return any_of(V->users(), [V](User *U) {
11383                   return isa<SelectInst>(U) &&
11384                          cast<SelectInst>(U)->getParent() !=
11385                              cast<Instruction>(V)->getParent();
11386                 });
11387               });
11388           if (ArePossiblyReducedInOtherBlock)
11389             return false;
11390           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
11391         },
11392         /*LimitForRegisterSize=*/true);
11393     Instructions.clear();
11394   } else {
11395     // Insert in reverse order since the PostponedCmps vector was filled in
11396     // reverse order.
11397     Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend());
11398   }
11399   return OpsChanged;
11400 }
11401 
11402 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
11403   bool Changed = false;
11404   SmallVector<Value *, 4> Incoming;
11405   SmallPtrSet<Value *, 16> VisitedInstrs;
11406   // Maps phi nodes to the non-phi nodes found in the use tree for each phi
11407   // node. Allows better to identify the chains that can be vectorized in the
11408   // better way.
11409   DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes;
11410   auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) {
11411     assert(isValidElementType(V1->getType()) &&
11412            isValidElementType(V2->getType()) &&
11413            "Expected vectorizable types only.");
11414     // It is fine to compare type IDs here, since we expect only vectorizable
11415     // types, like ints, floats and pointers, we don't care about other type.
11416     if (V1->getType()->getTypeID() < V2->getType()->getTypeID())
11417       return true;
11418     if (V1->getType()->getTypeID() > V2->getType()->getTypeID())
11419       return false;
11420     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
11421     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
11422     if (Opcodes1.size() < Opcodes2.size())
11423       return true;
11424     if (Opcodes1.size() > Opcodes2.size())
11425       return false;
11426     Optional<bool> ConstOrder;
11427     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
11428       // Undefs are compatible with any other value.
11429       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) {
11430         if (!ConstOrder)
11431           ConstOrder =
11432               !isa<UndefValue>(Opcodes1[I]) && isa<UndefValue>(Opcodes2[I]);
11433         continue;
11434       }
11435       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
11436         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
11437           DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent());
11438           DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent());
11439           if (!NodeI1)
11440             return NodeI2 != nullptr;
11441           if (!NodeI2)
11442             return false;
11443           assert((NodeI1 == NodeI2) ==
11444                      (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
11445                  "Different nodes should have different DFS numbers");
11446           if (NodeI1 != NodeI2)
11447             return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
11448           InstructionsState S = getSameOpcode({I1, I2});
11449           if (S.getOpcode())
11450             continue;
11451           return I1->getOpcode() < I2->getOpcode();
11452         }
11453       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) {
11454         if (!ConstOrder)
11455           ConstOrder = Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID();
11456         continue;
11457       }
11458       if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID())
11459         return true;
11460       if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID())
11461         return false;
11462     }
11463     return ConstOrder && *ConstOrder;
11464   };
11465   auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) {
11466     if (V1 == V2)
11467       return true;
11468     if (V1->getType() != V2->getType())
11469       return false;
11470     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
11471     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
11472     if (Opcodes1.size() != Opcodes2.size())
11473       return false;
11474     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
11475       // Undefs are compatible with any other value.
11476       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
11477         continue;
11478       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
11479         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
11480           if (I1->getParent() != I2->getParent())
11481             return false;
11482           InstructionsState S = getSameOpcode({I1, I2});
11483           if (S.getOpcode())
11484             continue;
11485           return false;
11486         }
11487       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
11488         continue;
11489       if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID())
11490         return false;
11491     }
11492     return true;
11493   };
11494   auto Limit = [&R](Value *V) {
11495     unsigned EltSize = R.getVectorElementSize(V);
11496     return std::max(2U, R.getMaxVecRegSize() / EltSize);
11497   };
11498 
11499   bool HaveVectorizedPhiNodes = false;
11500   do {
11501     // Collect the incoming values from the PHIs.
11502     Incoming.clear();
11503     for (Instruction &I : *BB) {
11504       PHINode *P = dyn_cast<PHINode>(&I);
11505       if (!P)
11506         break;
11507 
11508       // No need to analyze deleted, vectorized and non-vectorizable
11509       // instructions.
11510       if (!VisitedInstrs.count(P) && !R.isDeleted(P) &&
11511           isValidElementType(P->getType()))
11512         Incoming.push_back(P);
11513     }
11514 
11515     // Find the corresponding non-phi nodes for better matching when trying to
11516     // build the tree.
11517     for (Value *V : Incoming) {
11518       SmallVectorImpl<Value *> &Opcodes =
11519           PHIToOpcodes.try_emplace(V).first->getSecond();
11520       if (!Opcodes.empty())
11521         continue;
11522       SmallVector<Value *, 4> Nodes(1, V);
11523       SmallPtrSet<Value *, 4> Visited;
11524       while (!Nodes.empty()) {
11525         auto *PHI = cast<PHINode>(Nodes.pop_back_val());
11526         if (!Visited.insert(PHI).second)
11527           continue;
11528         for (Value *V : PHI->incoming_values()) {
11529           if (auto *PHI1 = dyn_cast<PHINode>((V))) {
11530             Nodes.push_back(PHI1);
11531             continue;
11532           }
11533           Opcodes.emplace_back(V);
11534         }
11535       }
11536     }
11537 
11538     HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>(
11539         Incoming, Limit, PHICompare, AreCompatiblePHIs,
11540         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
11541           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
11542         },
11543         /*LimitForRegisterSize=*/true);
11544     Changed |= HaveVectorizedPhiNodes;
11545     VisitedInstrs.insert(Incoming.begin(), Incoming.end());
11546   } while (HaveVectorizedPhiNodes);
11547 
11548   VisitedInstrs.clear();
11549 
11550   SmallVector<Instruction *, 8> PostProcessInstructions;
11551   SmallDenseSet<Instruction *, 4> KeyNodes;
11552   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
11553     // Skip instructions with scalable type. The num of elements is unknown at
11554     // compile-time for scalable type.
11555     if (isa<ScalableVectorType>(it->getType()))
11556       continue;
11557 
11558     // Skip instructions marked for the deletion.
11559     if (R.isDeleted(&*it))
11560       continue;
11561     // We may go through BB multiple times so skip the one we have checked.
11562     if (!VisitedInstrs.insert(&*it).second) {
11563       if (it->use_empty() && KeyNodes.contains(&*it) &&
11564           vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
11565                                       it->isTerminator())) {
11566         // We would like to start over since some instructions are deleted
11567         // and the iterator may become invalid value.
11568         Changed = true;
11569         it = BB->begin();
11570         e = BB->end();
11571       }
11572       continue;
11573     }
11574 
11575     if (isa<DbgInfoIntrinsic>(it))
11576       continue;
11577 
11578     // Try to vectorize reductions that use PHINodes.
11579     if (PHINode *P = dyn_cast<PHINode>(it)) {
11580       // Check that the PHI is a reduction PHI.
11581       if (P->getNumIncomingValues() == 2) {
11582         // Try to match and vectorize a horizontal reduction.
11583         if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
11584                                      TTI)) {
11585           Changed = true;
11586           it = BB->begin();
11587           e = BB->end();
11588           continue;
11589         }
11590       }
11591       // Try to vectorize the incoming values of the PHI, to catch reductions
11592       // that feed into PHIs.
11593       for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) {
11594         // Skip if the incoming block is the current BB for now. Also, bypass
11595         // unreachable IR for efficiency and to avoid crashing.
11596         // TODO: Collect the skipped incoming values and try to vectorize them
11597         // after processing BB.
11598         if (BB == P->getIncomingBlock(I) ||
11599             !DT->isReachableFromEntry(P->getIncomingBlock(I)))
11600           continue;
11601 
11602         Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I),
11603                                             P->getIncomingBlock(I), R, TTI);
11604       }
11605       continue;
11606     }
11607 
11608     // Ran into an instruction without users, like terminator, or function call
11609     // with ignored return value, store. Ignore unused instructions (basing on
11610     // instruction type, except for CallInst and InvokeInst).
11611     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
11612                             isa<InvokeInst>(it))) {
11613       KeyNodes.insert(&*it);
11614       bool OpsChanged = false;
11615       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
11616         for (auto *V : it->operand_values()) {
11617           // Try to match and vectorize a horizontal reduction.
11618           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
11619         }
11620       }
11621       // Start vectorization of post-process list of instructions from the
11622       // top-tree instructions to try to vectorize as many instructions as
11623       // possible.
11624       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
11625                                                 it->isTerminator());
11626       if (OpsChanged) {
11627         // We would like to start over since some instructions are deleted
11628         // and the iterator may become invalid value.
11629         Changed = true;
11630         it = BB->begin();
11631         e = BB->end();
11632         continue;
11633       }
11634     }
11635 
11636     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
11637         isa<InsertValueInst>(it))
11638       PostProcessInstructions.push_back(&*it);
11639   }
11640 
11641   return Changed;
11642 }
11643 
11644 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
11645   auto Changed = false;
11646   for (auto &Entry : GEPs) {
11647     // If the getelementptr list has fewer than two elements, there's nothing
11648     // to do.
11649     if (Entry.second.size() < 2)
11650       continue;
11651 
11652     LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
11653                       << Entry.second.size() << ".\n");
11654 
11655     // Process the GEP list in chunks suitable for the target's supported
11656     // vector size. If a vector register can't hold 1 element, we are done. We
11657     // are trying to vectorize the index computations, so the maximum number of
11658     // elements is based on the size of the index expression, rather than the
11659     // size of the GEP itself (the target's pointer size).
11660     unsigned MaxVecRegSize = R.getMaxVecRegSize();
11661     unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin());
11662     if (MaxVecRegSize < EltSize)
11663       continue;
11664 
11665     unsigned MaxElts = MaxVecRegSize / EltSize;
11666     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
11667       auto Len = std::min<unsigned>(BE - BI, MaxElts);
11668       ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len);
11669 
11670       // Initialize a set a candidate getelementptrs. Note that we use a
11671       // SetVector here to preserve program order. If the index computations
11672       // are vectorizable and begin with loads, we want to minimize the chance
11673       // of having to reorder them later.
11674       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
11675 
11676       // Some of the candidates may have already been vectorized after we
11677       // initially collected them. If so, they are marked as deleted, so remove
11678       // them from the set of candidates.
11679       Candidates.remove_if(
11680           [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
11681 
11682       // Remove from the set of candidates all pairs of getelementptrs with
11683       // constant differences. Such getelementptrs are likely not good
11684       // candidates for vectorization in a bottom-up phase since one can be
11685       // computed from the other. We also ensure all candidate getelementptr
11686       // indices are unique.
11687       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
11688         auto *GEPI = GEPList[I];
11689         if (!Candidates.count(GEPI))
11690           continue;
11691         auto *SCEVI = SE->getSCEV(GEPList[I]);
11692         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
11693           auto *GEPJ = GEPList[J];
11694           auto *SCEVJ = SE->getSCEV(GEPList[J]);
11695           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
11696             Candidates.remove(GEPI);
11697             Candidates.remove(GEPJ);
11698           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
11699             Candidates.remove(GEPJ);
11700           }
11701         }
11702       }
11703 
11704       // We break out of the above computation as soon as we know there are
11705       // fewer than two candidates remaining.
11706       if (Candidates.size() < 2)
11707         continue;
11708 
11709       // Add the single, non-constant index of each candidate to the bundle. We
11710       // ensured the indices met these constraints when we originally collected
11711       // the getelementptrs.
11712       SmallVector<Value *, 16> Bundle(Candidates.size());
11713       auto BundleIndex = 0u;
11714       for (auto *V : Candidates) {
11715         auto *GEP = cast<GetElementPtrInst>(V);
11716         auto *GEPIdx = GEP->idx_begin()->get();
11717         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
11718         Bundle[BundleIndex++] = GEPIdx;
11719       }
11720 
11721       // Try and vectorize the indices. We are currently only interested in
11722       // gather-like cases of the form:
11723       //
11724       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
11725       //
11726       // where the loads of "a", the loads of "b", and the subtractions can be
11727       // performed in parallel. It's likely that detecting this pattern in a
11728       // bottom-up phase will be simpler and less costly than building a
11729       // full-blown top-down phase beginning at the consecutive loads.
11730       Changed |= tryToVectorizeList(Bundle, R);
11731     }
11732   }
11733   return Changed;
11734 }
11735 
11736 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
11737   bool Changed = false;
11738   // Sort by type, base pointers and values operand. Value operands must be
11739   // compatible (have the same opcode, same parent), otherwise it is
11740   // definitely not profitable to try to vectorize them.
11741   auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) {
11742     if (V->getPointerOperandType()->getTypeID() <
11743         V2->getPointerOperandType()->getTypeID())
11744       return true;
11745     if (V->getPointerOperandType()->getTypeID() >
11746         V2->getPointerOperandType()->getTypeID())
11747       return false;
11748     // UndefValues are compatible with all other values.
11749     if (isa<UndefValue>(V->getValueOperand()) ||
11750         isa<UndefValue>(V2->getValueOperand()))
11751       return false;
11752     if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand()))
11753       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
11754         DomTreeNodeBase<llvm::BasicBlock> *NodeI1 =
11755             DT->getNode(I1->getParent());
11756         DomTreeNodeBase<llvm::BasicBlock> *NodeI2 =
11757             DT->getNode(I2->getParent());
11758         assert(NodeI1 && "Should only process reachable instructions");
11759         assert(NodeI2 && "Should only process reachable instructions");
11760         assert((NodeI1 == NodeI2) ==
11761                    (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
11762                "Different nodes should have different DFS numbers");
11763         if (NodeI1 != NodeI2)
11764           return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
11765         InstructionsState S = getSameOpcode({I1, I2});
11766         if (S.getOpcode())
11767           return false;
11768         return I1->getOpcode() < I2->getOpcode();
11769       }
11770     if (isa<Constant>(V->getValueOperand()) &&
11771         isa<Constant>(V2->getValueOperand()))
11772       return false;
11773     return V->getValueOperand()->getValueID() <
11774            V2->getValueOperand()->getValueID();
11775   };
11776 
11777   auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) {
11778     if (V1 == V2)
11779       return true;
11780     if (V1->getPointerOperandType() != V2->getPointerOperandType())
11781       return false;
11782     // Undefs are compatible with any other value.
11783     if (isa<UndefValue>(V1->getValueOperand()) ||
11784         isa<UndefValue>(V2->getValueOperand()))
11785       return true;
11786     if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand()))
11787       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
11788         if (I1->getParent() != I2->getParent())
11789           return false;
11790         InstructionsState S = getSameOpcode({I1, I2});
11791         return S.getOpcode() > 0;
11792       }
11793     if (isa<Constant>(V1->getValueOperand()) &&
11794         isa<Constant>(V2->getValueOperand()))
11795       return true;
11796     return V1->getValueOperand()->getValueID() ==
11797            V2->getValueOperand()->getValueID();
11798   };
11799   auto Limit = [&R, this](StoreInst *SI) {
11800     unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
11801     return R.getMinVF(EltSize);
11802   };
11803 
11804   // Attempt to sort and vectorize each of the store-groups.
11805   for (auto &Pair : Stores) {
11806     if (Pair.second.size() < 2)
11807       continue;
11808 
11809     LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
11810                       << Pair.second.size() << ".\n");
11811 
11812     if (!isValidElementType(Pair.second.front()->getValueOperand()->getType()))
11813       continue;
11814 
11815     Changed |= tryToVectorizeSequence<StoreInst>(
11816         Pair.second, Limit, StoreSorter, AreCompatibleStores,
11817         [this, &R](ArrayRef<StoreInst *> Candidates, bool) {
11818           return vectorizeStores(Candidates, R);
11819         },
11820         /*LimitForRegisterSize=*/false);
11821   }
11822   return Changed;
11823 }
11824 
11825 char SLPVectorizer::ID = 0;
11826 
11827 static const char lv_name[] = "SLP Vectorizer";
11828 
11829 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
11830 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
11831 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
11832 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
11833 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
11834 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
11835 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
11836 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
11837 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
11838 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
11839 
11840 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
11841