1 //===- SLPVectorizer.cpp - A bottom up SLP Vectorizer ---------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass implements the Bottom Up SLP vectorizer. It detects consecutive
10 // stores that can be put together into vector-stores. Next, it attempts to
11 // construct vectorizable tree using the use-def chains. If a profitable tree
12 // was found, the SLP vectorizer performs vectorization on the tree.
13 //
14 // The pass is inspired by the work described in the paper:
15 //  "Loop-Aware SLP in GCC" by Ira Rosen, Dorit Nuzman, Ayal Zaks.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "llvm/Transforms/Vectorize/SLPVectorizer.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/DenseSet.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/ADT/PostOrderIterator.h"
24 #include "llvm/ADT/PriorityQueue.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SetOperations.h"
27 #include "llvm/ADT/SetVector.h"
28 #include "llvm/ADT/SmallBitVector.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/iterator.h"
34 #include "llvm/ADT/iterator_range.h"
35 #include "llvm/Analysis/AliasAnalysis.h"
36 #include "llvm/Analysis/AssumptionCache.h"
37 #include "llvm/Analysis/CodeMetrics.h"
38 #include "llvm/Analysis/DemandedBits.h"
39 #include "llvm/Analysis/GlobalsModRef.h"
40 #include "llvm/Analysis/IVDescriptors.h"
41 #include "llvm/Analysis/LoopAccessAnalysis.h"
42 #include "llvm/Analysis/LoopInfo.h"
43 #include "llvm/Analysis/MemoryLocation.h"
44 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
45 #include "llvm/Analysis/ScalarEvolution.h"
46 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
47 #include "llvm/Analysis/TargetLibraryInfo.h"
48 #include "llvm/Analysis/TargetTransformInfo.h"
49 #include "llvm/Analysis/ValueTracking.h"
50 #include "llvm/Analysis/VectorUtils.h"
51 #include "llvm/IR/Attributes.h"
52 #include "llvm/IR/BasicBlock.h"
53 #include "llvm/IR/Constant.h"
54 #include "llvm/IR/Constants.h"
55 #include "llvm/IR/DataLayout.h"
56 #include "llvm/IR/DerivedTypes.h"
57 #include "llvm/IR/Dominators.h"
58 #include "llvm/IR/Function.h"
59 #include "llvm/IR/IRBuilder.h"
60 #include "llvm/IR/InstrTypes.h"
61 #include "llvm/IR/Instruction.h"
62 #include "llvm/IR/Instructions.h"
63 #include "llvm/IR/IntrinsicInst.h"
64 #include "llvm/IR/Intrinsics.h"
65 #include "llvm/IR/Module.h"
66 #include "llvm/IR/Operator.h"
67 #include "llvm/IR/PatternMatch.h"
68 #include "llvm/IR/Type.h"
69 #include "llvm/IR/Use.h"
70 #include "llvm/IR/User.h"
71 #include "llvm/IR/Value.h"
72 #include "llvm/IR/ValueHandle.h"
73 #ifdef EXPENSIVE_CHECKS
74 #include "llvm/IR/Verifier.h"
75 #endif
76 #include "llvm/Pass.h"
77 #include "llvm/Support/Casting.h"
78 #include "llvm/Support/CommandLine.h"
79 #include "llvm/Support/Compiler.h"
80 #include "llvm/Support/DOTGraphTraits.h"
81 #include "llvm/Support/Debug.h"
82 #include "llvm/Support/ErrorHandling.h"
83 #include "llvm/Support/GraphWriter.h"
84 #include "llvm/Support/InstructionCost.h"
85 #include "llvm/Support/KnownBits.h"
86 #include "llvm/Support/MathExtras.h"
87 #include "llvm/Support/raw_ostream.h"
88 #include "llvm/Transforms/Utils/InjectTLIMappings.h"
89 #include "llvm/Transforms/Utils/Local.h"
90 #include "llvm/Transforms/Utils/LoopUtils.h"
91 #include "llvm/Transforms/Vectorize.h"
92 #include <algorithm>
93 #include <cassert>
94 #include <cstdint>
95 #include <iterator>
96 #include <memory>
97 #include <set>
98 #include <string>
99 #include <tuple>
100 #include <utility>
101 #include <vector>
102 
103 using namespace llvm;
104 using namespace llvm::PatternMatch;
105 using namespace slpvectorizer;
106 
107 #define SV_NAME "slp-vectorizer"
108 #define DEBUG_TYPE "SLP"
109 
110 STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
111 
112 cl::opt<bool> RunSLPVectorization("vectorize-slp", cl::init(true), cl::Hidden,
113                                   cl::desc("Run the SLP vectorization passes"));
114 
115 static cl::opt<int>
116     SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
117                      cl::desc("Only vectorize if you gain more than this "
118                               "number "));
119 
120 static cl::opt<bool>
121 ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden,
122                    cl::desc("Attempt to vectorize horizontal reductions"));
123 
124 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
125     "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
126     cl::desc(
127         "Attempt to vectorize horizontal reductions feeding into a store"));
128 
129 static cl::opt<int>
130 MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden,
131     cl::desc("Attempt to vectorize for this register size in bits"));
132 
133 static cl::opt<unsigned>
134 MaxVFOption("slp-max-vf", cl::init(0), cl::Hidden,
135     cl::desc("Maximum SLP vectorization factor (0=unlimited)"));
136 
137 static cl::opt<int>
138 MaxStoreLookup("slp-max-store-lookup", cl::init(32), cl::Hidden,
139     cl::desc("Maximum depth of the lookup for consecutive stores."));
140 
141 /// Limits the size of scheduling regions in a block.
142 /// It avoid long compile times for _very_ large blocks where vector
143 /// instructions are spread over a wide range.
144 /// This limit is way higher than needed by real-world functions.
145 static cl::opt<int>
146 ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden,
147     cl::desc("Limit the size of the SLP scheduling region per block"));
148 
149 static cl::opt<int> MinVectorRegSizeOption(
150     "slp-min-reg-size", cl::init(128), cl::Hidden,
151     cl::desc("Attempt to vectorize for this register size in bits"));
152 
153 static cl::opt<unsigned> RecursionMaxDepth(
154     "slp-recursion-max-depth", cl::init(12), cl::Hidden,
155     cl::desc("Limit the recursion depth when building a vectorizable tree"));
156 
157 static cl::opt<unsigned> MinTreeSize(
158     "slp-min-tree-size", cl::init(3), cl::Hidden,
159     cl::desc("Only vectorize small trees if they are fully vectorizable"));
160 
161 // The maximum depth that the look-ahead score heuristic will explore.
162 // The higher this value, the higher the compilation time overhead.
163 static cl::opt<int> LookAheadMaxDepth(
164     "slp-max-look-ahead-depth", cl::init(2), cl::Hidden,
165     cl::desc("The maximum look-ahead depth for operand reordering scores"));
166 
167 // The maximum depth that the look-ahead score heuristic will explore
168 // when it probing among candidates for vectorization tree roots.
169 // The higher this value, the higher the compilation time overhead but unlike
170 // similar limit for operands ordering this is less frequently used, hence
171 // impact of higher value is less noticeable.
172 static cl::opt<int> RootLookAheadMaxDepth(
173     "slp-max-root-look-ahead-depth", cl::init(2), cl::Hidden,
174     cl::desc("The maximum look-ahead depth for searching best rooting option"));
175 
176 static cl::opt<bool>
177     ViewSLPTree("view-slp-tree", cl::Hidden,
178                 cl::desc("Display the SLP trees with Graphviz"));
179 
180 // Limit the number of alias checks. The limit is chosen so that
181 // it has no negative effect on the llvm benchmarks.
182 static const unsigned AliasedCheckLimit = 10;
183 
184 // Another limit for the alias checks: The maximum distance between load/store
185 // instructions where alias checks are done.
186 // This limit is useful for very large basic blocks.
187 static const unsigned MaxMemDepDistance = 160;
188 
189 /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
190 /// regions to be handled.
191 static const int MinScheduleRegionSize = 16;
192 
193 /// Predicate for the element types that the SLP vectorizer supports.
194 ///
195 /// The most important thing to filter here are types which are invalid in LLVM
196 /// vectors. We also filter target specific types which have absolutely no
197 /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
198 /// avoids spending time checking the cost model and realizing that they will
199 /// be inevitably scalarized.
200 static bool isValidElementType(Type *Ty) {
201   return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() &&
202          !Ty->isPPC_FP128Ty();
203 }
204 
205 /// \returns True if the value is a constant (but not globals/constant
206 /// expressions).
207 static bool isConstant(Value *V) {
208   return isa<Constant>(V) && !isa<ConstantExpr>(V) && !isa<GlobalValue>(V);
209 }
210 
211 /// Checks if \p V is one of vector-like instructions, i.e. undef,
212 /// insertelement/extractelement with constant indices for fixed vector type or
213 /// extractvalue instruction.
214 static bool isVectorLikeInstWithConstOps(Value *V) {
215   if (!isa<InsertElementInst, ExtractElementInst>(V) &&
216       !isa<ExtractValueInst, UndefValue>(V))
217     return false;
218   auto *I = dyn_cast<Instruction>(V);
219   if (!I || isa<ExtractValueInst>(I))
220     return true;
221   if (!isa<FixedVectorType>(I->getOperand(0)->getType()))
222     return false;
223   if (isa<ExtractElementInst>(I))
224     return isConstant(I->getOperand(1));
225   assert(isa<InsertElementInst>(V) && "Expected only insertelement.");
226   return isConstant(I->getOperand(2));
227 }
228 
229 /// \returns true if all of the instructions in \p VL are in the same block or
230 /// false otherwise.
231 static bool allSameBlock(ArrayRef<Value *> VL) {
232   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
233   if (!I0)
234     return false;
235   if (all_of(VL, isVectorLikeInstWithConstOps))
236     return true;
237 
238   BasicBlock *BB = I0->getParent();
239   for (int I = 1, E = VL.size(); I < E; I++) {
240     auto *II = dyn_cast<Instruction>(VL[I]);
241     if (!II)
242       return false;
243 
244     if (BB != II->getParent())
245       return false;
246   }
247   return true;
248 }
249 
250 /// \returns True if all of the values in \p VL are constants (but not
251 /// globals/constant expressions).
252 static bool allConstant(ArrayRef<Value *> VL) {
253   // Constant expressions and globals can't be vectorized like normal integer/FP
254   // constants.
255   return all_of(VL, isConstant);
256 }
257 
258 /// \returns True if all of the values in \p VL are identical or some of them
259 /// are UndefValue.
260 static bool isSplat(ArrayRef<Value *> VL) {
261   Value *FirstNonUndef = nullptr;
262   for (Value *V : VL) {
263     if (isa<UndefValue>(V))
264       continue;
265     if (!FirstNonUndef) {
266       FirstNonUndef = V;
267       continue;
268     }
269     if (V != FirstNonUndef)
270       return false;
271   }
272   return FirstNonUndef != nullptr;
273 }
274 
275 /// \returns True if \p I is commutative, handles CmpInst and BinaryOperator.
276 static bool isCommutative(Instruction *I) {
277   if (auto *Cmp = dyn_cast<CmpInst>(I))
278     return Cmp->isCommutative();
279   if (auto *BO = dyn_cast<BinaryOperator>(I))
280     return BO->isCommutative();
281   // TODO: This should check for generic Instruction::isCommutative(), but
282   //       we need to confirm that the caller code correctly handles Intrinsics
283   //       for example (does not have 2 operands).
284   return false;
285 }
286 
287 /// Checks if the given value is actually an undefined constant vector.
288 static bool isUndefVector(const Value *V) {
289   if (isa<UndefValue>(V))
290     return true;
291   auto *C = dyn_cast<Constant>(V);
292   if (!C)
293     return false;
294   if (!C->containsUndefOrPoisonElement())
295     return false;
296   auto *VecTy = dyn_cast<FixedVectorType>(C->getType());
297   if (!VecTy)
298     return false;
299   for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
300     if (Constant *Elem = C->getAggregateElement(I))
301       if (!isa<UndefValue>(Elem))
302         return false;
303   }
304   return true;
305 }
306 
307 /// Checks if the vector of instructions can be represented as a shuffle, like:
308 /// %x0 = extractelement <4 x i8> %x, i32 0
309 /// %x3 = extractelement <4 x i8> %x, i32 3
310 /// %y1 = extractelement <4 x i8> %y, i32 1
311 /// %y2 = extractelement <4 x i8> %y, i32 2
312 /// %x0x0 = mul i8 %x0, %x0
313 /// %x3x3 = mul i8 %x3, %x3
314 /// %y1y1 = mul i8 %y1, %y1
315 /// %y2y2 = mul i8 %y2, %y2
316 /// %ins1 = insertelement <4 x i8> poison, i8 %x0x0, i32 0
317 /// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1
318 /// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2
319 /// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3
320 /// ret <4 x i8> %ins4
321 /// can be transformed into:
322 /// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5,
323 ///                                                         i32 6>
324 /// %2 = mul <4 x i8> %1, %1
325 /// ret <4 x i8> %2
326 /// We convert this initially to something like:
327 /// %x0 = extractelement <4 x i8> %x, i32 0
328 /// %x3 = extractelement <4 x i8> %x, i32 3
329 /// %y1 = extractelement <4 x i8> %y, i32 1
330 /// %y2 = extractelement <4 x i8> %y, i32 2
331 /// %1 = insertelement <4 x i8> poison, i8 %x0, i32 0
332 /// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1
333 /// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2
334 /// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3
335 /// %5 = mul <4 x i8> %4, %4
336 /// %6 = extractelement <4 x i8> %5, i32 0
337 /// %ins1 = insertelement <4 x i8> poison, i8 %6, i32 0
338 /// %7 = extractelement <4 x i8> %5, i32 1
339 /// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1
340 /// %8 = extractelement <4 x i8> %5, i32 2
341 /// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2
342 /// %9 = extractelement <4 x i8> %5, i32 3
343 /// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3
344 /// ret <4 x i8> %ins4
345 /// InstCombiner transforms this into a shuffle and vector mul
346 /// Mask will return the Shuffle Mask equivalent to the extracted elements.
347 /// TODO: Can we split off and reuse the shuffle mask detection from
348 /// TargetTransformInfo::getInstructionThroughput?
349 static Optional<TargetTransformInfo::ShuffleKind>
350 isFixedVectorShuffle(ArrayRef<Value *> VL, SmallVectorImpl<int> &Mask) {
351   const auto *It =
352       find_if(VL, [](Value *V) { return isa<ExtractElementInst>(V); });
353   if (It == VL.end())
354     return None;
355   auto *EI0 = cast<ExtractElementInst>(*It);
356   if (isa<ScalableVectorType>(EI0->getVectorOperandType()))
357     return None;
358   unsigned Size =
359       cast<FixedVectorType>(EI0->getVectorOperandType())->getNumElements();
360   Value *Vec1 = nullptr;
361   Value *Vec2 = nullptr;
362   enum ShuffleMode { Unknown, Select, Permute };
363   ShuffleMode CommonShuffleMode = Unknown;
364   Mask.assign(VL.size(), UndefMaskElem);
365   for (unsigned I = 0, E = VL.size(); I < E; ++I) {
366     // Undef can be represented as an undef element in a vector.
367     if (isa<UndefValue>(VL[I]))
368       continue;
369     auto *EI = cast<ExtractElementInst>(VL[I]);
370     if (isa<ScalableVectorType>(EI->getVectorOperandType()))
371       return None;
372     auto *Vec = EI->getVectorOperand();
373     // We can extractelement from undef or poison vector.
374     if (isUndefVector(Vec))
375       continue;
376     // All vector operands must have the same number of vector elements.
377     if (cast<FixedVectorType>(Vec->getType())->getNumElements() != Size)
378       return None;
379     if (isa<UndefValue>(EI->getIndexOperand()))
380       continue;
381     auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand());
382     if (!Idx)
383       return None;
384     // Undefined behavior if Idx is negative or >= Size.
385     if (Idx->getValue().uge(Size))
386       continue;
387     unsigned IntIdx = Idx->getValue().getZExtValue();
388     Mask[I] = IntIdx;
389     // For correct shuffling we have to have at most 2 different vector operands
390     // in all extractelement instructions.
391     if (!Vec1 || Vec1 == Vec) {
392       Vec1 = Vec;
393     } else if (!Vec2 || Vec2 == Vec) {
394       Vec2 = Vec;
395       Mask[I] += Size;
396     } else {
397       return None;
398     }
399     if (CommonShuffleMode == Permute)
400       continue;
401     // If the extract index is not the same as the operation number, it is a
402     // permutation.
403     if (IntIdx != I) {
404       CommonShuffleMode = Permute;
405       continue;
406     }
407     CommonShuffleMode = Select;
408   }
409   // If we're not crossing lanes in different vectors, consider it as blending.
410   if (CommonShuffleMode == Select && Vec2)
411     return TargetTransformInfo::SK_Select;
412   // If Vec2 was never used, we have a permutation of a single vector, otherwise
413   // we have permutation of 2 vectors.
414   return Vec2 ? TargetTransformInfo::SK_PermuteTwoSrc
415               : TargetTransformInfo::SK_PermuteSingleSrc;
416 }
417 
418 namespace {
419 
420 /// Main data required for vectorization of instructions.
421 struct InstructionsState {
422   /// The very first instruction in the list with the main opcode.
423   Value *OpValue = nullptr;
424 
425   /// The main/alternate instruction.
426   Instruction *MainOp = nullptr;
427   Instruction *AltOp = nullptr;
428 
429   /// The main/alternate opcodes for the list of instructions.
430   unsigned getOpcode() const {
431     return MainOp ? MainOp->getOpcode() : 0;
432   }
433 
434   unsigned getAltOpcode() const {
435     return AltOp ? AltOp->getOpcode() : 0;
436   }
437 
438   /// Some of the instructions in the list have alternate opcodes.
439   bool isAltShuffle() const { return AltOp != MainOp; }
440 
441   bool isOpcodeOrAlt(Instruction *I) const {
442     unsigned CheckedOpcode = I->getOpcode();
443     return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode;
444   }
445 
446   InstructionsState() = delete;
447   InstructionsState(Value *OpValue, Instruction *MainOp, Instruction *AltOp)
448       : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {}
449 };
450 
451 } // end anonymous namespace
452 
453 /// Chooses the correct key for scheduling data. If \p Op has the same (or
454 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p
455 /// OpValue.
456 static Value *isOneOf(const InstructionsState &S, Value *Op) {
457   auto *I = dyn_cast<Instruction>(Op);
458   if (I && S.isOpcodeOrAlt(I))
459     return Op;
460   return S.OpValue;
461 }
462 
463 /// \returns true if \p Opcode is allowed as part of of the main/alternate
464 /// instruction for SLP vectorization.
465 ///
466 /// Example of unsupported opcode is SDIV that can potentially cause UB if the
467 /// "shuffled out" lane would result in division by zero.
468 static bool isValidForAlternation(unsigned Opcode) {
469   if (Instruction::isIntDivRem(Opcode))
470     return false;
471 
472   return true;
473 }
474 
475 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
476                                        unsigned BaseIndex = 0);
477 
478 /// Checks if the provided operands of 2 cmp instructions are compatible, i.e.
479 /// compatible instructions or constants, or just some other regular values.
480 static bool areCompatibleCmpOps(Value *BaseOp0, Value *BaseOp1, Value *Op0,
481                                 Value *Op1) {
482   return (isConstant(BaseOp0) && isConstant(Op0)) ||
483          (isConstant(BaseOp1) && isConstant(Op1)) ||
484          (!isa<Instruction>(BaseOp0) && !isa<Instruction>(Op0) &&
485           !isa<Instruction>(BaseOp1) && !isa<Instruction>(Op1)) ||
486          getSameOpcode({BaseOp0, Op0}).getOpcode() ||
487          getSameOpcode({BaseOp1, Op1}).getOpcode();
488 }
489 
490 /// \returns analysis of the Instructions in \p VL described in
491 /// InstructionsState, the Opcode that we suppose the whole list
492 /// could be vectorized even if its structure is diverse.
493 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
494                                        unsigned BaseIndex) {
495   // Make sure these are all Instructions.
496   if (llvm::any_of(VL, [](Value *V) { return !isa<Instruction>(V); }))
497     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
498 
499   bool IsCastOp = isa<CastInst>(VL[BaseIndex]);
500   bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]);
501   bool IsCmpOp = isa<CmpInst>(VL[BaseIndex]);
502   CmpInst::Predicate BasePred =
503       IsCmpOp ? cast<CmpInst>(VL[BaseIndex])->getPredicate()
504               : CmpInst::BAD_ICMP_PREDICATE;
505   unsigned Opcode = cast<Instruction>(VL[BaseIndex])->getOpcode();
506   unsigned AltOpcode = Opcode;
507   unsigned AltIndex = BaseIndex;
508 
509   // Check for one alternate opcode from another BinaryOperator.
510   // TODO - generalize to support all operators (types, calls etc.).
511   for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) {
512     unsigned InstOpcode = cast<Instruction>(VL[Cnt])->getOpcode();
513     if (IsBinOp && isa<BinaryOperator>(VL[Cnt])) {
514       if (InstOpcode == Opcode || InstOpcode == AltOpcode)
515         continue;
516       if (Opcode == AltOpcode && isValidForAlternation(InstOpcode) &&
517           isValidForAlternation(Opcode)) {
518         AltOpcode = InstOpcode;
519         AltIndex = Cnt;
520         continue;
521       }
522     } else if (IsCastOp && isa<CastInst>(VL[Cnt])) {
523       Type *Ty0 = cast<Instruction>(VL[BaseIndex])->getOperand(0)->getType();
524       Type *Ty1 = cast<Instruction>(VL[Cnt])->getOperand(0)->getType();
525       if (Ty0 == Ty1) {
526         if (InstOpcode == Opcode || InstOpcode == AltOpcode)
527           continue;
528         if (Opcode == AltOpcode) {
529           assert(isValidForAlternation(Opcode) &&
530                  isValidForAlternation(InstOpcode) &&
531                  "Cast isn't safe for alternation, logic needs to be updated!");
532           AltOpcode = InstOpcode;
533           AltIndex = Cnt;
534           continue;
535         }
536       }
537     } else if (IsCmpOp && isa<CmpInst>(VL[Cnt])) {
538       auto *BaseInst = cast<Instruction>(VL[BaseIndex]);
539       auto *Inst = cast<Instruction>(VL[Cnt]);
540       Type *Ty0 = BaseInst->getOperand(0)->getType();
541       Type *Ty1 = Inst->getOperand(0)->getType();
542       if (Ty0 == Ty1) {
543         Value *BaseOp0 = BaseInst->getOperand(0);
544         Value *BaseOp1 = BaseInst->getOperand(1);
545         Value *Op0 = Inst->getOperand(0);
546         Value *Op1 = Inst->getOperand(1);
547         CmpInst::Predicate CurrentPred =
548             cast<CmpInst>(VL[Cnt])->getPredicate();
549         CmpInst::Predicate SwappedCurrentPred =
550             CmpInst::getSwappedPredicate(CurrentPred);
551         // Check for compatible operands. If the corresponding operands are not
552         // compatible - need to perform alternate vectorization.
553         if (InstOpcode == Opcode) {
554           if (BasePred == CurrentPred &&
555               areCompatibleCmpOps(BaseOp0, BaseOp1, Op0, Op1))
556             continue;
557           if (BasePred == SwappedCurrentPred &&
558               areCompatibleCmpOps(BaseOp0, BaseOp1, Op1, Op0))
559             continue;
560           if (E == 2 &&
561               (BasePred == CurrentPred || BasePred == SwappedCurrentPred))
562             continue;
563           auto *AltInst = cast<CmpInst>(VL[AltIndex]);
564           CmpInst::Predicate AltPred = AltInst->getPredicate();
565           Value *AltOp0 = AltInst->getOperand(0);
566           Value *AltOp1 = AltInst->getOperand(1);
567           // Check if operands are compatible with alternate operands.
568           if (AltPred == CurrentPred &&
569               areCompatibleCmpOps(AltOp0, AltOp1, Op0, Op1))
570             continue;
571           if (AltPred == SwappedCurrentPred &&
572               areCompatibleCmpOps(AltOp0, AltOp1, Op1, Op0))
573             continue;
574         }
575         if (BaseIndex == AltIndex && BasePred != CurrentPred) {
576           assert(isValidForAlternation(Opcode) &&
577                  isValidForAlternation(InstOpcode) &&
578                  "Cast isn't safe for alternation, logic needs to be updated!");
579           AltIndex = Cnt;
580           continue;
581         }
582         auto *AltInst = cast<CmpInst>(VL[AltIndex]);
583         CmpInst::Predicate AltPred = AltInst->getPredicate();
584         if (BasePred == CurrentPred || BasePred == SwappedCurrentPred ||
585             AltPred == CurrentPred || AltPred == SwappedCurrentPred)
586           continue;
587       }
588     } else if (InstOpcode == Opcode || InstOpcode == AltOpcode)
589       continue;
590     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
591   }
592 
593   return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]),
594                            cast<Instruction>(VL[AltIndex]));
595 }
596 
597 /// \returns true if all of the values in \p VL have the same type or false
598 /// otherwise.
599 static bool allSameType(ArrayRef<Value *> VL) {
600   Type *Ty = VL[0]->getType();
601   for (int i = 1, e = VL.size(); i < e; i++)
602     if (VL[i]->getType() != Ty)
603       return false;
604 
605   return true;
606 }
607 
608 /// \returns True if Extract{Value,Element} instruction extracts element Idx.
609 static Optional<unsigned> getExtractIndex(Instruction *E) {
610   unsigned Opcode = E->getOpcode();
611   assert((Opcode == Instruction::ExtractElement ||
612           Opcode == Instruction::ExtractValue) &&
613          "Expected extractelement or extractvalue instruction.");
614   if (Opcode == Instruction::ExtractElement) {
615     auto *CI = dyn_cast<ConstantInt>(E->getOperand(1));
616     if (!CI)
617       return None;
618     return CI->getZExtValue();
619   }
620   ExtractValueInst *EI = cast<ExtractValueInst>(E);
621   if (EI->getNumIndices() != 1)
622     return None;
623   return *EI->idx_begin();
624 }
625 
626 /// \returns True if in-tree use also needs extract. This refers to
627 /// possible scalar operand in vectorized instruction.
628 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
629                                     TargetLibraryInfo *TLI) {
630   unsigned Opcode = UserInst->getOpcode();
631   switch (Opcode) {
632   case Instruction::Load: {
633     LoadInst *LI = cast<LoadInst>(UserInst);
634     return (LI->getPointerOperand() == Scalar);
635   }
636   case Instruction::Store: {
637     StoreInst *SI = cast<StoreInst>(UserInst);
638     return (SI->getPointerOperand() == Scalar);
639   }
640   case Instruction::Call: {
641     CallInst *CI = cast<CallInst>(UserInst);
642     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
643     for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
644       if (isVectorIntrinsicWithScalarOpAtArg(ID, i))
645         return (CI->getArgOperand(i) == Scalar);
646     }
647     LLVM_FALLTHROUGH;
648   }
649   default:
650     return false;
651   }
652 }
653 
654 /// \returns the AA location that is being access by the instruction.
655 static MemoryLocation getLocation(Instruction *I) {
656   if (StoreInst *SI = dyn_cast<StoreInst>(I))
657     return MemoryLocation::get(SI);
658   if (LoadInst *LI = dyn_cast<LoadInst>(I))
659     return MemoryLocation::get(LI);
660   return MemoryLocation();
661 }
662 
663 /// \returns True if the instruction is not a volatile or atomic load/store.
664 static bool isSimple(Instruction *I) {
665   if (LoadInst *LI = dyn_cast<LoadInst>(I))
666     return LI->isSimple();
667   if (StoreInst *SI = dyn_cast<StoreInst>(I))
668     return SI->isSimple();
669   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
670     return !MI->isVolatile();
671   return true;
672 }
673 
674 /// Shuffles \p Mask in accordance with the given \p SubMask.
675 static void addMask(SmallVectorImpl<int> &Mask, ArrayRef<int> SubMask) {
676   if (SubMask.empty())
677     return;
678   if (Mask.empty()) {
679     Mask.append(SubMask.begin(), SubMask.end());
680     return;
681   }
682   SmallVector<int> NewMask(SubMask.size(), UndefMaskElem);
683   int TermValue = std::min(Mask.size(), SubMask.size());
684   for (int I = 0, E = SubMask.size(); I < E; ++I) {
685     if (SubMask[I] >= TermValue || SubMask[I] == UndefMaskElem ||
686         Mask[SubMask[I]] >= TermValue)
687       continue;
688     NewMask[I] = Mask[SubMask[I]];
689   }
690   Mask.swap(NewMask);
691 }
692 
693 /// Order may have elements assigned special value (size) which is out of
694 /// bounds. Such indices only appear on places which correspond to undef values
695 /// (see canReuseExtract for details) and used in order to avoid undef values
696 /// have effect on operands ordering.
697 /// The first loop below simply finds all unused indices and then the next loop
698 /// nest assigns these indices for undef values positions.
699 /// As an example below Order has two undef positions and they have assigned
700 /// values 3 and 7 respectively:
701 /// before:  6 9 5 4 9 2 1 0
702 /// after:   6 3 5 4 7 2 1 0
703 static void fixupOrderingIndices(SmallVectorImpl<unsigned> &Order) {
704   const unsigned Sz = Order.size();
705   SmallBitVector UnusedIndices(Sz, /*t=*/true);
706   SmallBitVector MaskedIndices(Sz);
707   for (unsigned I = 0; I < Sz; ++I) {
708     if (Order[I] < Sz)
709       UnusedIndices.reset(Order[I]);
710     else
711       MaskedIndices.set(I);
712   }
713   if (MaskedIndices.none())
714     return;
715   assert(UnusedIndices.count() == MaskedIndices.count() &&
716          "Non-synced masked/available indices.");
717   int Idx = UnusedIndices.find_first();
718   int MIdx = MaskedIndices.find_first();
719   while (MIdx >= 0) {
720     assert(Idx >= 0 && "Indices must be synced.");
721     Order[MIdx] = Idx;
722     Idx = UnusedIndices.find_next(Idx);
723     MIdx = MaskedIndices.find_next(MIdx);
724   }
725 }
726 
727 namespace llvm {
728 
729 static void inversePermutation(ArrayRef<unsigned> Indices,
730                                SmallVectorImpl<int> &Mask) {
731   Mask.clear();
732   const unsigned E = Indices.size();
733   Mask.resize(E, UndefMaskElem);
734   for (unsigned I = 0; I < E; ++I)
735     Mask[Indices[I]] = I;
736 }
737 
738 /// \returns inserting index of InsertElement or InsertValue instruction,
739 /// using Offset as base offset for index.
740 static Optional<unsigned> getInsertIndex(Value *InsertInst,
741                                          unsigned Offset = 0) {
742   int Index = Offset;
743   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst)) {
744     if (auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2))) {
745       auto *VT = cast<FixedVectorType>(IE->getType());
746       if (CI->getValue().uge(VT->getNumElements()))
747         return None;
748       Index *= VT->getNumElements();
749       Index += CI->getZExtValue();
750       return Index;
751     }
752     return None;
753   }
754 
755   auto *IV = cast<InsertValueInst>(InsertInst);
756   Type *CurrentType = IV->getType();
757   for (unsigned I : IV->indices()) {
758     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
759       Index *= ST->getNumElements();
760       CurrentType = ST->getElementType(I);
761     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
762       Index *= AT->getNumElements();
763       CurrentType = AT->getElementType();
764     } else {
765       return None;
766     }
767     Index += I;
768   }
769   return Index;
770 }
771 
772 /// Reorders the list of scalars in accordance with the given \p Mask.
773 static void reorderScalars(SmallVectorImpl<Value *> &Scalars,
774                            ArrayRef<int> Mask) {
775   assert(!Mask.empty() && "Expected non-empty mask.");
776   SmallVector<Value *> Prev(Scalars.size(),
777                             UndefValue::get(Scalars.front()->getType()));
778   Prev.swap(Scalars);
779   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
780     if (Mask[I] != UndefMaskElem)
781       Scalars[Mask[I]] = Prev[I];
782 }
783 
784 /// Checks if the provided value does not require scheduling. It does not
785 /// require scheduling if this is not an instruction or it is an instruction
786 /// that does not read/write memory and all operands are either not instructions
787 /// or phi nodes or instructions from different blocks.
788 static bool areAllOperandsNonInsts(Value *V) {
789   auto *I = dyn_cast<Instruction>(V);
790   if (!I)
791     return true;
792   return !mayHaveNonDefUseDependency(*I) &&
793     all_of(I->operands(), [I](Value *V) {
794       auto *IO = dyn_cast<Instruction>(V);
795       if (!IO)
796         return true;
797       return isa<PHINode>(IO) || IO->getParent() != I->getParent();
798     });
799 }
800 
801 /// Checks if the provided value does not require scheduling. It does not
802 /// require scheduling if this is not an instruction or it is an instruction
803 /// that does not read/write memory and all users are phi nodes or instructions
804 /// from the different blocks.
805 static bool isUsedOutsideBlock(Value *V) {
806   auto *I = dyn_cast<Instruction>(V);
807   if (!I)
808     return true;
809   // Limits the number of uses to save compile time.
810   constexpr int UsesLimit = 8;
811   return !I->mayReadOrWriteMemory() && !I->hasNUsesOrMore(UsesLimit) &&
812          all_of(I->users(), [I](User *U) {
813            auto *IU = dyn_cast<Instruction>(U);
814            if (!IU)
815              return true;
816            return IU->getParent() != I->getParent() || isa<PHINode>(IU);
817          });
818 }
819 
820 /// Checks if the specified value does not require scheduling. It does not
821 /// require scheduling if all operands and all users do not need to be scheduled
822 /// in the current basic block.
823 static bool doesNotNeedToBeScheduled(Value *V) {
824   return areAllOperandsNonInsts(V) && isUsedOutsideBlock(V);
825 }
826 
827 /// Checks if the specified array of instructions does not require scheduling.
828 /// It is so if all either instructions have operands that do not require
829 /// scheduling or their users do not require scheduling since they are phis or
830 /// in other basic blocks.
831 static bool doesNotNeedToSchedule(ArrayRef<Value *> VL) {
832   return !VL.empty() &&
833          (all_of(VL, isUsedOutsideBlock) || all_of(VL, areAllOperandsNonInsts));
834 }
835 
836 namespace slpvectorizer {
837 
838 /// Bottom Up SLP Vectorizer.
839 class BoUpSLP {
840   struct TreeEntry;
841   struct ScheduleData;
842 
843 public:
844   using ValueList = SmallVector<Value *, 8>;
845   using InstrList = SmallVector<Instruction *, 16>;
846   using ValueSet = SmallPtrSet<Value *, 16>;
847   using StoreList = SmallVector<StoreInst *, 8>;
848   using ExtraValueToDebugLocsMap =
849       MapVector<Value *, SmallVector<Instruction *, 2>>;
850   using OrdersType = SmallVector<unsigned, 4>;
851 
852   BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
853           TargetLibraryInfo *TLi, AAResults *Aa, LoopInfo *Li,
854           DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB,
855           const DataLayout *DL, OptimizationRemarkEmitter *ORE)
856       : BatchAA(*Aa), F(Func), SE(Se), TTI(Tti), TLI(TLi), LI(Li),
857         DT(Dt), AC(AC), DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) {
858     CodeMetrics::collectEphemeralValues(F, AC, EphValues);
859     // Use the vector register size specified by the target unless overridden
860     // by a command-line option.
861     // TODO: It would be better to limit the vectorization factor based on
862     //       data type rather than just register size. For example, x86 AVX has
863     //       256-bit registers, but it does not support integer operations
864     //       at that width (that requires AVX2).
865     if (MaxVectorRegSizeOption.getNumOccurrences())
866       MaxVecRegSize = MaxVectorRegSizeOption;
867     else
868       MaxVecRegSize =
869           TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
870               .getFixedSize();
871 
872     if (MinVectorRegSizeOption.getNumOccurrences())
873       MinVecRegSize = MinVectorRegSizeOption;
874     else
875       MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
876   }
877 
878   /// Vectorize the tree that starts with the elements in \p VL.
879   /// Returns the vectorized root.
880   Value *vectorizeTree();
881 
882   /// Vectorize the tree but with the list of externally used values \p
883   /// ExternallyUsedValues. Values in this MapVector can be replaced but the
884   /// generated extractvalue instructions.
885   Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues);
886 
887   /// \returns the cost incurred by unwanted spills and fills, caused by
888   /// holding live values over call sites.
889   InstructionCost getSpillCost() const;
890 
891   /// \returns the vectorization cost of the subtree that starts at \p VL.
892   /// A negative number means that this is profitable.
893   InstructionCost getTreeCost(ArrayRef<Value *> VectorizedVals = None);
894 
895   /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
896   /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
897   void buildTree(ArrayRef<Value *> Roots,
898                  ArrayRef<Value *> UserIgnoreLst = None);
899 
900   /// Builds external uses of the vectorized scalars, i.e. the list of
901   /// vectorized scalars to be extracted, their lanes and their scalar users. \p
902   /// ExternallyUsedValues contains additional list of external uses to handle
903   /// vectorization of reductions.
904   void
905   buildExternalUses(const ExtraValueToDebugLocsMap &ExternallyUsedValues = {});
906 
907   /// Clear the internal data structures that are created by 'buildTree'.
908   void deleteTree() {
909     VectorizableTree.clear();
910     ScalarToTreeEntry.clear();
911     MustGather.clear();
912     ExternalUses.clear();
913     for (auto &Iter : BlocksSchedules) {
914       BlockScheduling *BS = Iter.second.get();
915       BS->clear();
916     }
917     MinBWs.clear();
918     InstrElementSize.clear();
919   }
920 
921   unsigned getTreeSize() const { return VectorizableTree.size(); }
922 
923   /// Perform LICM and CSE on the newly generated gather sequences.
924   void optimizeGatherSequence();
925 
926   /// Checks if the specified gather tree entry \p TE can be represented as a
927   /// shuffled vector entry + (possibly) permutation with other gathers. It
928   /// implements the checks only for possibly ordered scalars (Loads,
929   /// ExtractElement, ExtractValue), which can be part of the graph.
930   Optional<OrdersType> findReusedOrderedScalars(const TreeEntry &TE);
931 
932   /// Gets reordering data for the given tree entry. If the entry is vectorized
933   /// - just return ReorderIndices, otherwise check if the scalars can be
934   /// reordered and return the most optimal order.
935   /// \param TopToBottom If true, include the order of vectorized stores and
936   /// insertelement nodes, otherwise skip them.
937   Optional<OrdersType> getReorderingData(const TreeEntry &TE, bool TopToBottom);
938 
939   /// Reorders the current graph to the most profitable order starting from the
940   /// root node to the leaf nodes. The best order is chosen only from the nodes
941   /// of the same size (vectorization factor). Smaller nodes are considered
942   /// parts of subgraph with smaller VF and they are reordered independently. We
943   /// can make it because we still need to extend smaller nodes to the wider VF
944   /// and we can merge reordering shuffles with the widening shuffles.
945   void reorderTopToBottom();
946 
947   /// Reorders the current graph to the most profitable order starting from
948   /// leaves to the root. It allows to rotate small subgraphs and reduce the
949   /// number of reshuffles if the leaf nodes use the same order. In this case we
950   /// can merge the orders and just shuffle user node instead of shuffling its
951   /// operands. Plus, even the leaf nodes have different orders, it allows to
952   /// sink reordering in the graph closer to the root node and merge it later
953   /// during analysis.
954   void reorderBottomToTop(bool IgnoreReorder = false);
955 
956   /// \return The vector element size in bits to use when vectorizing the
957   /// expression tree ending at \p V. If V is a store, the size is the width of
958   /// the stored value. Otherwise, the size is the width of the largest loaded
959   /// value reaching V. This method is used by the vectorizer to calculate
960   /// vectorization factors.
961   unsigned getVectorElementSize(Value *V);
962 
963   /// Compute the minimum type sizes required to represent the entries in a
964   /// vectorizable tree.
965   void computeMinimumValueSizes();
966 
967   // \returns maximum vector register size as set by TTI or overridden by cl::opt.
968   unsigned getMaxVecRegSize() const {
969     return MaxVecRegSize;
970   }
971 
972   // \returns minimum vector register size as set by cl::opt.
973   unsigned getMinVecRegSize() const {
974     return MinVecRegSize;
975   }
976 
977   unsigned getMinVF(unsigned Sz) const {
978     return std::max(2U, getMinVecRegSize() / Sz);
979   }
980 
981   unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const {
982     unsigned MaxVF = MaxVFOption.getNumOccurrences() ?
983       MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode);
984     return MaxVF ? MaxVF : UINT_MAX;
985   }
986 
987   /// Check if homogeneous aggregate is isomorphic to some VectorType.
988   /// Accepts homogeneous multidimensional aggregate of scalars/vectors like
989   /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> },
990   /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on.
991   ///
992   /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
993   unsigned canMapToVector(Type *T, const DataLayout &DL) const;
994 
995   /// \returns True if the VectorizableTree is both tiny and not fully
996   /// vectorizable. We do not vectorize such trees.
997   bool isTreeTinyAndNotFullyVectorizable(bool ForReduction = false) const;
998 
999   /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values
1000   /// can be load combined in the backend. Load combining may not be allowed in
1001   /// the IR optimizer, so we do not want to alter the pattern. For example,
1002   /// partially transforming a scalar bswap() pattern into vector code is
1003   /// effectively impossible for the backend to undo.
1004   /// TODO: If load combining is allowed in the IR optimizer, this analysis
1005   ///       may not be necessary.
1006   bool isLoadCombineReductionCandidate(RecurKind RdxKind) const;
1007 
1008   /// Assume that a vector of stores of bitwise-or/shifted/zexted loaded values
1009   /// can be load combined in the backend. Load combining may not be allowed in
1010   /// the IR optimizer, so we do not want to alter the pattern. For example,
1011   /// partially transforming a scalar bswap() pattern into vector code is
1012   /// effectively impossible for the backend to undo.
1013   /// TODO: If load combining is allowed in the IR optimizer, this analysis
1014   ///       may not be necessary.
1015   bool isLoadCombineCandidate() const;
1016 
1017   OptimizationRemarkEmitter *getORE() { return ORE; }
1018 
1019   /// This structure holds any data we need about the edges being traversed
1020   /// during buildTree_rec(). We keep track of:
1021   /// (i) the user TreeEntry index, and
1022   /// (ii) the index of the edge.
1023   struct EdgeInfo {
1024     EdgeInfo() = default;
1025     EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx)
1026         : UserTE(UserTE), EdgeIdx(EdgeIdx) {}
1027     /// The user TreeEntry.
1028     TreeEntry *UserTE = nullptr;
1029     /// The operand index of the use.
1030     unsigned EdgeIdx = UINT_MAX;
1031 #ifndef NDEBUG
1032     friend inline raw_ostream &operator<<(raw_ostream &OS,
1033                                           const BoUpSLP::EdgeInfo &EI) {
1034       EI.dump(OS);
1035       return OS;
1036     }
1037     /// Debug print.
1038     void dump(raw_ostream &OS) const {
1039       OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null")
1040          << " EdgeIdx:" << EdgeIdx << "}";
1041     }
1042     LLVM_DUMP_METHOD void dump() const { dump(dbgs()); }
1043 #endif
1044   };
1045 
1046   /// A helper class used for scoring candidates for two consecutive lanes.
1047   class LookAheadHeuristics {
1048     const DataLayout &DL;
1049     ScalarEvolution &SE;
1050     const BoUpSLP &R;
1051     int NumLanes; // Total number of lanes (aka vectorization factor).
1052     int MaxLevel; // The maximum recursion depth for accumulating score.
1053 
1054   public:
1055     LookAheadHeuristics(const DataLayout &DL, ScalarEvolution &SE,
1056                         const BoUpSLP &R, int NumLanes, int MaxLevel)
1057         : DL(DL), SE(SE), R(R), NumLanes(NumLanes), MaxLevel(MaxLevel) {}
1058 
1059     // The hard-coded scores listed here are not very important, though it shall
1060     // be higher for better matches to improve the resulting cost. When
1061     // computing the scores of matching one sub-tree with another, we are
1062     // basically counting the number of values that are matching. So even if all
1063     // scores are set to 1, we would still get a decent matching result.
1064     // However, sometimes we have to break ties. For example we may have to
1065     // choose between matching loads vs matching opcodes. This is what these
1066     // scores are helping us with: they provide the order of preference. Also,
1067     // this is important if the scalar is externally used or used in another
1068     // tree entry node in the different lane.
1069 
1070     /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]).
1071     static const int ScoreConsecutiveLoads = 4;
1072     /// The same load multiple times. This should have a better score than
1073     /// `ScoreSplat` because it in x86 for a 2-lane vector we can represent it
1074     /// with `movddup (%reg), xmm0` which has a throughput of 0.5 versus 0.5 for
1075     /// a vector load and 1.0 for a broadcast.
1076     static const int ScoreSplatLoads = 3;
1077     /// Loads from reversed memory addresses, e.g. load(A[i+1]), load(A[i]).
1078     static const int ScoreReversedLoads = 3;
1079     /// ExtractElementInst from same vector and consecutive indexes.
1080     static const int ScoreConsecutiveExtracts = 4;
1081     /// ExtractElementInst from same vector and reversed indices.
1082     static const int ScoreReversedExtracts = 3;
1083     /// Constants.
1084     static const int ScoreConstants = 2;
1085     /// Instructions with the same opcode.
1086     static const int ScoreSameOpcode = 2;
1087     /// Instructions with alt opcodes (e.g, add + sub).
1088     static const int ScoreAltOpcodes = 1;
1089     /// Identical instructions (a.k.a. splat or broadcast).
1090     static const int ScoreSplat = 1;
1091     /// Matching with an undef is preferable to failing.
1092     static const int ScoreUndef = 1;
1093     /// Score for failing to find a decent match.
1094     static const int ScoreFail = 0;
1095     /// Score if all users are vectorized.
1096     static const int ScoreAllUserVectorized = 1;
1097 
1098     /// \returns the score of placing \p V1 and \p V2 in consecutive lanes.
1099     /// \p U1 and \p U2 are the users of \p V1 and \p V2.
1100     /// Also, checks if \p V1 and \p V2 are compatible with instructions in \p
1101     /// MainAltOps.
1102     int getShallowScore(Value *V1, Value *V2, Instruction *U1, Instruction *U2,
1103                         ArrayRef<Value *> MainAltOps) const {
1104       if (V1 == V2) {
1105         if (isa<LoadInst>(V1)) {
1106           // Retruns true if the users of V1 and V2 won't need to be extracted.
1107           auto AllUsersAreInternal = [U1, U2, this](Value *V1, Value *V2) {
1108             // Bail out if we have too many uses to save compilation time.
1109             static constexpr unsigned Limit = 8;
1110             if (V1->hasNUsesOrMore(Limit) || V2->hasNUsesOrMore(Limit))
1111               return false;
1112 
1113             auto AllUsersVectorized = [U1, U2, this](Value *V) {
1114               return llvm::all_of(V->users(), [U1, U2, this](Value *U) {
1115                 return U == U1 || U == U2 || R.getTreeEntry(U) != nullptr;
1116               });
1117             };
1118             return AllUsersVectorized(V1) && AllUsersVectorized(V2);
1119           };
1120           // A broadcast of a load can be cheaper on some targets.
1121           if (R.TTI->isLegalBroadcastLoad(V1->getType(),
1122                                           ElementCount::getFixed(NumLanes)) &&
1123               ((int)V1->getNumUses() == NumLanes ||
1124                AllUsersAreInternal(V1, V2)))
1125             return LookAheadHeuristics::ScoreSplatLoads;
1126         }
1127         return LookAheadHeuristics::ScoreSplat;
1128       }
1129 
1130       auto *LI1 = dyn_cast<LoadInst>(V1);
1131       auto *LI2 = dyn_cast<LoadInst>(V2);
1132       if (LI1 && LI2) {
1133         if (LI1->getParent() != LI2->getParent())
1134           return LookAheadHeuristics::ScoreFail;
1135 
1136         Optional<int> Dist = getPointersDiff(
1137             LI1->getType(), LI1->getPointerOperand(), LI2->getType(),
1138             LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true);
1139         if (!Dist || *Dist == 0)
1140           return LookAheadHeuristics::ScoreFail;
1141         // The distance is too large - still may be profitable to use masked
1142         // loads/gathers.
1143         if (std::abs(*Dist) > NumLanes / 2)
1144           return LookAheadHeuristics::ScoreAltOpcodes;
1145         // This still will detect consecutive loads, but we might have "holes"
1146         // in some cases. It is ok for non-power-2 vectorization and may produce
1147         // better results. It should not affect current vectorization.
1148         return (*Dist > 0) ? LookAheadHeuristics::ScoreConsecutiveLoads
1149                            : LookAheadHeuristics::ScoreReversedLoads;
1150       }
1151 
1152       auto *C1 = dyn_cast<Constant>(V1);
1153       auto *C2 = dyn_cast<Constant>(V2);
1154       if (C1 && C2)
1155         return LookAheadHeuristics::ScoreConstants;
1156 
1157       // Extracts from consecutive indexes of the same vector better score as
1158       // the extracts could be optimized away.
1159       Value *EV1;
1160       ConstantInt *Ex1Idx;
1161       if (match(V1, m_ExtractElt(m_Value(EV1), m_ConstantInt(Ex1Idx)))) {
1162         // Undefs are always profitable for extractelements.
1163         if (isa<UndefValue>(V2))
1164           return LookAheadHeuristics::ScoreConsecutiveExtracts;
1165         Value *EV2 = nullptr;
1166         ConstantInt *Ex2Idx = nullptr;
1167         if (match(V2,
1168                   m_ExtractElt(m_Value(EV2), m_CombineOr(m_ConstantInt(Ex2Idx),
1169                                                          m_Undef())))) {
1170           // Undefs are always profitable for extractelements.
1171           if (!Ex2Idx)
1172             return LookAheadHeuristics::ScoreConsecutiveExtracts;
1173           if (isUndefVector(EV2) && EV2->getType() == EV1->getType())
1174             return LookAheadHeuristics::ScoreConsecutiveExtracts;
1175           if (EV2 == EV1) {
1176             int Idx1 = Ex1Idx->getZExtValue();
1177             int Idx2 = Ex2Idx->getZExtValue();
1178             int Dist = Idx2 - Idx1;
1179             // The distance is too large - still may be profitable to use
1180             // shuffles.
1181             if (std::abs(Dist) == 0)
1182               return LookAheadHeuristics::ScoreSplat;
1183             if (std::abs(Dist) > NumLanes / 2)
1184               return LookAheadHeuristics::ScoreSameOpcode;
1185             return (Dist > 0) ? LookAheadHeuristics::ScoreConsecutiveExtracts
1186                               : LookAheadHeuristics::ScoreReversedExtracts;
1187           }
1188           return LookAheadHeuristics::ScoreAltOpcodes;
1189         }
1190         return LookAheadHeuristics::ScoreFail;
1191       }
1192 
1193       auto *I1 = dyn_cast<Instruction>(V1);
1194       auto *I2 = dyn_cast<Instruction>(V2);
1195       if (I1 && I2) {
1196         if (I1->getParent() != I2->getParent())
1197           return LookAheadHeuristics::ScoreFail;
1198         SmallVector<Value *, 4> Ops(MainAltOps.begin(), MainAltOps.end());
1199         Ops.push_back(I1);
1200         Ops.push_back(I2);
1201         InstructionsState S = getSameOpcode(Ops);
1202         // Note: Only consider instructions with <= 2 operands to avoid
1203         // complexity explosion.
1204         if (S.getOpcode() &&
1205             (S.MainOp->getNumOperands() <= 2 || !MainAltOps.empty() ||
1206              !S.isAltShuffle()) &&
1207             all_of(Ops, [&S](Value *V) {
1208               return cast<Instruction>(V)->getNumOperands() ==
1209                      S.MainOp->getNumOperands();
1210             }))
1211           return S.isAltShuffle() ? LookAheadHeuristics::ScoreAltOpcodes
1212                                   : LookAheadHeuristics::ScoreSameOpcode;
1213       }
1214 
1215       if (isa<UndefValue>(V2))
1216         return LookAheadHeuristics::ScoreUndef;
1217 
1218       return LookAheadHeuristics::ScoreFail;
1219     }
1220 
1221     /// Go through the operands of \p LHS and \p RHS recursively until
1222     /// MaxLevel, and return the cummulative score. \p U1 and \p U2 are
1223     /// the users of \p LHS and \p RHS (that is \p LHS and \p RHS are operands
1224     /// of \p U1 and \p U2), except at the beginning of the recursion where
1225     /// these are set to nullptr.
1226     ///
1227     /// For example:
1228     /// \verbatim
1229     ///  A[0]  B[0]  A[1]  B[1]  C[0] D[0]  B[1] A[1]
1230     ///     \ /         \ /         \ /        \ /
1231     ///      +           +           +          +
1232     ///     G1          G2          G3         G4
1233     /// \endverbatim
1234     /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at
1235     /// each level recursively, accumulating the score. It starts from matching
1236     /// the additions at level 0, then moves on to the loads (level 1). The
1237     /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and
1238     /// {B[0],B[1]} match with LookAheadHeuristics::ScoreConsecutiveLoads, while
1239     /// {A[0],C[0]} has a score of LookAheadHeuristics::ScoreFail.
1240     /// Please note that the order of the operands does not matter, as we
1241     /// evaluate the score of all profitable combinations of operands. In
1242     /// other words the score of G1 and G4 is the same as G1 and G2. This
1243     /// heuristic is based on ideas described in:
1244     ///   Look-ahead SLP: Auto-vectorization in the presence of commutative
1245     ///   operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha,
1246     ///   Luís F. W. Góes
1247     int getScoreAtLevelRec(Value *LHS, Value *RHS, Instruction *U1,
1248                            Instruction *U2, int CurrLevel,
1249                            ArrayRef<Value *> MainAltOps) const {
1250 
1251       // Get the shallow score of V1 and V2.
1252       int ShallowScoreAtThisLevel =
1253           getShallowScore(LHS, RHS, U1, U2, MainAltOps);
1254 
1255       // If reached MaxLevel,
1256       //  or if V1 and V2 are not instructions,
1257       //  or if they are SPLAT,
1258       //  or if they are not consecutive,
1259       //  or if profitable to vectorize loads or extractelements, early return
1260       //  the current cost.
1261       auto *I1 = dyn_cast<Instruction>(LHS);
1262       auto *I2 = dyn_cast<Instruction>(RHS);
1263       if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 ||
1264           ShallowScoreAtThisLevel == LookAheadHeuristics::ScoreFail ||
1265           (((isa<LoadInst>(I1) && isa<LoadInst>(I2)) ||
1266             (I1->getNumOperands() > 2 && I2->getNumOperands() > 2) ||
1267             (isa<ExtractElementInst>(I1) && isa<ExtractElementInst>(I2))) &&
1268            ShallowScoreAtThisLevel))
1269         return ShallowScoreAtThisLevel;
1270       assert(I1 && I2 && "Should have early exited.");
1271 
1272       // Contains the I2 operand indexes that got matched with I1 operands.
1273       SmallSet<unsigned, 4> Op2Used;
1274 
1275       // Recursion towards the operands of I1 and I2. We are trying all possible
1276       // operand pairs, and keeping track of the best score.
1277       for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands();
1278            OpIdx1 != NumOperands1; ++OpIdx1) {
1279         // Try to pair op1I with the best operand of I2.
1280         int MaxTmpScore = 0;
1281         unsigned MaxOpIdx2 = 0;
1282         bool FoundBest = false;
1283         // If I2 is commutative try all combinations.
1284         unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1;
1285         unsigned ToIdx = isCommutative(I2)
1286                              ? I2->getNumOperands()
1287                              : std::min(I2->getNumOperands(), OpIdx1 + 1);
1288         assert(FromIdx <= ToIdx && "Bad index");
1289         for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) {
1290           // Skip operands already paired with OpIdx1.
1291           if (Op2Used.count(OpIdx2))
1292             continue;
1293           // Recursively calculate the cost at each level
1294           int TmpScore =
1295               getScoreAtLevelRec(I1->getOperand(OpIdx1), I2->getOperand(OpIdx2),
1296                                  I1, I2, CurrLevel + 1, None);
1297           // Look for the best score.
1298           if (TmpScore > LookAheadHeuristics::ScoreFail &&
1299               TmpScore > MaxTmpScore) {
1300             MaxTmpScore = TmpScore;
1301             MaxOpIdx2 = OpIdx2;
1302             FoundBest = true;
1303           }
1304         }
1305         if (FoundBest) {
1306           // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it.
1307           Op2Used.insert(MaxOpIdx2);
1308           ShallowScoreAtThisLevel += MaxTmpScore;
1309         }
1310       }
1311       return ShallowScoreAtThisLevel;
1312     }
1313   };
1314   /// A helper data structure to hold the operands of a vector of instructions.
1315   /// This supports a fixed vector length for all operand vectors.
1316   class VLOperands {
1317     /// For each operand we need (i) the value, and (ii) the opcode that it
1318     /// would be attached to if the expression was in a left-linearized form.
1319     /// This is required to avoid illegal operand reordering.
1320     /// For example:
1321     /// \verbatim
1322     ///                         0 Op1
1323     ///                         |/
1324     /// Op1 Op2   Linearized    + Op2
1325     ///   \ /     ---------->   |/
1326     ///    -                    -
1327     ///
1328     /// Op1 - Op2            (0 + Op1) - Op2
1329     /// \endverbatim
1330     ///
1331     /// Value Op1 is attached to a '+' operation, and Op2 to a '-'.
1332     ///
1333     /// Another way to think of this is to track all the operations across the
1334     /// path from the operand all the way to the root of the tree and to
1335     /// calculate the operation that corresponds to this path. For example, the
1336     /// path from Op2 to the root crosses the RHS of the '-', therefore the
1337     /// corresponding operation is a '-' (which matches the one in the
1338     /// linearized tree, as shown above).
1339     ///
1340     /// For lack of a better term, we refer to this operation as Accumulated
1341     /// Path Operation (APO).
1342     struct OperandData {
1343       OperandData() = default;
1344       OperandData(Value *V, bool APO, bool IsUsed)
1345           : V(V), APO(APO), IsUsed(IsUsed) {}
1346       /// The operand value.
1347       Value *V = nullptr;
1348       /// TreeEntries only allow a single opcode, or an alternate sequence of
1349       /// them (e.g, +, -). Therefore, we can safely use a boolean value for the
1350       /// APO. It is set to 'true' if 'V' is attached to an inverse operation
1351       /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise
1352       /// (e.g., Add/Mul)
1353       bool APO = false;
1354       /// Helper data for the reordering function.
1355       bool IsUsed = false;
1356     };
1357 
1358     /// During operand reordering, we are trying to select the operand at lane
1359     /// that matches best with the operand at the neighboring lane. Our
1360     /// selection is based on the type of value we are looking for. For example,
1361     /// if the neighboring lane has a load, we need to look for a load that is
1362     /// accessing a consecutive address. These strategies are summarized in the
1363     /// 'ReorderingMode' enumerator.
1364     enum class ReorderingMode {
1365       Load,     ///< Matching loads to consecutive memory addresses
1366       Opcode,   ///< Matching instructions based on opcode (same or alternate)
1367       Constant, ///< Matching constants
1368       Splat,    ///< Matching the same instruction multiple times (broadcast)
1369       Failed,   ///< We failed to create a vectorizable group
1370     };
1371 
1372     using OperandDataVec = SmallVector<OperandData, 2>;
1373 
1374     /// A vector of operand vectors.
1375     SmallVector<OperandDataVec, 4> OpsVec;
1376 
1377     const DataLayout &DL;
1378     ScalarEvolution &SE;
1379     const BoUpSLP &R;
1380 
1381     /// \returns the operand data at \p OpIdx and \p Lane.
1382     OperandData &getData(unsigned OpIdx, unsigned Lane) {
1383       return OpsVec[OpIdx][Lane];
1384     }
1385 
1386     /// \returns the operand data at \p OpIdx and \p Lane. Const version.
1387     const OperandData &getData(unsigned OpIdx, unsigned Lane) const {
1388       return OpsVec[OpIdx][Lane];
1389     }
1390 
1391     /// Clears the used flag for all entries.
1392     void clearUsed() {
1393       for (unsigned OpIdx = 0, NumOperands = getNumOperands();
1394            OpIdx != NumOperands; ++OpIdx)
1395         for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
1396              ++Lane)
1397           OpsVec[OpIdx][Lane].IsUsed = false;
1398     }
1399 
1400     /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2.
1401     void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) {
1402       std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]);
1403     }
1404 
1405     /// \param Lane lane of the operands under analysis.
1406     /// \param OpIdx operand index in \p Lane lane we're looking the best
1407     /// candidate for.
1408     /// \param Idx operand index of the current candidate value.
1409     /// \returns The additional score due to possible broadcasting of the
1410     /// elements in the lane. It is more profitable to have power-of-2 unique
1411     /// elements in the lane, it will be vectorized with higher probability
1412     /// after removing duplicates. Currently the SLP vectorizer supports only
1413     /// vectorization of the power-of-2 number of unique scalars.
1414     int getSplatScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1415       Value *IdxLaneV = getData(Idx, Lane).V;
1416       if (!isa<Instruction>(IdxLaneV) || IdxLaneV == getData(OpIdx, Lane).V)
1417         return 0;
1418       SmallPtrSet<Value *, 4> Uniques;
1419       for (unsigned Ln = 0, E = getNumLanes(); Ln < E; ++Ln) {
1420         if (Ln == Lane)
1421           continue;
1422         Value *OpIdxLnV = getData(OpIdx, Ln).V;
1423         if (!isa<Instruction>(OpIdxLnV))
1424           return 0;
1425         Uniques.insert(OpIdxLnV);
1426       }
1427       int UniquesCount = Uniques.size();
1428       int UniquesCntWithIdxLaneV =
1429           Uniques.contains(IdxLaneV) ? UniquesCount : UniquesCount + 1;
1430       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1431       int UniquesCntWithOpIdxLaneV =
1432           Uniques.contains(OpIdxLaneV) ? UniquesCount : UniquesCount + 1;
1433       if (UniquesCntWithIdxLaneV == UniquesCntWithOpIdxLaneV)
1434         return 0;
1435       return (PowerOf2Ceil(UniquesCntWithOpIdxLaneV) -
1436               UniquesCntWithOpIdxLaneV) -
1437              (PowerOf2Ceil(UniquesCntWithIdxLaneV) - UniquesCntWithIdxLaneV);
1438     }
1439 
1440     /// \param Lane lane of the operands under analysis.
1441     /// \param OpIdx operand index in \p Lane lane we're looking the best
1442     /// candidate for.
1443     /// \param Idx operand index of the current candidate value.
1444     /// \returns The additional score for the scalar which users are all
1445     /// vectorized.
1446     int getExternalUseScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1447       Value *IdxLaneV = getData(Idx, Lane).V;
1448       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1449       // Do not care about number of uses for vector-like instructions
1450       // (extractelement/extractvalue with constant indices), they are extracts
1451       // themselves and already externally used. Vectorization of such
1452       // instructions does not add extra extractelement instruction, just may
1453       // remove it.
1454       if (isVectorLikeInstWithConstOps(IdxLaneV) &&
1455           isVectorLikeInstWithConstOps(OpIdxLaneV))
1456         return LookAheadHeuristics::ScoreAllUserVectorized;
1457       auto *IdxLaneI = dyn_cast<Instruction>(IdxLaneV);
1458       if (!IdxLaneI || !isa<Instruction>(OpIdxLaneV))
1459         return 0;
1460       return R.areAllUsersVectorized(IdxLaneI, None)
1461                  ? LookAheadHeuristics::ScoreAllUserVectorized
1462                  : 0;
1463     }
1464 
1465     /// Score scaling factor for fully compatible instructions but with
1466     /// different number of external uses. Allows better selection of the
1467     /// instructions with less external uses.
1468     static const int ScoreScaleFactor = 10;
1469 
1470     /// \Returns the look-ahead score, which tells us how much the sub-trees
1471     /// rooted at \p LHS and \p RHS match, the more they match the higher the
1472     /// score. This helps break ties in an informed way when we cannot decide on
1473     /// the order of the operands by just considering the immediate
1474     /// predecessors.
1475     int getLookAheadScore(Value *LHS, Value *RHS, ArrayRef<Value *> MainAltOps,
1476                           int Lane, unsigned OpIdx, unsigned Idx,
1477                           bool &IsUsed) {
1478       LookAheadHeuristics LookAhead(DL, SE, R, getNumLanes(),
1479                                     LookAheadMaxDepth);
1480       // Keep track of the instruction stack as we recurse into the operands
1481       // during the look-ahead score exploration.
1482       int Score =
1483           LookAhead.getScoreAtLevelRec(LHS, RHS, /*U1=*/nullptr, /*U2=*/nullptr,
1484                                        /*CurrLevel=*/1, MainAltOps);
1485       if (Score) {
1486         int SplatScore = getSplatScore(Lane, OpIdx, Idx);
1487         if (Score <= -SplatScore) {
1488           // Set the minimum score for splat-like sequence to avoid setting
1489           // failed state.
1490           Score = 1;
1491         } else {
1492           Score += SplatScore;
1493           // Scale score to see the difference between different operands
1494           // and similar operands but all vectorized/not all vectorized
1495           // uses. It does not affect actual selection of the best
1496           // compatible operand in general, just allows to select the
1497           // operand with all vectorized uses.
1498           Score *= ScoreScaleFactor;
1499           Score += getExternalUseScore(Lane, OpIdx, Idx);
1500           IsUsed = true;
1501         }
1502       }
1503       return Score;
1504     }
1505 
1506     /// Best defined scores per lanes between the passes. Used to choose the
1507     /// best operand (with the highest score) between the passes.
1508     /// The key - {Operand Index, Lane}.
1509     /// The value - the best score between the passes for the lane and the
1510     /// operand.
1511     SmallDenseMap<std::pair<unsigned, unsigned>, unsigned, 8>
1512         BestScoresPerLanes;
1513 
1514     // Search all operands in Ops[*][Lane] for the one that matches best
1515     // Ops[OpIdx][LastLane] and return its opreand index.
1516     // If no good match can be found, return None.
1517     Optional<unsigned> getBestOperand(unsigned OpIdx, int Lane, int LastLane,
1518                                       ArrayRef<ReorderingMode> ReorderingModes,
1519                                       ArrayRef<Value *> MainAltOps) {
1520       unsigned NumOperands = getNumOperands();
1521 
1522       // The operand of the previous lane at OpIdx.
1523       Value *OpLastLane = getData(OpIdx, LastLane).V;
1524 
1525       // Our strategy mode for OpIdx.
1526       ReorderingMode RMode = ReorderingModes[OpIdx];
1527       if (RMode == ReorderingMode::Failed)
1528         return None;
1529 
1530       // The linearized opcode of the operand at OpIdx, Lane.
1531       bool OpIdxAPO = getData(OpIdx, Lane).APO;
1532 
1533       // The best operand index and its score.
1534       // Sometimes we have more than one option (e.g., Opcode and Undefs), so we
1535       // are using the score to differentiate between the two.
1536       struct BestOpData {
1537         Optional<unsigned> Idx = None;
1538         unsigned Score = 0;
1539       } BestOp;
1540       BestOp.Score =
1541           BestScoresPerLanes.try_emplace(std::make_pair(OpIdx, Lane), 0)
1542               .first->second;
1543 
1544       // Track if the operand must be marked as used. If the operand is set to
1545       // Score 1 explicitly (because of non power-of-2 unique scalars, we may
1546       // want to reestimate the operands again on the following iterations).
1547       bool IsUsed =
1548           RMode == ReorderingMode::Splat || RMode == ReorderingMode::Constant;
1549       // Iterate through all unused operands and look for the best.
1550       for (unsigned Idx = 0; Idx != NumOperands; ++Idx) {
1551         // Get the operand at Idx and Lane.
1552         OperandData &OpData = getData(Idx, Lane);
1553         Value *Op = OpData.V;
1554         bool OpAPO = OpData.APO;
1555 
1556         // Skip already selected operands.
1557         if (OpData.IsUsed)
1558           continue;
1559 
1560         // Skip if we are trying to move the operand to a position with a
1561         // different opcode in the linearized tree form. This would break the
1562         // semantics.
1563         if (OpAPO != OpIdxAPO)
1564           continue;
1565 
1566         // Look for an operand that matches the current mode.
1567         switch (RMode) {
1568         case ReorderingMode::Load:
1569         case ReorderingMode::Constant:
1570         case ReorderingMode::Opcode: {
1571           bool LeftToRight = Lane > LastLane;
1572           Value *OpLeft = (LeftToRight) ? OpLastLane : Op;
1573           Value *OpRight = (LeftToRight) ? Op : OpLastLane;
1574           int Score = getLookAheadScore(OpLeft, OpRight, MainAltOps, Lane,
1575                                         OpIdx, Idx, IsUsed);
1576           if (Score > static_cast<int>(BestOp.Score)) {
1577             BestOp.Idx = Idx;
1578             BestOp.Score = Score;
1579             BestScoresPerLanes[std::make_pair(OpIdx, Lane)] = Score;
1580           }
1581           break;
1582         }
1583         case ReorderingMode::Splat:
1584           if (Op == OpLastLane)
1585             BestOp.Idx = Idx;
1586           break;
1587         case ReorderingMode::Failed:
1588           llvm_unreachable("Not expected Failed reordering mode.");
1589         }
1590       }
1591 
1592       if (BestOp.Idx) {
1593         getData(BestOp.Idx.getValue(), Lane).IsUsed = IsUsed;
1594         return BestOp.Idx;
1595       }
1596       // If we could not find a good match return None.
1597       return None;
1598     }
1599 
1600     /// Helper for reorderOperandVecs.
1601     /// \returns the lane that we should start reordering from. This is the one
1602     /// which has the least number of operands that can freely move about or
1603     /// less profitable because it already has the most optimal set of operands.
1604     unsigned getBestLaneToStartReordering() const {
1605       unsigned Min = UINT_MAX;
1606       unsigned SameOpNumber = 0;
1607       // std::pair<unsigned, unsigned> is used to implement a simple voting
1608       // algorithm and choose the lane with the least number of operands that
1609       // can freely move about or less profitable because it already has the
1610       // most optimal set of operands. The first unsigned is a counter for
1611       // voting, the second unsigned is the counter of lanes with instructions
1612       // with same/alternate opcodes and same parent basic block.
1613       MapVector<unsigned, std::pair<unsigned, unsigned>> HashMap;
1614       // Try to be closer to the original results, if we have multiple lanes
1615       // with same cost. If 2 lanes have the same cost, use the one with the
1616       // lowest index.
1617       for (int I = getNumLanes(); I > 0; --I) {
1618         unsigned Lane = I - 1;
1619         OperandsOrderData NumFreeOpsHash =
1620             getMaxNumOperandsThatCanBeReordered(Lane);
1621         // Compare the number of operands that can move and choose the one with
1622         // the least number.
1623         if (NumFreeOpsHash.NumOfAPOs < Min) {
1624           Min = NumFreeOpsHash.NumOfAPOs;
1625           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1626           HashMap.clear();
1627           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1628         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1629                    NumFreeOpsHash.NumOpsWithSameOpcodeParent < SameOpNumber) {
1630           // Select the most optimal lane in terms of number of operands that
1631           // should be moved around.
1632           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1633           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1634         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1635                    NumFreeOpsHash.NumOpsWithSameOpcodeParent == SameOpNumber) {
1636           auto It = HashMap.find(NumFreeOpsHash.Hash);
1637           if (It == HashMap.end())
1638             HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1639           else
1640             ++It->second.first;
1641         }
1642       }
1643       // Select the lane with the minimum counter.
1644       unsigned BestLane = 0;
1645       unsigned CntMin = UINT_MAX;
1646       for (const auto &Data : reverse(HashMap)) {
1647         if (Data.second.first < CntMin) {
1648           CntMin = Data.second.first;
1649           BestLane = Data.second.second;
1650         }
1651       }
1652       return BestLane;
1653     }
1654 
1655     /// Data structure that helps to reorder operands.
1656     struct OperandsOrderData {
1657       /// The best number of operands with the same APOs, which can be
1658       /// reordered.
1659       unsigned NumOfAPOs = UINT_MAX;
1660       /// Number of operands with the same/alternate instruction opcode and
1661       /// parent.
1662       unsigned NumOpsWithSameOpcodeParent = 0;
1663       /// Hash for the actual operands ordering.
1664       /// Used to count operands, actually their position id and opcode
1665       /// value. It is used in the voting mechanism to find the lane with the
1666       /// least number of operands that can freely move about or less profitable
1667       /// because it already has the most optimal set of operands. Can be
1668       /// replaced with SmallVector<unsigned> instead but hash code is faster
1669       /// and requires less memory.
1670       unsigned Hash = 0;
1671     };
1672     /// \returns the maximum number of operands that are allowed to be reordered
1673     /// for \p Lane and the number of compatible instructions(with the same
1674     /// parent/opcode). This is used as a heuristic for selecting the first lane
1675     /// to start operand reordering.
1676     OperandsOrderData getMaxNumOperandsThatCanBeReordered(unsigned Lane) const {
1677       unsigned CntTrue = 0;
1678       unsigned NumOperands = getNumOperands();
1679       // Operands with the same APO can be reordered. We therefore need to count
1680       // how many of them we have for each APO, like this: Cnt[APO] = x.
1681       // Since we only have two APOs, namely true and false, we can avoid using
1682       // a map. Instead we can simply count the number of operands that
1683       // correspond to one of them (in this case the 'true' APO), and calculate
1684       // the other by subtracting it from the total number of operands.
1685       // Operands with the same instruction opcode and parent are more
1686       // profitable since we don't need to move them in many cases, with a high
1687       // probability such lane already can be vectorized effectively.
1688       bool AllUndefs = true;
1689       unsigned NumOpsWithSameOpcodeParent = 0;
1690       Instruction *OpcodeI = nullptr;
1691       BasicBlock *Parent = nullptr;
1692       unsigned Hash = 0;
1693       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1694         const OperandData &OpData = getData(OpIdx, Lane);
1695         if (OpData.APO)
1696           ++CntTrue;
1697         // Use Boyer-Moore majority voting for finding the majority opcode and
1698         // the number of times it occurs.
1699         if (auto *I = dyn_cast<Instruction>(OpData.V)) {
1700           if (!OpcodeI || !getSameOpcode({OpcodeI, I}).getOpcode() ||
1701               I->getParent() != Parent) {
1702             if (NumOpsWithSameOpcodeParent == 0) {
1703               NumOpsWithSameOpcodeParent = 1;
1704               OpcodeI = I;
1705               Parent = I->getParent();
1706             } else {
1707               --NumOpsWithSameOpcodeParent;
1708             }
1709           } else {
1710             ++NumOpsWithSameOpcodeParent;
1711           }
1712         }
1713         Hash = hash_combine(
1714             Hash, hash_value((OpIdx + 1) * (OpData.V->getValueID() + 1)));
1715         AllUndefs = AllUndefs && isa<UndefValue>(OpData.V);
1716       }
1717       if (AllUndefs)
1718         return {};
1719       OperandsOrderData Data;
1720       Data.NumOfAPOs = std::max(CntTrue, NumOperands - CntTrue);
1721       Data.NumOpsWithSameOpcodeParent = NumOpsWithSameOpcodeParent;
1722       Data.Hash = Hash;
1723       return Data;
1724     }
1725 
1726     /// Go through the instructions in VL and append their operands.
1727     void appendOperandsOfVL(ArrayRef<Value *> VL) {
1728       assert(!VL.empty() && "Bad VL");
1729       assert((empty() || VL.size() == getNumLanes()) &&
1730              "Expected same number of lanes");
1731       assert(isa<Instruction>(VL[0]) && "Expected instruction");
1732       unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands();
1733       OpsVec.resize(NumOperands);
1734       unsigned NumLanes = VL.size();
1735       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1736         OpsVec[OpIdx].resize(NumLanes);
1737         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1738           assert(isa<Instruction>(VL[Lane]) && "Expected instruction");
1739           // Our tree has just 3 nodes: the root and two operands.
1740           // It is therefore trivial to get the APO. We only need to check the
1741           // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or
1742           // RHS operand. The LHS operand of both add and sub is never attached
1743           // to an inversese operation in the linearized form, therefore its APO
1744           // is false. The RHS is true only if VL[Lane] is an inverse operation.
1745 
1746           // Since operand reordering is performed on groups of commutative
1747           // operations or alternating sequences (e.g., +, -), we can safely
1748           // tell the inverse operations by checking commutativity.
1749           bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane]));
1750           bool APO = (OpIdx == 0) ? false : IsInverseOperation;
1751           OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx),
1752                                  APO, false};
1753         }
1754       }
1755     }
1756 
1757     /// \returns the number of operands.
1758     unsigned getNumOperands() const { return OpsVec.size(); }
1759 
1760     /// \returns the number of lanes.
1761     unsigned getNumLanes() const { return OpsVec[0].size(); }
1762 
1763     /// \returns the operand value at \p OpIdx and \p Lane.
1764     Value *getValue(unsigned OpIdx, unsigned Lane) const {
1765       return getData(OpIdx, Lane).V;
1766     }
1767 
1768     /// \returns true if the data structure is empty.
1769     bool empty() const { return OpsVec.empty(); }
1770 
1771     /// Clears the data.
1772     void clear() { OpsVec.clear(); }
1773 
1774     /// \Returns true if there are enough operands identical to \p Op to fill
1775     /// the whole vector.
1776     /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow.
1777     bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) {
1778       bool OpAPO = getData(OpIdx, Lane).APO;
1779       for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) {
1780         if (Ln == Lane)
1781           continue;
1782         // This is set to true if we found a candidate for broadcast at Lane.
1783         bool FoundCandidate = false;
1784         for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) {
1785           OperandData &Data = getData(OpI, Ln);
1786           if (Data.APO != OpAPO || Data.IsUsed)
1787             continue;
1788           if (Data.V == Op) {
1789             FoundCandidate = true;
1790             Data.IsUsed = true;
1791             break;
1792           }
1793         }
1794         if (!FoundCandidate)
1795           return false;
1796       }
1797       return true;
1798     }
1799 
1800   public:
1801     /// Initialize with all the operands of the instruction vector \p RootVL.
1802     VLOperands(ArrayRef<Value *> RootVL, const DataLayout &DL,
1803                ScalarEvolution &SE, const BoUpSLP &R)
1804         : DL(DL), SE(SE), R(R) {
1805       // Append all the operands of RootVL.
1806       appendOperandsOfVL(RootVL);
1807     }
1808 
1809     /// \Returns a value vector with the operands across all lanes for the
1810     /// opearnd at \p OpIdx.
1811     ValueList getVL(unsigned OpIdx) const {
1812       ValueList OpVL(OpsVec[OpIdx].size());
1813       assert(OpsVec[OpIdx].size() == getNumLanes() &&
1814              "Expected same num of lanes across all operands");
1815       for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane)
1816         OpVL[Lane] = OpsVec[OpIdx][Lane].V;
1817       return OpVL;
1818     }
1819 
1820     // Performs operand reordering for 2 or more operands.
1821     // The original operands are in OrigOps[OpIdx][Lane].
1822     // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'.
1823     void reorder() {
1824       unsigned NumOperands = getNumOperands();
1825       unsigned NumLanes = getNumLanes();
1826       // Each operand has its own mode. We are using this mode to help us select
1827       // the instructions for each lane, so that they match best with the ones
1828       // we have selected so far.
1829       SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands);
1830 
1831       // This is a greedy single-pass algorithm. We are going over each lane
1832       // once and deciding on the best order right away with no back-tracking.
1833       // However, in order to increase its effectiveness, we start with the lane
1834       // that has operands that can move the least. For example, given the
1835       // following lanes:
1836       //  Lane 0 : A[0] = B[0] + C[0]   // Visited 3rd
1837       //  Lane 1 : A[1] = C[1] - B[1]   // Visited 1st
1838       //  Lane 2 : A[2] = B[2] + C[2]   // Visited 2nd
1839       //  Lane 3 : A[3] = C[3] - B[3]   // Visited 4th
1840       // we will start at Lane 1, since the operands of the subtraction cannot
1841       // be reordered. Then we will visit the rest of the lanes in a circular
1842       // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3.
1843 
1844       // Find the first lane that we will start our search from.
1845       unsigned FirstLane = getBestLaneToStartReordering();
1846 
1847       // Initialize the modes.
1848       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1849         Value *OpLane0 = getValue(OpIdx, FirstLane);
1850         // Keep track if we have instructions with all the same opcode on one
1851         // side.
1852         if (isa<LoadInst>(OpLane0))
1853           ReorderingModes[OpIdx] = ReorderingMode::Load;
1854         else if (isa<Instruction>(OpLane0)) {
1855           // Check if OpLane0 should be broadcast.
1856           if (shouldBroadcast(OpLane0, OpIdx, FirstLane))
1857             ReorderingModes[OpIdx] = ReorderingMode::Splat;
1858           else
1859             ReorderingModes[OpIdx] = ReorderingMode::Opcode;
1860         }
1861         else if (isa<Constant>(OpLane0))
1862           ReorderingModes[OpIdx] = ReorderingMode::Constant;
1863         else if (isa<Argument>(OpLane0))
1864           // Our best hope is a Splat. It may save some cost in some cases.
1865           ReorderingModes[OpIdx] = ReorderingMode::Splat;
1866         else
1867           // NOTE: This should be unreachable.
1868           ReorderingModes[OpIdx] = ReorderingMode::Failed;
1869       }
1870 
1871       // Check that we don't have same operands. No need to reorder if operands
1872       // are just perfect diamond or shuffled diamond match. Do not do it only
1873       // for possible broadcasts or non-power of 2 number of scalars (just for
1874       // now).
1875       auto &&SkipReordering = [this]() {
1876         SmallPtrSet<Value *, 4> UniqueValues;
1877         ArrayRef<OperandData> Op0 = OpsVec.front();
1878         for (const OperandData &Data : Op0)
1879           UniqueValues.insert(Data.V);
1880         for (ArrayRef<OperandData> Op : drop_begin(OpsVec, 1)) {
1881           if (any_of(Op, [&UniqueValues](const OperandData &Data) {
1882                 return !UniqueValues.contains(Data.V);
1883               }))
1884             return false;
1885         }
1886         // TODO: Check if we can remove a check for non-power-2 number of
1887         // scalars after full support of non-power-2 vectorization.
1888         return UniqueValues.size() != 2 && isPowerOf2_32(UniqueValues.size());
1889       };
1890 
1891       // If the initial strategy fails for any of the operand indexes, then we
1892       // perform reordering again in a second pass. This helps avoid assigning
1893       // high priority to the failed strategy, and should improve reordering for
1894       // the non-failed operand indexes.
1895       for (int Pass = 0; Pass != 2; ++Pass) {
1896         // Check if no need to reorder operands since they're are perfect or
1897         // shuffled diamond match.
1898         // Need to to do it to avoid extra external use cost counting for
1899         // shuffled matches, which may cause regressions.
1900         if (SkipReordering())
1901           break;
1902         // Skip the second pass if the first pass did not fail.
1903         bool StrategyFailed = false;
1904         // Mark all operand data as free to use.
1905         clearUsed();
1906         // We keep the original operand order for the FirstLane, so reorder the
1907         // rest of the lanes. We are visiting the nodes in a circular fashion,
1908         // using FirstLane as the center point and increasing the radius
1909         // distance.
1910         SmallVector<SmallVector<Value *, 2>> MainAltOps(NumOperands);
1911         for (unsigned I = 0; I < NumOperands; ++I)
1912           MainAltOps[I].push_back(getData(I, FirstLane).V);
1913 
1914         for (unsigned Distance = 1; Distance != NumLanes; ++Distance) {
1915           // Visit the lane on the right and then the lane on the left.
1916           for (int Direction : {+1, -1}) {
1917             int Lane = FirstLane + Direction * Distance;
1918             if (Lane < 0 || Lane >= (int)NumLanes)
1919               continue;
1920             int LastLane = Lane - Direction;
1921             assert(LastLane >= 0 && LastLane < (int)NumLanes &&
1922                    "Out of bounds");
1923             // Look for a good match for each operand.
1924             for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1925               // Search for the operand that matches SortedOps[OpIdx][Lane-1].
1926               Optional<unsigned> BestIdx = getBestOperand(
1927                   OpIdx, Lane, LastLane, ReorderingModes, MainAltOps[OpIdx]);
1928               // By not selecting a value, we allow the operands that follow to
1929               // select a better matching value. We will get a non-null value in
1930               // the next run of getBestOperand().
1931               if (BestIdx) {
1932                 // Swap the current operand with the one returned by
1933                 // getBestOperand().
1934                 swap(OpIdx, BestIdx.getValue(), Lane);
1935               } else {
1936                 // We failed to find a best operand, set mode to 'Failed'.
1937                 ReorderingModes[OpIdx] = ReorderingMode::Failed;
1938                 // Enable the second pass.
1939                 StrategyFailed = true;
1940               }
1941               // Try to get the alternate opcode and follow it during analysis.
1942               if (MainAltOps[OpIdx].size() != 2) {
1943                 OperandData &AltOp = getData(OpIdx, Lane);
1944                 InstructionsState OpS =
1945                     getSameOpcode({MainAltOps[OpIdx].front(), AltOp.V});
1946                 if (OpS.getOpcode() && OpS.isAltShuffle())
1947                   MainAltOps[OpIdx].push_back(AltOp.V);
1948               }
1949             }
1950           }
1951         }
1952         // Skip second pass if the strategy did not fail.
1953         if (!StrategyFailed)
1954           break;
1955       }
1956     }
1957 
1958 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1959     LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) {
1960       switch (RMode) {
1961       case ReorderingMode::Load:
1962         return "Load";
1963       case ReorderingMode::Opcode:
1964         return "Opcode";
1965       case ReorderingMode::Constant:
1966         return "Constant";
1967       case ReorderingMode::Splat:
1968         return "Splat";
1969       case ReorderingMode::Failed:
1970         return "Failed";
1971       }
1972       llvm_unreachable("Unimplemented Reordering Type");
1973     }
1974 
1975     LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode,
1976                                                    raw_ostream &OS) {
1977       return OS << getModeStr(RMode);
1978     }
1979 
1980     /// Debug print.
1981     LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) {
1982       printMode(RMode, dbgs());
1983     }
1984 
1985     friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) {
1986       return printMode(RMode, OS);
1987     }
1988 
1989     LLVM_DUMP_METHOD raw_ostream &print(raw_ostream &OS) const {
1990       const unsigned Indent = 2;
1991       unsigned Cnt = 0;
1992       for (const OperandDataVec &OpDataVec : OpsVec) {
1993         OS << "Operand " << Cnt++ << "\n";
1994         for (const OperandData &OpData : OpDataVec) {
1995           OS.indent(Indent) << "{";
1996           if (Value *V = OpData.V)
1997             OS << *V;
1998           else
1999             OS << "null";
2000           OS << ", APO:" << OpData.APO << "}\n";
2001         }
2002         OS << "\n";
2003       }
2004       return OS;
2005     }
2006 
2007     /// Debug print.
2008     LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
2009 #endif
2010   };
2011 
2012   /// Evaluate each pair in \p Candidates and return index into \p Candidates
2013   /// for a pair which have highest score deemed to have best chance to form
2014   /// root of profitable tree to vectorize. Return None if no candidate scored
2015   /// above the LookAheadHeuristics::ScoreFail.
2016   Optional<int>
2017   findBestRootPair(ArrayRef<std::pair<Value *, Value *>> Candidates) {
2018     LookAheadHeuristics LookAhead(*DL, *SE, *this, /*NumLanes=*/2,
2019                                   RootLookAheadMaxDepth);
2020     int BestScore = LookAheadHeuristics::ScoreFail;
2021     Optional<int> Index = None;
2022     for (int I : seq<int>(0, Candidates.size())) {
2023       int Score = LookAhead.getScoreAtLevelRec(Candidates[I].first,
2024                                                Candidates[I].second,
2025                                                /*U1=*/nullptr, /*U2=*/nullptr,
2026                                                /*Level=*/1, None);
2027       if (Score > BestScore) {
2028         BestScore = Score;
2029         Index = I;
2030       }
2031     }
2032     return Index;
2033   }
2034 
2035   /// Checks if the instruction is marked for deletion.
2036   bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); }
2037 
2038   /// Removes an instruction from its block and eventually deletes it.
2039   /// It's like Instruction::eraseFromParent() except that the actual deletion
2040   /// is delayed until BoUpSLP is destructed.
2041   void eraseInstruction(Instruction *I) {
2042     DeletedInstructions.insert(I);
2043   }
2044 
2045   /// Checks if the instruction was already analyzed for being possible
2046   /// reduction root.
2047   bool isAnalizedReductionRoot(Instruction *I) const {
2048     return AnalizedReductionsRoots.count(I);
2049   }
2050   /// Register given instruction as already analyzed for being possible
2051   /// reduction root.
2052   void analyzedReductionRoot(Instruction *I) {
2053     AnalizedReductionsRoots.insert(I);
2054   }
2055   /// Checks if the provided list of reduced values was checked already for
2056   /// vectorization.
2057   bool areAnalyzedReductionVals(ArrayRef<Value *> VL) {
2058     return AnalyzedReductionVals.contains(hash_value(VL));
2059   }
2060   /// Adds the list of reduced values to list of already checked values for the
2061   /// vectorization.
2062   void analyzedReductionVals(ArrayRef<Value *> VL) {
2063     AnalyzedReductionVals.insert(hash_value(VL));
2064   }
2065   /// Clear the list of the analyzed reduction root instructions.
2066   void clearReductionData() {
2067     AnalizedReductionsRoots.clear();
2068     AnalyzedReductionVals.clear();
2069   }
2070   /// Checks if the given value is gathered in one of the nodes.
2071   bool isGathered(Value *V) const {
2072     return MustGather.contains(V);
2073   }
2074 
2075   ~BoUpSLP();
2076 
2077 private:
2078   /// Check if the operands on the edges \p Edges of the \p UserTE allows
2079   /// reordering (i.e. the operands can be reordered because they have only one
2080   /// user and reordarable).
2081   /// \param ReorderableGathers List of all gather nodes that require reordering
2082   /// (e.g., gather of extractlements or partially vectorizable loads).
2083   /// \param GatherOps List of gather operand nodes for \p UserTE that require
2084   /// reordering, subset of \p NonVectorized.
2085   bool
2086   canReorderOperands(TreeEntry *UserTE,
2087                      SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
2088                      ArrayRef<TreeEntry *> ReorderableGathers,
2089                      SmallVectorImpl<TreeEntry *> &GatherOps);
2090 
2091   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
2092   /// if any. If it is not vectorized (gather node), returns nullptr.
2093   TreeEntry *getVectorizedOperand(TreeEntry *UserTE, unsigned OpIdx) {
2094     ArrayRef<Value *> VL = UserTE->getOperand(OpIdx);
2095     TreeEntry *TE = nullptr;
2096     const auto *It = find_if(VL, [this, &TE](Value *V) {
2097       TE = getTreeEntry(V);
2098       return TE;
2099     });
2100     if (It != VL.end() && TE->isSame(VL))
2101       return TE;
2102     return nullptr;
2103   }
2104 
2105   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
2106   /// if any. If it is not vectorized (gather node), returns nullptr.
2107   const TreeEntry *getVectorizedOperand(const TreeEntry *UserTE,
2108                                         unsigned OpIdx) const {
2109     return const_cast<BoUpSLP *>(this)->getVectorizedOperand(
2110         const_cast<TreeEntry *>(UserTE), OpIdx);
2111   }
2112 
2113   /// Checks if all users of \p I are the part of the vectorization tree.
2114   bool areAllUsersVectorized(Instruction *I,
2115                              ArrayRef<Value *> VectorizedVals) const;
2116 
2117   /// \returns the cost of the vectorizable entry.
2118   InstructionCost getEntryCost(const TreeEntry *E,
2119                                ArrayRef<Value *> VectorizedVals);
2120 
2121   /// This is the recursive part of buildTree.
2122   void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth,
2123                      const EdgeInfo &EI);
2124 
2125   /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
2126   /// be vectorized to use the original vector (or aggregate "bitcast" to a
2127   /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
2128   /// returns false, setting \p CurrentOrder to either an empty vector or a
2129   /// non-identity permutation that allows to reuse extract instructions.
2130   bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
2131                        SmallVectorImpl<unsigned> &CurrentOrder) const;
2132 
2133   /// Vectorize a single entry in the tree.
2134   Value *vectorizeTree(TreeEntry *E);
2135 
2136   /// Vectorize a single entry in the tree, starting in \p VL.
2137   Value *vectorizeTree(ArrayRef<Value *> VL);
2138 
2139   /// Create a new vector from a list of scalar values.  Produces a sequence
2140   /// which exploits values reused across lanes, and arranges the inserts
2141   /// for ease of later optimization.
2142   Value *createBuildVector(ArrayRef<Value *> VL);
2143 
2144   /// \returns the scalarization cost for this type. Scalarization in this
2145   /// context means the creation of vectors from a group of scalars. If \p
2146   /// NeedToShuffle is true, need to add a cost of reshuffling some of the
2147   /// vector elements.
2148   InstructionCost getGatherCost(FixedVectorType *Ty,
2149                                 const APInt &ShuffledIndices,
2150                                 bool NeedToShuffle) const;
2151 
2152   /// Checks if the gathered \p VL can be represented as shuffle(s) of previous
2153   /// tree entries.
2154   /// \returns ShuffleKind, if gathered values can be represented as shuffles of
2155   /// previous tree entries. \p Mask is filled with the shuffle mask.
2156   Optional<TargetTransformInfo::ShuffleKind>
2157   isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
2158                         SmallVectorImpl<const TreeEntry *> &Entries);
2159 
2160   /// \returns the scalarization cost for this list of values. Assuming that
2161   /// this subtree gets vectorized, we may need to extract the values from the
2162   /// roots. This method calculates the cost of extracting the values.
2163   InstructionCost getGatherCost(ArrayRef<Value *> VL) const;
2164 
2165   /// Set the Builder insert point to one after the last instruction in
2166   /// the bundle
2167   void setInsertPointAfterBundle(const TreeEntry *E);
2168 
2169   /// \returns a vector from a collection of scalars in \p VL.
2170   Value *gather(ArrayRef<Value *> VL);
2171 
2172   /// \returns whether the VectorizableTree is fully vectorizable and will
2173   /// be beneficial even the tree height is tiny.
2174   bool isFullyVectorizableTinyTree(bool ForReduction) const;
2175 
2176   /// Reorder commutative or alt operands to get better probability of
2177   /// generating vectorized code.
2178   static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
2179                                              SmallVectorImpl<Value *> &Left,
2180                                              SmallVectorImpl<Value *> &Right,
2181                                              const DataLayout &DL,
2182                                              ScalarEvolution &SE,
2183                                              const BoUpSLP &R);
2184   struct TreeEntry {
2185     using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>;
2186     TreeEntry(VecTreeTy &Container) : Container(Container) {}
2187 
2188     /// \returns true if the scalars in VL are equal to this entry.
2189     bool isSame(ArrayRef<Value *> VL) const {
2190       auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) {
2191         if (Mask.size() != VL.size() && VL.size() == Scalars.size())
2192           return std::equal(VL.begin(), VL.end(), Scalars.begin());
2193         return VL.size() == Mask.size() &&
2194                std::equal(VL.begin(), VL.end(), Mask.begin(),
2195                           [Scalars](Value *V, int Idx) {
2196                             return (isa<UndefValue>(V) &&
2197                                     Idx == UndefMaskElem) ||
2198                                    (Idx != UndefMaskElem && V == Scalars[Idx]);
2199                           });
2200       };
2201       if (!ReorderIndices.empty()) {
2202         // TODO: implement matching if the nodes are just reordered, still can
2203         // treat the vector as the same if the list of scalars matches VL
2204         // directly, without reordering.
2205         SmallVector<int> Mask;
2206         inversePermutation(ReorderIndices, Mask);
2207         if (VL.size() == Scalars.size())
2208           return IsSame(Scalars, Mask);
2209         if (VL.size() == ReuseShuffleIndices.size()) {
2210           ::addMask(Mask, ReuseShuffleIndices);
2211           return IsSame(Scalars, Mask);
2212         }
2213         return false;
2214       }
2215       return IsSame(Scalars, ReuseShuffleIndices);
2216     }
2217 
2218     /// \returns true if current entry has same operands as \p TE.
2219     bool hasEqualOperands(const TreeEntry &TE) const {
2220       if (TE.getNumOperands() != getNumOperands())
2221         return false;
2222       SmallBitVector Used(getNumOperands());
2223       for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
2224         unsigned PrevCount = Used.count();
2225         for (unsigned K = 0; K < E; ++K) {
2226           if (Used.test(K))
2227             continue;
2228           if (getOperand(K) == TE.getOperand(I)) {
2229             Used.set(K);
2230             break;
2231           }
2232         }
2233         // Check if we actually found the matching operand.
2234         if (PrevCount == Used.count())
2235           return false;
2236       }
2237       return true;
2238     }
2239 
2240     /// \return Final vectorization factor for the node. Defined by the total
2241     /// number of vectorized scalars, including those, used several times in the
2242     /// entry and counted in the \a ReuseShuffleIndices, if any.
2243     unsigned getVectorFactor() const {
2244       if (!ReuseShuffleIndices.empty())
2245         return ReuseShuffleIndices.size();
2246       return Scalars.size();
2247     };
2248 
2249     /// A vector of scalars.
2250     ValueList Scalars;
2251 
2252     /// The Scalars are vectorized into this value. It is initialized to Null.
2253     Value *VectorizedValue = nullptr;
2254 
2255     /// Do we need to gather this sequence or vectorize it
2256     /// (either with vector instruction or with scatter/gather
2257     /// intrinsics for store/load)?
2258     enum EntryState { Vectorize, ScatterVectorize, NeedToGather };
2259     EntryState State;
2260 
2261     /// Does this sequence require some shuffling?
2262     SmallVector<int, 4> ReuseShuffleIndices;
2263 
2264     /// Does this entry require reordering?
2265     SmallVector<unsigned, 4> ReorderIndices;
2266 
2267     /// Points back to the VectorizableTree.
2268     ///
2269     /// Only used for Graphviz right now.  Unfortunately GraphTrait::NodeRef has
2270     /// to be a pointer and needs to be able to initialize the child iterator.
2271     /// Thus we need a reference back to the container to translate the indices
2272     /// to entries.
2273     VecTreeTy &Container;
2274 
2275     /// The TreeEntry index containing the user of this entry.  We can actually
2276     /// have multiple users so the data structure is not truly a tree.
2277     SmallVector<EdgeInfo, 1> UserTreeIndices;
2278 
2279     /// The index of this treeEntry in VectorizableTree.
2280     int Idx = -1;
2281 
2282   private:
2283     /// The operands of each instruction in each lane Operands[op_index][lane].
2284     /// Note: This helps avoid the replication of the code that performs the
2285     /// reordering of operands during buildTree_rec() and vectorizeTree().
2286     SmallVector<ValueList, 2> Operands;
2287 
2288     /// The main/alternate instruction.
2289     Instruction *MainOp = nullptr;
2290     Instruction *AltOp = nullptr;
2291 
2292   public:
2293     /// Set this bundle's \p OpIdx'th operand to \p OpVL.
2294     void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) {
2295       if (Operands.size() < OpIdx + 1)
2296         Operands.resize(OpIdx + 1);
2297       assert(Operands[OpIdx].empty() && "Already resized?");
2298       assert(OpVL.size() <= Scalars.size() &&
2299              "Number of operands is greater than the number of scalars.");
2300       Operands[OpIdx].resize(OpVL.size());
2301       copy(OpVL, Operands[OpIdx].begin());
2302     }
2303 
2304     /// Set the operands of this bundle in their original order.
2305     void setOperandsInOrder() {
2306       assert(Operands.empty() && "Already initialized?");
2307       auto *I0 = cast<Instruction>(Scalars[0]);
2308       Operands.resize(I0->getNumOperands());
2309       unsigned NumLanes = Scalars.size();
2310       for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands();
2311            OpIdx != NumOperands; ++OpIdx) {
2312         Operands[OpIdx].resize(NumLanes);
2313         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
2314           auto *I = cast<Instruction>(Scalars[Lane]);
2315           assert(I->getNumOperands() == NumOperands &&
2316                  "Expected same number of operands");
2317           Operands[OpIdx][Lane] = I->getOperand(OpIdx);
2318         }
2319       }
2320     }
2321 
2322     /// Reorders operands of the node to the given mask \p Mask.
2323     void reorderOperands(ArrayRef<int> Mask) {
2324       for (ValueList &Operand : Operands)
2325         reorderScalars(Operand, Mask);
2326     }
2327 
2328     /// \returns the \p OpIdx operand of this TreeEntry.
2329     ValueList &getOperand(unsigned OpIdx) {
2330       assert(OpIdx < Operands.size() && "Off bounds");
2331       return Operands[OpIdx];
2332     }
2333 
2334     /// \returns the \p OpIdx operand of this TreeEntry.
2335     ArrayRef<Value *> getOperand(unsigned OpIdx) const {
2336       assert(OpIdx < Operands.size() && "Off bounds");
2337       return Operands[OpIdx];
2338     }
2339 
2340     /// \returns the number of operands.
2341     unsigned getNumOperands() const { return Operands.size(); }
2342 
2343     /// \return the single \p OpIdx operand.
2344     Value *getSingleOperand(unsigned OpIdx) const {
2345       assert(OpIdx < Operands.size() && "Off bounds");
2346       assert(!Operands[OpIdx].empty() && "No operand available");
2347       return Operands[OpIdx][0];
2348     }
2349 
2350     /// Some of the instructions in the list have alternate opcodes.
2351     bool isAltShuffle() const { return MainOp != AltOp; }
2352 
2353     bool isOpcodeOrAlt(Instruction *I) const {
2354       unsigned CheckedOpcode = I->getOpcode();
2355       return (getOpcode() == CheckedOpcode ||
2356               getAltOpcode() == CheckedOpcode);
2357     }
2358 
2359     /// Chooses the correct key for scheduling data. If \p Op has the same (or
2360     /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is
2361     /// \p OpValue.
2362     Value *isOneOf(Value *Op) const {
2363       auto *I = dyn_cast<Instruction>(Op);
2364       if (I && isOpcodeOrAlt(I))
2365         return Op;
2366       return MainOp;
2367     }
2368 
2369     void setOperations(const InstructionsState &S) {
2370       MainOp = S.MainOp;
2371       AltOp = S.AltOp;
2372     }
2373 
2374     Instruction *getMainOp() const {
2375       return MainOp;
2376     }
2377 
2378     Instruction *getAltOp() const {
2379       return AltOp;
2380     }
2381 
2382     /// The main/alternate opcodes for the list of instructions.
2383     unsigned getOpcode() const {
2384       return MainOp ? MainOp->getOpcode() : 0;
2385     }
2386 
2387     unsigned getAltOpcode() const {
2388       return AltOp ? AltOp->getOpcode() : 0;
2389     }
2390 
2391     /// When ReuseReorderShuffleIndices is empty it just returns position of \p
2392     /// V within vector of Scalars. Otherwise, try to remap on its reuse index.
2393     int findLaneForValue(Value *V) const {
2394       unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V));
2395       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2396       if (!ReorderIndices.empty())
2397         FoundLane = ReorderIndices[FoundLane];
2398       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2399       if (!ReuseShuffleIndices.empty()) {
2400         FoundLane = std::distance(ReuseShuffleIndices.begin(),
2401                                   find(ReuseShuffleIndices, FoundLane));
2402       }
2403       return FoundLane;
2404     }
2405 
2406 #ifndef NDEBUG
2407     /// Debug printer.
2408     LLVM_DUMP_METHOD void dump() const {
2409       dbgs() << Idx << ".\n";
2410       for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) {
2411         dbgs() << "Operand " << OpI << ":\n";
2412         for (const Value *V : Operands[OpI])
2413           dbgs().indent(2) << *V << "\n";
2414       }
2415       dbgs() << "Scalars: \n";
2416       for (Value *V : Scalars)
2417         dbgs().indent(2) << *V << "\n";
2418       dbgs() << "State: ";
2419       switch (State) {
2420       case Vectorize:
2421         dbgs() << "Vectorize\n";
2422         break;
2423       case ScatterVectorize:
2424         dbgs() << "ScatterVectorize\n";
2425         break;
2426       case NeedToGather:
2427         dbgs() << "NeedToGather\n";
2428         break;
2429       }
2430       dbgs() << "MainOp: ";
2431       if (MainOp)
2432         dbgs() << *MainOp << "\n";
2433       else
2434         dbgs() << "NULL\n";
2435       dbgs() << "AltOp: ";
2436       if (AltOp)
2437         dbgs() << *AltOp << "\n";
2438       else
2439         dbgs() << "NULL\n";
2440       dbgs() << "VectorizedValue: ";
2441       if (VectorizedValue)
2442         dbgs() << *VectorizedValue << "\n";
2443       else
2444         dbgs() << "NULL\n";
2445       dbgs() << "ReuseShuffleIndices: ";
2446       if (ReuseShuffleIndices.empty())
2447         dbgs() << "Empty";
2448       else
2449         for (int ReuseIdx : ReuseShuffleIndices)
2450           dbgs() << ReuseIdx << ", ";
2451       dbgs() << "\n";
2452       dbgs() << "ReorderIndices: ";
2453       for (unsigned ReorderIdx : ReorderIndices)
2454         dbgs() << ReorderIdx << ", ";
2455       dbgs() << "\n";
2456       dbgs() << "UserTreeIndices: ";
2457       for (const auto &EInfo : UserTreeIndices)
2458         dbgs() << EInfo << ", ";
2459       dbgs() << "\n";
2460     }
2461 #endif
2462   };
2463 
2464 #ifndef NDEBUG
2465   void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost,
2466                      InstructionCost VecCost,
2467                      InstructionCost ScalarCost) const {
2468     dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump();
2469     dbgs() << "SLP: Costs:\n";
2470     dbgs() << "SLP:     ReuseShuffleCost = " << ReuseShuffleCost << "\n";
2471     dbgs() << "SLP:     VectorCost = " << VecCost << "\n";
2472     dbgs() << "SLP:     ScalarCost = " << ScalarCost << "\n";
2473     dbgs() << "SLP:     ReuseShuffleCost + VecCost - ScalarCost = " <<
2474                ReuseShuffleCost + VecCost - ScalarCost << "\n";
2475   }
2476 #endif
2477 
2478   /// Create a new VectorizableTree entry.
2479   TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle,
2480                           const InstructionsState &S,
2481                           const EdgeInfo &UserTreeIdx,
2482                           ArrayRef<int> ReuseShuffleIndices = None,
2483                           ArrayRef<unsigned> ReorderIndices = None) {
2484     TreeEntry::EntryState EntryState =
2485         Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather;
2486     return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx,
2487                         ReuseShuffleIndices, ReorderIndices);
2488   }
2489 
2490   TreeEntry *newTreeEntry(ArrayRef<Value *> VL,
2491                           TreeEntry::EntryState EntryState,
2492                           Optional<ScheduleData *> Bundle,
2493                           const InstructionsState &S,
2494                           const EdgeInfo &UserTreeIdx,
2495                           ArrayRef<int> ReuseShuffleIndices = None,
2496                           ArrayRef<unsigned> ReorderIndices = None) {
2497     assert(((!Bundle && EntryState == TreeEntry::NeedToGather) ||
2498             (Bundle && EntryState != TreeEntry::NeedToGather)) &&
2499            "Need to vectorize gather entry?");
2500     VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree));
2501     TreeEntry *Last = VectorizableTree.back().get();
2502     Last->Idx = VectorizableTree.size() - 1;
2503     Last->State = EntryState;
2504     Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
2505                                      ReuseShuffleIndices.end());
2506     if (ReorderIndices.empty()) {
2507       Last->Scalars.assign(VL.begin(), VL.end());
2508       Last->setOperations(S);
2509     } else {
2510       // Reorder scalars and build final mask.
2511       Last->Scalars.assign(VL.size(), nullptr);
2512       transform(ReorderIndices, Last->Scalars.begin(),
2513                 [VL](unsigned Idx) -> Value * {
2514                   if (Idx >= VL.size())
2515                     return UndefValue::get(VL.front()->getType());
2516                   return VL[Idx];
2517                 });
2518       InstructionsState S = getSameOpcode(Last->Scalars);
2519       Last->setOperations(S);
2520       Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end());
2521     }
2522     if (Last->State != TreeEntry::NeedToGather) {
2523       for (Value *V : VL) {
2524         assert(!getTreeEntry(V) && "Scalar already in tree!");
2525         ScalarToTreeEntry[V] = Last;
2526       }
2527       // Update the scheduler bundle to point to this TreeEntry.
2528       ScheduleData *BundleMember = Bundle.getValue();
2529       assert((BundleMember || isa<PHINode>(S.MainOp) ||
2530               isVectorLikeInstWithConstOps(S.MainOp) ||
2531               doesNotNeedToSchedule(VL)) &&
2532              "Bundle and VL out of sync");
2533       if (BundleMember) {
2534         for (Value *V : VL) {
2535           if (doesNotNeedToBeScheduled(V))
2536             continue;
2537           assert(BundleMember && "Unexpected end of bundle.");
2538           BundleMember->TE = Last;
2539           BundleMember = BundleMember->NextInBundle;
2540         }
2541       }
2542       assert(!BundleMember && "Bundle and VL out of sync");
2543     } else {
2544       MustGather.insert(VL.begin(), VL.end());
2545     }
2546 
2547     if (UserTreeIdx.UserTE)
2548       Last->UserTreeIndices.push_back(UserTreeIdx);
2549 
2550     return Last;
2551   }
2552 
2553   /// -- Vectorization State --
2554   /// Holds all of the tree entries.
2555   TreeEntry::VecTreeTy VectorizableTree;
2556 
2557 #ifndef NDEBUG
2558   /// Debug printer.
2559   LLVM_DUMP_METHOD void dumpVectorizableTree() const {
2560     for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) {
2561       VectorizableTree[Id]->dump();
2562       dbgs() << "\n";
2563     }
2564   }
2565 #endif
2566 
2567   TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); }
2568 
2569   const TreeEntry *getTreeEntry(Value *V) const {
2570     return ScalarToTreeEntry.lookup(V);
2571   }
2572 
2573   /// Maps a specific scalar to its tree entry.
2574   SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry;
2575 
2576   /// Maps a value to the proposed vectorizable size.
2577   SmallDenseMap<Value *, unsigned> InstrElementSize;
2578 
2579   /// A list of scalars that we found that we need to keep as scalars.
2580   ValueSet MustGather;
2581 
2582   /// This POD struct describes one external user in the vectorized tree.
2583   struct ExternalUser {
2584     ExternalUser(Value *S, llvm::User *U, int L)
2585         : Scalar(S), User(U), Lane(L) {}
2586 
2587     // Which scalar in our function.
2588     Value *Scalar;
2589 
2590     // Which user that uses the scalar.
2591     llvm::User *User;
2592 
2593     // Which lane does the scalar belong to.
2594     int Lane;
2595   };
2596   using UserList = SmallVector<ExternalUser, 16>;
2597 
2598   /// Checks if two instructions may access the same memory.
2599   ///
2600   /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
2601   /// is invariant in the calling loop.
2602   bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
2603                  Instruction *Inst2) {
2604     // First check if the result is already in the cache.
2605     AliasCacheKey key = std::make_pair(Inst1, Inst2);
2606     Optional<bool> &result = AliasCache[key];
2607     if (result.hasValue()) {
2608       return result.getValue();
2609     }
2610     bool aliased = true;
2611     if (Loc1.Ptr && isSimple(Inst1))
2612       aliased = isModOrRefSet(BatchAA.getModRefInfo(Inst2, Loc1));
2613     // Store the result in the cache.
2614     result = aliased;
2615     return aliased;
2616   }
2617 
2618   using AliasCacheKey = std::pair<Instruction *, Instruction *>;
2619 
2620   /// Cache for alias results.
2621   /// TODO: consider moving this to the AliasAnalysis itself.
2622   DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
2623 
2624   // Cache for pointerMayBeCaptured calls inside AA.  This is preserved
2625   // globally through SLP because we don't perform any action which
2626   // invalidates capture results.
2627   BatchAAResults BatchAA;
2628 
2629   /// Temporary store for deleted instructions. Instructions will be deleted
2630   /// eventually when the BoUpSLP is destructed.  The deferral is required to
2631   /// ensure that there are no incorrect collisions in the AliasCache, which
2632   /// can happen if a new instruction is allocated at the same address as a
2633   /// previously deleted instruction.
2634   DenseSet<Instruction *> DeletedInstructions;
2635 
2636   /// Set of the instruction, being analyzed already for reductions.
2637   SmallPtrSet<Instruction *, 16> AnalizedReductionsRoots;
2638 
2639   /// Set of hashes for the list of reduction values already being analyzed.
2640   DenseSet<size_t> AnalyzedReductionVals;
2641 
2642   /// A list of values that need to extracted out of the tree.
2643   /// This list holds pairs of (Internal Scalar : External User). External User
2644   /// can be nullptr, it means that this Internal Scalar will be used later,
2645   /// after vectorization.
2646   UserList ExternalUses;
2647 
2648   /// Values used only by @llvm.assume calls.
2649   SmallPtrSet<const Value *, 32> EphValues;
2650 
2651   /// Holds all of the instructions that we gathered.
2652   SetVector<Instruction *> GatherShuffleSeq;
2653 
2654   /// A list of blocks that we are going to CSE.
2655   SetVector<BasicBlock *> CSEBlocks;
2656 
2657   /// Contains all scheduling relevant data for an instruction.
2658   /// A ScheduleData either represents a single instruction or a member of an
2659   /// instruction bundle (= a group of instructions which is combined into a
2660   /// vector instruction).
2661   struct ScheduleData {
2662     // The initial value for the dependency counters. It means that the
2663     // dependencies are not calculated yet.
2664     enum { InvalidDeps = -1 };
2665 
2666     ScheduleData() = default;
2667 
2668     void init(int BlockSchedulingRegionID, Value *OpVal) {
2669       FirstInBundle = this;
2670       NextInBundle = nullptr;
2671       NextLoadStore = nullptr;
2672       IsScheduled = false;
2673       SchedulingRegionID = BlockSchedulingRegionID;
2674       clearDependencies();
2675       OpValue = OpVal;
2676       TE = nullptr;
2677     }
2678 
2679     /// Verify basic self consistency properties
2680     void verify() {
2681       if (hasValidDependencies()) {
2682         assert(UnscheduledDeps <= Dependencies && "invariant");
2683       } else {
2684         assert(UnscheduledDeps == Dependencies && "invariant");
2685       }
2686 
2687       if (IsScheduled) {
2688         assert(isSchedulingEntity() &&
2689                 "unexpected scheduled state");
2690         for (const ScheduleData *BundleMember = this; BundleMember;
2691              BundleMember = BundleMember->NextInBundle) {
2692           assert(BundleMember->hasValidDependencies() &&
2693                  BundleMember->UnscheduledDeps == 0 &&
2694                  "unexpected scheduled state");
2695           assert((BundleMember == this || !BundleMember->IsScheduled) &&
2696                  "only bundle is marked scheduled");
2697         }
2698       }
2699 
2700       assert(Inst->getParent() == FirstInBundle->Inst->getParent() &&
2701              "all bundle members must be in same basic block");
2702     }
2703 
2704     /// Returns true if the dependency information has been calculated.
2705     /// Note that depenendency validity can vary between instructions within
2706     /// a single bundle.
2707     bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
2708 
2709     /// Returns true for single instructions and for bundle representatives
2710     /// (= the head of a bundle).
2711     bool isSchedulingEntity() const { return FirstInBundle == this; }
2712 
2713     /// Returns true if it represents an instruction bundle and not only a
2714     /// single instruction.
2715     bool isPartOfBundle() const {
2716       return NextInBundle != nullptr || FirstInBundle != this || TE;
2717     }
2718 
2719     /// Returns true if it is ready for scheduling, i.e. it has no more
2720     /// unscheduled depending instructions/bundles.
2721     bool isReady() const {
2722       assert(isSchedulingEntity() &&
2723              "can't consider non-scheduling entity for ready list");
2724       return unscheduledDepsInBundle() == 0 && !IsScheduled;
2725     }
2726 
2727     /// Modifies the number of unscheduled dependencies for this instruction,
2728     /// and returns the number of remaining dependencies for the containing
2729     /// bundle.
2730     int incrementUnscheduledDeps(int Incr) {
2731       assert(hasValidDependencies() &&
2732              "increment of unscheduled deps would be meaningless");
2733       UnscheduledDeps += Incr;
2734       return FirstInBundle->unscheduledDepsInBundle();
2735     }
2736 
2737     /// Sets the number of unscheduled dependencies to the number of
2738     /// dependencies.
2739     void resetUnscheduledDeps() {
2740       UnscheduledDeps = Dependencies;
2741     }
2742 
2743     /// Clears all dependency information.
2744     void clearDependencies() {
2745       Dependencies = InvalidDeps;
2746       resetUnscheduledDeps();
2747       MemoryDependencies.clear();
2748       ControlDependencies.clear();
2749     }
2750 
2751     int unscheduledDepsInBundle() const {
2752       assert(isSchedulingEntity() && "only meaningful on the bundle");
2753       int Sum = 0;
2754       for (const ScheduleData *BundleMember = this; BundleMember;
2755            BundleMember = BundleMember->NextInBundle) {
2756         if (BundleMember->UnscheduledDeps == InvalidDeps)
2757           return InvalidDeps;
2758         Sum += BundleMember->UnscheduledDeps;
2759       }
2760       return Sum;
2761     }
2762 
2763     void dump(raw_ostream &os) const {
2764       if (!isSchedulingEntity()) {
2765         os << "/ " << *Inst;
2766       } else if (NextInBundle) {
2767         os << '[' << *Inst;
2768         ScheduleData *SD = NextInBundle;
2769         while (SD) {
2770           os << ';' << *SD->Inst;
2771           SD = SD->NextInBundle;
2772         }
2773         os << ']';
2774       } else {
2775         os << *Inst;
2776       }
2777     }
2778 
2779     Instruction *Inst = nullptr;
2780 
2781     /// Opcode of the current instruction in the schedule data.
2782     Value *OpValue = nullptr;
2783 
2784     /// The TreeEntry that this instruction corresponds to.
2785     TreeEntry *TE = nullptr;
2786 
2787     /// Points to the head in an instruction bundle (and always to this for
2788     /// single instructions).
2789     ScheduleData *FirstInBundle = nullptr;
2790 
2791     /// Single linked list of all instructions in a bundle. Null if it is a
2792     /// single instruction.
2793     ScheduleData *NextInBundle = nullptr;
2794 
2795     /// Single linked list of all memory instructions (e.g. load, store, call)
2796     /// in the block - until the end of the scheduling region.
2797     ScheduleData *NextLoadStore = nullptr;
2798 
2799     /// The dependent memory instructions.
2800     /// This list is derived on demand in calculateDependencies().
2801     SmallVector<ScheduleData *, 4> MemoryDependencies;
2802 
2803     /// List of instructions which this instruction could be control dependent
2804     /// on.  Allowing such nodes to be scheduled below this one could introduce
2805     /// a runtime fault which didn't exist in the original program.
2806     /// ex: this is a load or udiv following a readonly call which inf loops
2807     SmallVector<ScheduleData *, 4> ControlDependencies;
2808 
2809     /// This ScheduleData is in the current scheduling region if this matches
2810     /// the current SchedulingRegionID of BlockScheduling.
2811     int SchedulingRegionID = 0;
2812 
2813     /// Used for getting a "good" final ordering of instructions.
2814     int SchedulingPriority = 0;
2815 
2816     /// The number of dependencies. Constitutes of the number of users of the
2817     /// instruction plus the number of dependent memory instructions (if any).
2818     /// This value is calculated on demand.
2819     /// If InvalidDeps, the number of dependencies is not calculated yet.
2820     int Dependencies = InvalidDeps;
2821 
2822     /// The number of dependencies minus the number of dependencies of scheduled
2823     /// instructions. As soon as this is zero, the instruction/bundle gets ready
2824     /// for scheduling.
2825     /// Note that this is negative as long as Dependencies is not calculated.
2826     int UnscheduledDeps = InvalidDeps;
2827 
2828     /// True if this instruction is scheduled (or considered as scheduled in the
2829     /// dry-run).
2830     bool IsScheduled = false;
2831   };
2832 
2833 #ifndef NDEBUG
2834   friend inline raw_ostream &operator<<(raw_ostream &os,
2835                                         const BoUpSLP::ScheduleData &SD) {
2836     SD.dump(os);
2837     return os;
2838   }
2839 #endif
2840 
2841   friend struct GraphTraits<BoUpSLP *>;
2842   friend struct DOTGraphTraits<BoUpSLP *>;
2843 
2844   /// Contains all scheduling data for a basic block.
2845   /// It does not schedules instructions, which are not memory read/write
2846   /// instructions and their operands are either constants, or arguments, or
2847   /// phis, or instructions from others blocks, or their users are phis or from
2848   /// the other blocks. The resulting vector instructions can be placed at the
2849   /// beginning of the basic block without scheduling (if operands does not need
2850   /// to be scheduled) or at the end of the block (if users are outside of the
2851   /// block). It allows to save some compile time and memory used by the
2852   /// compiler.
2853   /// ScheduleData is assigned for each instruction in between the boundaries of
2854   /// the tree entry, even for those, which are not part of the graph. It is
2855   /// required to correctly follow the dependencies between the instructions and
2856   /// their correct scheduling. The ScheduleData is not allocated for the
2857   /// instructions, which do not require scheduling, like phis, nodes with
2858   /// extractelements/insertelements only or nodes with instructions, with
2859   /// uses/operands outside of the block.
2860   struct BlockScheduling {
2861     BlockScheduling(BasicBlock *BB)
2862         : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
2863 
2864     void clear() {
2865       ReadyInsts.clear();
2866       ScheduleStart = nullptr;
2867       ScheduleEnd = nullptr;
2868       FirstLoadStoreInRegion = nullptr;
2869       LastLoadStoreInRegion = nullptr;
2870       RegionHasStackSave = false;
2871 
2872       // Reduce the maximum schedule region size by the size of the
2873       // previous scheduling run.
2874       ScheduleRegionSizeLimit -= ScheduleRegionSize;
2875       if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
2876         ScheduleRegionSizeLimit = MinScheduleRegionSize;
2877       ScheduleRegionSize = 0;
2878 
2879       // Make a new scheduling region, i.e. all existing ScheduleData is not
2880       // in the new region yet.
2881       ++SchedulingRegionID;
2882     }
2883 
2884     ScheduleData *getScheduleData(Instruction *I) {
2885       if (BB != I->getParent())
2886         // Avoid lookup if can't possibly be in map.
2887         return nullptr;
2888       ScheduleData *SD = ScheduleDataMap.lookup(I);
2889       if (SD && isInSchedulingRegion(SD))
2890         return SD;
2891       return nullptr;
2892     }
2893 
2894     ScheduleData *getScheduleData(Value *V) {
2895       if (auto *I = dyn_cast<Instruction>(V))
2896         return getScheduleData(I);
2897       return nullptr;
2898     }
2899 
2900     ScheduleData *getScheduleData(Value *V, Value *Key) {
2901       if (V == Key)
2902         return getScheduleData(V);
2903       auto I = ExtraScheduleDataMap.find(V);
2904       if (I != ExtraScheduleDataMap.end()) {
2905         ScheduleData *SD = I->second.lookup(Key);
2906         if (SD && isInSchedulingRegion(SD))
2907           return SD;
2908       }
2909       return nullptr;
2910     }
2911 
2912     bool isInSchedulingRegion(ScheduleData *SD) const {
2913       return SD->SchedulingRegionID == SchedulingRegionID;
2914     }
2915 
2916     /// Marks an instruction as scheduled and puts all dependent ready
2917     /// instructions into the ready-list.
2918     template <typename ReadyListType>
2919     void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
2920       SD->IsScheduled = true;
2921       LLVM_DEBUG(dbgs() << "SLP:   schedule " << *SD << "\n");
2922 
2923       for (ScheduleData *BundleMember = SD; BundleMember;
2924            BundleMember = BundleMember->NextInBundle) {
2925         if (BundleMember->Inst != BundleMember->OpValue)
2926           continue;
2927 
2928         // Handle the def-use chain dependencies.
2929 
2930         // Decrement the unscheduled counter and insert to ready list if ready.
2931         auto &&DecrUnsched = [this, &ReadyList](Instruction *I) {
2932           doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
2933             if (OpDef && OpDef->hasValidDependencies() &&
2934                 OpDef->incrementUnscheduledDeps(-1) == 0) {
2935               // There are no more unscheduled dependencies after
2936               // decrementing, so we can put the dependent instruction
2937               // into the ready list.
2938               ScheduleData *DepBundle = OpDef->FirstInBundle;
2939               assert(!DepBundle->IsScheduled &&
2940                      "already scheduled bundle gets ready");
2941               ReadyList.insert(DepBundle);
2942               LLVM_DEBUG(dbgs()
2943                          << "SLP:    gets ready (def): " << *DepBundle << "\n");
2944             }
2945           });
2946         };
2947 
2948         // If BundleMember is a vector bundle, its operands may have been
2949         // reordered during buildTree(). We therefore need to get its operands
2950         // through the TreeEntry.
2951         if (TreeEntry *TE = BundleMember->TE) {
2952           // Need to search for the lane since the tree entry can be reordered.
2953           int Lane = std::distance(TE->Scalars.begin(),
2954                                    find(TE->Scalars, BundleMember->Inst));
2955           assert(Lane >= 0 && "Lane not set");
2956 
2957           // Since vectorization tree is being built recursively this assertion
2958           // ensures that the tree entry has all operands set before reaching
2959           // this code. Couple of exceptions known at the moment are extracts
2960           // where their second (immediate) operand is not added. Since
2961           // immediates do not affect scheduler behavior this is considered
2962           // okay.
2963           auto *In = BundleMember->Inst;
2964           assert(In &&
2965                  (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) ||
2966                   In->getNumOperands() == TE->getNumOperands()) &&
2967                  "Missed TreeEntry operands?");
2968           (void)In; // fake use to avoid build failure when assertions disabled
2969 
2970           for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands();
2971                OpIdx != NumOperands; ++OpIdx)
2972             if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane]))
2973               DecrUnsched(I);
2974         } else {
2975           // If BundleMember is a stand-alone instruction, no operand reordering
2976           // has taken place, so we directly access its operands.
2977           for (Use &U : BundleMember->Inst->operands())
2978             if (auto *I = dyn_cast<Instruction>(U.get()))
2979               DecrUnsched(I);
2980         }
2981         // Handle the memory dependencies.
2982         for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
2983           if (MemoryDepSD->hasValidDependencies() &&
2984               MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
2985             // There are no more unscheduled dependencies after decrementing,
2986             // so we can put the dependent instruction into the ready list.
2987             ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
2988             assert(!DepBundle->IsScheduled &&
2989                    "already scheduled bundle gets ready");
2990             ReadyList.insert(DepBundle);
2991             LLVM_DEBUG(dbgs()
2992                        << "SLP:    gets ready (mem): " << *DepBundle << "\n");
2993           }
2994         }
2995         // Handle the control dependencies.
2996         for (ScheduleData *DepSD : BundleMember->ControlDependencies) {
2997           if (DepSD->incrementUnscheduledDeps(-1) == 0) {
2998             // There are no more unscheduled dependencies after decrementing,
2999             // so we can put the dependent instruction into the ready list.
3000             ScheduleData *DepBundle = DepSD->FirstInBundle;
3001             assert(!DepBundle->IsScheduled &&
3002                    "already scheduled bundle gets ready");
3003             ReadyList.insert(DepBundle);
3004             LLVM_DEBUG(dbgs()
3005                        << "SLP:    gets ready (ctl): " << *DepBundle << "\n");
3006           }
3007         }
3008 
3009       }
3010     }
3011 
3012     /// Verify basic self consistency properties of the data structure.
3013     void verify() {
3014       if (!ScheduleStart)
3015         return;
3016 
3017       assert(ScheduleStart->getParent() == ScheduleEnd->getParent() &&
3018              ScheduleStart->comesBefore(ScheduleEnd) &&
3019              "Not a valid scheduling region?");
3020 
3021       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
3022         auto *SD = getScheduleData(I);
3023         if (!SD)
3024           continue;
3025         assert(isInSchedulingRegion(SD) &&
3026                "primary schedule data not in window?");
3027         assert(isInSchedulingRegion(SD->FirstInBundle) &&
3028                "entire bundle in window!");
3029         (void)SD;
3030         doForAllOpcodes(I, [](ScheduleData *SD) { SD->verify(); });
3031       }
3032 
3033       for (auto *SD : ReadyInsts) {
3034         assert(SD->isSchedulingEntity() && SD->isReady() &&
3035                "item in ready list not ready?");
3036         (void)SD;
3037       }
3038     }
3039 
3040     void doForAllOpcodes(Value *V,
3041                          function_ref<void(ScheduleData *SD)> Action) {
3042       if (ScheduleData *SD = getScheduleData(V))
3043         Action(SD);
3044       auto I = ExtraScheduleDataMap.find(V);
3045       if (I != ExtraScheduleDataMap.end())
3046         for (auto &P : I->second)
3047           if (isInSchedulingRegion(P.second))
3048             Action(P.second);
3049     }
3050 
3051     /// Put all instructions into the ReadyList which are ready for scheduling.
3052     template <typename ReadyListType>
3053     void initialFillReadyList(ReadyListType &ReadyList) {
3054       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
3055         doForAllOpcodes(I, [&](ScheduleData *SD) {
3056           if (SD->isSchedulingEntity() && SD->hasValidDependencies() &&
3057               SD->isReady()) {
3058             ReadyList.insert(SD);
3059             LLVM_DEBUG(dbgs()
3060                        << "SLP:    initially in ready list: " << *SD << "\n");
3061           }
3062         });
3063       }
3064     }
3065 
3066     /// Build a bundle from the ScheduleData nodes corresponding to the
3067     /// scalar instruction for each lane.
3068     ScheduleData *buildBundle(ArrayRef<Value *> VL);
3069 
3070     /// Checks if a bundle of instructions can be scheduled, i.e. has no
3071     /// cyclic dependencies. This is only a dry-run, no instructions are
3072     /// actually moved at this stage.
3073     /// \returns the scheduling bundle. The returned Optional value is non-None
3074     /// if \p VL is allowed to be scheduled.
3075     Optional<ScheduleData *>
3076     tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
3077                       const InstructionsState &S);
3078 
3079     /// Un-bundles a group of instructions.
3080     void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
3081 
3082     /// Allocates schedule data chunk.
3083     ScheduleData *allocateScheduleDataChunks();
3084 
3085     /// Extends the scheduling region so that V is inside the region.
3086     /// \returns true if the region size is within the limit.
3087     bool extendSchedulingRegion(Value *V, const InstructionsState &S);
3088 
3089     /// Initialize the ScheduleData structures for new instructions in the
3090     /// scheduling region.
3091     void initScheduleData(Instruction *FromI, Instruction *ToI,
3092                           ScheduleData *PrevLoadStore,
3093                           ScheduleData *NextLoadStore);
3094 
3095     /// Updates the dependency information of a bundle and of all instructions/
3096     /// bundles which depend on the original bundle.
3097     void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
3098                                BoUpSLP *SLP);
3099 
3100     /// Sets all instruction in the scheduling region to un-scheduled.
3101     void resetSchedule();
3102 
3103     BasicBlock *BB;
3104 
3105     /// Simple memory allocation for ScheduleData.
3106     std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
3107 
3108     /// The size of a ScheduleData array in ScheduleDataChunks.
3109     int ChunkSize;
3110 
3111     /// The allocator position in the current chunk, which is the last entry
3112     /// of ScheduleDataChunks.
3113     int ChunkPos;
3114 
3115     /// Attaches ScheduleData to Instruction.
3116     /// Note that the mapping survives during all vectorization iterations, i.e.
3117     /// ScheduleData structures are recycled.
3118     DenseMap<Instruction *, ScheduleData *> ScheduleDataMap;
3119 
3120     /// Attaches ScheduleData to Instruction with the leading key.
3121     DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
3122         ExtraScheduleDataMap;
3123 
3124     /// The ready-list for scheduling (only used for the dry-run).
3125     SetVector<ScheduleData *> ReadyInsts;
3126 
3127     /// The first instruction of the scheduling region.
3128     Instruction *ScheduleStart = nullptr;
3129 
3130     /// The first instruction _after_ the scheduling region.
3131     Instruction *ScheduleEnd = nullptr;
3132 
3133     /// The first memory accessing instruction in the scheduling region
3134     /// (can be null).
3135     ScheduleData *FirstLoadStoreInRegion = nullptr;
3136 
3137     /// The last memory accessing instruction in the scheduling region
3138     /// (can be null).
3139     ScheduleData *LastLoadStoreInRegion = nullptr;
3140 
3141     /// Is there an llvm.stacksave or llvm.stackrestore in the scheduling
3142     /// region?  Used to optimize the dependence calculation for the
3143     /// common case where there isn't.
3144     bool RegionHasStackSave = false;
3145 
3146     /// The current size of the scheduling region.
3147     int ScheduleRegionSize = 0;
3148 
3149     /// The maximum size allowed for the scheduling region.
3150     int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
3151 
3152     /// The ID of the scheduling region. For a new vectorization iteration this
3153     /// is incremented which "removes" all ScheduleData from the region.
3154     /// Make sure that the initial SchedulingRegionID is greater than the
3155     /// initial SchedulingRegionID in ScheduleData (which is 0).
3156     int SchedulingRegionID = 1;
3157   };
3158 
3159   /// Attaches the BlockScheduling structures to basic blocks.
3160   MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
3161 
3162   /// Performs the "real" scheduling. Done before vectorization is actually
3163   /// performed in a basic block.
3164   void scheduleBlock(BlockScheduling *BS);
3165 
3166   /// List of users to ignore during scheduling and that don't need extracting.
3167   ArrayRef<Value *> UserIgnoreList;
3168 
3169   /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
3170   /// sorted SmallVectors of unsigned.
3171   struct OrdersTypeDenseMapInfo {
3172     static OrdersType getEmptyKey() {
3173       OrdersType V;
3174       V.push_back(~1U);
3175       return V;
3176     }
3177 
3178     static OrdersType getTombstoneKey() {
3179       OrdersType V;
3180       V.push_back(~2U);
3181       return V;
3182     }
3183 
3184     static unsigned getHashValue(const OrdersType &V) {
3185       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
3186     }
3187 
3188     static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
3189       return LHS == RHS;
3190     }
3191   };
3192 
3193   // Analysis and block reference.
3194   Function *F;
3195   ScalarEvolution *SE;
3196   TargetTransformInfo *TTI;
3197   TargetLibraryInfo *TLI;
3198   LoopInfo *LI;
3199   DominatorTree *DT;
3200   AssumptionCache *AC;
3201   DemandedBits *DB;
3202   const DataLayout *DL;
3203   OptimizationRemarkEmitter *ORE;
3204 
3205   unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
3206   unsigned MinVecRegSize; // Set by cl::opt (default: 128).
3207 
3208   /// Instruction builder to construct the vectorized tree.
3209   IRBuilder<> Builder;
3210 
3211   /// A map of scalar integer values to the smallest bit width with which they
3212   /// can legally be represented. The values map to (width, signed) pairs,
3213   /// where "width" indicates the minimum bit width and "signed" is True if the
3214   /// value must be signed-extended, rather than zero-extended, back to its
3215   /// original width.
3216   MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
3217 };
3218 
3219 } // end namespace slpvectorizer
3220 
3221 template <> struct GraphTraits<BoUpSLP *> {
3222   using TreeEntry = BoUpSLP::TreeEntry;
3223 
3224   /// NodeRef has to be a pointer per the GraphWriter.
3225   using NodeRef = TreeEntry *;
3226 
3227   using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy;
3228 
3229   /// Add the VectorizableTree to the index iterator to be able to return
3230   /// TreeEntry pointers.
3231   struct ChildIteratorType
3232       : public iterator_adaptor_base<
3233             ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
3234     ContainerTy &VectorizableTree;
3235 
3236     ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W,
3237                       ContainerTy &VT)
3238         : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
3239 
3240     NodeRef operator*() { return I->UserTE; }
3241   };
3242 
3243   static NodeRef getEntryNode(BoUpSLP &R) {
3244     return R.VectorizableTree[0].get();
3245   }
3246 
3247   static ChildIteratorType child_begin(NodeRef N) {
3248     return {N->UserTreeIndices.begin(), N->Container};
3249   }
3250 
3251   static ChildIteratorType child_end(NodeRef N) {
3252     return {N->UserTreeIndices.end(), N->Container};
3253   }
3254 
3255   /// For the node iterator we just need to turn the TreeEntry iterator into a
3256   /// TreeEntry* iterator so that it dereferences to NodeRef.
3257   class nodes_iterator {
3258     using ItTy = ContainerTy::iterator;
3259     ItTy It;
3260 
3261   public:
3262     nodes_iterator(const ItTy &It2) : It(It2) {}
3263     NodeRef operator*() { return It->get(); }
3264     nodes_iterator operator++() {
3265       ++It;
3266       return *this;
3267     }
3268     bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
3269   };
3270 
3271   static nodes_iterator nodes_begin(BoUpSLP *R) {
3272     return nodes_iterator(R->VectorizableTree.begin());
3273   }
3274 
3275   static nodes_iterator nodes_end(BoUpSLP *R) {
3276     return nodes_iterator(R->VectorizableTree.end());
3277   }
3278 
3279   static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
3280 };
3281 
3282 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
3283   using TreeEntry = BoUpSLP::TreeEntry;
3284 
3285   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
3286 
3287   std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
3288     std::string Str;
3289     raw_string_ostream OS(Str);
3290     if (isSplat(Entry->Scalars))
3291       OS << "<splat> ";
3292     for (auto V : Entry->Scalars) {
3293       OS << *V;
3294       if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) {
3295             return EU.Scalar == V;
3296           }))
3297         OS << " <extract>";
3298       OS << "\n";
3299     }
3300     return Str;
3301   }
3302 
3303   static std::string getNodeAttributes(const TreeEntry *Entry,
3304                                        const BoUpSLP *) {
3305     if (Entry->State == TreeEntry::NeedToGather)
3306       return "color=red";
3307     return "";
3308   }
3309 };
3310 
3311 } // end namespace llvm
3312 
3313 BoUpSLP::~BoUpSLP() {
3314   SmallVector<WeakTrackingVH> DeadInsts;
3315   for (auto *I : DeletedInstructions) {
3316     for (Use &U : I->operands()) {
3317       auto *Op = dyn_cast<Instruction>(U.get());
3318       if (Op && !DeletedInstructions.count(Op) && Op->hasOneUser() &&
3319           wouldInstructionBeTriviallyDead(Op, TLI))
3320         DeadInsts.emplace_back(Op);
3321     }
3322     I->dropAllReferences();
3323   }
3324   for (auto *I : DeletedInstructions) {
3325     assert(I->use_empty() &&
3326            "trying to erase instruction with users.");
3327     I->eraseFromParent();
3328   }
3329 
3330   // Cleanup any dead scalar code feeding the vectorized instructions
3331   RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI);
3332 
3333 #ifdef EXPENSIVE_CHECKS
3334   // If we could guarantee that this call is not extremely slow, we could
3335   // remove the ifdef limitation (see PR47712).
3336   assert(!verifyFunction(*F, &dbgs()));
3337 #endif
3338 }
3339 
3340 /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses
3341 /// contains original mask for the scalars reused in the node. Procedure
3342 /// transform this mask in accordance with the given \p Mask.
3343 static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) {
3344   assert(!Mask.empty() && Reuses.size() == Mask.size() &&
3345          "Expected non-empty mask.");
3346   SmallVector<int> Prev(Reuses.begin(), Reuses.end());
3347   Prev.swap(Reuses);
3348   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
3349     if (Mask[I] != UndefMaskElem)
3350       Reuses[Mask[I]] = Prev[I];
3351 }
3352 
3353 /// Reorders the given \p Order according to the given \p Mask. \p Order - is
3354 /// the original order of the scalars. Procedure transforms the provided order
3355 /// in accordance with the given \p Mask. If the resulting \p Order is just an
3356 /// identity order, \p Order is cleared.
3357 static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) {
3358   assert(!Mask.empty() && "Expected non-empty mask.");
3359   SmallVector<int> MaskOrder;
3360   if (Order.empty()) {
3361     MaskOrder.resize(Mask.size());
3362     std::iota(MaskOrder.begin(), MaskOrder.end(), 0);
3363   } else {
3364     inversePermutation(Order, MaskOrder);
3365   }
3366   reorderReuses(MaskOrder, Mask);
3367   if (ShuffleVectorInst::isIdentityMask(MaskOrder)) {
3368     Order.clear();
3369     return;
3370   }
3371   Order.assign(Mask.size(), Mask.size());
3372   for (unsigned I = 0, E = Mask.size(); I < E; ++I)
3373     if (MaskOrder[I] != UndefMaskElem)
3374       Order[MaskOrder[I]] = I;
3375   fixupOrderingIndices(Order);
3376 }
3377 
3378 Optional<BoUpSLP::OrdersType>
3379 BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) {
3380   assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
3381   unsigned NumScalars = TE.Scalars.size();
3382   OrdersType CurrentOrder(NumScalars, NumScalars);
3383   SmallVector<int> Positions;
3384   SmallBitVector UsedPositions(NumScalars);
3385   const TreeEntry *STE = nullptr;
3386   // Try to find all gathered scalars that are gets vectorized in other
3387   // vectorize node. Here we can have only one single tree vector node to
3388   // correctly identify order of the gathered scalars.
3389   for (unsigned I = 0; I < NumScalars; ++I) {
3390     Value *V = TE.Scalars[I];
3391     if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V))
3392       continue;
3393     if (const auto *LocalSTE = getTreeEntry(V)) {
3394       if (!STE)
3395         STE = LocalSTE;
3396       else if (STE != LocalSTE)
3397         // Take the order only from the single vector node.
3398         return None;
3399       unsigned Lane =
3400           std::distance(STE->Scalars.begin(), find(STE->Scalars, V));
3401       if (Lane >= NumScalars)
3402         return None;
3403       if (CurrentOrder[Lane] != NumScalars) {
3404         if (Lane != I)
3405           continue;
3406         UsedPositions.reset(CurrentOrder[Lane]);
3407       }
3408       // The partial identity (where only some elements of the gather node are
3409       // in the identity order) is good.
3410       CurrentOrder[Lane] = I;
3411       UsedPositions.set(I);
3412     }
3413   }
3414   // Need to keep the order if we have a vector entry and at least 2 scalars or
3415   // the vectorized entry has just 2 scalars.
3416   if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) {
3417     auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) {
3418       for (unsigned I = 0; I < NumScalars; ++I)
3419         if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars)
3420           return false;
3421       return true;
3422     };
3423     if (IsIdentityOrder(CurrentOrder)) {
3424       CurrentOrder.clear();
3425       return CurrentOrder;
3426     }
3427     auto *It = CurrentOrder.begin();
3428     for (unsigned I = 0; I < NumScalars;) {
3429       if (UsedPositions.test(I)) {
3430         ++I;
3431         continue;
3432       }
3433       if (*It == NumScalars) {
3434         *It = I;
3435         ++I;
3436       }
3437       ++It;
3438     }
3439     return CurrentOrder;
3440   }
3441   return None;
3442 }
3443 
3444 Optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE,
3445                                                          bool TopToBottom) {
3446   // No need to reorder if need to shuffle reuses, still need to shuffle the
3447   // node.
3448   if (!TE.ReuseShuffleIndices.empty())
3449     return None;
3450   if (TE.State == TreeEntry::Vectorize &&
3451       (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) ||
3452        (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) &&
3453       !TE.isAltShuffle())
3454     return TE.ReorderIndices;
3455   if (TE.State == TreeEntry::NeedToGather) {
3456     // TODO: add analysis of other gather nodes with extractelement
3457     // instructions and other values/instructions, not only undefs.
3458     if (((TE.getOpcode() == Instruction::ExtractElement &&
3459           !TE.isAltShuffle()) ||
3460          (all_of(TE.Scalars,
3461                  [](Value *V) {
3462                    return isa<UndefValue, ExtractElementInst>(V);
3463                  }) &&
3464           any_of(TE.Scalars,
3465                  [](Value *V) { return isa<ExtractElementInst>(V); }))) &&
3466         all_of(TE.Scalars,
3467                [](Value *V) {
3468                  auto *EE = dyn_cast<ExtractElementInst>(V);
3469                  return !EE || isa<FixedVectorType>(EE->getVectorOperandType());
3470                }) &&
3471         allSameType(TE.Scalars)) {
3472       // Check that gather of extractelements can be represented as
3473       // just a shuffle of a single vector.
3474       OrdersType CurrentOrder;
3475       bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder);
3476       if (Reuse || !CurrentOrder.empty()) {
3477         if (!CurrentOrder.empty())
3478           fixupOrderingIndices(CurrentOrder);
3479         return CurrentOrder;
3480       }
3481     }
3482     if (Optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE))
3483       return CurrentOrder;
3484   }
3485   return None;
3486 }
3487 
3488 void BoUpSLP::reorderTopToBottom() {
3489   // Maps VF to the graph nodes.
3490   DenseMap<unsigned, SetVector<TreeEntry *>> VFToOrderedEntries;
3491   // ExtractElement gather nodes which can be vectorized and need to handle
3492   // their ordering.
3493   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3494   // Find all reorderable nodes with the given VF.
3495   // Currently the are vectorized stores,loads,extracts + some gathering of
3496   // extracts.
3497   for_each(VectorizableTree, [this, &VFToOrderedEntries, &GathersToOrders](
3498                                  const std::unique_ptr<TreeEntry> &TE) {
3499     if (Optional<OrdersType> CurrentOrder =
3500             getReorderingData(*TE, /*TopToBottom=*/true)) {
3501       // Do not include ordering for nodes used in the alt opcode vectorization,
3502       // better to reorder them during bottom-to-top stage. If follow the order
3503       // here, it causes reordering of the whole graph though actually it is
3504       // profitable just to reorder the subgraph that starts from the alternate
3505       // opcode vectorization node. Such nodes already end-up with the shuffle
3506       // instruction and it is just enough to change this shuffle rather than
3507       // rotate the scalars for the whole graph.
3508       unsigned Cnt = 0;
3509       const TreeEntry *UserTE = TE.get();
3510       while (UserTE && Cnt < RecursionMaxDepth) {
3511         if (UserTE->UserTreeIndices.size() != 1)
3512           break;
3513         if (all_of(UserTE->UserTreeIndices, [](const EdgeInfo &EI) {
3514               return EI.UserTE->State == TreeEntry::Vectorize &&
3515                      EI.UserTE->isAltShuffle() && EI.UserTE->Idx != 0;
3516             }))
3517           return;
3518         if (UserTE->UserTreeIndices.empty())
3519           UserTE = nullptr;
3520         else
3521           UserTE = UserTE->UserTreeIndices.back().UserTE;
3522         ++Cnt;
3523       }
3524       VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
3525       if (TE->State != TreeEntry::Vectorize)
3526         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3527     }
3528   });
3529 
3530   // Reorder the graph nodes according to their vectorization factor.
3531   for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1;
3532        VF /= 2) {
3533     auto It = VFToOrderedEntries.find(VF);
3534     if (It == VFToOrderedEntries.end())
3535       continue;
3536     // Try to find the most profitable order. We just are looking for the most
3537     // used order and reorder scalar elements in the nodes according to this
3538     // mostly used order.
3539     ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef();
3540     // All operands are reordered and used only in this node - propagate the
3541     // most used order to the user node.
3542     MapVector<OrdersType, unsigned,
3543               DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3544         OrdersUses;
3545     SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3546     for (const TreeEntry *OpTE : OrderedEntries) {
3547       // No need to reorder this nodes, still need to extend and to use shuffle,
3548       // just need to merge reordering shuffle and the reuse shuffle.
3549       if (!OpTE->ReuseShuffleIndices.empty())
3550         continue;
3551       // Count number of orders uses.
3552       const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3553         if (OpTE->State == TreeEntry::NeedToGather)
3554           return GathersToOrders.find(OpTE)->second;
3555         return OpTE->ReorderIndices;
3556       }();
3557       // Stores actually store the mask, not the order, need to invert.
3558       if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3559           OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3560         SmallVector<int> Mask;
3561         inversePermutation(Order, Mask);
3562         unsigned E = Order.size();
3563         OrdersType CurrentOrder(E, E);
3564         transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3565           return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3566         });
3567         fixupOrderingIndices(CurrentOrder);
3568         ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
3569       } else {
3570         ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
3571       }
3572     }
3573     // Set order of the user node.
3574     if (OrdersUses.empty())
3575       continue;
3576     // Choose the most used order.
3577     ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3578     unsigned Cnt = OrdersUses.front().second;
3579     for (const auto &Pair : drop_begin(OrdersUses)) {
3580       if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3581         BestOrder = Pair.first;
3582         Cnt = Pair.second;
3583       }
3584     }
3585     // Set order of the user node.
3586     if (BestOrder.empty())
3587       continue;
3588     SmallVector<int> Mask;
3589     inversePermutation(BestOrder, Mask);
3590     SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3591     unsigned E = BestOrder.size();
3592     transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3593       return I < E ? static_cast<int>(I) : UndefMaskElem;
3594     });
3595     // Do an actual reordering, if profitable.
3596     for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
3597       // Just do the reordering for the nodes with the given VF.
3598       if (TE->Scalars.size() != VF) {
3599         if (TE->ReuseShuffleIndices.size() == VF) {
3600           // Need to reorder the reuses masks of the operands with smaller VF to
3601           // be able to find the match between the graph nodes and scalar
3602           // operands of the given node during vectorization/cost estimation.
3603           assert(all_of(TE->UserTreeIndices,
3604                         [VF, &TE](const EdgeInfo &EI) {
3605                           return EI.UserTE->Scalars.size() == VF ||
3606                                  EI.UserTE->Scalars.size() ==
3607                                      TE->Scalars.size();
3608                         }) &&
3609                  "All users must be of VF size.");
3610           // Update ordering of the operands with the smaller VF than the given
3611           // one.
3612           reorderReuses(TE->ReuseShuffleIndices, Mask);
3613         }
3614         continue;
3615       }
3616       if (TE->State == TreeEntry::Vectorize &&
3617           isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst,
3618               InsertElementInst>(TE->getMainOp()) &&
3619           !TE->isAltShuffle()) {
3620         // Build correct orders for extract{element,value}, loads and
3621         // stores.
3622         reorderOrder(TE->ReorderIndices, Mask);
3623         if (isa<InsertElementInst, StoreInst>(TE->getMainOp()))
3624           TE->reorderOperands(Mask);
3625       } else {
3626         // Reorder the node and its operands.
3627         TE->reorderOperands(Mask);
3628         assert(TE->ReorderIndices.empty() &&
3629                "Expected empty reorder sequence.");
3630         reorderScalars(TE->Scalars, Mask);
3631       }
3632       if (!TE->ReuseShuffleIndices.empty()) {
3633         // Apply reversed order to keep the original ordering of the reused
3634         // elements to avoid extra reorder indices shuffling.
3635         OrdersType CurrentOrder;
3636         reorderOrder(CurrentOrder, MaskOrder);
3637         SmallVector<int> NewReuses;
3638         inversePermutation(CurrentOrder, NewReuses);
3639         addMask(NewReuses, TE->ReuseShuffleIndices);
3640         TE->ReuseShuffleIndices.swap(NewReuses);
3641       }
3642     }
3643   }
3644 }
3645 
3646 bool BoUpSLP::canReorderOperands(
3647     TreeEntry *UserTE, SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
3648     ArrayRef<TreeEntry *> ReorderableGathers,
3649     SmallVectorImpl<TreeEntry *> &GatherOps) {
3650   for (unsigned I = 0, E = UserTE->getNumOperands(); I < E; ++I) {
3651     if (any_of(Edges, [I](const std::pair<unsigned, TreeEntry *> &OpData) {
3652           return OpData.first == I &&
3653                  OpData.second->State == TreeEntry::Vectorize;
3654         }))
3655       continue;
3656     if (TreeEntry *TE = getVectorizedOperand(UserTE, I)) {
3657       // Do not reorder if operand node is used by many user nodes.
3658       if (any_of(TE->UserTreeIndices,
3659                  [UserTE](const EdgeInfo &EI) { return EI.UserTE != UserTE; }))
3660         return false;
3661       // Add the node to the list of the ordered nodes with the identity
3662       // order.
3663       Edges.emplace_back(I, TE);
3664       continue;
3665     }
3666     ArrayRef<Value *> VL = UserTE->getOperand(I);
3667     TreeEntry *Gather = nullptr;
3668     if (count_if(ReorderableGathers, [VL, &Gather](TreeEntry *TE) {
3669           assert(TE->State != TreeEntry::Vectorize &&
3670                  "Only non-vectorized nodes are expected.");
3671           if (TE->isSame(VL)) {
3672             Gather = TE;
3673             return true;
3674           }
3675           return false;
3676         }) > 1)
3677       return false;
3678     if (Gather)
3679       GatherOps.push_back(Gather);
3680   }
3681   return true;
3682 }
3683 
3684 void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) {
3685   SetVector<TreeEntry *> OrderedEntries;
3686   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3687   // Find all reorderable leaf nodes with the given VF.
3688   // Currently the are vectorized loads,extracts without alternate operands +
3689   // some gathering of extracts.
3690   SmallVector<TreeEntry *> NonVectorized;
3691   for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders,
3692                               &NonVectorized](
3693                                  const std::unique_ptr<TreeEntry> &TE) {
3694     if (TE->State != TreeEntry::Vectorize)
3695       NonVectorized.push_back(TE.get());
3696     if (Optional<OrdersType> CurrentOrder =
3697             getReorderingData(*TE, /*TopToBottom=*/false)) {
3698       OrderedEntries.insert(TE.get());
3699       if (TE->State != TreeEntry::Vectorize)
3700         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3701     }
3702   });
3703 
3704   // 1. Propagate order to the graph nodes, which use only reordered nodes.
3705   // I.e., if the node has operands, that are reordered, try to make at least
3706   // one operand order in the natural order and reorder others + reorder the
3707   // user node itself.
3708   SmallPtrSet<const TreeEntry *, 4> Visited;
3709   while (!OrderedEntries.empty()) {
3710     // 1. Filter out only reordered nodes.
3711     // 2. If the entry has multiple uses - skip it and jump to the next node.
3712     MapVector<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users;
3713     SmallVector<TreeEntry *> Filtered;
3714     for (TreeEntry *TE : OrderedEntries) {
3715       if (!(TE->State == TreeEntry::Vectorize ||
3716             (TE->State == TreeEntry::NeedToGather &&
3717              GathersToOrders.count(TE))) ||
3718           TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3719           !all_of(drop_begin(TE->UserTreeIndices),
3720                   [TE](const EdgeInfo &EI) {
3721                     return EI.UserTE == TE->UserTreeIndices.front().UserTE;
3722                   }) ||
3723           !Visited.insert(TE).second) {
3724         Filtered.push_back(TE);
3725         continue;
3726       }
3727       // Build a map between user nodes and their operands order to speedup
3728       // search. The graph currently does not provide this dependency directly.
3729       for (EdgeInfo &EI : TE->UserTreeIndices) {
3730         TreeEntry *UserTE = EI.UserTE;
3731         auto It = Users.find(UserTE);
3732         if (It == Users.end())
3733           It = Users.insert({UserTE, {}}).first;
3734         It->second.emplace_back(EI.EdgeIdx, TE);
3735       }
3736     }
3737     // Erase filtered entries.
3738     for_each(Filtered,
3739              [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); });
3740     for (auto &Data : Users) {
3741       // Check that operands are used only in the User node.
3742       SmallVector<TreeEntry *> GatherOps;
3743       if (!canReorderOperands(Data.first, Data.second, NonVectorized,
3744                               GatherOps)) {
3745         for_each(Data.second,
3746                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3747                    OrderedEntries.remove(Op.second);
3748                  });
3749         continue;
3750       }
3751       // All operands are reordered and used only in this node - propagate the
3752       // most used order to the user node.
3753       MapVector<OrdersType, unsigned,
3754                 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3755           OrdersUses;
3756       // Do the analysis for each tree entry only once, otherwise the order of
3757       // the same node my be considered several times, though might be not
3758       // profitable.
3759       SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3760       SmallPtrSet<const TreeEntry *, 4> VisitedUsers;
3761       for (const auto &Op : Data.second) {
3762         TreeEntry *OpTE = Op.second;
3763         if (!VisitedOps.insert(OpTE).second)
3764           continue;
3765         if (!OpTE->ReuseShuffleIndices.empty() ||
3766             (IgnoreReorder && OpTE == VectorizableTree.front().get()))
3767           continue;
3768         const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3769           if (OpTE->State == TreeEntry::NeedToGather)
3770             return GathersToOrders.find(OpTE)->second;
3771           return OpTE->ReorderIndices;
3772         }();
3773         unsigned NumOps = count_if(
3774             Data.second, [OpTE](const std::pair<unsigned, TreeEntry *> &P) {
3775               return P.second == OpTE;
3776             });
3777         // Stores actually store the mask, not the order, need to invert.
3778         if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3779             OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3780           SmallVector<int> Mask;
3781           inversePermutation(Order, Mask);
3782           unsigned E = Order.size();
3783           OrdersType CurrentOrder(E, E);
3784           transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3785             return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3786           });
3787           fixupOrderingIndices(CurrentOrder);
3788           OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second +=
3789               NumOps;
3790         } else {
3791           OrdersUses.insert(std::make_pair(Order, 0)).first->second += NumOps;
3792         }
3793         auto Res = OrdersUses.insert(std::make_pair(OrdersType(), 0));
3794         const auto &&AllowsReordering = [IgnoreReorder, &GathersToOrders](
3795                                             const TreeEntry *TE) {
3796           if (!TE->ReorderIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3797               (TE->State == TreeEntry::Vectorize && TE->isAltShuffle()) ||
3798               (IgnoreReorder && TE->Idx == 0))
3799             return true;
3800           if (TE->State == TreeEntry::NeedToGather) {
3801             auto It = GathersToOrders.find(TE);
3802             if (It != GathersToOrders.end())
3803               return !It->second.empty();
3804             return true;
3805           }
3806           return false;
3807         };
3808         for (const EdgeInfo &EI : OpTE->UserTreeIndices) {
3809           TreeEntry *UserTE = EI.UserTE;
3810           if (!VisitedUsers.insert(UserTE).second)
3811             continue;
3812           // May reorder user node if it requires reordering, has reused
3813           // scalars, is an alternate op vectorize node or its op nodes require
3814           // reordering.
3815           if (AllowsReordering(UserTE))
3816             continue;
3817           // Check if users allow reordering.
3818           // Currently look up just 1 level of operands to avoid increase of
3819           // the compile time.
3820           // Profitable to reorder if definitely more operands allow
3821           // reordering rather than those with natural order.
3822           ArrayRef<std::pair<unsigned, TreeEntry *>> Ops = Users[UserTE];
3823           if (static_cast<unsigned>(count_if(
3824                   Ops, [UserTE, &AllowsReordering](
3825                            const std::pair<unsigned, TreeEntry *> &Op) {
3826                     return AllowsReordering(Op.second) &&
3827                            all_of(Op.second->UserTreeIndices,
3828                                   [UserTE](const EdgeInfo &EI) {
3829                                     return EI.UserTE == UserTE;
3830                                   });
3831                   })) <= Ops.size() / 2)
3832             ++Res.first->second;
3833         }
3834       }
3835       // If no orders - skip current nodes and jump to the next one, if any.
3836       if (OrdersUses.empty()) {
3837         for_each(Data.second,
3838                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3839                    OrderedEntries.remove(Op.second);
3840                  });
3841         continue;
3842       }
3843       // Choose the best order.
3844       ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3845       unsigned Cnt = OrdersUses.front().second;
3846       for (const auto &Pair : drop_begin(OrdersUses)) {
3847         if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3848           BestOrder = Pair.first;
3849           Cnt = Pair.second;
3850         }
3851       }
3852       // Set order of the user node (reordering of operands and user nodes).
3853       if (BestOrder.empty()) {
3854         for_each(Data.second,
3855                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3856                    OrderedEntries.remove(Op.second);
3857                  });
3858         continue;
3859       }
3860       // Erase operands from OrderedEntries list and adjust their orders.
3861       VisitedOps.clear();
3862       SmallVector<int> Mask;
3863       inversePermutation(BestOrder, Mask);
3864       SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3865       unsigned E = BestOrder.size();
3866       transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3867         return I < E ? static_cast<int>(I) : UndefMaskElem;
3868       });
3869       for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) {
3870         TreeEntry *TE = Op.second;
3871         OrderedEntries.remove(TE);
3872         if (!VisitedOps.insert(TE).second)
3873           continue;
3874         if (TE->ReuseShuffleIndices.size() == BestOrder.size()) {
3875           // Just reorder reuses indices.
3876           reorderReuses(TE->ReuseShuffleIndices, Mask);
3877           continue;
3878         }
3879         // Gathers are processed separately.
3880         if (TE->State != TreeEntry::Vectorize)
3881           continue;
3882         assert((BestOrder.size() == TE->ReorderIndices.size() ||
3883                 TE->ReorderIndices.empty()) &&
3884                "Non-matching sizes of user/operand entries.");
3885         reorderOrder(TE->ReorderIndices, Mask);
3886       }
3887       // For gathers just need to reorder its scalars.
3888       for (TreeEntry *Gather : GatherOps) {
3889         assert(Gather->ReorderIndices.empty() &&
3890                "Unexpected reordering of gathers.");
3891         if (!Gather->ReuseShuffleIndices.empty()) {
3892           // Just reorder reuses indices.
3893           reorderReuses(Gather->ReuseShuffleIndices, Mask);
3894           continue;
3895         }
3896         reorderScalars(Gather->Scalars, Mask);
3897         OrderedEntries.remove(Gather);
3898       }
3899       // Reorder operands of the user node and set the ordering for the user
3900       // node itself.
3901       if (Data.first->State != TreeEntry::Vectorize ||
3902           !isa<ExtractElementInst, ExtractValueInst, LoadInst>(
3903               Data.first->getMainOp()) ||
3904           Data.first->isAltShuffle())
3905         Data.first->reorderOperands(Mask);
3906       if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) ||
3907           Data.first->isAltShuffle()) {
3908         reorderScalars(Data.first->Scalars, Mask);
3909         reorderOrder(Data.first->ReorderIndices, MaskOrder);
3910         if (Data.first->ReuseShuffleIndices.empty() &&
3911             !Data.first->ReorderIndices.empty() &&
3912             !Data.first->isAltShuffle()) {
3913           // Insert user node to the list to try to sink reordering deeper in
3914           // the graph.
3915           OrderedEntries.insert(Data.first);
3916         }
3917       } else {
3918         reorderOrder(Data.first->ReorderIndices, Mask);
3919       }
3920     }
3921   }
3922   // If the reordering is unnecessary, just remove the reorder.
3923   if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() &&
3924       VectorizableTree.front()->ReuseShuffleIndices.empty())
3925     VectorizableTree.front()->ReorderIndices.clear();
3926 }
3927 
3928 void BoUpSLP::buildExternalUses(
3929     const ExtraValueToDebugLocsMap &ExternallyUsedValues) {
3930   // Collect the values that we need to extract from the tree.
3931   for (auto &TEPtr : VectorizableTree) {
3932     TreeEntry *Entry = TEPtr.get();
3933 
3934     // No need to handle users of gathered values.
3935     if (Entry->State == TreeEntry::NeedToGather)
3936       continue;
3937 
3938     // For each lane:
3939     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
3940       Value *Scalar = Entry->Scalars[Lane];
3941       int FoundLane = Entry->findLaneForValue(Scalar);
3942 
3943       // Check if the scalar is externally used as an extra arg.
3944       auto ExtI = ExternallyUsedValues.find(Scalar);
3945       if (ExtI != ExternallyUsedValues.end()) {
3946         LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
3947                           << Lane << " from " << *Scalar << ".\n");
3948         ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
3949       }
3950       for (User *U : Scalar->users()) {
3951         LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
3952 
3953         Instruction *UserInst = dyn_cast<Instruction>(U);
3954         if (!UserInst)
3955           continue;
3956 
3957         if (isDeleted(UserInst))
3958           continue;
3959 
3960         // Skip in-tree scalars that become vectors
3961         if (TreeEntry *UseEntry = getTreeEntry(U)) {
3962           Value *UseScalar = UseEntry->Scalars[0];
3963           // Some in-tree scalars will remain as scalar in vectorized
3964           // instructions. If that is the case, the one in Lane 0 will
3965           // be used.
3966           if (UseScalar != U ||
3967               UseEntry->State == TreeEntry::ScatterVectorize ||
3968               !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
3969             LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
3970                               << ".\n");
3971             assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state");
3972             continue;
3973           }
3974         }
3975 
3976         // Ignore users in the user ignore list.
3977         if (is_contained(UserIgnoreList, UserInst))
3978           continue;
3979 
3980         LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
3981                           << Lane << " from " << *Scalar << ".\n");
3982         ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
3983       }
3984     }
3985   }
3986 }
3987 
3988 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
3989                         ArrayRef<Value *> UserIgnoreLst) {
3990   deleteTree();
3991   UserIgnoreList = UserIgnoreLst;
3992   if (!allSameType(Roots))
3993     return;
3994   buildTree_rec(Roots, 0, EdgeInfo());
3995 }
3996 
3997 namespace {
3998 /// Tracks the state we can represent the loads in the given sequence.
3999 enum class LoadsState { Gather, Vectorize, ScatterVectorize };
4000 } // anonymous namespace
4001 
4002 /// Checks if the given array of loads can be represented as a vectorized,
4003 /// scatter or just simple gather.
4004 static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0,
4005                                     const TargetTransformInfo &TTI,
4006                                     const DataLayout &DL, ScalarEvolution &SE,
4007                                     SmallVectorImpl<unsigned> &Order,
4008                                     SmallVectorImpl<Value *> &PointerOps) {
4009   // Check that a vectorized load would load the same memory as a scalar
4010   // load. For example, we don't want to vectorize loads that are smaller
4011   // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
4012   // treats loading/storing it as an i8 struct. If we vectorize loads/stores
4013   // from such a struct, we read/write packed bits disagreeing with the
4014   // unvectorized version.
4015   Type *ScalarTy = VL0->getType();
4016 
4017   if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy))
4018     return LoadsState::Gather;
4019 
4020   // Make sure all loads in the bundle are simple - we can't vectorize
4021   // atomic or volatile loads.
4022   PointerOps.clear();
4023   PointerOps.resize(VL.size());
4024   auto *POIter = PointerOps.begin();
4025   for (Value *V : VL) {
4026     auto *L = cast<LoadInst>(V);
4027     if (!L->isSimple())
4028       return LoadsState::Gather;
4029     *POIter = L->getPointerOperand();
4030     ++POIter;
4031   }
4032 
4033   Order.clear();
4034   // Check the order of pointer operands.
4035   if (llvm::sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order)) {
4036     Value *Ptr0;
4037     Value *PtrN;
4038     if (Order.empty()) {
4039       Ptr0 = PointerOps.front();
4040       PtrN = PointerOps.back();
4041     } else {
4042       Ptr0 = PointerOps[Order.front()];
4043       PtrN = PointerOps[Order.back()];
4044     }
4045     Optional<int> Diff =
4046         getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE);
4047     // Check that the sorted loads are consecutive.
4048     if (static_cast<unsigned>(*Diff) == VL.size() - 1)
4049       return LoadsState::Vectorize;
4050     Align CommonAlignment = cast<LoadInst>(VL0)->getAlign();
4051     for (Value *V : VL)
4052       CommonAlignment =
4053           commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
4054     if (TTI.isLegalMaskedGather(FixedVectorType::get(ScalarTy, VL.size()),
4055                                 CommonAlignment))
4056       return LoadsState::ScatterVectorize;
4057   }
4058 
4059   return LoadsState::Gather;
4060 }
4061 
4062 /// \return true if the specified list of values has only one instruction that
4063 /// requires scheduling, false otherwise.
4064 #ifndef NDEBUG
4065 static bool needToScheduleSingleInstruction(ArrayRef<Value *> VL) {
4066   Value *NeedsScheduling = nullptr;
4067   for (Value *V : VL) {
4068     if (doesNotNeedToBeScheduled(V))
4069       continue;
4070     if (!NeedsScheduling) {
4071       NeedsScheduling = V;
4072       continue;
4073     }
4074     return false;
4075   }
4076   return NeedsScheduling;
4077 }
4078 #endif
4079 
4080 /// Generates key/subkey pair for the given value to provide effective sorting
4081 /// of the values and better detection of the vectorizable values sequences. The
4082 /// keys/subkeys can be used for better sorting of the values themselves (keys)
4083 /// and in values subgroups (subkeys).
4084 static std::pair<size_t, size_t> generateKeySubkey(
4085     Value *V, const TargetLibraryInfo *TLI,
4086     function_ref<hash_code(size_t, LoadInst *)> LoadsSubkeyGenerator,
4087     bool AllowAlternate) {
4088   hash_code Key = hash_value(V->getValueID() + 2);
4089   hash_code SubKey = hash_value(0);
4090   // Sort the loads by the distance between the pointers.
4091   if (auto *LI = dyn_cast<LoadInst>(V)) {
4092     Key = hash_combine(hash_value(Instruction::Load), Key);
4093     if (LI->isSimple())
4094       SubKey = hash_value(LoadsSubkeyGenerator(Key, LI));
4095     else
4096       SubKey = hash_value(LI);
4097   } else if (isVectorLikeInstWithConstOps(V)) {
4098     // Sort extracts by the vector operands.
4099     if (isa<ExtractElementInst, UndefValue>(V))
4100       Key = hash_value(Value::UndefValueVal + 1);
4101     if (auto *EI = dyn_cast<ExtractElementInst>(V)) {
4102       if (!isUndefVector(EI->getVectorOperand()) &&
4103           !isa<UndefValue>(EI->getIndexOperand()))
4104         SubKey = hash_value(EI->getVectorOperand());
4105     }
4106   } else if (auto *I = dyn_cast<Instruction>(V)) {
4107     // Sort other instructions just by the opcodes except for CMPInst.
4108     // For CMP also sort by the predicate kind.
4109     if ((isa<BinaryOperator>(I) || isa<CastInst>(I)) &&
4110         isValidForAlternation(I->getOpcode())) {
4111       if (AllowAlternate)
4112         Key = hash_value(isa<BinaryOperator>(I) ? 1 : 0);
4113       else
4114         Key = hash_combine(hash_value(I->getOpcode()), Key);
4115       SubKey = hash_combine(
4116           hash_value(I->getOpcode()), hash_value(I->getType()),
4117           hash_value(isa<BinaryOperator>(I)
4118                          ? I->getType()
4119                          : cast<CastInst>(I)->getOperand(0)->getType()));
4120     } else if (auto *CI = dyn_cast<CmpInst>(I)) {
4121       CmpInst::Predicate Pred = CI->getPredicate();
4122       if (CI->isCommutative())
4123         Pred = std::min(Pred, CmpInst::getInversePredicate(Pred));
4124       CmpInst::Predicate SwapPred = CmpInst::getSwappedPredicate(Pred);
4125       SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(Pred),
4126                             hash_value(SwapPred),
4127                             hash_value(CI->getOperand(0)->getType()));
4128     } else if (auto *Call = dyn_cast<CallInst>(I)) {
4129       Intrinsic::ID ID = getVectorIntrinsicIDForCall(Call, TLI);
4130       if (isTriviallyVectorizable(ID))
4131         SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(ID));
4132       else if (!VFDatabase(*Call).getMappings(*Call).empty())
4133         SubKey = hash_combine(hash_value(I->getOpcode()),
4134                               hash_value(Call->getCalledFunction()));
4135       else
4136         SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(Call));
4137       for (const CallBase::BundleOpInfo &Op : Call->bundle_op_infos())
4138         SubKey = hash_combine(hash_value(Op.Begin), hash_value(Op.End),
4139                               hash_value(Op.Tag), SubKey);
4140     } else if (auto *Gep = dyn_cast<GetElementPtrInst>(I)) {
4141       if (Gep->getNumOperands() == 2 && isa<ConstantInt>(Gep->getOperand(1)))
4142         SubKey = hash_value(Gep->getPointerOperand());
4143       else
4144         SubKey = hash_value(Gep);
4145     } else if (BinaryOperator::isIntDivRem(I->getOpcode()) &&
4146                !isa<ConstantInt>(I->getOperand(1))) {
4147       // Do not try to vectorize instructions with potentially high cost.
4148       SubKey = hash_value(I);
4149     } else {
4150       SubKey = hash_value(I->getOpcode());
4151     }
4152     Key = hash_combine(hash_value(I->getParent()), Key);
4153   }
4154   return std::make_pair(Key, SubKey);
4155 }
4156 
4157 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
4158                             const EdgeInfo &UserTreeIdx) {
4159   assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
4160 
4161   SmallVector<int> ReuseShuffleIndicies;
4162   SmallVector<Value *> UniqueValues;
4163   auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues,
4164                                 &UserTreeIdx,
4165                                 this](const InstructionsState &S) {
4166     // Check that every instruction appears once in this bundle.
4167     DenseMap<Value *, unsigned> UniquePositions;
4168     for (Value *V : VL) {
4169       if (isConstant(V)) {
4170         ReuseShuffleIndicies.emplace_back(
4171             isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size());
4172         UniqueValues.emplace_back(V);
4173         continue;
4174       }
4175       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
4176       ReuseShuffleIndicies.emplace_back(Res.first->second);
4177       if (Res.second)
4178         UniqueValues.emplace_back(V);
4179     }
4180     size_t NumUniqueScalarValues = UniqueValues.size();
4181     if (NumUniqueScalarValues == VL.size()) {
4182       ReuseShuffleIndicies.clear();
4183     } else {
4184       LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
4185       if (NumUniqueScalarValues <= 1 ||
4186           (UniquePositions.size() == 1 && all_of(UniqueValues,
4187                                                  [](Value *V) {
4188                                                    return isa<UndefValue>(V) ||
4189                                                           !isConstant(V);
4190                                                  })) ||
4191           !llvm::isPowerOf2_32(NumUniqueScalarValues)) {
4192         LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
4193         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4194         return false;
4195       }
4196       VL = UniqueValues;
4197     }
4198     return true;
4199   };
4200 
4201   InstructionsState S = getSameOpcode(VL);
4202   if (Depth == RecursionMaxDepth) {
4203     LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
4204     if (TryToFindDuplicates(S))
4205       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4206                    ReuseShuffleIndicies);
4207     return;
4208   }
4209 
4210   // Don't handle scalable vectors
4211   if (S.getOpcode() == Instruction::ExtractElement &&
4212       isa<ScalableVectorType>(
4213           cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) {
4214     LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n");
4215     if (TryToFindDuplicates(S))
4216       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4217                    ReuseShuffleIndicies);
4218     return;
4219   }
4220 
4221   // Don't handle vectors.
4222   if (S.OpValue->getType()->isVectorTy() &&
4223       !isa<InsertElementInst>(S.OpValue)) {
4224     LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
4225     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4226     return;
4227   }
4228 
4229   if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
4230     if (SI->getValueOperand()->getType()->isVectorTy()) {
4231       LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
4232       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4233       return;
4234     }
4235 
4236   // If all of the operands are identical or constant we have a simple solution.
4237   // If we deal with insert/extract instructions, they all must have constant
4238   // indices, otherwise we should gather them, not try to vectorize.
4239   if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode() ||
4240       (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(S.MainOp) &&
4241        !all_of(VL, isVectorLikeInstWithConstOps))) {
4242     LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
4243     if (TryToFindDuplicates(S))
4244       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4245                    ReuseShuffleIndicies);
4246     return;
4247   }
4248 
4249   // We now know that this is a vector of instructions of the same type from
4250   // the same block.
4251 
4252   // Don't vectorize ephemeral values.
4253   for (Value *V : VL) {
4254     if (EphValues.count(V)) {
4255       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
4256                         << ") is ephemeral.\n");
4257       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4258       return;
4259     }
4260   }
4261 
4262   // Check if this is a duplicate of another entry.
4263   if (TreeEntry *E = getTreeEntry(S.OpValue)) {
4264     LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n");
4265     if (!E->isSame(VL)) {
4266       LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
4267       if (TryToFindDuplicates(S))
4268         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4269                      ReuseShuffleIndicies);
4270       return;
4271     }
4272     // Record the reuse of the tree node.  FIXME, currently this is only used to
4273     // properly draw the graph rather than for the actual vectorization.
4274     E->UserTreeIndices.push_back(UserTreeIdx);
4275     LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue
4276                       << ".\n");
4277     return;
4278   }
4279 
4280   // Check that none of the instructions in the bundle are already in the tree.
4281   for (Value *V : VL) {
4282     auto *I = dyn_cast<Instruction>(V);
4283     if (!I)
4284       continue;
4285     if (getTreeEntry(I)) {
4286       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
4287                         << ") is already in tree.\n");
4288       if (TryToFindDuplicates(S))
4289         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4290                      ReuseShuffleIndicies);
4291       return;
4292     }
4293   }
4294 
4295   // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
4296   for (Value *V : VL) {
4297     if (is_contained(UserIgnoreList, V)) {
4298       LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
4299       if (TryToFindDuplicates(S))
4300         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4301                      ReuseShuffleIndicies);
4302       return;
4303     }
4304   }
4305 
4306   // Check that all of the users of the scalars that we want to vectorize are
4307   // schedulable.
4308   auto *VL0 = cast<Instruction>(S.OpValue);
4309   BasicBlock *BB = VL0->getParent();
4310 
4311   if (!DT->isReachableFromEntry(BB)) {
4312     // Don't go into unreachable blocks. They may contain instructions with
4313     // dependency cycles which confuse the final scheduling.
4314     LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
4315     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4316     return;
4317   }
4318 
4319   // Check that every instruction appears once in this bundle.
4320   if (!TryToFindDuplicates(S))
4321     return;
4322 
4323   auto &BSRef = BlocksSchedules[BB];
4324   if (!BSRef)
4325     BSRef = std::make_unique<BlockScheduling>(BB);
4326 
4327   BlockScheduling &BS = *BSRef;
4328 
4329   Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S);
4330 #ifdef EXPENSIVE_CHECKS
4331   // Make sure we didn't break any internal invariants
4332   BS.verify();
4333 #endif
4334   if (!Bundle) {
4335     LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
4336     assert((!BS.getScheduleData(VL0) ||
4337             !BS.getScheduleData(VL0)->isPartOfBundle()) &&
4338            "tryScheduleBundle should cancelScheduling on failure");
4339     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4340                  ReuseShuffleIndicies);
4341     return;
4342   }
4343   LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
4344 
4345   unsigned ShuffleOrOp = S.isAltShuffle() ?
4346                 (unsigned) Instruction::ShuffleVector : S.getOpcode();
4347   switch (ShuffleOrOp) {
4348     case Instruction::PHI: {
4349       auto *PH = cast<PHINode>(VL0);
4350 
4351       // Check for terminator values (e.g. invoke).
4352       for (Value *V : VL)
4353         for (Value *Incoming : cast<PHINode>(V)->incoming_values()) {
4354           Instruction *Term = dyn_cast<Instruction>(Incoming);
4355           if (Term && Term->isTerminator()) {
4356             LLVM_DEBUG(dbgs()
4357                        << "SLP: Need to swizzle PHINodes (terminator use).\n");
4358             BS.cancelScheduling(VL, VL0);
4359             newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4360                          ReuseShuffleIndicies);
4361             return;
4362           }
4363         }
4364 
4365       TreeEntry *TE =
4366           newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies);
4367       LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
4368 
4369       // Keeps the reordered operands to avoid code duplication.
4370       SmallVector<ValueList, 2> OperandsVec;
4371       for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
4372         if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) {
4373           ValueList Operands(VL.size(), PoisonValue::get(PH->getType()));
4374           TE->setOperand(I, Operands);
4375           OperandsVec.push_back(Operands);
4376           continue;
4377         }
4378         ValueList Operands;
4379         // Prepare the operand vector.
4380         for (Value *V : VL)
4381           Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(
4382               PH->getIncomingBlock(I)));
4383         TE->setOperand(I, Operands);
4384         OperandsVec.push_back(Operands);
4385       }
4386       for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx)
4387         buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx});
4388       return;
4389     }
4390     case Instruction::ExtractValue:
4391     case Instruction::ExtractElement: {
4392       OrdersType CurrentOrder;
4393       bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
4394       if (Reuse) {
4395         LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
4396         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4397                      ReuseShuffleIndicies);
4398         // This is a special case, as it does not gather, but at the same time
4399         // we are not extending buildTree_rec() towards the operands.
4400         ValueList Op0;
4401         Op0.assign(VL.size(), VL0->getOperand(0));
4402         VectorizableTree.back()->setOperand(0, Op0);
4403         return;
4404       }
4405       if (!CurrentOrder.empty()) {
4406         LLVM_DEBUG({
4407           dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
4408                     "with order";
4409           for (unsigned Idx : CurrentOrder)
4410             dbgs() << " " << Idx;
4411           dbgs() << "\n";
4412         });
4413         fixupOrderingIndices(CurrentOrder);
4414         // Insert new order with initial value 0, if it does not exist,
4415         // otherwise return the iterator to the existing one.
4416         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4417                      ReuseShuffleIndicies, CurrentOrder);
4418         // This is a special case, as it does not gather, but at the same time
4419         // we are not extending buildTree_rec() towards the operands.
4420         ValueList Op0;
4421         Op0.assign(VL.size(), VL0->getOperand(0));
4422         VectorizableTree.back()->setOperand(0, Op0);
4423         return;
4424       }
4425       LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
4426       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4427                    ReuseShuffleIndicies);
4428       BS.cancelScheduling(VL, VL0);
4429       return;
4430     }
4431     case Instruction::InsertElement: {
4432       assert(ReuseShuffleIndicies.empty() && "All inserts should be unique");
4433 
4434       // Check that we have a buildvector and not a shuffle of 2 or more
4435       // different vectors.
4436       ValueSet SourceVectors;
4437       for (Value *V : VL) {
4438         SourceVectors.insert(cast<Instruction>(V)->getOperand(0));
4439         assert(getInsertIndex(V) != None && "Non-constant or undef index?");
4440       }
4441 
4442       if (count_if(VL, [&SourceVectors](Value *V) {
4443             return !SourceVectors.contains(V);
4444           }) >= 2) {
4445         // Found 2nd source vector - cancel.
4446         LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with "
4447                              "different source vectors.\n");
4448         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4449         BS.cancelScheduling(VL, VL0);
4450         return;
4451       }
4452 
4453       auto OrdCompare = [](const std::pair<int, int> &P1,
4454                            const std::pair<int, int> &P2) {
4455         return P1.first > P2.first;
4456       };
4457       PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>,
4458                     decltype(OrdCompare)>
4459           Indices(OrdCompare);
4460       for (int I = 0, E = VL.size(); I < E; ++I) {
4461         unsigned Idx = *getInsertIndex(VL[I]);
4462         Indices.emplace(Idx, I);
4463       }
4464       OrdersType CurrentOrder(VL.size(), VL.size());
4465       bool IsIdentity = true;
4466       for (int I = 0, E = VL.size(); I < E; ++I) {
4467         CurrentOrder[Indices.top().second] = I;
4468         IsIdentity &= Indices.top().second == I;
4469         Indices.pop();
4470       }
4471       if (IsIdentity)
4472         CurrentOrder.clear();
4473       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4474                                    None, CurrentOrder);
4475       LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n");
4476 
4477       constexpr int NumOps = 2;
4478       ValueList VectorOperands[NumOps];
4479       for (int I = 0; I < NumOps; ++I) {
4480         for (Value *V : VL)
4481           VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I));
4482 
4483         TE->setOperand(I, VectorOperands[I]);
4484       }
4485       buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1});
4486       return;
4487     }
4488     case Instruction::Load: {
4489       // Check that a vectorized load would load the same memory as a scalar
4490       // load. For example, we don't want to vectorize loads that are smaller
4491       // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
4492       // treats loading/storing it as an i8 struct. If we vectorize loads/stores
4493       // from such a struct, we read/write packed bits disagreeing with the
4494       // unvectorized version.
4495       SmallVector<Value *> PointerOps;
4496       OrdersType CurrentOrder;
4497       TreeEntry *TE = nullptr;
4498       switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, CurrentOrder,
4499                                 PointerOps)) {
4500       case LoadsState::Vectorize:
4501         if (CurrentOrder.empty()) {
4502           // Original loads are consecutive and does not require reordering.
4503           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4504                             ReuseShuffleIndicies);
4505           LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
4506         } else {
4507           fixupOrderingIndices(CurrentOrder);
4508           // Need to reorder.
4509           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4510                             ReuseShuffleIndicies, CurrentOrder);
4511           LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
4512         }
4513         TE->setOperandsInOrder();
4514         break;
4515       case LoadsState::ScatterVectorize:
4516         // Vectorizing non-consecutive loads with `llvm.masked.gather`.
4517         TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S,
4518                           UserTreeIdx, ReuseShuffleIndicies);
4519         TE->setOperandsInOrder();
4520         buildTree_rec(PointerOps, Depth + 1, {TE, 0});
4521         LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n");
4522         break;
4523       case LoadsState::Gather:
4524         BS.cancelScheduling(VL, VL0);
4525         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4526                      ReuseShuffleIndicies);
4527 #ifndef NDEBUG
4528         Type *ScalarTy = VL0->getType();
4529         if (DL->getTypeSizeInBits(ScalarTy) !=
4530             DL->getTypeAllocSizeInBits(ScalarTy))
4531           LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
4532         else if (any_of(VL, [](Value *V) {
4533                    return !cast<LoadInst>(V)->isSimple();
4534                  }))
4535           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
4536         else
4537           LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
4538 #endif // NDEBUG
4539         break;
4540       }
4541       return;
4542     }
4543     case Instruction::ZExt:
4544     case Instruction::SExt:
4545     case Instruction::FPToUI:
4546     case Instruction::FPToSI:
4547     case Instruction::FPExt:
4548     case Instruction::PtrToInt:
4549     case Instruction::IntToPtr:
4550     case Instruction::SIToFP:
4551     case Instruction::UIToFP:
4552     case Instruction::Trunc:
4553     case Instruction::FPTrunc:
4554     case Instruction::BitCast: {
4555       Type *SrcTy = VL0->getOperand(0)->getType();
4556       for (Value *V : VL) {
4557         Type *Ty = cast<Instruction>(V)->getOperand(0)->getType();
4558         if (Ty != SrcTy || !isValidElementType(Ty)) {
4559           BS.cancelScheduling(VL, VL0);
4560           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4561                        ReuseShuffleIndicies);
4562           LLVM_DEBUG(dbgs()
4563                      << "SLP: Gathering casts with different src types.\n");
4564           return;
4565         }
4566       }
4567       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4568                                    ReuseShuffleIndicies);
4569       LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
4570 
4571       TE->setOperandsInOrder();
4572       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4573         ValueList Operands;
4574         // Prepare the operand vector.
4575         for (Value *V : VL)
4576           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4577 
4578         buildTree_rec(Operands, Depth + 1, {TE, i});
4579       }
4580       return;
4581     }
4582     case Instruction::ICmp:
4583     case Instruction::FCmp: {
4584       // Check that all of the compares have the same predicate.
4585       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
4586       CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0);
4587       Type *ComparedTy = VL0->getOperand(0)->getType();
4588       for (Value *V : VL) {
4589         CmpInst *Cmp = cast<CmpInst>(V);
4590         if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) ||
4591             Cmp->getOperand(0)->getType() != ComparedTy) {
4592           BS.cancelScheduling(VL, VL0);
4593           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4594                        ReuseShuffleIndicies);
4595           LLVM_DEBUG(dbgs()
4596                      << "SLP: Gathering cmp with different predicate.\n");
4597           return;
4598         }
4599       }
4600 
4601       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4602                                    ReuseShuffleIndicies);
4603       LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
4604 
4605       ValueList Left, Right;
4606       if (cast<CmpInst>(VL0)->isCommutative()) {
4607         // Commutative predicate - collect + sort operands of the instructions
4608         // so that each side is more likely to have the same opcode.
4609         assert(P0 == SwapP0 && "Commutative Predicate mismatch");
4610         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4611       } else {
4612         // Collect operands - commute if it uses the swapped predicate.
4613         for (Value *V : VL) {
4614           auto *Cmp = cast<CmpInst>(V);
4615           Value *LHS = Cmp->getOperand(0);
4616           Value *RHS = Cmp->getOperand(1);
4617           if (Cmp->getPredicate() != P0)
4618             std::swap(LHS, RHS);
4619           Left.push_back(LHS);
4620           Right.push_back(RHS);
4621         }
4622       }
4623       TE->setOperand(0, Left);
4624       TE->setOperand(1, Right);
4625       buildTree_rec(Left, Depth + 1, {TE, 0});
4626       buildTree_rec(Right, Depth + 1, {TE, 1});
4627       return;
4628     }
4629     case Instruction::Select:
4630     case Instruction::FNeg:
4631     case Instruction::Add:
4632     case Instruction::FAdd:
4633     case Instruction::Sub:
4634     case Instruction::FSub:
4635     case Instruction::Mul:
4636     case Instruction::FMul:
4637     case Instruction::UDiv:
4638     case Instruction::SDiv:
4639     case Instruction::FDiv:
4640     case Instruction::URem:
4641     case Instruction::SRem:
4642     case Instruction::FRem:
4643     case Instruction::Shl:
4644     case Instruction::LShr:
4645     case Instruction::AShr:
4646     case Instruction::And:
4647     case Instruction::Or:
4648     case Instruction::Xor: {
4649       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4650                                    ReuseShuffleIndicies);
4651       LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n");
4652 
4653       // Sort operands of the instructions so that each side is more likely to
4654       // have the same opcode.
4655       if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
4656         ValueList Left, Right;
4657         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4658         TE->setOperand(0, Left);
4659         TE->setOperand(1, Right);
4660         buildTree_rec(Left, Depth + 1, {TE, 0});
4661         buildTree_rec(Right, Depth + 1, {TE, 1});
4662         return;
4663       }
4664 
4665       TE->setOperandsInOrder();
4666       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4667         ValueList Operands;
4668         // Prepare the operand vector.
4669         for (Value *V : VL)
4670           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4671 
4672         buildTree_rec(Operands, Depth + 1, {TE, i});
4673       }
4674       return;
4675     }
4676     case Instruction::GetElementPtr: {
4677       // We don't combine GEPs with complicated (nested) indexing.
4678       for (Value *V : VL) {
4679         if (cast<Instruction>(V)->getNumOperands() != 2) {
4680           LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
4681           BS.cancelScheduling(VL, VL0);
4682           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4683                        ReuseShuffleIndicies);
4684           return;
4685         }
4686       }
4687 
4688       // We can't combine several GEPs into one vector if they operate on
4689       // different types.
4690       Type *Ty0 = cast<GEPOperator>(VL0)->getSourceElementType();
4691       for (Value *V : VL) {
4692         Type *CurTy = cast<GEPOperator>(V)->getSourceElementType();
4693         if (Ty0 != CurTy) {
4694           LLVM_DEBUG(dbgs()
4695                      << "SLP: not-vectorizable GEP (different types).\n");
4696           BS.cancelScheduling(VL, VL0);
4697           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4698                        ReuseShuffleIndicies);
4699           return;
4700         }
4701       }
4702 
4703       // We don't combine GEPs with non-constant indexes.
4704       Type *Ty1 = VL0->getOperand(1)->getType();
4705       for (Value *V : VL) {
4706         auto Op = cast<Instruction>(V)->getOperand(1);
4707         if (!isa<ConstantInt>(Op) ||
4708             (Op->getType() != Ty1 &&
4709              Op->getType()->getScalarSizeInBits() >
4710                  DL->getIndexSizeInBits(
4711                      V->getType()->getPointerAddressSpace()))) {
4712           LLVM_DEBUG(dbgs()
4713                      << "SLP: not-vectorizable GEP (non-constant indexes).\n");
4714           BS.cancelScheduling(VL, VL0);
4715           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4716                        ReuseShuffleIndicies);
4717           return;
4718         }
4719       }
4720 
4721       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4722                                    ReuseShuffleIndicies);
4723       LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
4724       SmallVector<ValueList, 2> Operands(2);
4725       // Prepare the operand vector for pointer operands.
4726       for (Value *V : VL)
4727         Operands.front().push_back(
4728             cast<GetElementPtrInst>(V)->getPointerOperand());
4729       TE->setOperand(0, Operands.front());
4730       // Need to cast all indices to the same type before vectorization to
4731       // avoid crash.
4732       // Required to be able to find correct matches between different gather
4733       // nodes and reuse the vectorized values rather than trying to gather them
4734       // again.
4735       int IndexIdx = 1;
4736       Type *VL0Ty = VL0->getOperand(IndexIdx)->getType();
4737       Type *Ty = all_of(VL,
4738                         [VL0Ty, IndexIdx](Value *V) {
4739                           return VL0Ty == cast<GetElementPtrInst>(V)
4740                                               ->getOperand(IndexIdx)
4741                                               ->getType();
4742                         })
4743                      ? VL0Ty
4744                      : DL->getIndexType(cast<GetElementPtrInst>(VL0)
4745                                             ->getPointerOperandType()
4746                                             ->getScalarType());
4747       // Prepare the operand vector.
4748       for (Value *V : VL) {
4749         auto *Op = cast<Instruction>(V)->getOperand(IndexIdx);
4750         auto *CI = cast<ConstantInt>(Op);
4751         Operands.back().push_back(ConstantExpr::getIntegerCast(
4752             CI, Ty, CI->getValue().isSignBitSet()));
4753       }
4754       TE->setOperand(IndexIdx, Operands.back());
4755 
4756       for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I)
4757         buildTree_rec(Operands[I], Depth + 1, {TE, I});
4758       return;
4759     }
4760     case Instruction::Store: {
4761       // Check if the stores are consecutive or if we need to swizzle them.
4762       llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType();
4763       // Avoid types that are padded when being allocated as scalars, while
4764       // being packed together in a vector (such as i1).
4765       if (DL->getTypeSizeInBits(ScalarTy) !=
4766           DL->getTypeAllocSizeInBits(ScalarTy)) {
4767         BS.cancelScheduling(VL, VL0);
4768         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4769                      ReuseShuffleIndicies);
4770         LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n");
4771         return;
4772       }
4773       // Make sure all stores in the bundle are simple - we can't vectorize
4774       // atomic or volatile stores.
4775       SmallVector<Value *, 4> PointerOps(VL.size());
4776       ValueList Operands(VL.size());
4777       auto POIter = PointerOps.begin();
4778       auto OIter = Operands.begin();
4779       for (Value *V : VL) {
4780         auto *SI = cast<StoreInst>(V);
4781         if (!SI->isSimple()) {
4782           BS.cancelScheduling(VL, VL0);
4783           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4784                        ReuseShuffleIndicies);
4785           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n");
4786           return;
4787         }
4788         *POIter = SI->getPointerOperand();
4789         *OIter = SI->getValueOperand();
4790         ++POIter;
4791         ++OIter;
4792       }
4793 
4794       OrdersType CurrentOrder;
4795       // Check the order of pointer operands.
4796       if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) {
4797         Value *Ptr0;
4798         Value *PtrN;
4799         if (CurrentOrder.empty()) {
4800           Ptr0 = PointerOps.front();
4801           PtrN = PointerOps.back();
4802         } else {
4803           Ptr0 = PointerOps[CurrentOrder.front()];
4804           PtrN = PointerOps[CurrentOrder.back()];
4805         }
4806         Optional<int> Dist =
4807             getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE);
4808         // Check that the sorted pointer operands are consecutive.
4809         if (static_cast<unsigned>(*Dist) == VL.size() - 1) {
4810           if (CurrentOrder.empty()) {
4811             // Original stores are consecutive and does not require reordering.
4812             TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
4813                                          UserTreeIdx, ReuseShuffleIndicies);
4814             TE->setOperandsInOrder();
4815             buildTree_rec(Operands, Depth + 1, {TE, 0});
4816             LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
4817           } else {
4818             fixupOrderingIndices(CurrentOrder);
4819             TreeEntry *TE =
4820                 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4821                              ReuseShuffleIndicies, CurrentOrder);
4822             TE->setOperandsInOrder();
4823             buildTree_rec(Operands, Depth + 1, {TE, 0});
4824             LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n");
4825           }
4826           return;
4827         }
4828       }
4829 
4830       BS.cancelScheduling(VL, VL0);
4831       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4832                    ReuseShuffleIndicies);
4833       LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
4834       return;
4835     }
4836     case Instruction::Call: {
4837       // Check if the calls are all to the same vectorizable intrinsic or
4838       // library function.
4839       CallInst *CI = cast<CallInst>(VL0);
4840       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4841 
4842       VFShape Shape = VFShape::get(
4843           *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())),
4844           false /*HasGlobalPred*/);
4845       Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4846 
4847       if (!VecFunc && !isTriviallyVectorizable(ID)) {
4848         BS.cancelScheduling(VL, VL0);
4849         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4850                      ReuseShuffleIndicies);
4851         LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
4852         return;
4853       }
4854       Function *F = CI->getCalledFunction();
4855       unsigned NumArgs = CI->arg_size();
4856       SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr);
4857       for (unsigned j = 0; j != NumArgs; ++j)
4858         if (isVectorIntrinsicWithScalarOpAtArg(ID, j))
4859           ScalarArgs[j] = CI->getArgOperand(j);
4860       for (Value *V : VL) {
4861         CallInst *CI2 = dyn_cast<CallInst>(V);
4862         if (!CI2 || CI2->getCalledFunction() != F ||
4863             getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
4864             (VecFunc &&
4865              VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) ||
4866             !CI->hasIdenticalOperandBundleSchema(*CI2)) {
4867           BS.cancelScheduling(VL, VL0);
4868           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4869                        ReuseShuffleIndicies);
4870           LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V
4871                             << "\n");
4872           return;
4873         }
4874         // Some intrinsics have scalar arguments and should be same in order for
4875         // them to be vectorized.
4876         for (unsigned j = 0; j != NumArgs; ++j) {
4877           if (isVectorIntrinsicWithScalarOpAtArg(ID, j)) {
4878             Value *A1J = CI2->getArgOperand(j);
4879             if (ScalarArgs[j] != A1J) {
4880               BS.cancelScheduling(VL, VL0);
4881               newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4882                            ReuseShuffleIndicies);
4883               LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
4884                                 << " argument " << ScalarArgs[j] << "!=" << A1J
4885                                 << "\n");
4886               return;
4887             }
4888           }
4889         }
4890         // Verify that the bundle operands are identical between the two calls.
4891         if (CI->hasOperandBundles() &&
4892             !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
4893                         CI->op_begin() + CI->getBundleOperandsEndIndex(),
4894                         CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
4895           BS.cancelScheduling(VL, VL0);
4896           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4897                        ReuseShuffleIndicies);
4898           LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
4899                             << *CI << "!=" << *V << '\n');
4900           return;
4901         }
4902       }
4903 
4904       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4905                                    ReuseShuffleIndicies);
4906       TE->setOperandsInOrder();
4907       for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
4908         // For scalar operands no need to to create an entry since no need to
4909         // vectorize it.
4910         if (isVectorIntrinsicWithScalarOpAtArg(ID, i))
4911           continue;
4912         ValueList Operands;
4913         // Prepare the operand vector.
4914         for (Value *V : VL) {
4915           auto *CI2 = cast<CallInst>(V);
4916           Operands.push_back(CI2->getArgOperand(i));
4917         }
4918         buildTree_rec(Operands, Depth + 1, {TE, i});
4919       }
4920       return;
4921     }
4922     case Instruction::ShuffleVector: {
4923       // If this is not an alternate sequence of opcode like add-sub
4924       // then do not vectorize this instruction.
4925       if (!S.isAltShuffle()) {
4926         BS.cancelScheduling(VL, VL0);
4927         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4928                      ReuseShuffleIndicies);
4929         LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
4930         return;
4931       }
4932       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4933                                    ReuseShuffleIndicies);
4934       LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
4935 
4936       // Reorder operands if reordering would enable vectorization.
4937       auto *CI = dyn_cast<CmpInst>(VL0);
4938       if (isa<BinaryOperator>(VL0) || CI) {
4939         ValueList Left, Right;
4940         if (!CI || all_of(VL, [](Value *V) {
4941               return cast<CmpInst>(V)->isCommutative();
4942             })) {
4943           reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4944         } else {
4945           CmpInst::Predicate P0 = CI->getPredicate();
4946           CmpInst::Predicate AltP0 = cast<CmpInst>(S.AltOp)->getPredicate();
4947           assert(P0 != AltP0 &&
4948                  "Expected different main/alternate predicates.");
4949           CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
4950           Value *BaseOp0 = VL0->getOperand(0);
4951           Value *BaseOp1 = VL0->getOperand(1);
4952           // Collect operands - commute if it uses the swapped predicate or
4953           // alternate operation.
4954           for (Value *V : VL) {
4955             auto *Cmp = cast<CmpInst>(V);
4956             Value *LHS = Cmp->getOperand(0);
4957             Value *RHS = Cmp->getOperand(1);
4958             CmpInst::Predicate CurrentPred = Cmp->getPredicate();
4959             if (P0 == AltP0Swapped) {
4960               if (CI != Cmp && S.AltOp != Cmp &&
4961                   ((P0 == CurrentPred &&
4962                     !areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)) ||
4963                    (AltP0 == CurrentPred &&
4964                     areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS))))
4965                 std::swap(LHS, RHS);
4966             } else if (P0 != CurrentPred && AltP0 != CurrentPred) {
4967               std::swap(LHS, RHS);
4968             }
4969             Left.push_back(LHS);
4970             Right.push_back(RHS);
4971           }
4972         }
4973         TE->setOperand(0, Left);
4974         TE->setOperand(1, Right);
4975         buildTree_rec(Left, Depth + 1, {TE, 0});
4976         buildTree_rec(Right, Depth + 1, {TE, 1});
4977         return;
4978       }
4979 
4980       TE->setOperandsInOrder();
4981       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4982         ValueList Operands;
4983         // Prepare the operand vector.
4984         for (Value *V : VL)
4985           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4986 
4987         buildTree_rec(Operands, Depth + 1, {TE, i});
4988       }
4989       return;
4990     }
4991     default:
4992       BS.cancelScheduling(VL, VL0);
4993       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4994                    ReuseShuffleIndicies);
4995       LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
4996       return;
4997   }
4998 }
4999 
5000 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
5001   unsigned N = 1;
5002   Type *EltTy = T;
5003 
5004   while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) ||
5005          isa<VectorType>(EltTy)) {
5006     if (auto *ST = dyn_cast<StructType>(EltTy)) {
5007       // Check that struct is homogeneous.
5008       for (const auto *Ty : ST->elements())
5009         if (Ty != *ST->element_begin())
5010           return 0;
5011       N *= ST->getNumElements();
5012       EltTy = *ST->element_begin();
5013     } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) {
5014       N *= AT->getNumElements();
5015       EltTy = AT->getElementType();
5016     } else {
5017       auto *VT = cast<FixedVectorType>(EltTy);
5018       N *= VT->getNumElements();
5019       EltTy = VT->getElementType();
5020     }
5021   }
5022 
5023   if (!isValidElementType(EltTy))
5024     return 0;
5025   uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N));
5026   if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
5027     return 0;
5028   return N;
5029 }
5030 
5031 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
5032                               SmallVectorImpl<unsigned> &CurrentOrder) const {
5033   const auto *It = find_if(VL, [](Value *V) {
5034     return isa<ExtractElementInst, ExtractValueInst>(V);
5035   });
5036   assert(It != VL.end() && "Expected at least one extract instruction.");
5037   auto *E0 = cast<Instruction>(*It);
5038   assert(all_of(VL,
5039                 [](Value *V) {
5040                   return isa<UndefValue, ExtractElementInst, ExtractValueInst>(
5041                       V);
5042                 }) &&
5043          "Invalid opcode");
5044   // Check if all of the extracts come from the same vector and from the
5045   // correct offset.
5046   Value *Vec = E0->getOperand(0);
5047 
5048   CurrentOrder.clear();
5049 
5050   // We have to extract from a vector/aggregate with the same number of elements.
5051   unsigned NElts;
5052   if (E0->getOpcode() == Instruction::ExtractValue) {
5053     const DataLayout &DL = E0->getModule()->getDataLayout();
5054     NElts = canMapToVector(Vec->getType(), DL);
5055     if (!NElts)
5056       return false;
5057     // Check if load can be rewritten as load of vector.
5058     LoadInst *LI = dyn_cast<LoadInst>(Vec);
5059     if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
5060       return false;
5061   } else {
5062     NElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
5063   }
5064 
5065   if (NElts != VL.size())
5066     return false;
5067 
5068   // Check that all of the indices extract from the correct offset.
5069   bool ShouldKeepOrder = true;
5070   unsigned E = VL.size();
5071   // Assign to all items the initial value E + 1 so we can check if the extract
5072   // instruction index was used already.
5073   // Also, later we can check that all the indices are used and we have a
5074   // consecutive access in the extract instructions, by checking that no
5075   // element of CurrentOrder still has value E + 1.
5076   CurrentOrder.assign(E, E);
5077   unsigned I = 0;
5078   for (; I < E; ++I) {
5079     auto *Inst = dyn_cast<Instruction>(VL[I]);
5080     if (!Inst)
5081       continue;
5082     if (Inst->getOperand(0) != Vec)
5083       break;
5084     if (auto *EE = dyn_cast<ExtractElementInst>(Inst))
5085       if (isa<UndefValue>(EE->getIndexOperand()))
5086         continue;
5087     Optional<unsigned> Idx = getExtractIndex(Inst);
5088     if (!Idx)
5089       break;
5090     const unsigned ExtIdx = *Idx;
5091     if (ExtIdx != I) {
5092       if (ExtIdx >= E || CurrentOrder[ExtIdx] != E)
5093         break;
5094       ShouldKeepOrder = false;
5095       CurrentOrder[ExtIdx] = I;
5096     } else {
5097       if (CurrentOrder[I] != E)
5098         break;
5099       CurrentOrder[I] = I;
5100     }
5101   }
5102   if (I < E) {
5103     CurrentOrder.clear();
5104     return false;
5105   }
5106   if (ShouldKeepOrder)
5107     CurrentOrder.clear();
5108 
5109   return ShouldKeepOrder;
5110 }
5111 
5112 bool BoUpSLP::areAllUsersVectorized(Instruction *I,
5113                                     ArrayRef<Value *> VectorizedVals) const {
5114   return (I->hasOneUse() && is_contained(VectorizedVals, I)) ||
5115          all_of(I->users(), [this](User *U) {
5116            return ScalarToTreeEntry.count(U) > 0 ||
5117                   isVectorLikeInstWithConstOps(U) ||
5118                   (isa<ExtractElementInst>(U) && MustGather.contains(U));
5119          });
5120 }
5121 
5122 static std::pair<InstructionCost, InstructionCost>
5123 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy,
5124                    TargetTransformInfo *TTI, TargetLibraryInfo *TLI) {
5125   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5126 
5127   // Calculate the cost of the scalar and vector calls.
5128   SmallVector<Type *, 4> VecTys;
5129   for (Use &Arg : CI->args())
5130     VecTys.push_back(
5131         FixedVectorType::get(Arg->getType(), VecTy->getNumElements()));
5132   FastMathFlags FMF;
5133   if (auto *FPCI = dyn_cast<FPMathOperator>(CI))
5134     FMF = FPCI->getFastMathFlags();
5135   SmallVector<const Value *> Arguments(CI->args());
5136   IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF,
5137                                     dyn_cast<IntrinsicInst>(CI));
5138   auto IntrinsicCost =
5139     TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput);
5140 
5141   auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
5142                                      VecTy->getNumElements())),
5143                             false /*HasGlobalPred*/);
5144   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
5145   auto LibCost = IntrinsicCost;
5146   if (!CI->isNoBuiltin() && VecFunc) {
5147     // Calculate the cost of the vector library call.
5148     // If the corresponding vector call is cheaper, return its cost.
5149     LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys,
5150                                     TTI::TCK_RecipThroughput);
5151   }
5152   return {IntrinsicCost, LibCost};
5153 }
5154 
5155 /// Compute the cost of creating a vector of type \p VecTy containing the
5156 /// extracted values from \p VL.
5157 static InstructionCost
5158 computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy,
5159                    TargetTransformInfo::ShuffleKind ShuffleKind,
5160                    ArrayRef<int> Mask, TargetTransformInfo &TTI) {
5161   unsigned NumOfParts = TTI.getNumberOfParts(VecTy);
5162 
5163   if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts ||
5164       VecTy->getNumElements() < NumOfParts)
5165     return TTI.getShuffleCost(ShuffleKind, VecTy, Mask);
5166 
5167   bool AllConsecutive = true;
5168   unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts;
5169   unsigned Idx = -1;
5170   InstructionCost Cost = 0;
5171 
5172   // Process extracts in blocks of EltsPerVector to check if the source vector
5173   // operand can be re-used directly. If not, add the cost of creating a shuffle
5174   // to extract the values into a vector register.
5175   SmallVector<int> RegMask(EltsPerVector, UndefMaskElem);
5176   for (auto *V : VL) {
5177     ++Idx;
5178 
5179     // Need to exclude undefs from analysis.
5180     if (isa<UndefValue>(V) || Mask[Idx] == UndefMaskElem)
5181       continue;
5182 
5183     // Reached the start of a new vector registers.
5184     if (Idx % EltsPerVector == 0) {
5185       RegMask.assign(EltsPerVector, UndefMaskElem);
5186       AllConsecutive = true;
5187       continue;
5188     }
5189 
5190     // Check all extracts for a vector register on the target directly
5191     // extract values in order.
5192     unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V));
5193     if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != UndefMaskElem) {
5194       unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1]));
5195       AllConsecutive &= PrevIdx + 1 == CurrentIdx &&
5196                         CurrentIdx % EltsPerVector == Idx % EltsPerVector;
5197       RegMask[Idx % EltsPerVector] = CurrentIdx % EltsPerVector;
5198     }
5199 
5200     if (AllConsecutive)
5201       continue;
5202 
5203     // Skip all indices, except for the last index per vector block.
5204     if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size())
5205       continue;
5206 
5207     // If we have a series of extracts which are not consecutive and hence
5208     // cannot re-use the source vector register directly, compute the shuffle
5209     // cost to extract the vector with EltsPerVector elements.
5210     Cost += TTI.getShuffleCost(
5211         TargetTransformInfo::SK_PermuteSingleSrc,
5212         FixedVectorType::get(VecTy->getElementType(), EltsPerVector), RegMask);
5213   }
5214   return Cost;
5215 }
5216 
5217 /// Build shuffle mask for shuffle graph entries and lists of main and alternate
5218 /// operations operands.
5219 static void
5220 buildShuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices,
5221                       ArrayRef<int> ReusesIndices,
5222                       const function_ref<bool(Instruction *)> IsAltOp,
5223                       SmallVectorImpl<int> &Mask,
5224                       SmallVectorImpl<Value *> *OpScalars = nullptr,
5225                       SmallVectorImpl<Value *> *AltScalars = nullptr) {
5226   unsigned Sz = VL.size();
5227   Mask.assign(Sz, UndefMaskElem);
5228   SmallVector<int> OrderMask;
5229   if (!ReorderIndices.empty())
5230     inversePermutation(ReorderIndices, OrderMask);
5231   for (unsigned I = 0; I < Sz; ++I) {
5232     unsigned Idx = I;
5233     if (!ReorderIndices.empty())
5234       Idx = OrderMask[I];
5235     auto *OpInst = cast<Instruction>(VL[Idx]);
5236     if (IsAltOp(OpInst)) {
5237       Mask[I] = Sz + Idx;
5238       if (AltScalars)
5239         AltScalars->push_back(OpInst);
5240     } else {
5241       Mask[I] = Idx;
5242       if (OpScalars)
5243         OpScalars->push_back(OpInst);
5244     }
5245   }
5246   if (!ReusesIndices.empty()) {
5247     SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem);
5248     transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) {
5249       return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem;
5250     });
5251     Mask.swap(NewMask);
5252   }
5253 }
5254 
5255 /// Checks if the specified instruction \p I is an alternate operation for the
5256 /// given \p MainOp and \p AltOp instructions.
5257 static bool isAlternateInstruction(const Instruction *I,
5258                                    const Instruction *MainOp,
5259                                    const Instruction *AltOp) {
5260   if (auto *CI0 = dyn_cast<CmpInst>(MainOp)) {
5261     auto *AltCI0 = cast<CmpInst>(AltOp);
5262     auto *CI = cast<CmpInst>(I);
5263     CmpInst::Predicate P0 = CI0->getPredicate();
5264     CmpInst::Predicate AltP0 = AltCI0->getPredicate();
5265     assert(P0 != AltP0 && "Expected different main/alternate predicates.");
5266     CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
5267     CmpInst::Predicate CurrentPred = CI->getPredicate();
5268     if (P0 == AltP0Swapped)
5269       return I == AltCI0 ||
5270              (I != MainOp &&
5271               !areCompatibleCmpOps(CI0->getOperand(0), CI0->getOperand(1),
5272                                    CI->getOperand(0), CI->getOperand(1)));
5273     return AltP0 == CurrentPred || AltP0Swapped == CurrentPred;
5274   }
5275   return I->getOpcode() == AltOp->getOpcode();
5276 }
5277 
5278 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E,
5279                                       ArrayRef<Value *> VectorizedVals) {
5280   ArrayRef<Value*> VL = E->Scalars;
5281 
5282   Type *ScalarTy = VL[0]->getType();
5283   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
5284     ScalarTy = SI->getValueOperand()->getType();
5285   else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
5286     ScalarTy = CI->getOperand(0)->getType();
5287   else if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
5288     ScalarTy = IE->getOperand(1)->getType();
5289   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
5290   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
5291 
5292   // If we have computed a smaller type for the expression, update VecTy so
5293   // that the costs will be accurate.
5294   if (MinBWs.count(VL[0]))
5295     VecTy = FixedVectorType::get(
5296         IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
5297   unsigned EntryVF = E->getVectorFactor();
5298   auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF);
5299 
5300   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
5301   // FIXME: it tries to fix a problem with MSVC buildbots.
5302   TargetTransformInfo &TTIRef = *TTI;
5303   auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy,
5304                                VectorizedVals, E](InstructionCost &Cost) {
5305     DenseMap<Value *, int> ExtractVectorsTys;
5306     SmallPtrSet<Value *, 4> CheckedExtracts;
5307     for (auto *V : VL) {
5308       if (isa<UndefValue>(V))
5309         continue;
5310       // If all users of instruction are going to be vectorized and this
5311       // instruction itself is not going to be vectorized, consider this
5312       // instruction as dead and remove its cost from the final cost of the
5313       // vectorized tree.
5314       // Also, avoid adjusting the cost for extractelements with multiple uses
5315       // in different graph entries.
5316       const TreeEntry *VE = getTreeEntry(V);
5317       if (!CheckedExtracts.insert(V).second ||
5318           !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) ||
5319           (VE && VE != E))
5320         continue;
5321       auto *EE = cast<ExtractElementInst>(V);
5322       Optional<unsigned> EEIdx = getExtractIndex(EE);
5323       if (!EEIdx)
5324         continue;
5325       unsigned Idx = *EEIdx;
5326       if (TTIRef.getNumberOfParts(VecTy) !=
5327           TTIRef.getNumberOfParts(EE->getVectorOperandType())) {
5328         auto It =
5329             ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first;
5330         It->getSecond() = std::min<int>(It->second, Idx);
5331       }
5332       // Take credit for instruction that will become dead.
5333       if (EE->hasOneUse()) {
5334         Instruction *Ext = EE->user_back();
5335         if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5336             all_of(Ext->users(),
5337                    [](User *U) { return isa<GetElementPtrInst>(U); })) {
5338           // Use getExtractWithExtendCost() to calculate the cost of
5339           // extractelement/ext pair.
5340           Cost -=
5341               TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(),
5342                                               EE->getVectorOperandType(), Idx);
5343           // Add back the cost of s|zext which is subtracted separately.
5344           Cost += TTIRef.getCastInstrCost(
5345               Ext->getOpcode(), Ext->getType(), EE->getType(),
5346               TTI::getCastContextHint(Ext), CostKind, Ext);
5347           continue;
5348         }
5349       }
5350       Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement,
5351                                         EE->getVectorOperandType(), Idx);
5352     }
5353     // Add a cost for subvector extracts/inserts if required.
5354     for (const auto &Data : ExtractVectorsTys) {
5355       auto *EEVTy = cast<FixedVectorType>(Data.first->getType());
5356       unsigned NumElts = VecTy->getNumElements();
5357       if (Data.second % NumElts == 0)
5358         continue;
5359       if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) {
5360         unsigned Idx = (Data.second / NumElts) * NumElts;
5361         unsigned EENumElts = EEVTy->getNumElements();
5362         if (Idx + NumElts <= EENumElts) {
5363           Cost +=
5364               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5365                                     EEVTy, None, Idx, VecTy);
5366         } else {
5367           // Need to round up the subvector type vectorization factor to avoid a
5368           // crash in cost model functions. Make SubVT so that Idx + VF of SubVT
5369           // <= EENumElts.
5370           auto *SubVT =
5371               FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx);
5372           Cost +=
5373               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5374                                     EEVTy, None, Idx, SubVT);
5375         }
5376       } else {
5377         Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector,
5378                                       VecTy, None, 0, EEVTy);
5379       }
5380     }
5381   };
5382   if (E->State == TreeEntry::NeedToGather) {
5383     if (allConstant(VL))
5384       return 0;
5385     if (isa<InsertElementInst>(VL[0]))
5386       return InstructionCost::getInvalid();
5387     SmallVector<int> Mask;
5388     SmallVector<const TreeEntry *> Entries;
5389     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
5390         isGatherShuffledEntry(E, Mask, Entries);
5391     if (Shuffle.hasValue()) {
5392       InstructionCost GatherCost = 0;
5393       if (ShuffleVectorInst::isIdentityMask(Mask)) {
5394         // Perfect match in the graph, will reuse the previously vectorized
5395         // node. Cost is 0.
5396         LLVM_DEBUG(
5397             dbgs()
5398             << "SLP: perfect diamond match for gather bundle that starts with "
5399             << *VL.front() << ".\n");
5400         if (NeedToShuffleReuses)
5401           GatherCost =
5402               TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5403                                   FinalVecTy, E->ReuseShuffleIndices);
5404       } else {
5405         LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size()
5406                           << " entries for bundle that starts with "
5407                           << *VL.front() << ".\n");
5408         // Detected that instead of gather we can emit a shuffle of single/two
5409         // previously vectorized nodes. Add the cost of the permutation rather
5410         // than gather.
5411         ::addMask(Mask, E->ReuseShuffleIndices);
5412         GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask);
5413       }
5414       return GatherCost;
5415     }
5416     if ((E->getOpcode() == Instruction::ExtractElement ||
5417          all_of(E->Scalars,
5418                 [](Value *V) {
5419                   return isa<ExtractElementInst, UndefValue>(V);
5420                 })) &&
5421         allSameType(VL)) {
5422       // Check that gather of extractelements can be represented as just a
5423       // shuffle of a single/two vectors the scalars are extracted from.
5424       SmallVector<int> Mask;
5425       Optional<TargetTransformInfo::ShuffleKind> ShuffleKind =
5426           isFixedVectorShuffle(VL, Mask);
5427       if (ShuffleKind.hasValue()) {
5428         // Found the bunch of extractelement instructions that must be gathered
5429         // into a vector and can be represented as a permutation elements in a
5430         // single input vector or of 2 input vectors.
5431         InstructionCost Cost =
5432             computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI);
5433         AdjustExtractsCost(Cost);
5434         if (NeedToShuffleReuses)
5435           Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5436                                       FinalVecTy, E->ReuseShuffleIndices);
5437         return Cost;
5438       }
5439     }
5440     if (isSplat(VL)) {
5441       // Found the broadcasting of the single scalar, calculate the cost as the
5442       // broadcast.
5443       assert(VecTy == FinalVecTy &&
5444              "No reused scalars expected for broadcast.");
5445       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy,
5446                                  /*Mask=*/None, /*Index=*/0,
5447                                  /*SubTp=*/nullptr, /*Args=*/VL[0]);
5448     }
5449     InstructionCost ReuseShuffleCost = 0;
5450     if (NeedToShuffleReuses)
5451       ReuseShuffleCost = TTI->getShuffleCost(
5452           TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices);
5453     // Improve gather cost for gather of loads, if we can group some of the
5454     // loads into vector loads.
5455     if (VL.size() > 2 && E->getOpcode() == Instruction::Load &&
5456         !E->isAltShuffle()) {
5457       BoUpSLP::ValueSet VectorizedLoads;
5458       unsigned StartIdx = 0;
5459       unsigned VF = VL.size() / 2;
5460       unsigned VectorizedCnt = 0;
5461       unsigned ScatterVectorizeCnt = 0;
5462       const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType());
5463       for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) {
5464         for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End;
5465              Cnt += VF) {
5466           ArrayRef<Value *> Slice = VL.slice(Cnt, VF);
5467           if (!VectorizedLoads.count(Slice.front()) &&
5468               !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) {
5469             SmallVector<Value *> PointerOps;
5470             OrdersType CurrentOrder;
5471             LoadsState LS = canVectorizeLoads(Slice, Slice.front(), *TTI, *DL,
5472                                               *SE, CurrentOrder, PointerOps);
5473             switch (LS) {
5474             case LoadsState::Vectorize:
5475             case LoadsState::ScatterVectorize:
5476               // Mark the vectorized loads so that we don't vectorize them
5477               // again.
5478               if (LS == LoadsState::Vectorize)
5479                 ++VectorizedCnt;
5480               else
5481                 ++ScatterVectorizeCnt;
5482               VectorizedLoads.insert(Slice.begin(), Slice.end());
5483               // If we vectorized initial block, no need to try to vectorize it
5484               // again.
5485               if (Cnt == StartIdx)
5486                 StartIdx += VF;
5487               break;
5488             case LoadsState::Gather:
5489               break;
5490             }
5491           }
5492         }
5493         // Check if the whole array was vectorized already - exit.
5494         if (StartIdx >= VL.size())
5495           break;
5496         // Found vectorizable parts - exit.
5497         if (!VectorizedLoads.empty())
5498           break;
5499       }
5500       if (!VectorizedLoads.empty()) {
5501         InstructionCost GatherCost = 0;
5502         unsigned NumParts = TTI->getNumberOfParts(VecTy);
5503         bool NeedInsertSubvectorAnalysis =
5504             !NumParts || (VL.size() / VF) > NumParts;
5505         // Get the cost for gathered loads.
5506         for (unsigned I = 0, End = VL.size(); I < End; I += VF) {
5507           if (VectorizedLoads.contains(VL[I]))
5508             continue;
5509           GatherCost += getGatherCost(VL.slice(I, VF));
5510         }
5511         // The cost for vectorized loads.
5512         InstructionCost ScalarsCost = 0;
5513         for (Value *V : VectorizedLoads) {
5514           auto *LI = cast<LoadInst>(V);
5515           ScalarsCost += TTI->getMemoryOpCost(
5516               Instruction::Load, LI->getType(), LI->getAlign(),
5517               LI->getPointerAddressSpace(), CostKind, LI);
5518         }
5519         auto *LI = cast<LoadInst>(E->getMainOp());
5520         auto *LoadTy = FixedVectorType::get(LI->getType(), VF);
5521         Align Alignment = LI->getAlign();
5522         GatherCost +=
5523             VectorizedCnt *
5524             TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment,
5525                                  LI->getPointerAddressSpace(), CostKind, LI);
5526         GatherCost += ScatterVectorizeCnt *
5527                       TTI->getGatherScatterOpCost(
5528                           Instruction::Load, LoadTy, LI->getPointerOperand(),
5529                           /*VariableMask=*/false, Alignment, CostKind, LI);
5530         if (NeedInsertSubvectorAnalysis) {
5531           // Add the cost for the subvectors insert.
5532           for (int I = VF, E = VL.size(); I < E; I += VF)
5533             GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy,
5534                                               None, I, LoadTy);
5535         }
5536         return ReuseShuffleCost + GatherCost - ScalarsCost;
5537       }
5538     }
5539     return ReuseShuffleCost + getGatherCost(VL);
5540   }
5541   InstructionCost CommonCost = 0;
5542   SmallVector<int> Mask;
5543   if (!E->ReorderIndices.empty()) {
5544     SmallVector<int> NewMask;
5545     if (E->getOpcode() == Instruction::Store) {
5546       // For stores the order is actually a mask.
5547       NewMask.resize(E->ReorderIndices.size());
5548       copy(E->ReorderIndices, NewMask.begin());
5549     } else {
5550       inversePermutation(E->ReorderIndices, NewMask);
5551     }
5552     ::addMask(Mask, NewMask);
5553   }
5554   if (NeedToShuffleReuses)
5555     ::addMask(Mask, E->ReuseShuffleIndices);
5556   if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask))
5557     CommonCost =
5558         TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask);
5559   assert((E->State == TreeEntry::Vectorize ||
5560           E->State == TreeEntry::ScatterVectorize) &&
5561          "Unhandled state");
5562   assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
5563   Instruction *VL0 = E->getMainOp();
5564   unsigned ShuffleOrOp =
5565       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
5566   switch (ShuffleOrOp) {
5567     case Instruction::PHI:
5568       return 0;
5569 
5570     case Instruction::ExtractValue:
5571     case Instruction::ExtractElement: {
5572       // The common cost of removal ExtractElement/ExtractValue instructions +
5573       // the cost of shuffles, if required to resuffle the original vector.
5574       if (NeedToShuffleReuses) {
5575         unsigned Idx = 0;
5576         for (unsigned I : E->ReuseShuffleIndices) {
5577           if (ShuffleOrOp == Instruction::ExtractElement) {
5578             auto *EE = cast<ExtractElementInst>(VL[I]);
5579             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5580                                                   EE->getVectorOperandType(),
5581                                                   *getExtractIndex(EE));
5582           } else {
5583             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5584                                                   VecTy, Idx);
5585             ++Idx;
5586           }
5587         }
5588         Idx = EntryVF;
5589         for (Value *V : VL) {
5590           if (ShuffleOrOp == Instruction::ExtractElement) {
5591             auto *EE = cast<ExtractElementInst>(V);
5592             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5593                                                   EE->getVectorOperandType(),
5594                                                   *getExtractIndex(EE));
5595           } else {
5596             --Idx;
5597             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5598                                                   VecTy, Idx);
5599           }
5600         }
5601       }
5602       if (ShuffleOrOp == Instruction::ExtractValue) {
5603         for (unsigned I = 0, E = VL.size(); I < E; ++I) {
5604           auto *EI = cast<Instruction>(VL[I]);
5605           // Take credit for instruction that will become dead.
5606           if (EI->hasOneUse()) {
5607             Instruction *Ext = EI->user_back();
5608             if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5609                 all_of(Ext->users(),
5610                        [](User *U) { return isa<GetElementPtrInst>(U); })) {
5611               // Use getExtractWithExtendCost() to calculate the cost of
5612               // extractelement/ext pair.
5613               CommonCost -= TTI->getExtractWithExtendCost(
5614                   Ext->getOpcode(), Ext->getType(), VecTy, I);
5615               // Add back the cost of s|zext which is subtracted separately.
5616               CommonCost += TTI->getCastInstrCost(
5617                   Ext->getOpcode(), Ext->getType(), EI->getType(),
5618                   TTI::getCastContextHint(Ext), CostKind, Ext);
5619               continue;
5620             }
5621           }
5622           CommonCost -=
5623               TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I);
5624         }
5625       } else {
5626         AdjustExtractsCost(CommonCost);
5627       }
5628       return CommonCost;
5629     }
5630     case Instruction::InsertElement: {
5631       assert(E->ReuseShuffleIndices.empty() &&
5632              "Unique insertelements only are expected.");
5633       auto *SrcVecTy = cast<FixedVectorType>(VL0->getType());
5634 
5635       unsigned const NumElts = SrcVecTy->getNumElements();
5636       unsigned const NumScalars = VL.size();
5637       APInt DemandedElts = APInt::getZero(NumElts);
5638       // TODO: Add support for Instruction::InsertValue.
5639       SmallVector<int> Mask;
5640       if (!E->ReorderIndices.empty()) {
5641         inversePermutation(E->ReorderIndices, Mask);
5642         Mask.append(NumElts - NumScalars, UndefMaskElem);
5643       } else {
5644         Mask.assign(NumElts, UndefMaskElem);
5645         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
5646       }
5647       unsigned Offset = *getInsertIndex(VL0);
5648       bool IsIdentity = true;
5649       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
5650       Mask.swap(PrevMask);
5651       for (unsigned I = 0; I < NumScalars; ++I) {
5652         unsigned InsertIdx = *getInsertIndex(VL[PrevMask[I]]);
5653         DemandedElts.setBit(InsertIdx);
5654         IsIdentity &= InsertIdx - Offset == I;
5655         Mask[InsertIdx - Offset] = I;
5656       }
5657       assert(Offset < NumElts && "Failed to find vector index offset");
5658 
5659       InstructionCost Cost = 0;
5660       Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts,
5661                                             /*Insert*/ true, /*Extract*/ false);
5662 
5663       if (IsIdentity && NumElts != NumScalars && Offset % NumScalars != 0) {
5664         // FIXME: Replace with SK_InsertSubvector once it is properly supported.
5665         unsigned Sz = PowerOf2Ceil(Offset + NumScalars);
5666         Cost += TTI->getShuffleCost(
5667             TargetTransformInfo::SK_PermuteSingleSrc,
5668             FixedVectorType::get(SrcVecTy->getElementType(), Sz));
5669       } else if (!IsIdentity) {
5670         auto *FirstInsert =
5671             cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
5672               return !is_contained(E->Scalars,
5673                                    cast<Instruction>(V)->getOperand(0));
5674             }));
5675         if (isUndefVector(FirstInsert->getOperand(0))) {
5676           Cost += TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, SrcVecTy, Mask);
5677         } else {
5678           SmallVector<int> InsertMask(NumElts);
5679           std::iota(InsertMask.begin(), InsertMask.end(), 0);
5680           for (unsigned I = 0; I < NumElts; I++) {
5681             if (Mask[I] != UndefMaskElem)
5682               InsertMask[Offset + I] = NumElts + I;
5683           }
5684           Cost +=
5685               TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVecTy, InsertMask);
5686         }
5687       }
5688 
5689       return Cost;
5690     }
5691     case Instruction::ZExt:
5692     case Instruction::SExt:
5693     case Instruction::FPToUI:
5694     case Instruction::FPToSI:
5695     case Instruction::FPExt:
5696     case Instruction::PtrToInt:
5697     case Instruction::IntToPtr:
5698     case Instruction::SIToFP:
5699     case Instruction::UIToFP:
5700     case Instruction::Trunc:
5701     case Instruction::FPTrunc:
5702     case Instruction::BitCast: {
5703       Type *SrcTy = VL0->getOperand(0)->getType();
5704       InstructionCost ScalarEltCost =
5705           TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy,
5706                                 TTI::getCastContextHint(VL0), CostKind, VL0);
5707       if (NeedToShuffleReuses) {
5708         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5709       }
5710 
5711       // Calculate the cost of this instruction.
5712       InstructionCost ScalarCost = VL.size() * ScalarEltCost;
5713 
5714       auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size());
5715       InstructionCost VecCost = 0;
5716       // Check if the values are candidates to demote.
5717       if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
5718         VecCost = CommonCost + TTI->getCastInstrCost(
5719                                    E->getOpcode(), VecTy, SrcVecTy,
5720                                    TTI::getCastContextHint(VL0), CostKind, VL0);
5721       }
5722       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5723       return VecCost - ScalarCost;
5724     }
5725     case Instruction::FCmp:
5726     case Instruction::ICmp:
5727     case Instruction::Select: {
5728       // Calculate the cost of this instruction.
5729       InstructionCost ScalarEltCost =
5730           TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5731                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0);
5732       if (NeedToShuffleReuses) {
5733         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5734       }
5735       auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size());
5736       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5737 
5738       // Check if all entries in VL are either compares or selects with compares
5739       // as condition that have the same predicates.
5740       CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE;
5741       bool First = true;
5742       for (auto *V : VL) {
5743         CmpInst::Predicate CurrentPred;
5744         auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value());
5745         if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) &&
5746              !match(V, MatchCmp)) ||
5747             (!First && VecPred != CurrentPred)) {
5748           VecPred = CmpInst::BAD_ICMP_PREDICATE;
5749           break;
5750         }
5751         First = false;
5752         VecPred = CurrentPred;
5753       }
5754 
5755       InstructionCost VecCost = TTI->getCmpSelInstrCost(
5756           E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0);
5757       // Check if it is possible and profitable to use min/max for selects in
5758       // VL.
5759       //
5760       auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL);
5761       if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) {
5762         IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy,
5763                                           {VecTy, VecTy});
5764         InstructionCost IntrinsicCost =
5765             TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5766         // If the selects are the only uses of the compares, they will be dead
5767         // and we can adjust the cost by removing their cost.
5768         if (IntrinsicAndUse.second)
5769           IntrinsicCost -= TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy,
5770                                                    MaskTy, VecPred, CostKind);
5771         VecCost = std::min(VecCost, IntrinsicCost);
5772       }
5773       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5774       return CommonCost + VecCost - ScalarCost;
5775     }
5776     case Instruction::FNeg:
5777     case Instruction::Add:
5778     case Instruction::FAdd:
5779     case Instruction::Sub:
5780     case Instruction::FSub:
5781     case Instruction::Mul:
5782     case Instruction::FMul:
5783     case Instruction::UDiv:
5784     case Instruction::SDiv:
5785     case Instruction::FDiv:
5786     case Instruction::URem:
5787     case Instruction::SRem:
5788     case Instruction::FRem:
5789     case Instruction::Shl:
5790     case Instruction::LShr:
5791     case Instruction::AShr:
5792     case Instruction::And:
5793     case Instruction::Or:
5794     case Instruction::Xor: {
5795       // Certain instructions can be cheaper to vectorize if they have a
5796       // constant second vector operand.
5797       TargetTransformInfo::OperandValueKind Op1VK =
5798           TargetTransformInfo::OK_AnyValue;
5799       TargetTransformInfo::OperandValueKind Op2VK =
5800           TargetTransformInfo::OK_UniformConstantValue;
5801       TargetTransformInfo::OperandValueProperties Op1VP =
5802           TargetTransformInfo::OP_None;
5803       TargetTransformInfo::OperandValueProperties Op2VP =
5804           TargetTransformInfo::OP_PowerOf2;
5805 
5806       // If all operands are exactly the same ConstantInt then set the
5807       // operand kind to OK_UniformConstantValue.
5808       // If instead not all operands are constants, then set the operand kind
5809       // to OK_AnyValue. If all operands are constants but not the same,
5810       // then set the operand kind to OK_NonUniformConstantValue.
5811       ConstantInt *CInt0 = nullptr;
5812       for (unsigned i = 0, e = VL.size(); i < e; ++i) {
5813         const Instruction *I = cast<Instruction>(VL[i]);
5814         unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0;
5815         ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx));
5816         if (!CInt) {
5817           Op2VK = TargetTransformInfo::OK_AnyValue;
5818           Op2VP = TargetTransformInfo::OP_None;
5819           break;
5820         }
5821         if (Op2VP == TargetTransformInfo::OP_PowerOf2 &&
5822             !CInt->getValue().isPowerOf2())
5823           Op2VP = TargetTransformInfo::OP_None;
5824         if (i == 0) {
5825           CInt0 = CInt;
5826           continue;
5827         }
5828         if (CInt0 != CInt)
5829           Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5830       }
5831 
5832       SmallVector<const Value *, 4> Operands(VL0->operand_values());
5833       InstructionCost ScalarEltCost =
5834           TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK,
5835                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5836       if (NeedToShuffleReuses) {
5837         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5838       }
5839       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5840       InstructionCost VecCost =
5841           TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK,
5842                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5843       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5844       return CommonCost + VecCost - ScalarCost;
5845     }
5846     case Instruction::GetElementPtr: {
5847       TargetTransformInfo::OperandValueKind Op1VK =
5848           TargetTransformInfo::OK_AnyValue;
5849       TargetTransformInfo::OperandValueKind Op2VK =
5850           TargetTransformInfo::OK_UniformConstantValue;
5851 
5852       InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost(
5853           Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK);
5854       if (NeedToShuffleReuses) {
5855         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5856       }
5857       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5858       InstructionCost VecCost = TTI->getArithmeticInstrCost(
5859           Instruction::Add, VecTy, CostKind, Op1VK, Op2VK);
5860       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5861       return CommonCost + VecCost - ScalarCost;
5862     }
5863     case Instruction::Load: {
5864       // Cost of wide load - cost of scalar loads.
5865       Align Alignment = cast<LoadInst>(VL0)->getAlign();
5866       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5867           Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0);
5868       if (NeedToShuffleReuses) {
5869         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5870       }
5871       InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost;
5872       InstructionCost VecLdCost;
5873       if (E->State == TreeEntry::Vectorize) {
5874         VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0,
5875                                          CostKind, VL0);
5876       } else {
5877         assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState");
5878         Align CommonAlignment = Alignment;
5879         for (Value *V : VL)
5880           CommonAlignment =
5881               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
5882         VecLdCost = TTI->getGatherScatterOpCost(
5883             Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(),
5884             /*VariableMask=*/false, CommonAlignment, CostKind, VL0);
5885       }
5886       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost));
5887       return CommonCost + VecLdCost - ScalarLdCost;
5888     }
5889     case Instruction::Store: {
5890       // We know that we can merge the stores. Calculate the cost.
5891       bool IsReorder = !E->ReorderIndices.empty();
5892       auto *SI =
5893           cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0);
5894       Align Alignment = SI->getAlign();
5895       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5896           Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0);
5897       InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost;
5898       InstructionCost VecStCost = TTI->getMemoryOpCost(
5899           Instruction::Store, VecTy, Alignment, 0, CostKind, VL0);
5900       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost));
5901       return CommonCost + VecStCost - ScalarStCost;
5902     }
5903     case Instruction::Call: {
5904       CallInst *CI = cast<CallInst>(VL0);
5905       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5906 
5907       // Calculate the cost of the scalar and vector calls.
5908       IntrinsicCostAttributes CostAttrs(ID, *CI, 1);
5909       InstructionCost ScalarEltCost =
5910           TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5911       if (NeedToShuffleReuses) {
5912         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5913       }
5914       InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
5915 
5916       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
5917       InstructionCost VecCallCost =
5918           std::min(VecCallCosts.first, VecCallCosts.second);
5919 
5920       LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
5921                         << " (" << VecCallCost << "-" << ScalarCallCost << ")"
5922                         << " for " << *CI << "\n");
5923 
5924       return CommonCost + VecCallCost - ScalarCallCost;
5925     }
5926     case Instruction::ShuffleVector: {
5927       assert(E->isAltShuffle() &&
5928              ((Instruction::isBinaryOp(E->getOpcode()) &&
5929                Instruction::isBinaryOp(E->getAltOpcode())) ||
5930               (Instruction::isCast(E->getOpcode()) &&
5931                Instruction::isCast(E->getAltOpcode())) ||
5932               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
5933              "Invalid Shuffle Vector Operand");
5934       InstructionCost ScalarCost = 0;
5935       if (NeedToShuffleReuses) {
5936         for (unsigned Idx : E->ReuseShuffleIndices) {
5937           Instruction *I = cast<Instruction>(VL[Idx]);
5938           CommonCost -= TTI->getInstructionCost(I, CostKind);
5939         }
5940         for (Value *V : VL) {
5941           Instruction *I = cast<Instruction>(V);
5942           CommonCost += TTI->getInstructionCost(I, CostKind);
5943         }
5944       }
5945       for (Value *V : VL) {
5946         Instruction *I = cast<Instruction>(V);
5947         assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5948         ScalarCost += TTI->getInstructionCost(I, CostKind);
5949       }
5950       // VecCost is equal to sum of the cost of creating 2 vectors
5951       // and the cost of creating shuffle.
5952       InstructionCost VecCost = 0;
5953       // Try to find the previous shuffle node with the same operands and same
5954       // main/alternate ops.
5955       auto &&TryFindNodeWithEqualOperands = [this, E]() {
5956         for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
5957           if (TE.get() == E)
5958             break;
5959           if (TE->isAltShuffle() &&
5960               ((TE->getOpcode() == E->getOpcode() &&
5961                 TE->getAltOpcode() == E->getAltOpcode()) ||
5962                (TE->getOpcode() == E->getAltOpcode() &&
5963                 TE->getAltOpcode() == E->getOpcode())) &&
5964               TE->hasEqualOperands(*E))
5965             return true;
5966         }
5967         return false;
5968       };
5969       if (TryFindNodeWithEqualOperands()) {
5970         LLVM_DEBUG({
5971           dbgs() << "SLP: diamond match for alternate node found.\n";
5972           E->dump();
5973         });
5974         // No need to add new vector costs here since we're going to reuse
5975         // same main/alternate vector ops, just do different shuffling.
5976       } else if (Instruction::isBinaryOp(E->getOpcode())) {
5977         VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind);
5978         VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy,
5979                                                CostKind);
5980       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
5981         VecCost = TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy,
5982                                           Builder.getInt1Ty(),
5983                                           CI0->getPredicate(), CostKind, VL0);
5984         VecCost += TTI->getCmpSelInstrCost(
5985             E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5986             cast<CmpInst>(E->getAltOp())->getPredicate(), CostKind,
5987             E->getAltOp());
5988       } else {
5989         Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
5990         Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
5991         auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size());
5992         auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size());
5993         VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty,
5994                                         TTI::CastContextHint::None, CostKind);
5995         VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty,
5996                                          TTI::CastContextHint::None, CostKind);
5997       }
5998 
5999       if (E->ReuseShuffleIndices.empty()) {
6000         CommonCost =
6001             TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy);
6002       } else {
6003         SmallVector<int> Mask;
6004         buildShuffleEntryMask(
6005             E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
6006             [E](Instruction *I) {
6007               assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
6008               return I->getOpcode() == E->getAltOpcode();
6009             },
6010             Mask);
6011         CommonCost = TTI->getShuffleCost(TargetTransformInfo::SK_PermuteTwoSrc,
6012                                          FinalVecTy, Mask);
6013       }
6014       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
6015       return CommonCost + VecCost - ScalarCost;
6016     }
6017     default:
6018       llvm_unreachable("Unknown instruction");
6019   }
6020 }
6021 
6022 bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const {
6023   LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
6024                     << VectorizableTree.size() << " is fully vectorizable .\n");
6025 
6026   auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) {
6027     SmallVector<int> Mask;
6028     return TE->State == TreeEntry::NeedToGather &&
6029            !any_of(TE->Scalars,
6030                    [this](Value *V) { return EphValues.contains(V); }) &&
6031            (allConstant(TE->Scalars) || isSplat(TE->Scalars) ||
6032             TE->Scalars.size() < Limit ||
6033             ((TE->getOpcode() == Instruction::ExtractElement ||
6034               all_of(TE->Scalars,
6035                      [](Value *V) {
6036                        return isa<ExtractElementInst, UndefValue>(V);
6037                      })) &&
6038              isFixedVectorShuffle(TE->Scalars, Mask)) ||
6039             (TE->State == TreeEntry::NeedToGather &&
6040              TE->getOpcode() == Instruction::Load && !TE->isAltShuffle()));
6041   };
6042 
6043   // We only handle trees of heights 1 and 2.
6044   if (VectorizableTree.size() == 1 &&
6045       (VectorizableTree[0]->State == TreeEntry::Vectorize ||
6046        (ForReduction &&
6047         AreVectorizableGathers(VectorizableTree[0].get(),
6048                                VectorizableTree[0]->Scalars.size()) &&
6049         VectorizableTree[0]->getVectorFactor() > 2)))
6050     return true;
6051 
6052   if (VectorizableTree.size() != 2)
6053     return false;
6054 
6055   // Handle splat and all-constants stores. Also try to vectorize tiny trees
6056   // with the second gather nodes if they have less scalar operands rather than
6057   // the initial tree element (may be profitable to shuffle the second gather)
6058   // or they are extractelements, which form shuffle.
6059   SmallVector<int> Mask;
6060   if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
6061       AreVectorizableGathers(VectorizableTree[1].get(),
6062                              VectorizableTree[0]->Scalars.size()))
6063     return true;
6064 
6065   // Gathering cost would be too much for tiny trees.
6066   if (VectorizableTree[0]->State == TreeEntry::NeedToGather ||
6067       (VectorizableTree[1]->State == TreeEntry::NeedToGather &&
6068        VectorizableTree[0]->State != TreeEntry::ScatterVectorize))
6069     return false;
6070 
6071   return true;
6072 }
6073 
6074 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts,
6075                                        TargetTransformInfo *TTI,
6076                                        bool MustMatchOrInst) {
6077   // Look past the root to find a source value. Arbitrarily follow the
6078   // path through operand 0 of any 'or'. Also, peek through optional
6079   // shift-left-by-multiple-of-8-bits.
6080   Value *ZextLoad = Root;
6081   const APInt *ShAmtC;
6082   bool FoundOr = false;
6083   while (!isa<ConstantExpr>(ZextLoad) &&
6084          (match(ZextLoad, m_Or(m_Value(), m_Value())) ||
6085           (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) &&
6086            ShAmtC->urem(8) == 0))) {
6087     auto *BinOp = cast<BinaryOperator>(ZextLoad);
6088     ZextLoad = BinOp->getOperand(0);
6089     if (BinOp->getOpcode() == Instruction::Or)
6090       FoundOr = true;
6091   }
6092   // Check if the input is an extended load of the required or/shift expression.
6093   Value *Load;
6094   if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root ||
6095       !match(ZextLoad, m_ZExt(m_Value(Load))) || !isa<LoadInst>(Load))
6096     return false;
6097 
6098   // Require that the total load bit width is a legal integer type.
6099   // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
6100   // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
6101   Type *SrcTy = Load->getType();
6102   unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts;
6103   if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth)))
6104     return false;
6105 
6106   // Everything matched - assume that we can fold the whole sequence using
6107   // load combining.
6108   LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "
6109              << *(cast<Instruction>(Root)) << "\n");
6110 
6111   return true;
6112 }
6113 
6114 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const {
6115   if (RdxKind != RecurKind::Or)
6116     return false;
6117 
6118   unsigned NumElts = VectorizableTree[0]->Scalars.size();
6119   Value *FirstReduced = VectorizableTree[0]->Scalars[0];
6120   return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI,
6121                                     /* MatchOr */ false);
6122 }
6123 
6124 bool BoUpSLP::isLoadCombineCandidate() const {
6125   // Peek through a final sequence of stores and check if all operations are
6126   // likely to be load-combined.
6127   unsigned NumElts = VectorizableTree[0]->Scalars.size();
6128   for (Value *Scalar : VectorizableTree[0]->Scalars) {
6129     Value *X;
6130     if (!match(Scalar, m_Store(m_Value(X), m_Value())) ||
6131         !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true))
6132       return false;
6133   }
6134   return true;
6135 }
6136 
6137 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const {
6138   // No need to vectorize inserts of gathered values.
6139   if (VectorizableTree.size() == 2 &&
6140       isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) &&
6141       VectorizableTree[1]->State == TreeEntry::NeedToGather)
6142     return true;
6143 
6144   // We can vectorize the tree if its size is greater than or equal to the
6145   // minimum size specified by the MinTreeSize command line option.
6146   if (VectorizableTree.size() >= MinTreeSize)
6147     return false;
6148 
6149   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
6150   // can vectorize it if we can prove it fully vectorizable.
6151   if (isFullyVectorizableTinyTree(ForReduction))
6152     return false;
6153 
6154   assert(VectorizableTree.empty()
6155              ? ExternalUses.empty()
6156              : true && "We shouldn't have any external users");
6157 
6158   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
6159   // vectorizable.
6160   return true;
6161 }
6162 
6163 InstructionCost BoUpSLP::getSpillCost() const {
6164   // Walk from the bottom of the tree to the top, tracking which values are
6165   // live. When we see a call instruction that is not part of our tree,
6166   // query TTI to see if there is a cost to keeping values live over it
6167   // (for example, if spills and fills are required).
6168   unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
6169   InstructionCost Cost = 0;
6170 
6171   SmallPtrSet<Instruction*, 4> LiveValues;
6172   Instruction *PrevInst = nullptr;
6173 
6174   // The entries in VectorizableTree are not necessarily ordered by their
6175   // position in basic blocks. Collect them and order them by dominance so later
6176   // instructions are guaranteed to be visited first. For instructions in
6177   // different basic blocks, we only scan to the beginning of the block, so
6178   // their order does not matter, as long as all instructions in a basic block
6179   // are grouped together. Using dominance ensures a deterministic order.
6180   SmallVector<Instruction *, 16> OrderedScalars;
6181   for (const auto &TEPtr : VectorizableTree) {
6182     Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
6183     if (!Inst)
6184       continue;
6185     OrderedScalars.push_back(Inst);
6186   }
6187   llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) {
6188     auto *NodeA = DT->getNode(A->getParent());
6189     auto *NodeB = DT->getNode(B->getParent());
6190     assert(NodeA && "Should only process reachable instructions");
6191     assert(NodeB && "Should only process reachable instructions");
6192     assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
6193            "Different nodes should have different DFS numbers");
6194     if (NodeA != NodeB)
6195       return NodeA->getDFSNumIn() < NodeB->getDFSNumIn();
6196     return B->comesBefore(A);
6197   });
6198 
6199   for (Instruction *Inst : OrderedScalars) {
6200     if (!PrevInst) {
6201       PrevInst = Inst;
6202       continue;
6203     }
6204 
6205     // Update LiveValues.
6206     LiveValues.erase(PrevInst);
6207     for (auto &J : PrevInst->operands()) {
6208       if (isa<Instruction>(&*J) && getTreeEntry(&*J))
6209         LiveValues.insert(cast<Instruction>(&*J));
6210     }
6211 
6212     LLVM_DEBUG({
6213       dbgs() << "SLP: #LV: " << LiveValues.size();
6214       for (auto *X : LiveValues)
6215         dbgs() << " " << X->getName();
6216       dbgs() << ", Looking at ";
6217       Inst->dump();
6218     });
6219 
6220     // Now find the sequence of instructions between PrevInst and Inst.
6221     unsigned NumCalls = 0;
6222     BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
6223                                  PrevInstIt =
6224                                      PrevInst->getIterator().getReverse();
6225     while (InstIt != PrevInstIt) {
6226       if (PrevInstIt == PrevInst->getParent()->rend()) {
6227         PrevInstIt = Inst->getParent()->rbegin();
6228         continue;
6229       }
6230 
6231       // Debug information does not impact spill cost.
6232       if ((isa<CallInst>(&*PrevInstIt) &&
6233            !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
6234           &*PrevInstIt != PrevInst)
6235         NumCalls++;
6236 
6237       ++PrevInstIt;
6238     }
6239 
6240     if (NumCalls) {
6241       SmallVector<Type*, 4> V;
6242       for (auto *II : LiveValues) {
6243         auto *ScalarTy = II->getType();
6244         if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy))
6245           ScalarTy = VectorTy->getElementType();
6246         V.push_back(FixedVectorType::get(ScalarTy, BundleWidth));
6247       }
6248       Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
6249     }
6250 
6251     PrevInst = Inst;
6252   }
6253 
6254   return Cost;
6255 }
6256 
6257 /// Check if two insertelement instructions are from the same buildvector.
6258 static bool areTwoInsertFromSameBuildVector(InsertElementInst *VU,
6259                                             InsertElementInst *V) {
6260   // Instructions must be from the same basic blocks.
6261   if (VU->getParent() != V->getParent())
6262     return false;
6263   // Checks if 2 insertelements are from the same buildvector.
6264   if (VU->getType() != V->getType())
6265     return false;
6266   // Multiple used inserts are separate nodes.
6267   if (!VU->hasOneUse() && !V->hasOneUse())
6268     return false;
6269   auto *IE1 = VU;
6270   auto *IE2 = V;
6271   // Go through the vector operand of insertelement instructions trying to find
6272   // either VU as the original vector for IE2 or V as the original vector for
6273   // IE1.
6274   do {
6275     if (IE2 == VU || IE1 == V)
6276       return true;
6277     if (IE1) {
6278       if (IE1 != VU && !IE1->hasOneUse())
6279         IE1 = nullptr;
6280       else
6281         IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0));
6282     }
6283     if (IE2) {
6284       if (IE2 != V && !IE2->hasOneUse())
6285         IE2 = nullptr;
6286       else
6287         IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0));
6288     }
6289   } while (IE1 || IE2);
6290   return false;
6291 }
6292 
6293 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) {
6294   InstructionCost Cost = 0;
6295   LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
6296                     << VectorizableTree.size() << ".\n");
6297 
6298   unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
6299 
6300   for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
6301     TreeEntry &TE = *VectorizableTree[I];
6302 
6303     InstructionCost C = getEntryCost(&TE, VectorizedVals);
6304     Cost += C;
6305     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6306                       << " for bundle that starts with " << *TE.Scalars[0]
6307                       << ".\n"
6308                       << "SLP: Current total cost = " << Cost << "\n");
6309   }
6310 
6311   SmallPtrSet<Value *, 16> ExtractCostCalculated;
6312   InstructionCost ExtractCost = 0;
6313   SmallVector<unsigned> VF;
6314   SmallVector<SmallVector<int>> ShuffleMask;
6315   SmallVector<Value *> FirstUsers;
6316   SmallVector<APInt> DemandedElts;
6317   for (ExternalUser &EU : ExternalUses) {
6318     // We only add extract cost once for the same scalar.
6319     if (!isa_and_nonnull<InsertElementInst>(EU.User) &&
6320         !ExtractCostCalculated.insert(EU.Scalar).second)
6321       continue;
6322 
6323     // Uses by ephemeral values are free (because the ephemeral value will be
6324     // removed prior to code generation, and so the extraction will be
6325     // removed as well).
6326     if (EphValues.count(EU.User))
6327       continue;
6328 
6329     // No extract cost for vector "scalar"
6330     if (isa<FixedVectorType>(EU.Scalar->getType()))
6331       continue;
6332 
6333     // Already counted the cost for external uses when tried to adjust the cost
6334     // for extractelements, no need to add it again.
6335     if (isa<ExtractElementInst>(EU.Scalar))
6336       continue;
6337 
6338     // If found user is an insertelement, do not calculate extract cost but try
6339     // to detect it as a final shuffled/identity match.
6340     if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) {
6341       if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) {
6342         Optional<unsigned> InsertIdx = getInsertIndex(VU);
6343         if (InsertIdx) {
6344           auto *It = find_if(FirstUsers, [VU](Value *V) {
6345             return areTwoInsertFromSameBuildVector(VU,
6346                                                    cast<InsertElementInst>(V));
6347           });
6348           int VecId = -1;
6349           if (It == FirstUsers.end()) {
6350             VF.push_back(FTy->getNumElements());
6351             ShuffleMask.emplace_back(VF.back(), UndefMaskElem);
6352             // Find the insertvector, vectorized in tree, if any.
6353             Value *Base = VU;
6354             while (auto *IEBase = dyn_cast<InsertElementInst>(Base)) {
6355               // Build the mask for the vectorized insertelement instructions.
6356               if (const TreeEntry *E = getTreeEntry(IEBase)) {
6357                 VU = IEBase;
6358                 do {
6359                   int Idx = E->findLaneForValue(Base);
6360                   ShuffleMask.back()[Idx] = Idx;
6361                   Base = cast<InsertElementInst>(Base)->getOperand(0);
6362                 } while (E == getTreeEntry(Base));
6363                 break;
6364               }
6365               Base = cast<InsertElementInst>(Base)->getOperand(0);
6366             }
6367             FirstUsers.push_back(VU);
6368             DemandedElts.push_back(APInt::getZero(VF.back()));
6369             VecId = FirstUsers.size() - 1;
6370           } else {
6371             VecId = std::distance(FirstUsers.begin(), It);
6372           }
6373           int InIdx = *InsertIdx;
6374           ShuffleMask[VecId][InIdx] = EU.Lane;
6375           DemandedElts[VecId].setBit(InIdx);
6376           continue;
6377         }
6378       }
6379     }
6380 
6381     // If we plan to rewrite the tree in a smaller type, we will need to sign
6382     // extend the extracted value back to the original type. Here, we account
6383     // for the extract and the added cost of the sign extend if needed.
6384     auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth);
6385     auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
6386     if (MinBWs.count(ScalarRoot)) {
6387       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
6388       auto Extend =
6389           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
6390       VecTy = FixedVectorType::get(MinTy, BundleWidth);
6391       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
6392                                                    VecTy, EU.Lane);
6393     } else {
6394       ExtractCost +=
6395           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
6396     }
6397   }
6398 
6399   InstructionCost SpillCost = getSpillCost();
6400   Cost += SpillCost + ExtractCost;
6401   if (FirstUsers.size() == 1) {
6402     int Limit = ShuffleMask.front().size() * 2;
6403     if (!all_of(ShuffleMask.front(),
6404                 [Limit](int Idx) { return Idx < Limit; }) ||
6405         !ShuffleVectorInst::isIdentityMask(ShuffleMask.front())) {
6406       InstructionCost C = TTI->getShuffleCost(
6407           TTI::SK_PermuteSingleSrc,
6408           cast<FixedVectorType>(FirstUsers.front()->getType()),
6409           ShuffleMask.front());
6410       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6411                         << " for final shuffle of insertelement external users "
6412                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6413                         << "SLP: Current total cost = " << Cost << "\n");
6414       Cost += C;
6415     }
6416     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6417         cast<FixedVectorType>(FirstUsers.front()->getType()),
6418         DemandedElts.front(), /*Insert*/ true, /*Extract*/ false);
6419     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6420                       << " for insertelements gather.\n"
6421                       << "SLP: Current total cost = " << Cost << "\n");
6422     Cost -= InsertCost;
6423   } else if (FirstUsers.size() >= 2) {
6424     unsigned MaxVF = *std::max_element(VF.begin(), VF.end());
6425     // Combined masks of the first 2 vectors.
6426     SmallVector<int> CombinedMask(MaxVF, UndefMaskElem);
6427     copy(ShuffleMask.front(), CombinedMask.begin());
6428     APInt CombinedDemandedElts = DemandedElts.front().zextOrSelf(MaxVF);
6429     auto *VecTy = FixedVectorType::get(
6430         cast<VectorType>(FirstUsers.front()->getType())->getElementType(),
6431         MaxVF);
6432     for (int I = 0, E = ShuffleMask[1].size(); I < E; ++I) {
6433       if (ShuffleMask[1][I] != UndefMaskElem) {
6434         CombinedMask[I] = ShuffleMask[1][I] + MaxVF;
6435         CombinedDemandedElts.setBit(I);
6436       }
6437     }
6438     InstructionCost C =
6439         TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6440     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6441                       << " for final shuffle of vector node and external "
6442                          "insertelement users "
6443                       << *VectorizableTree.front()->Scalars.front() << ".\n"
6444                       << "SLP: Current total cost = " << Cost << "\n");
6445     Cost += C;
6446     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6447         VecTy, CombinedDemandedElts, /*Insert*/ true, /*Extract*/ false);
6448     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6449                       << " for insertelements gather.\n"
6450                       << "SLP: Current total cost = " << Cost << "\n");
6451     Cost -= InsertCost;
6452     for (int I = 2, E = FirstUsers.size(); I < E; ++I) {
6453       if (ShuffleMask[I].empty())
6454         continue;
6455       // Other elements - permutation of 2 vectors (the initial one and the
6456       // next Ith incoming vector).
6457       unsigned VF = ShuffleMask[I].size();
6458       for (unsigned Idx = 0; Idx < VF; ++Idx) {
6459         int Mask = ShuffleMask[I][Idx];
6460         if (Mask != UndefMaskElem)
6461           CombinedMask[Idx] = MaxVF + Mask;
6462         else if (CombinedMask[Idx] != UndefMaskElem)
6463           CombinedMask[Idx] = Idx;
6464       }
6465       for (unsigned Idx = VF; Idx < MaxVF; ++Idx)
6466         if (CombinedMask[Idx] != UndefMaskElem)
6467           CombinedMask[Idx] = Idx;
6468       InstructionCost C =
6469           TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6470       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6471                         << " for final shuffle of vector node and external "
6472                            "insertelement users "
6473                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6474                         << "SLP: Current total cost = " << Cost << "\n");
6475       Cost += C;
6476       InstructionCost InsertCost = TTI->getScalarizationOverhead(
6477           cast<FixedVectorType>(FirstUsers[I]->getType()), DemandedElts[I],
6478           /*Insert*/ true, /*Extract*/ false);
6479       LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6480                         << " for insertelements gather.\n"
6481                         << "SLP: Current total cost = " << Cost << "\n");
6482       Cost -= InsertCost;
6483     }
6484   }
6485 
6486 #ifndef NDEBUG
6487   SmallString<256> Str;
6488   {
6489     raw_svector_ostream OS(Str);
6490     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
6491        << "SLP: Extract Cost = " << ExtractCost << ".\n"
6492        << "SLP: Total Cost = " << Cost << ".\n";
6493   }
6494   LLVM_DEBUG(dbgs() << Str);
6495   if (ViewSLPTree)
6496     ViewGraph(this, "SLP" + F->getName(), false, Str);
6497 #endif
6498 
6499   return Cost;
6500 }
6501 
6502 Optional<TargetTransformInfo::ShuffleKind>
6503 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
6504                                SmallVectorImpl<const TreeEntry *> &Entries) {
6505   // TODO: currently checking only for Scalars in the tree entry, need to count
6506   // reused elements too for better cost estimation.
6507   Mask.assign(TE->Scalars.size(), UndefMaskElem);
6508   Entries.clear();
6509   // Build a lists of values to tree entries.
6510   DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs;
6511   for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) {
6512     if (EntryPtr.get() == TE)
6513       break;
6514     if (EntryPtr->State != TreeEntry::NeedToGather)
6515       continue;
6516     for (Value *V : EntryPtr->Scalars)
6517       ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get());
6518   }
6519   // Find all tree entries used by the gathered values. If no common entries
6520   // found - not a shuffle.
6521   // Here we build a set of tree nodes for each gathered value and trying to
6522   // find the intersection between these sets. If we have at least one common
6523   // tree node for each gathered value - we have just a permutation of the
6524   // single vector. If we have 2 different sets, we're in situation where we
6525   // have a permutation of 2 input vectors.
6526   SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs;
6527   DenseMap<Value *, int> UsedValuesEntry;
6528   for (Value *V : TE->Scalars) {
6529     if (isa<UndefValue>(V))
6530       continue;
6531     // Build a list of tree entries where V is used.
6532     SmallPtrSet<const TreeEntry *, 4> VToTEs;
6533     auto It = ValueToTEs.find(V);
6534     if (It != ValueToTEs.end())
6535       VToTEs = It->second;
6536     if (const TreeEntry *VTE = getTreeEntry(V))
6537       VToTEs.insert(VTE);
6538     if (VToTEs.empty())
6539       return None;
6540     if (UsedTEs.empty()) {
6541       // The first iteration, just insert the list of nodes to vector.
6542       UsedTEs.push_back(VToTEs);
6543     } else {
6544       // Need to check if there are any previously used tree nodes which use V.
6545       // If there are no such nodes, consider that we have another one input
6546       // vector.
6547       SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs);
6548       unsigned Idx = 0;
6549       for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) {
6550         // Do we have a non-empty intersection of previously listed tree entries
6551         // and tree entries using current V?
6552         set_intersect(VToTEs, Set);
6553         if (!VToTEs.empty()) {
6554           // Yes, write the new subset and continue analysis for the next
6555           // scalar.
6556           Set.swap(VToTEs);
6557           break;
6558         }
6559         VToTEs = SavedVToTEs;
6560         ++Idx;
6561       }
6562       // No non-empty intersection found - need to add a second set of possible
6563       // source vectors.
6564       if (Idx == UsedTEs.size()) {
6565         // If the number of input vectors is greater than 2 - not a permutation,
6566         // fallback to the regular gather.
6567         if (UsedTEs.size() == 2)
6568           return None;
6569         UsedTEs.push_back(SavedVToTEs);
6570         Idx = UsedTEs.size() - 1;
6571       }
6572       UsedValuesEntry.try_emplace(V, Idx);
6573     }
6574   }
6575 
6576   if (UsedTEs.empty()) {
6577     assert(all_of(TE->Scalars, UndefValue::classof) &&
6578            "Expected vector of undefs only.");
6579     return None;
6580   }
6581 
6582   unsigned VF = 0;
6583   if (UsedTEs.size() == 1) {
6584     // Try to find the perfect match in another gather node at first.
6585     auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) {
6586       return EntryPtr->isSame(TE->Scalars);
6587     });
6588     if (It != UsedTEs.front().end()) {
6589       Entries.push_back(*It);
6590       std::iota(Mask.begin(), Mask.end(), 0);
6591       return TargetTransformInfo::SK_PermuteSingleSrc;
6592     }
6593     // No perfect match, just shuffle, so choose the first tree node.
6594     Entries.push_back(*UsedTEs.front().begin());
6595   } else {
6596     // Try to find nodes with the same vector factor.
6597     assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries.");
6598     DenseMap<int, const TreeEntry *> VFToTE;
6599     for (const TreeEntry *TE : UsedTEs.front())
6600       VFToTE.try_emplace(TE->getVectorFactor(), TE);
6601     for (const TreeEntry *TE : UsedTEs.back()) {
6602       auto It = VFToTE.find(TE->getVectorFactor());
6603       if (It != VFToTE.end()) {
6604         VF = It->first;
6605         Entries.push_back(It->second);
6606         Entries.push_back(TE);
6607         break;
6608       }
6609     }
6610     // No 2 source vectors with the same vector factor - give up and do regular
6611     // gather.
6612     if (Entries.empty())
6613       return None;
6614   }
6615 
6616   // Build a shuffle mask for better cost estimation and vector emission.
6617   for (int I = 0, E = TE->Scalars.size(); I < E; ++I) {
6618     Value *V = TE->Scalars[I];
6619     if (isa<UndefValue>(V))
6620       continue;
6621     unsigned Idx = UsedValuesEntry.lookup(V);
6622     const TreeEntry *VTE = Entries[Idx];
6623     int FoundLane = VTE->findLaneForValue(V);
6624     Mask[I] = Idx * VF + FoundLane;
6625     // Extra check required by isSingleSourceMaskImpl function (called by
6626     // ShuffleVectorInst::isSingleSourceMask).
6627     if (Mask[I] >= 2 * E)
6628       return None;
6629   }
6630   switch (Entries.size()) {
6631   case 1:
6632     return TargetTransformInfo::SK_PermuteSingleSrc;
6633   case 2:
6634     return TargetTransformInfo::SK_PermuteTwoSrc;
6635   default:
6636     break;
6637   }
6638   return None;
6639 }
6640 
6641 InstructionCost BoUpSLP::getGatherCost(FixedVectorType *Ty,
6642                                        const APInt &ShuffledIndices,
6643                                        bool NeedToShuffle) const {
6644   InstructionCost Cost =
6645       TTI->getScalarizationOverhead(Ty, ~ShuffledIndices, /*Insert*/ true,
6646                                     /*Extract*/ false);
6647   if (NeedToShuffle)
6648     Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
6649   return Cost;
6650 }
6651 
6652 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
6653   // Find the type of the operands in VL.
6654   Type *ScalarTy = VL[0]->getType();
6655   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
6656     ScalarTy = SI->getValueOperand()->getType();
6657   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
6658   bool DuplicateNonConst = false;
6659   // Find the cost of inserting/extracting values from the vector.
6660   // Check if the same elements are inserted several times and count them as
6661   // shuffle candidates.
6662   APInt ShuffledElements = APInt::getZero(VL.size());
6663   DenseSet<Value *> UniqueElements;
6664   // Iterate in reverse order to consider insert elements with the high cost.
6665   for (unsigned I = VL.size(); I > 0; --I) {
6666     unsigned Idx = I - 1;
6667     // No need to shuffle duplicates for constants.
6668     if (isConstant(VL[Idx])) {
6669       ShuffledElements.setBit(Idx);
6670       continue;
6671     }
6672     if (!UniqueElements.insert(VL[Idx]).second) {
6673       DuplicateNonConst = true;
6674       ShuffledElements.setBit(Idx);
6675     }
6676   }
6677   return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst);
6678 }
6679 
6680 // Perform operand reordering on the instructions in VL and return the reordered
6681 // operands in Left and Right.
6682 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
6683                                              SmallVectorImpl<Value *> &Left,
6684                                              SmallVectorImpl<Value *> &Right,
6685                                              const DataLayout &DL,
6686                                              ScalarEvolution &SE,
6687                                              const BoUpSLP &R) {
6688   if (VL.empty())
6689     return;
6690   VLOperands Ops(VL, DL, SE, R);
6691   // Reorder the operands in place.
6692   Ops.reorder();
6693   Left = Ops.getVL(0);
6694   Right = Ops.getVL(1);
6695 }
6696 
6697 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) {
6698   // Get the basic block this bundle is in. All instructions in the bundle
6699   // should be in this block.
6700   auto *Front = E->getMainOp();
6701   auto *BB = Front->getParent();
6702   assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool {
6703     auto *I = cast<Instruction>(V);
6704     return !E->isOpcodeOrAlt(I) || I->getParent() == BB;
6705   }));
6706 
6707   auto &&FindLastInst = [E, Front]() {
6708     Instruction *LastInst = Front;
6709     for (Value *V : E->Scalars) {
6710       auto *I = dyn_cast<Instruction>(V);
6711       if (!I)
6712         continue;
6713       if (LastInst->comesBefore(I))
6714         LastInst = I;
6715     }
6716     return LastInst;
6717   };
6718 
6719   auto &&FindFirstInst = [E, Front]() {
6720     Instruction *FirstInst = Front;
6721     for (Value *V : E->Scalars) {
6722       auto *I = dyn_cast<Instruction>(V);
6723       if (!I)
6724         continue;
6725       if (I->comesBefore(FirstInst))
6726         FirstInst = I;
6727     }
6728     return FirstInst;
6729   };
6730 
6731   // Set the insert point to the beginning of the basic block if the entry
6732   // should not be scheduled.
6733   if (E->State != TreeEntry::NeedToGather &&
6734       doesNotNeedToSchedule(E->Scalars)) {
6735     Instruction *InsertInst;
6736     if (all_of(E->Scalars, isUsedOutsideBlock))
6737       InsertInst = FindLastInst();
6738     else
6739       InsertInst = FindFirstInst();
6740     // If the instruction is PHI, set the insert point after all the PHIs.
6741     if (isa<PHINode>(InsertInst))
6742       InsertInst = BB->getFirstNonPHI();
6743     BasicBlock::iterator InsertPt = InsertInst->getIterator();
6744     Builder.SetInsertPoint(BB, InsertPt);
6745     Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6746     return;
6747   }
6748 
6749   // The last instruction in the bundle in program order.
6750   Instruction *LastInst = nullptr;
6751 
6752   // Find the last instruction. The common case should be that BB has been
6753   // scheduled, and the last instruction is VL.back(). So we start with
6754   // VL.back() and iterate over schedule data until we reach the end of the
6755   // bundle. The end of the bundle is marked by null ScheduleData.
6756   if (BlocksSchedules.count(BB)) {
6757     Value *V = E->isOneOf(E->Scalars.back());
6758     if (doesNotNeedToBeScheduled(V))
6759       V = *find_if_not(E->Scalars, doesNotNeedToBeScheduled);
6760     auto *Bundle = BlocksSchedules[BB]->getScheduleData(V);
6761     if (Bundle && Bundle->isPartOfBundle())
6762       for (; Bundle; Bundle = Bundle->NextInBundle)
6763         if (Bundle->OpValue == Bundle->Inst)
6764           LastInst = Bundle->Inst;
6765   }
6766 
6767   // LastInst can still be null at this point if there's either not an entry
6768   // for BB in BlocksSchedules or there's no ScheduleData available for
6769   // VL.back(). This can be the case if buildTree_rec aborts for various
6770   // reasons (e.g., the maximum recursion depth is reached, the maximum region
6771   // size is reached, etc.). ScheduleData is initialized in the scheduling
6772   // "dry-run".
6773   //
6774   // If this happens, we can still find the last instruction by brute force. We
6775   // iterate forwards from Front (inclusive) until we either see all
6776   // instructions in the bundle or reach the end of the block. If Front is the
6777   // last instruction in program order, LastInst will be set to Front, and we
6778   // will visit all the remaining instructions in the block.
6779   //
6780   // One of the reasons we exit early from buildTree_rec is to place an upper
6781   // bound on compile-time. Thus, taking an additional compile-time hit here is
6782   // not ideal. However, this should be exceedingly rare since it requires that
6783   // we both exit early from buildTree_rec and that the bundle be out-of-order
6784   // (causing us to iterate all the way to the end of the block).
6785   if (!LastInst) {
6786     LastInst = FindLastInst();
6787     // If the instruction is PHI, set the insert point after all the PHIs.
6788     if (isa<PHINode>(LastInst))
6789       LastInst = BB->getFirstNonPHI()->getPrevNode();
6790   }
6791   assert(LastInst && "Failed to find last instruction in bundle");
6792 
6793   // Set the insertion point after the last instruction in the bundle. Set the
6794   // debug location to Front.
6795   Builder.SetInsertPoint(BB, std::next(LastInst->getIterator()));
6796   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6797 }
6798 
6799 Value *BoUpSLP::gather(ArrayRef<Value *> VL) {
6800   // List of instructions/lanes from current block and/or the blocks which are
6801   // part of the current loop. These instructions will be inserted at the end to
6802   // make it possible to optimize loops and hoist invariant instructions out of
6803   // the loops body with better chances for success.
6804   SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts;
6805   SmallSet<int, 4> PostponedIndices;
6806   Loop *L = LI->getLoopFor(Builder.GetInsertBlock());
6807   auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) {
6808     SmallPtrSet<BasicBlock *, 4> Visited;
6809     while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second)
6810       InsertBB = InsertBB->getSinglePredecessor();
6811     return InsertBB && InsertBB == InstBB;
6812   };
6813   for (int I = 0, E = VL.size(); I < E; ++I) {
6814     if (auto *Inst = dyn_cast<Instruction>(VL[I]))
6815       if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) ||
6816            getTreeEntry(Inst) || (L && (L->contains(Inst)))) &&
6817           PostponedIndices.insert(I).second)
6818         PostponedInsts.emplace_back(Inst, I);
6819   }
6820 
6821   auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) {
6822     Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos));
6823     auto *InsElt = dyn_cast<InsertElementInst>(Vec);
6824     if (!InsElt)
6825       return Vec;
6826     GatherShuffleSeq.insert(InsElt);
6827     CSEBlocks.insert(InsElt->getParent());
6828     // Add to our 'need-to-extract' list.
6829     if (TreeEntry *Entry = getTreeEntry(V)) {
6830       // Find which lane we need to extract.
6831       unsigned FoundLane = Entry->findLaneForValue(V);
6832       ExternalUses.emplace_back(V, InsElt, FoundLane);
6833     }
6834     return Vec;
6835   };
6836   Value *Val0 =
6837       isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0];
6838   FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size());
6839   Value *Vec = PoisonValue::get(VecTy);
6840   SmallVector<int> NonConsts;
6841   // Insert constant values at first.
6842   for (int I = 0, E = VL.size(); I < E; ++I) {
6843     if (PostponedIndices.contains(I))
6844       continue;
6845     if (!isConstant(VL[I])) {
6846       NonConsts.push_back(I);
6847       continue;
6848     }
6849     Vec = CreateInsertElement(Vec, VL[I], I);
6850   }
6851   // Insert non-constant values.
6852   for (int I : NonConsts)
6853     Vec = CreateInsertElement(Vec, VL[I], I);
6854   // Append instructions, which are/may be part of the loop, in the end to make
6855   // it possible to hoist non-loop-based instructions.
6856   for (const std::pair<Value *, unsigned> &Pair : PostponedInsts)
6857     Vec = CreateInsertElement(Vec, Pair.first, Pair.second);
6858 
6859   return Vec;
6860 }
6861 
6862 namespace {
6863 /// Merges shuffle masks and emits final shuffle instruction, if required.
6864 class ShuffleInstructionBuilder {
6865   IRBuilderBase &Builder;
6866   const unsigned VF = 0;
6867   bool IsFinalized = false;
6868   SmallVector<int, 4> Mask;
6869   /// Holds all of the instructions that we gathered.
6870   SetVector<Instruction *> &GatherShuffleSeq;
6871   /// A list of blocks that we are going to CSE.
6872   SetVector<BasicBlock *> &CSEBlocks;
6873 
6874 public:
6875   ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF,
6876                             SetVector<Instruction *> &GatherShuffleSeq,
6877                             SetVector<BasicBlock *> &CSEBlocks)
6878       : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq),
6879         CSEBlocks(CSEBlocks) {}
6880 
6881   /// Adds a mask, inverting it before applying.
6882   void addInversedMask(ArrayRef<unsigned> SubMask) {
6883     if (SubMask.empty())
6884       return;
6885     SmallVector<int, 4> NewMask;
6886     inversePermutation(SubMask, NewMask);
6887     addMask(NewMask);
6888   }
6889 
6890   /// Functions adds masks, merging them into  single one.
6891   void addMask(ArrayRef<unsigned> SubMask) {
6892     SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end());
6893     addMask(NewMask);
6894   }
6895 
6896   void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); }
6897 
6898   Value *finalize(Value *V) {
6899     IsFinalized = true;
6900     unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements();
6901     if (VF == ValueVF && Mask.empty())
6902       return V;
6903     SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem);
6904     std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0);
6905     addMask(NormalizedMask);
6906 
6907     if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask))
6908       return V;
6909     Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle");
6910     if (auto *I = dyn_cast<Instruction>(Vec)) {
6911       GatherShuffleSeq.insert(I);
6912       CSEBlocks.insert(I->getParent());
6913     }
6914     return Vec;
6915   }
6916 
6917   ~ShuffleInstructionBuilder() {
6918     assert((IsFinalized || Mask.empty()) &&
6919            "Shuffle construction must be finalized.");
6920   }
6921 };
6922 } // namespace
6923 
6924 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
6925   const unsigned VF = VL.size();
6926   InstructionsState S = getSameOpcode(VL);
6927   if (S.getOpcode()) {
6928     if (TreeEntry *E = getTreeEntry(S.OpValue))
6929       if (E->isSame(VL)) {
6930         Value *V = vectorizeTree(E);
6931         if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) {
6932           if (!E->ReuseShuffleIndices.empty()) {
6933             // Reshuffle to get only unique values.
6934             // If some of the scalars are duplicated in the vectorization tree
6935             // entry, we do not vectorize them but instead generate a mask for
6936             // the reuses. But if there are several users of the same entry,
6937             // they may have different vectorization factors. This is especially
6938             // important for PHI nodes. In this case, we need to adapt the
6939             // resulting instruction for the user vectorization factor and have
6940             // to reshuffle it again to take only unique elements of the vector.
6941             // Without this code the function incorrectly returns reduced vector
6942             // instruction with the same elements, not with the unique ones.
6943 
6944             // block:
6945             // %phi = phi <2 x > { .., %entry} {%shuffle, %block}
6946             // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0>
6947             // ... (use %2)
6948             // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0}
6949             // br %block
6950             SmallVector<int> UniqueIdxs(VF, UndefMaskElem);
6951             SmallSet<int, 4> UsedIdxs;
6952             int Pos = 0;
6953             int Sz = VL.size();
6954             for (int Idx : E->ReuseShuffleIndices) {
6955               if (Idx != Sz && Idx != UndefMaskElem &&
6956                   UsedIdxs.insert(Idx).second)
6957                 UniqueIdxs[Idx] = Pos;
6958               ++Pos;
6959             }
6960             assert(VF >= UsedIdxs.size() && "Expected vectorization factor "
6961                                             "less than original vector size.");
6962             UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem);
6963             V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle");
6964           } else {
6965             assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() &&
6966                    "Expected vectorization factor less "
6967                    "than original vector size.");
6968             SmallVector<int> UniformMask(VF, 0);
6969             std::iota(UniformMask.begin(), UniformMask.end(), 0);
6970             V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle");
6971           }
6972           if (auto *I = dyn_cast<Instruction>(V)) {
6973             GatherShuffleSeq.insert(I);
6974             CSEBlocks.insert(I->getParent());
6975           }
6976         }
6977         return V;
6978       }
6979   }
6980 
6981   // Can't vectorize this, so simply build a new vector with each lane
6982   // corresponding to the requested value.
6983   return createBuildVector(VL);
6984 }
6985 Value *BoUpSLP::createBuildVector(ArrayRef<Value *> VL) {
6986   unsigned VF = VL.size();
6987   // Exploit possible reuse of values across lanes.
6988   SmallVector<int> ReuseShuffleIndicies;
6989   SmallVector<Value *> UniqueValues;
6990   if (VL.size() > 2) {
6991     DenseMap<Value *, unsigned> UniquePositions;
6992     unsigned NumValues =
6993         std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) {
6994                                     return !isa<UndefValue>(V);
6995                                   }).base());
6996     VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues));
6997     int UniqueVals = 0;
6998     for (Value *V : VL.drop_back(VL.size() - VF)) {
6999       if (isa<UndefValue>(V)) {
7000         ReuseShuffleIndicies.emplace_back(UndefMaskElem);
7001         continue;
7002       }
7003       if (isConstant(V)) {
7004         ReuseShuffleIndicies.emplace_back(UniqueValues.size());
7005         UniqueValues.emplace_back(V);
7006         continue;
7007       }
7008       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
7009       ReuseShuffleIndicies.emplace_back(Res.first->second);
7010       if (Res.second) {
7011         UniqueValues.emplace_back(V);
7012         ++UniqueVals;
7013       }
7014     }
7015     if (UniqueVals == 1 && UniqueValues.size() == 1) {
7016       // Emit pure splat vector.
7017       ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(),
7018                                   UndefMaskElem);
7019     } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) {
7020       ReuseShuffleIndicies.clear();
7021       UniqueValues.clear();
7022       UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues));
7023     }
7024     UniqueValues.append(VF - UniqueValues.size(),
7025                         PoisonValue::get(VL[0]->getType()));
7026     VL = UniqueValues;
7027   }
7028 
7029   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
7030                                            CSEBlocks);
7031   Value *Vec = gather(VL);
7032   if (!ReuseShuffleIndicies.empty()) {
7033     ShuffleBuilder.addMask(ReuseShuffleIndicies);
7034     Vec = ShuffleBuilder.finalize(Vec);
7035   }
7036   return Vec;
7037 }
7038 
7039 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
7040   IRBuilder<>::InsertPointGuard Guard(Builder);
7041 
7042   if (E->VectorizedValue) {
7043     LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
7044     return E->VectorizedValue;
7045   }
7046 
7047   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
7048   unsigned VF = E->getVectorFactor();
7049   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
7050                                            CSEBlocks);
7051   if (E->State == TreeEntry::NeedToGather) {
7052     if (E->getMainOp())
7053       setInsertPointAfterBundle(E);
7054     Value *Vec;
7055     SmallVector<int> Mask;
7056     SmallVector<const TreeEntry *> Entries;
7057     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
7058         isGatherShuffledEntry(E, Mask, Entries);
7059     if (Shuffle.hasValue()) {
7060       assert((Entries.size() == 1 || Entries.size() == 2) &&
7061              "Expected shuffle of 1 or 2 entries.");
7062       Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue,
7063                                         Entries.back()->VectorizedValue, Mask);
7064       if (auto *I = dyn_cast<Instruction>(Vec)) {
7065         GatherShuffleSeq.insert(I);
7066         CSEBlocks.insert(I->getParent());
7067       }
7068     } else {
7069       Vec = gather(E->Scalars);
7070     }
7071     if (NeedToShuffleReuses) {
7072       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7073       Vec = ShuffleBuilder.finalize(Vec);
7074     }
7075     E->VectorizedValue = Vec;
7076     return Vec;
7077   }
7078 
7079   assert((E->State == TreeEntry::Vectorize ||
7080           E->State == TreeEntry::ScatterVectorize) &&
7081          "Unhandled state");
7082   unsigned ShuffleOrOp =
7083       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
7084   Instruction *VL0 = E->getMainOp();
7085   Type *ScalarTy = VL0->getType();
7086   if (auto *Store = dyn_cast<StoreInst>(VL0))
7087     ScalarTy = Store->getValueOperand()->getType();
7088   else if (auto *IE = dyn_cast<InsertElementInst>(VL0))
7089     ScalarTy = IE->getOperand(1)->getType();
7090   auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
7091   switch (ShuffleOrOp) {
7092     case Instruction::PHI: {
7093       assert(
7094           (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) &&
7095           "PHI reordering is free.");
7096       auto *PH = cast<PHINode>(VL0);
7097       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
7098       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
7099       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
7100       Value *V = NewPhi;
7101 
7102       // Adjust insertion point once all PHI's have been generated.
7103       Builder.SetInsertPoint(&*PH->getParent()->getFirstInsertionPt());
7104       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
7105 
7106       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7107       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7108       V = ShuffleBuilder.finalize(V);
7109 
7110       E->VectorizedValue = V;
7111 
7112       // PHINodes may have multiple entries from the same block. We want to
7113       // visit every block once.
7114       SmallPtrSet<BasicBlock*, 4> VisitedBBs;
7115 
7116       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
7117         ValueList Operands;
7118         BasicBlock *IBB = PH->getIncomingBlock(i);
7119 
7120         if (!VisitedBBs.insert(IBB).second) {
7121           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
7122           continue;
7123         }
7124 
7125         Builder.SetInsertPoint(IBB->getTerminator());
7126         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
7127         Value *Vec = vectorizeTree(E->getOperand(i));
7128         NewPhi->addIncoming(Vec, IBB);
7129       }
7130 
7131       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
7132              "Invalid number of incoming values");
7133       return V;
7134     }
7135 
7136     case Instruction::ExtractElement: {
7137       Value *V = E->getSingleOperand(0);
7138       Builder.SetInsertPoint(VL0);
7139       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7140       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7141       V = ShuffleBuilder.finalize(V);
7142       E->VectorizedValue = V;
7143       return V;
7144     }
7145     case Instruction::ExtractValue: {
7146       auto *LI = cast<LoadInst>(E->getSingleOperand(0));
7147       Builder.SetInsertPoint(LI);
7148       auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
7149       Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
7150       LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
7151       Value *NewV = propagateMetadata(V, E->Scalars);
7152       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7153       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7154       NewV = ShuffleBuilder.finalize(NewV);
7155       E->VectorizedValue = NewV;
7156       return NewV;
7157     }
7158     case Instruction::InsertElement: {
7159       assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique");
7160       Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back()));
7161       Value *V = vectorizeTree(E->getOperand(1));
7162 
7163       // Create InsertVector shuffle if necessary
7164       auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
7165         return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0));
7166       }));
7167       const unsigned NumElts =
7168           cast<FixedVectorType>(FirstInsert->getType())->getNumElements();
7169       const unsigned NumScalars = E->Scalars.size();
7170 
7171       unsigned Offset = *getInsertIndex(VL0);
7172       assert(Offset < NumElts && "Failed to find vector index offset");
7173 
7174       // Create shuffle to resize vector
7175       SmallVector<int> Mask;
7176       if (!E->ReorderIndices.empty()) {
7177         inversePermutation(E->ReorderIndices, Mask);
7178         Mask.append(NumElts - NumScalars, UndefMaskElem);
7179       } else {
7180         Mask.assign(NumElts, UndefMaskElem);
7181         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
7182       }
7183       // Create InsertVector shuffle if necessary
7184       bool IsIdentity = true;
7185       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
7186       Mask.swap(PrevMask);
7187       for (unsigned I = 0; I < NumScalars; ++I) {
7188         Value *Scalar = E->Scalars[PrevMask[I]];
7189         unsigned InsertIdx = *getInsertIndex(Scalar);
7190         IsIdentity &= InsertIdx - Offset == I;
7191         Mask[InsertIdx - Offset] = I;
7192       }
7193       if (!IsIdentity || NumElts != NumScalars) {
7194         V = Builder.CreateShuffleVector(V, Mask);
7195         if (auto *I = dyn_cast<Instruction>(V)) {
7196           GatherShuffleSeq.insert(I);
7197           CSEBlocks.insert(I->getParent());
7198         }
7199       }
7200 
7201       if ((!IsIdentity || Offset != 0 ||
7202            !isUndefVector(FirstInsert->getOperand(0))) &&
7203           NumElts != NumScalars) {
7204         SmallVector<int> InsertMask(NumElts);
7205         std::iota(InsertMask.begin(), InsertMask.end(), 0);
7206         for (unsigned I = 0; I < NumElts; I++) {
7207           if (Mask[I] != UndefMaskElem)
7208             InsertMask[Offset + I] = NumElts + I;
7209         }
7210 
7211         V = Builder.CreateShuffleVector(
7212             FirstInsert->getOperand(0), V, InsertMask,
7213             cast<Instruction>(E->Scalars.back())->getName());
7214         if (auto *I = dyn_cast<Instruction>(V)) {
7215           GatherShuffleSeq.insert(I);
7216           CSEBlocks.insert(I->getParent());
7217         }
7218       }
7219 
7220       ++NumVectorInstructions;
7221       E->VectorizedValue = V;
7222       return V;
7223     }
7224     case Instruction::ZExt:
7225     case Instruction::SExt:
7226     case Instruction::FPToUI:
7227     case Instruction::FPToSI:
7228     case Instruction::FPExt:
7229     case Instruction::PtrToInt:
7230     case Instruction::IntToPtr:
7231     case Instruction::SIToFP:
7232     case Instruction::UIToFP:
7233     case Instruction::Trunc:
7234     case Instruction::FPTrunc:
7235     case Instruction::BitCast: {
7236       setInsertPointAfterBundle(E);
7237 
7238       Value *InVec = vectorizeTree(E->getOperand(0));
7239 
7240       if (E->VectorizedValue) {
7241         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7242         return E->VectorizedValue;
7243       }
7244 
7245       auto *CI = cast<CastInst>(VL0);
7246       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
7247       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7248       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7249       V = ShuffleBuilder.finalize(V);
7250 
7251       E->VectorizedValue = V;
7252       ++NumVectorInstructions;
7253       return V;
7254     }
7255     case Instruction::FCmp:
7256     case Instruction::ICmp: {
7257       setInsertPointAfterBundle(E);
7258 
7259       Value *L = vectorizeTree(E->getOperand(0));
7260       Value *R = vectorizeTree(E->getOperand(1));
7261 
7262       if (E->VectorizedValue) {
7263         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7264         return E->VectorizedValue;
7265       }
7266 
7267       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
7268       Value *V = Builder.CreateCmp(P0, L, R);
7269       propagateIRFlags(V, E->Scalars, VL0);
7270       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7271       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7272       V = ShuffleBuilder.finalize(V);
7273 
7274       E->VectorizedValue = V;
7275       ++NumVectorInstructions;
7276       return V;
7277     }
7278     case Instruction::Select: {
7279       setInsertPointAfterBundle(E);
7280 
7281       Value *Cond = vectorizeTree(E->getOperand(0));
7282       Value *True = vectorizeTree(E->getOperand(1));
7283       Value *False = vectorizeTree(E->getOperand(2));
7284 
7285       if (E->VectorizedValue) {
7286         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7287         return E->VectorizedValue;
7288       }
7289 
7290       Value *V = Builder.CreateSelect(Cond, True, False);
7291       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7292       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7293       V = ShuffleBuilder.finalize(V);
7294 
7295       E->VectorizedValue = V;
7296       ++NumVectorInstructions;
7297       return V;
7298     }
7299     case Instruction::FNeg: {
7300       setInsertPointAfterBundle(E);
7301 
7302       Value *Op = vectorizeTree(E->getOperand(0));
7303 
7304       if (E->VectorizedValue) {
7305         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7306         return E->VectorizedValue;
7307       }
7308 
7309       Value *V = Builder.CreateUnOp(
7310           static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
7311       propagateIRFlags(V, E->Scalars, VL0);
7312       if (auto *I = dyn_cast<Instruction>(V))
7313         V = propagateMetadata(I, E->Scalars);
7314 
7315       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7316       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7317       V = ShuffleBuilder.finalize(V);
7318 
7319       E->VectorizedValue = V;
7320       ++NumVectorInstructions;
7321 
7322       return V;
7323     }
7324     case Instruction::Add:
7325     case Instruction::FAdd:
7326     case Instruction::Sub:
7327     case Instruction::FSub:
7328     case Instruction::Mul:
7329     case Instruction::FMul:
7330     case Instruction::UDiv:
7331     case Instruction::SDiv:
7332     case Instruction::FDiv:
7333     case Instruction::URem:
7334     case Instruction::SRem:
7335     case Instruction::FRem:
7336     case Instruction::Shl:
7337     case Instruction::LShr:
7338     case Instruction::AShr:
7339     case Instruction::And:
7340     case Instruction::Or:
7341     case Instruction::Xor: {
7342       setInsertPointAfterBundle(E);
7343 
7344       Value *LHS = vectorizeTree(E->getOperand(0));
7345       Value *RHS = vectorizeTree(E->getOperand(1));
7346 
7347       if (E->VectorizedValue) {
7348         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7349         return E->VectorizedValue;
7350       }
7351 
7352       Value *V = Builder.CreateBinOp(
7353           static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
7354           RHS);
7355       propagateIRFlags(V, E->Scalars, VL0);
7356       if (auto *I = dyn_cast<Instruction>(V))
7357         V = propagateMetadata(I, E->Scalars);
7358 
7359       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7360       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7361       V = ShuffleBuilder.finalize(V);
7362 
7363       E->VectorizedValue = V;
7364       ++NumVectorInstructions;
7365 
7366       return V;
7367     }
7368     case Instruction::Load: {
7369       // Loads are inserted at the head of the tree because we don't want to
7370       // sink them all the way down past store instructions.
7371       setInsertPointAfterBundle(E);
7372 
7373       LoadInst *LI = cast<LoadInst>(VL0);
7374       Instruction *NewLI;
7375       unsigned AS = LI->getPointerAddressSpace();
7376       Value *PO = LI->getPointerOperand();
7377       if (E->State == TreeEntry::Vectorize) {
7378         Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS));
7379         NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
7380 
7381         // The pointer operand uses an in-tree scalar so we add the new BitCast
7382         // or LoadInst to ExternalUses list to make sure that an extract will
7383         // be generated in the future.
7384         if (TreeEntry *Entry = getTreeEntry(PO)) {
7385           // Find which lane we need to extract.
7386           unsigned FoundLane = Entry->findLaneForValue(PO);
7387           ExternalUses.emplace_back(
7388               PO, PO != VecPtr ? cast<User>(VecPtr) : NewLI, FoundLane);
7389         }
7390       } else {
7391         assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state");
7392         Value *VecPtr = vectorizeTree(E->getOperand(0));
7393         // Use the minimum alignment of the gathered loads.
7394         Align CommonAlignment = LI->getAlign();
7395         for (Value *V : E->Scalars)
7396           CommonAlignment =
7397               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
7398         NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment);
7399       }
7400       Value *V = propagateMetadata(NewLI, E->Scalars);
7401 
7402       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7403       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7404       V = ShuffleBuilder.finalize(V);
7405       E->VectorizedValue = V;
7406       ++NumVectorInstructions;
7407       return V;
7408     }
7409     case Instruction::Store: {
7410       auto *SI = cast<StoreInst>(VL0);
7411       unsigned AS = SI->getPointerAddressSpace();
7412 
7413       setInsertPointAfterBundle(E);
7414 
7415       Value *VecValue = vectorizeTree(E->getOperand(0));
7416       ShuffleBuilder.addMask(E->ReorderIndices);
7417       VecValue = ShuffleBuilder.finalize(VecValue);
7418 
7419       Value *ScalarPtr = SI->getPointerOperand();
7420       Value *VecPtr = Builder.CreateBitCast(
7421           ScalarPtr, VecValue->getType()->getPointerTo(AS));
7422       StoreInst *ST =
7423           Builder.CreateAlignedStore(VecValue, VecPtr, SI->getAlign());
7424 
7425       // The pointer operand uses an in-tree scalar, so add the new BitCast or
7426       // StoreInst to ExternalUses to make sure that an extract will be
7427       // generated in the future.
7428       if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) {
7429         // Find which lane we need to extract.
7430         unsigned FoundLane = Entry->findLaneForValue(ScalarPtr);
7431         ExternalUses.push_back(ExternalUser(
7432             ScalarPtr, ScalarPtr != VecPtr ? cast<User>(VecPtr) : ST,
7433             FoundLane));
7434       }
7435 
7436       Value *V = propagateMetadata(ST, E->Scalars);
7437 
7438       E->VectorizedValue = V;
7439       ++NumVectorInstructions;
7440       return V;
7441     }
7442     case Instruction::GetElementPtr: {
7443       auto *GEP0 = cast<GetElementPtrInst>(VL0);
7444       setInsertPointAfterBundle(E);
7445 
7446       Value *Op0 = vectorizeTree(E->getOperand(0));
7447 
7448       SmallVector<Value *> OpVecs;
7449       for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) {
7450         Value *OpVec = vectorizeTree(E->getOperand(J));
7451         OpVecs.push_back(OpVec);
7452       }
7453 
7454       Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs);
7455       if (Instruction *I = dyn_cast<Instruction>(V))
7456         V = propagateMetadata(I, E->Scalars);
7457 
7458       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7459       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7460       V = ShuffleBuilder.finalize(V);
7461 
7462       E->VectorizedValue = V;
7463       ++NumVectorInstructions;
7464 
7465       return V;
7466     }
7467     case Instruction::Call: {
7468       CallInst *CI = cast<CallInst>(VL0);
7469       setInsertPointAfterBundle(E);
7470 
7471       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
7472       if (Function *FI = CI->getCalledFunction())
7473         IID = FI->getIntrinsicID();
7474 
7475       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
7476 
7477       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
7478       bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
7479                           VecCallCosts.first <= VecCallCosts.second;
7480 
7481       Value *ScalarArg = nullptr;
7482       std::vector<Value *> OpVecs;
7483       SmallVector<Type *, 2> TysForDecl =
7484           {FixedVectorType::get(CI->getType(), E->Scalars.size())};
7485       for (int j = 0, e = CI->arg_size(); j < e; ++j) {
7486         ValueList OpVL;
7487         // Some intrinsics have scalar arguments. This argument should not be
7488         // vectorized.
7489         if (UseIntrinsic && isVectorIntrinsicWithScalarOpAtArg(IID, j)) {
7490           CallInst *CEI = cast<CallInst>(VL0);
7491           ScalarArg = CEI->getArgOperand(j);
7492           OpVecs.push_back(CEI->getArgOperand(j));
7493           if (isVectorIntrinsicWithOverloadTypeAtArg(IID, j))
7494             TysForDecl.push_back(ScalarArg->getType());
7495           continue;
7496         }
7497 
7498         Value *OpVec = vectorizeTree(E->getOperand(j));
7499         LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
7500         OpVecs.push_back(OpVec);
7501         if (isVectorIntrinsicWithOverloadTypeAtArg(IID, j))
7502           TysForDecl.push_back(OpVec->getType());
7503       }
7504 
7505       Function *CF;
7506       if (!UseIntrinsic) {
7507         VFShape Shape =
7508             VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
7509                                   VecTy->getNumElements())),
7510                          false /*HasGlobalPred*/);
7511         CF = VFDatabase(*CI).getVectorizedFunction(Shape);
7512       } else {
7513         CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl);
7514       }
7515 
7516       SmallVector<OperandBundleDef, 1> OpBundles;
7517       CI->getOperandBundlesAsDefs(OpBundles);
7518       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
7519 
7520       // The scalar argument uses an in-tree scalar so we add the new vectorized
7521       // call to ExternalUses list to make sure that an extract will be
7522       // generated in the future.
7523       if (ScalarArg) {
7524         if (TreeEntry *Entry = getTreeEntry(ScalarArg)) {
7525           // Find which lane we need to extract.
7526           unsigned FoundLane = Entry->findLaneForValue(ScalarArg);
7527           ExternalUses.push_back(
7528               ExternalUser(ScalarArg, cast<User>(V), FoundLane));
7529         }
7530       }
7531 
7532       propagateIRFlags(V, E->Scalars, VL0);
7533       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7534       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7535       V = ShuffleBuilder.finalize(V);
7536 
7537       E->VectorizedValue = V;
7538       ++NumVectorInstructions;
7539       return V;
7540     }
7541     case Instruction::ShuffleVector: {
7542       assert(E->isAltShuffle() &&
7543              ((Instruction::isBinaryOp(E->getOpcode()) &&
7544                Instruction::isBinaryOp(E->getAltOpcode())) ||
7545               (Instruction::isCast(E->getOpcode()) &&
7546                Instruction::isCast(E->getAltOpcode())) ||
7547               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
7548              "Invalid Shuffle Vector Operand");
7549 
7550       Value *LHS = nullptr, *RHS = nullptr;
7551       if (Instruction::isBinaryOp(E->getOpcode()) || isa<CmpInst>(VL0)) {
7552         setInsertPointAfterBundle(E);
7553         LHS = vectorizeTree(E->getOperand(0));
7554         RHS = vectorizeTree(E->getOperand(1));
7555       } else {
7556         setInsertPointAfterBundle(E);
7557         LHS = vectorizeTree(E->getOperand(0));
7558       }
7559 
7560       if (E->VectorizedValue) {
7561         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7562         return E->VectorizedValue;
7563       }
7564 
7565       Value *V0, *V1;
7566       if (Instruction::isBinaryOp(E->getOpcode())) {
7567         V0 = Builder.CreateBinOp(
7568             static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
7569         V1 = Builder.CreateBinOp(
7570             static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
7571       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
7572         V0 = Builder.CreateCmp(CI0->getPredicate(), LHS, RHS);
7573         auto *AltCI = cast<CmpInst>(E->getAltOp());
7574         CmpInst::Predicate AltPred = AltCI->getPredicate();
7575         V1 = Builder.CreateCmp(AltPred, LHS, RHS);
7576       } else {
7577         V0 = Builder.CreateCast(
7578             static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
7579         V1 = Builder.CreateCast(
7580             static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
7581       }
7582       // Add V0 and V1 to later analysis to try to find and remove matching
7583       // instruction, if any.
7584       for (Value *V : {V0, V1}) {
7585         if (auto *I = dyn_cast<Instruction>(V)) {
7586           GatherShuffleSeq.insert(I);
7587           CSEBlocks.insert(I->getParent());
7588         }
7589       }
7590 
7591       // Create shuffle to take alternate operations from the vector.
7592       // Also, gather up main and alt scalar ops to propagate IR flags to
7593       // each vector operation.
7594       ValueList OpScalars, AltScalars;
7595       SmallVector<int> Mask;
7596       buildShuffleEntryMask(
7597           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
7598           [E](Instruction *I) {
7599             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
7600             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
7601           },
7602           Mask, &OpScalars, &AltScalars);
7603 
7604       propagateIRFlags(V0, OpScalars);
7605       propagateIRFlags(V1, AltScalars);
7606 
7607       Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
7608       if (auto *I = dyn_cast<Instruction>(V)) {
7609         V = propagateMetadata(I, E->Scalars);
7610         GatherShuffleSeq.insert(I);
7611         CSEBlocks.insert(I->getParent());
7612       }
7613       V = ShuffleBuilder.finalize(V);
7614 
7615       E->VectorizedValue = V;
7616       ++NumVectorInstructions;
7617 
7618       return V;
7619     }
7620     default:
7621     llvm_unreachable("unknown inst");
7622   }
7623   return nullptr;
7624 }
7625 
7626 Value *BoUpSLP::vectorizeTree() {
7627   ExtraValueToDebugLocsMap ExternallyUsedValues;
7628   return vectorizeTree(ExternallyUsedValues);
7629 }
7630 
7631 Value *
7632 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
7633   // All blocks must be scheduled before any instructions are inserted.
7634   for (auto &BSIter : BlocksSchedules) {
7635     scheduleBlock(BSIter.second.get());
7636   }
7637 
7638   Builder.SetInsertPoint(&F->getEntryBlock().front());
7639   auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
7640 
7641   // If the vectorized tree can be rewritten in a smaller type, we truncate the
7642   // vectorized root. InstCombine will then rewrite the entire expression. We
7643   // sign extend the extracted values below.
7644   auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
7645   if (MinBWs.count(ScalarRoot)) {
7646     if (auto *I = dyn_cast<Instruction>(VectorRoot)) {
7647       // If current instr is a phi and not the last phi, insert it after the
7648       // last phi node.
7649       if (isa<PHINode>(I))
7650         Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt());
7651       else
7652         Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
7653     }
7654     auto BundleWidth = VectorizableTree[0]->Scalars.size();
7655     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
7656     auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
7657     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
7658     VectorizableTree[0]->VectorizedValue = Trunc;
7659   }
7660 
7661   LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
7662                     << " values .\n");
7663 
7664   // Extract all of the elements with the external uses.
7665   for (const auto &ExternalUse : ExternalUses) {
7666     Value *Scalar = ExternalUse.Scalar;
7667     llvm::User *User = ExternalUse.User;
7668 
7669     // Skip users that we already RAUW. This happens when one instruction
7670     // has multiple uses of the same value.
7671     if (User && !is_contained(Scalar->users(), User))
7672       continue;
7673     TreeEntry *E = getTreeEntry(Scalar);
7674     assert(E && "Invalid scalar");
7675     assert(E->State != TreeEntry::NeedToGather &&
7676            "Extracting from a gather list");
7677 
7678     Value *Vec = E->VectorizedValue;
7679     assert(Vec && "Can't find vectorizable value");
7680 
7681     Value *Lane = Builder.getInt32(ExternalUse.Lane);
7682     auto ExtractAndExtendIfNeeded = [&](Value *Vec) {
7683       if (Scalar->getType() != Vec->getType()) {
7684         Value *Ex;
7685         // "Reuse" the existing extract to improve final codegen.
7686         if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) {
7687           Ex = Builder.CreateExtractElement(ES->getOperand(0),
7688                                             ES->getOperand(1));
7689         } else {
7690           Ex = Builder.CreateExtractElement(Vec, Lane);
7691         }
7692         // If necessary, sign-extend or zero-extend ScalarRoot
7693         // to the larger type.
7694         if (!MinBWs.count(ScalarRoot))
7695           return Ex;
7696         if (MinBWs[ScalarRoot].second)
7697           return Builder.CreateSExt(Ex, Scalar->getType());
7698         return Builder.CreateZExt(Ex, Scalar->getType());
7699       }
7700       assert(isa<FixedVectorType>(Scalar->getType()) &&
7701              isa<InsertElementInst>(Scalar) &&
7702              "In-tree scalar of vector type is not insertelement?");
7703       return Vec;
7704     };
7705     // If User == nullptr, the Scalar is used as extra arg. Generate
7706     // ExtractElement instruction and update the record for this scalar in
7707     // ExternallyUsedValues.
7708     if (!User) {
7709       assert(ExternallyUsedValues.count(Scalar) &&
7710              "Scalar with nullptr as an external user must be registered in "
7711              "ExternallyUsedValues map");
7712       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7713         Builder.SetInsertPoint(VecI->getParent(),
7714                                std::next(VecI->getIterator()));
7715       } else {
7716         Builder.SetInsertPoint(&F->getEntryBlock().front());
7717       }
7718       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7719       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
7720       auto &NewInstLocs = ExternallyUsedValues[NewInst];
7721       auto It = ExternallyUsedValues.find(Scalar);
7722       assert(It != ExternallyUsedValues.end() &&
7723              "Externally used scalar is not found in ExternallyUsedValues");
7724       NewInstLocs.append(It->second);
7725       ExternallyUsedValues.erase(Scalar);
7726       // Required to update internally referenced instructions.
7727       Scalar->replaceAllUsesWith(NewInst);
7728       continue;
7729     }
7730 
7731     // Generate extracts for out-of-tree users.
7732     // Find the insertion point for the extractelement lane.
7733     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7734       if (PHINode *PH = dyn_cast<PHINode>(User)) {
7735         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
7736           if (PH->getIncomingValue(i) == Scalar) {
7737             Instruction *IncomingTerminator =
7738                 PH->getIncomingBlock(i)->getTerminator();
7739             if (isa<CatchSwitchInst>(IncomingTerminator)) {
7740               Builder.SetInsertPoint(VecI->getParent(),
7741                                      std::next(VecI->getIterator()));
7742             } else {
7743               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
7744             }
7745             Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7746             CSEBlocks.insert(PH->getIncomingBlock(i));
7747             PH->setOperand(i, NewInst);
7748           }
7749         }
7750       } else {
7751         Builder.SetInsertPoint(cast<Instruction>(User));
7752         Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7753         CSEBlocks.insert(cast<Instruction>(User)->getParent());
7754         User->replaceUsesOfWith(Scalar, NewInst);
7755       }
7756     } else {
7757       Builder.SetInsertPoint(&F->getEntryBlock().front());
7758       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7759       CSEBlocks.insert(&F->getEntryBlock());
7760       User->replaceUsesOfWith(Scalar, NewInst);
7761     }
7762 
7763     LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
7764   }
7765 
7766   // For each vectorized value:
7767   for (auto &TEPtr : VectorizableTree) {
7768     TreeEntry *Entry = TEPtr.get();
7769 
7770     // No need to handle users of gathered values.
7771     if (Entry->State == TreeEntry::NeedToGather)
7772       continue;
7773 
7774     assert(Entry->VectorizedValue && "Can't find vectorizable value");
7775 
7776     // For each lane:
7777     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
7778       Value *Scalar = Entry->Scalars[Lane];
7779 
7780 #ifndef NDEBUG
7781       Type *Ty = Scalar->getType();
7782       if (!Ty->isVoidTy()) {
7783         for (User *U : Scalar->users()) {
7784           LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
7785 
7786           // It is legal to delete users in the ignorelist.
7787           assert((getTreeEntry(U) || is_contained(UserIgnoreList, U) ||
7788                   (isa_and_nonnull<Instruction>(U) &&
7789                    isDeleted(cast<Instruction>(U)))) &&
7790                  "Deleting out-of-tree value");
7791         }
7792       }
7793 #endif
7794       LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
7795       eraseInstruction(cast<Instruction>(Scalar));
7796     }
7797   }
7798 
7799   Builder.ClearInsertionPoint();
7800   InstrElementSize.clear();
7801 
7802   return VectorizableTree[0]->VectorizedValue;
7803 }
7804 
7805 void BoUpSLP::optimizeGatherSequence() {
7806   LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleSeq.size()
7807                     << " gather sequences instructions.\n");
7808   // LICM InsertElementInst sequences.
7809   for (Instruction *I : GatherShuffleSeq) {
7810     if (isDeleted(I))
7811       continue;
7812 
7813     // Check if this block is inside a loop.
7814     Loop *L = LI->getLoopFor(I->getParent());
7815     if (!L)
7816       continue;
7817 
7818     // Check if it has a preheader.
7819     BasicBlock *PreHeader = L->getLoopPreheader();
7820     if (!PreHeader)
7821       continue;
7822 
7823     // If the vector or the element that we insert into it are
7824     // instructions that are defined in this basic block then we can't
7825     // hoist this instruction.
7826     if (any_of(I->operands(), [L](Value *V) {
7827           auto *OpI = dyn_cast<Instruction>(V);
7828           return OpI && L->contains(OpI);
7829         }))
7830       continue;
7831 
7832     // We can hoist this instruction. Move it to the pre-header.
7833     I->moveBefore(PreHeader->getTerminator());
7834   }
7835 
7836   // Make a list of all reachable blocks in our CSE queue.
7837   SmallVector<const DomTreeNode *, 8> CSEWorkList;
7838   CSEWorkList.reserve(CSEBlocks.size());
7839   for (BasicBlock *BB : CSEBlocks)
7840     if (DomTreeNode *N = DT->getNode(BB)) {
7841       assert(DT->isReachableFromEntry(N));
7842       CSEWorkList.push_back(N);
7843     }
7844 
7845   // Sort blocks by domination. This ensures we visit a block after all blocks
7846   // dominating it are visited.
7847   llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) {
7848     assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) &&
7849            "Different nodes should have different DFS numbers");
7850     return A->getDFSNumIn() < B->getDFSNumIn();
7851   });
7852 
7853   // Less defined shuffles can be replaced by the more defined copies.
7854   // Between two shuffles one is less defined if it has the same vector operands
7855   // and its mask indeces are the same as in the first one or undefs. E.g.
7856   // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0,
7857   // poison, <0, 0, 0, 0>.
7858   auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2,
7859                                            SmallVectorImpl<int> &NewMask) {
7860     if (I1->getType() != I2->getType())
7861       return false;
7862     auto *SI1 = dyn_cast<ShuffleVectorInst>(I1);
7863     auto *SI2 = dyn_cast<ShuffleVectorInst>(I2);
7864     if (!SI1 || !SI2)
7865       return I1->isIdenticalTo(I2);
7866     if (SI1->isIdenticalTo(SI2))
7867       return true;
7868     for (int I = 0, E = SI1->getNumOperands(); I < E; ++I)
7869       if (SI1->getOperand(I) != SI2->getOperand(I))
7870         return false;
7871     // Check if the second instruction is more defined than the first one.
7872     NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end());
7873     ArrayRef<int> SM1 = SI1->getShuffleMask();
7874     // Count trailing undefs in the mask to check the final number of used
7875     // registers.
7876     unsigned LastUndefsCnt = 0;
7877     for (int I = 0, E = NewMask.size(); I < E; ++I) {
7878       if (SM1[I] == UndefMaskElem)
7879         ++LastUndefsCnt;
7880       else
7881         LastUndefsCnt = 0;
7882       if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem &&
7883           NewMask[I] != SM1[I])
7884         return false;
7885       if (NewMask[I] == UndefMaskElem)
7886         NewMask[I] = SM1[I];
7887     }
7888     // Check if the last undefs actually change the final number of used vector
7889     // registers.
7890     return SM1.size() - LastUndefsCnt > 1 &&
7891            TTI->getNumberOfParts(SI1->getType()) ==
7892                TTI->getNumberOfParts(
7893                    FixedVectorType::get(SI1->getType()->getElementType(),
7894                                         SM1.size() - LastUndefsCnt));
7895   };
7896   // Perform O(N^2) search over the gather/shuffle sequences and merge identical
7897   // instructions. TODO: We can further optimize this scan if we split the
7898   // instructions into different buckets based on the insert lane.
7899   SmallVector<Instruction *, 16> Visited;
7900   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
7901     assert(*I &&
7902            (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
7903            "Worklist not sorted properly!");
7904     BasicBlock *BB = (*I)->getBlock();
7905     // For all instructions in blocks containing gather sequences:
7906     for (Instruction &In : llvm::make_early_inc_range(*BB)) {
7907       if (isDeleted(&In))
7908         continue;
7909       if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) &&
7910           !isa<ShuffleVectorInst>(&In) && !GatherShuffleSeq.contains(&In))
7911         continue;
7912 
7913       // Check if we can replace this instruction with any of the
7914       // visited instructions.
7915       bool Replaced = false;
7916       for (Instruction *&V : Visited) {
7917         SmallVector<int> NewMask;
7918         if (IsIdenticalOrLessDefined(&In, V, NewMask) &&
7919             DT->dominates(V->getParent(), In.getParent())) {
7920           In.replaceAllUsesWith(V);
7921           eraseInstruction(&In);
7922           if (auto *SI = dyn_cast<ShuffleVectorInst>(V))
7923             if (!NewMask.empty())
7924               SI->setShuffleMask(NewMask);
7925           Replaced = true;
7926           break;
7927         }
7928         if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) &&
7929             GatherShuffleSeq.contains(V) &&
7930             IsIdenticalOrLessDefined(V, &In, NewMask) &&
7931             DT->dominates(In.getParent(), V->getParent())) {
7932           In.moveAfter(V);
7933           V->replaceAllUsesWith(&In);
7934           eraseInstruction(V);
7935           if (auto *SI = dyn_cast<ShuffleVectorInst>(&In))
7936             if (!NewMask.empty())
7937               SI->setShuffleMask(NewMask);
7938           V = &In;
7939           Replaced = true;
7940           break;
7941         }
7942       }
7943       if (!Replaced) {
7944         assert(!is_contained(Visited, &In));
7945         Visited.push_back(&In);
7946       }
7947     }
7948   }
7949   CSEBlocks.clear();
7950   GatherShuffleSeq.clear();
7951 }
7952 
7953 BoUpSLP::ScheduleData *
7954 BoUpSLP::BlockScheduling::buildBundle(ArrayRef<Value *> VL) {
7955   ScheduleData *Bundle = nullptr;
7956   ScheduleData *PrevInBundle = nullptr;
7957   for (Value *V : VL) {
7958     if (doesNotNeedToBeScheduled(V))
7959       continue;
7960     ScheduleData *BundleMember = getScheduleData(V);
7961     assert(BundleMember &&
7962            "no ScheduleData for bundle member "
7963            "(maybe not in same basic block)");
7964     assert(BundleMember->isSchedulingEntity() &&
7965            "bundle member already part of other bundle");
7966     if (PrevInBundle) {
7967       PrevInBundle->NextInBundle = BundleMember;
7968     } else {
7969       Bundle = BundleMember;
7970     }
7971 
7972     // Group the instructions to a bundle.
7973     BundleMember->FirstInBundle = Bundle;
7974     PrevInBundle = BundleMember;
7975   }
7976   assert(Bundle && "Failed to find schedule bundle");
7977   return Bundle;
7978 }
7979 
7980 // Groups the instructions to a bundle (which is then a single scheduling entity)
7981 // and schedules instructions until the bundle gets ready.
7982 Optional<BoUpSLP::ScheduleData *>
7983 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
7984                                             const InstructionsState &S) {
7985   // No need to schedule PHIs, insertelement, extractelement and extractvalue
7986   // instructions.
7987   if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue) ||
7988       doesNotNeedToSchedule(VL))
7989     return nullptr;
7990 
7991   // Initialize the instruction bundle.
7992   Instruction *OldScheduleEnd = ScheduleEnd;
7993   LLVM_DEBUG(dbgs() << "SLP:  bundle: " << *S.OpValue << "\n");
7994 
7995   auto TryScheduleBundleImpl = [this, OldScheduleEnd, SLP](bool ReSchedule,
7996                                                          ScheduleData *Bundle) {
7997     // The scheduling region got new instructions at the lower end (or it is a
7998     // new region for the first bundle). This makes it necessary to
7999     // recalculate all dependencies.
8000     // It is seldom that this needs to be done a second time after adding the
8001     // initial bundle to the region.
8002     if (ScheduleEnd != OldScheduleEnd) {
8003       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode())
8004         doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); });
8005       ReSchedule = true;
8006     }
8007     if (Bundle) {
8008       LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle
8009                         << " in block " << BB->getName() << "\n");
8010       calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP);
8011     }
8012 
8013     if (ReSchedule) {
8014       resetSchedule();
8015       initialFillReadyList(ReadyInsts);
8016     }
8017 
8018     // Now try to schedule the new bundle or (if no bundle) just calculate
8019     // dependencies. As soon as the bundle is "ready" it means that there are no
8020     // cyclic dependencies and we can schedule it. Note that's important that we
8021     // don't "schedule" the bundle yet (see cancelScheduling).
8022     while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) &&
8023            !ReadyInsts.empty()) {
8024       ScheduleData *Picked = ReadyInsts.pop_back_val();
8025       assert(Picked->isSchedulingEntity() && Picked->isReady() &&
8026              "must be ready to schedule");
8027       schedule(Picked, ReadyInsts);
8028     }
8029   };
8030 
8031   // Make sure that the scheduling region contains all
8032   // instructions of the bundle.
8033   for (Value *V : VL) {
8034     if (doesNotNeedToBeScheduled(V))
8035       continue;
8036     if (!extendSchedulingRegion(V, S)) {
8037       // If the scheduling region got new instructions at the lower end (or it
8038       // is a new region for the first bundle). This makes it necessary to
8039       // recalculate all dependencies.
8040       // Otherwise the compiler may crash trying to incorrectly calculate
8041       // dependencies and emit instruction in the wrong order at the actual
8042       // scheduling.
8043       TryScheduleBundleImpl(/*ReSchedule=*/false, nullptr);
8044       return None;
8045     }
8046   }
8047 
8048   bool ReSchedule = false;
8049   for (Value *V : VL) {
8050     if (doesNotNeedToBeScheduled(V))
8051       continue;
8052     ScheduleData *BundleMember = getScheduleData(V);
8053     assert(BundleMember &&
8054            "no ScheduleData for bundle member (maybe not in same basic block)");
8055 
8056     // Make sure we don't leave the pieces of the bundle in the ready list when
8057     // whole bundle might not be ready.
8058     ReadyInsts.remove(BundleMember);
8059 
8060     if (!BundleMember->IsScheduled)
8061       continue;
8062     // A bundle member was scheduled as single instruction before and now
8063     // needs to be scheduled as part of the bundle. We just get rid of the
8064     // existing schedule.
8065     LLVM_DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
8066                       << " was already scheduled\n");
8067     ReSchedule = true;
8068   }
8069 
8070   auto *Bundle = buildBundle(VL);
8071   TryScheduleBundleImpl(ReSchedule, Bundle);
8072   if (!Bundle->isReady()) {
8073     cancelScheduling(VL, S.OpValue);
8074     return None;
8075   }
8076   return Bundle;
8077 }
8078 
8079 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
8080                                                 Value *OpValue) {
8081   if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue) ||
8082       doesNotNeedToSchedule(VL))
8083     return;
8084 
8085   if (doesNotNeedToBeScheduled(OpValue))
8086     OpValue = *find_if_not(VL, doesNotNeedToBeScheduled);
8087   ScheduleData *Bundle = getScheduleData(OpValue);
8088   LLVM_DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
8089   assert(!Bundle->IsScheduled &&
8090          "Can't cancel bundle which is already scheduled");
8091   assert(Bundle->isSchedulingEntity() &&
8092          (Bundle->isPartOfBundle() || needToScheduleSingleInstruction(VL)) &&
8093          "tried to unbundle something which is not a bundle");
8094 
8095   // Remove the bundle from the ready list.
8096   if (Bundle->isReady())
8097     ReadyInsts.remove(Bundle);
8098 
8099   // Un-bundle: make single instructions out of the bundle.
8100   ScheduleData *BundleMember = Bundle;
8101   while (BundleMember) {
8102     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
8103     BundleMember->FirstInBundle = BundleMember;
8104     ScheduleData *Next = BundleMember->NextInBundle;
8105     BundleMember->NextInBundle = nullptr;
8106     BundleMember->TE = nullptr;
8107     if (BundleMember->unscheduledDepsInBundle() == 0) {
8108       ReadyInsts.insert(BundleMember);
8109     }
8110     BundleMember = Next;
8111   }
8112 }
8113 
8114 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
8115   // Allocate a new ScheduleData for the instruction.
8116   if (ChunkPos >= ChunkSize) {
8117     ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
8118     ChunkPos = 0;
8119   }
8120   return &(ScheduleDataChunks.back()[ChunkPos++]);
8121 }
8122 
8123 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
8124                                                       const InstructionsState &S) {
8125   if (getScheduleData(V, isOneOf(S, V)))
8126     return true;
8127   Instruction *I = dyn_cast<Instruction>(V);
8128   assert(I && "bundle member must be an instruction");
8129   assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) &&
8130          !doesNotNeedToBeScheduled(I) &&
8131          "phi nodes/insertelements/extractelements/extractvalues don't need to "
8132          "be scheduled");
8133   auto &&CheckScheduleForI = [this, &S](Instruction *I) -> bool {
8134     ScheduleData *ISD = getScheduleData(I);
8135     if (!ISD)
8136       return false;
8137     assert(isInSchedulingRegion(ISD) &&
8138            "ScheduleData not in scheduling region");
8139     ScheduleData *SD = allocateScheduleDataChunks();
8140     SD->Inst = I;
8141     SD->init(SchedulingRegionID, S.OpValue);
8142     ExtraScheduleDataMap[I][S.OpValue] = SD;
8143     return true;
8144   };
8145   if (CheckScheduleForI(I))
8146     return true;
8147   if (!ScheduleStart) {
8148     // It's the first instruction in the new region.
8149     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
8150     ScheduleStart = I;
8151     ScheduleEnd = I->getNextNode();
8152     if (isOneOf(S, I) != I)
8153       CheckScheduleForI(I);
8154     assert(ScheduleEnd && "tried to vectorize a terminator?");
8155     LLVM_DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
8156     return true;
8157   }
8158   // Search up and down at the same time, because we don't know if the new
8159   // instruction is above or below the existing scheduling region.
8160   BasicBlock::reverse_iterator UpIter =
8161       ++ScheduleStart->getIterator().getReverse();
8162   BasicBlock::reverse_iterator UpperEnd = BB->rend();
8163   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
8164   BasicBlock::iterator LowerEnd = BB->end();
8165   while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I &&
8166          &*DownIter != I) {
8167     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
8168       LLVM_DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
8169       return false;
8170     }
8171 
8172     ++UpIter;
8173     ++DownIter;
8174   }
8175   if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) {
8176     assert(I->getParent() == ScheduleStart->getParent() &&
8177            "Instruction is in wrong basic block.");
8178     initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
8179     ScheduleStart = I;
8180     if (isOneOf(S, I) != I)
8181       CheckScheduleForI(I);
8182     LLVM_DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I
8183                       << "\n");
8184     return true;
8185   }
8186   assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) &&
8187          "Expected to reach top of the basic block or instruction down the "
8188          "lower end.");
8189   assert(I->getParent() == ScheduleEnd->getParent() &&
8190          "Instruction is in wrong basic block.");
8191   initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
8192                    nullptr);
8193   ScheduleEnd = I->getNextNode();
8194   if (isOneOf(S, I) != I)
8195     CheckScheduleForI(I);
8196   assert(ScheduleEnd && "tried to vectorize a terminator?");
8197   LLVM_DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
8198   return true;
8199 }
8200 
8201 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
8202                                                 Instruction *ToI,
8203                                                 ScheduleData *PrevLoadStore,
8204                                                 ScheduleData *NextLoadStore) {
8205   ScheduleData *CurrentLoadStore = PrevLoadStore;
8206   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
8207     // No need to allocate data for non-schedulable instructions.
8208     if (doesNotNeedToBeScheduled(I))
8209       continue;
8210     ScheduleData *SD = ScheduleDataMap.lookup(I);
8211     if (!SD) {
8212       SD = allocateScheduleDataChunks();
8213       ScheduleDataMap[I] = SD;
8214       SD->Inst = I;
8215     }
8216     assert(!isInSchedulingRegion(SD) &&
8217            "new ScheduleData already in scheduling region");
8218     SD->init(SchedulingRegionID, I);
8219 
8220     if (I->mayReadOrWriteMemory() &&
8221         (!isa<IntrinsicInst>(I) ||
8222          (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect &&
8223           cast<IntrinsicInst>(I)->getIntrinsicID() !=
8224               Intrinsic::pseudoprobe))) {
8225       // Update the linked list of memory accessing instructions.
8226       if (CurrentLoadStore) {
8227         CurrentLoadStore->NextLoadStore = SD;
8228       } else {
8229         FirstLoadStoreInRegion = SD;
8230       }
8231       CurrentLoadStore = SD;
8232     }
8233 
8234     if (match(I, m_Intrinsic<Intrinsic::stacksave>()) ||
8235         match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8236       RegionHasStackSave = true;
8237   }
8238   if (NextLoadStore) {
8239     if (CurrentLoadStore)
8240       CurrentLoadStore->NextLoadStore = NextLoadStore;
8241   } else {
8242     LastLoadStoreInRegion = CurrentLoadStore;
8243   }
8244 }
8245 
8246 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
8247                                                      bool InsertInReadyList,
8248                                                      BoUpSLP *SLP) {
8249   assert(SD->isSchedulingEntity());
8250 
8251   SmallVector<ScheduleData *, 10> WorkList;
8252   WorkList.push_back(SD);
8253 
8254   while (!WorkList.empty()) {
8255     ScheduleData *SD = WorkList.pop_back_val();
8256     for (ScheduleData *BundleMember = SD; BundleMember;
8257          BundleMember = BundleMember->NextInBundle) {
8258       assert(isInSchedulingRegion(BundleMember));
8259       if (BundleMember->hasValidDependencies())
8260         continue;
8261 
8262       LLVM_DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember
8263                  << "\n");
8264       BundleMember->Dependencies = 0;
8265       BundleMember->resetUnscheduledDeps();
8266 
8267       // Handle def-use chain dependencies.
8268       if (BundleMember->OpValue != BundleMember->Inst) {
8269         if (ScheduleData *UseSD = getScheduleData(BundleMember->Inst)) {
8270           BundleMember->Dependencies++;
8271           ScheduleData *DestBundle = UseSD->FirstInBundle;
8272           if (!DestBundle->IsScheduled)
8273             BundleMember->incrementUnscheduledDeps(1);
8274           if (!DestBundle->hasValidDependencies())
8275             WorkList.push_back(DestBundle);
8276         }
8277       } else {
8278         for (User *U : BundleMember->Inst->users()) {
8279           if (ScheduleData *UseSD = getScheduleData(cast<Instruction>(U))) {
8280             BundleMember->Dependencies++;
8281             ScheduleData *DestBundle = UseSD->FirstInBundle;
8282             if (!DestBundle->IsScheduled)
8283               BundleMember->incrementUnscheduledDeps(1);
8284             if (!DestBundle->hasValidDependencies())
8285               WorkList.push_back(DestBundle);
8286           }
8287         }
8288       }
8289 
8290       auto makeControlDependent = [&](Instruction *I) {
8291         auto *DepDest = getScheduleData(I);
8292         assert(DepDest && "must be in schedule window");
8293         DepDest->ControlDependencies.push_back(BundleMember);
8294         BundleMember->Dependencies++;
8295         ScheduleData *DestBundle = DepDest->FirstInBundle;
8296         if (!DestBundle->IsScheduled)
8297           BundleMember->incrementUnscheduledDeps(1);
8298         if (!DestBundle->hasValidDependencies())
8299           WorkList.push_back(DestBundle);
8300       };
8301 
8302       // Any instruction which isn't safe to speculate at the begining of the
8303       // block is control dependend on any early exit or non-willreturn call
8304       // which proceeds it.
8305       if (!isGuaranteedToTransferExecutionToSuccessor(BundleMember->Inst)) {
8306         for (Instruction *I = BundleMember->Inst->getNextNode();
8307              I != ScheduleEnd; I = I->getNextNode()) {
8308           if (isSafeToSpeculativelyExecute(I, &*BB->begin()))
8309             continue;
8310 
8311           // Add the dependency
8312           makeControlDependent(I);
8313 
8314           if (!isGuaranteedToTransferExecutionToSuccessor(I))
8315             // Everything past here must be control dependent on I.
8316             break;
8317         }
8318       }
8319 
8320       if (RegionHasStackSave) {
8321         // If we have an inalloc alloca instruction, it needs to be scheduled
8322         // after any preceeding stacksave.  We also need to prevent any alloca
8323         // from reordering above a preceeding stackrestore.
8324         if (match(BundleMember->Inst, m_Intrinsic<Intrinsic::stacksave>()) ||
8325             match(BundleMember->Inst, m_Intrinsic<Intrinsic::stackrestore>())) {
8326           for (Instruction *I = BundleMember->Inst->getNextNode();
8327                I != ScheduleEnd; I = I->getNextNode()) {
8328             if (match(I, m_Intrinsic<Intrinsic::stacksave>()) ||
8329                 match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8330               // Any allocas past here must be control dependent on I, and I
8331               // must be memory dependend on BundleMember->Inst.
8332               break;
8333 
8334             if (!isa<AllocaInst>(I))
8335               continue;
8336 
8337             // Add the dependency
8338             makeControlDependent(I);
8339           }
8340         }
8341 
8342         // In addition to the cases handle just above, we need to prevent
8343         // allocas from moving below a stacksave.  The stackrestore case
8344         // is currently thought to be conservatism.
8345         if (isa<AllocaInst>(BundleMember->Inst)) {
8346           for (Instruction *I = BundleMember->Inst->getNextNode();
8347                I != ScheduleEnd; I = I->getNextNode()) {
8348             if (!match(I, m_Intrinsic<Intrinsic::stacksave>()) &&
8349                 !match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8350               continue;
8351 
8352             // Add the dependency
8353             makeControlDependent(I);
8354             break;
8355           }
8356         }
8357       }
8358 
8359       // Handle the memory dependencies (if any).
8360       ScheduleData *DepDest = BundleMember->NextLoadStore;
8361       if (!DepDest)
8362         continue;
8363       Instruction *SrcInst = BundleMember->Inst;
8364       assert(SrcInst->mayReadOrWriteMemory() &&
8365              "NextLoadStore list for non memory effecting bundle?");
8366       MemoryLocation SrcLoc = getLocation(SrcInst);
8367       bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
8368       unsigned numAliased = 0;
8369       unsigned DistToSrc = 1;
8370 
8371       for ( ; DepDest; DepDest = DepDest->NextLoadStore) {
8372         assert(isInSchedulingRegion(DepDest));
8373 
8374         // We have two limits to reduce the complexity:
8375         // 1) AliasedCheckLimit: It's a small limit to reduce calls to
8376         //    SLP->isAliased (which is the expensive part in this loop).
8377         // 2) MaxMemDepDistance: It's for very large blocks and it aborts
8378         //    the whole loop (even if the loop is fast, it's quadratic).
8379         //    It's important for the loop break condition (see below) to
8380         //    check this limit even between two read-only instructions.
8381         if (DistToSrc >= MaxMemDepDistance ||
8382             ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
8383              (numAliased >= AliasedCheckLimit ||
8384               SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
8385 
8386           // We increment the counter only if the locations are aliased
8387           // (instead of counting all alias checks). This gives a better
8388           // balance between reduced runtime and accurate dependencies.
8389           numAliased++;
8390 
8391           DepDest->MemoryDependencies.push_back(BundleMember);
8392           BundleMember->Dependencies++;
8393           ScheduleData *DestBundle = DepDest->FirstInBundle;
8394           if (!DestBundle->IsScheduled) {
8395             BundleMember->incrementUnscheduledDeps(1);
8396           }
8397           if (!DestBundle->hasValidDependencies()) {
8398             WorkList.push_back(DestBundle);
8399           }
8400         }
8401 
8402         // Example, explaining the loop break condition: Let's assume our
8403         // starting instruction is i0 and MaxMemDepDistance = 3.
8404         //
8405         //                      +--------v--v--v
8406         //             i0,i1,i2,i3,i4,i5,i6,i7,i8
8407         //             +--------^--^--^
8408         //
8409         // MaxMemDepDistance let us stop alias-checking at i3 and we add
8410         // dependencies from i0 to i3,i4,.. (even if they are not aliased).
8411         // Previously we already added dependencies from i3 to i6,i7,i8
8412         // (because of MaxMemDepDistance). As we added a dependency from
8413         // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
8414         // and we can abort this loop at i6.
8415         if (DistToSrc >= 2 * MaxMemDepDistance)
8416           break;
8417         DistToSrc++;
8418       }
8419     }
8420     if (InsertInReadyList && SD->isReady()) {
8421       ReadyInsts.insert(SD);
8422       LLVM_DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst
8423                         << "\n");
8424     }
8425   }
8426 }
8427 
8428 void BoUpSLP::BlockScheduling::resetSchedule() {
8429   assert(ScheduleStart &&
8430          "tried to reset schedule on block which has not been scheduled");
8431   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
8432     doForAllOpcodes(I, [&](ScheduleData *SD) {
8433       assert(isInSchedulingRegion(SD) &&
8434              "ScheduleData not in scheduling region");
8435       SD->IsScheduled = false;
8436       SD->resetUnscheduledDeps();
8437     });
8438   }
8439   ReadyInsts.clear();
8440 }
8441 
8442 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
8443   if (!BS->ScheduleStart)
8444     return;
8445 
8446   LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
8447 
8448   // A key point - if we got here, pre-scheduling was able to find a valid
8449   // scheduling of the sub-graph of the scheduling window which consists
8450   // of all vector bundles and their transitive users.  As such, we do not
8451   // need to reschedule anything *outside of* that subgraph.
8452 
8453   BS->resetSchedule();
8454 
8455   // For the real scheduling we use a more sophisticated ready-list: it is
8456   // sorted by the original instruction location. This lets the final schedule
8457   // be as  close as possible to the original instruction order.
8458   // WARNING: If changing this order causes a correctness issue, that means
8459   // there is some missing dependence edge in the schedule data graph.
8460   struct ScheduleDataCompare {
8461     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
8462       return SD2->SchedulingPriority < SD1->SchedulingPriority;
8463     }
8464   };
8465   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
8466 
8467   // Ensure that all dependency data is updated (for nodes in the sub-graph)
8468   // and fill the ready-list with initial instructions.
8469   int Idx = 0;
8470   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
8471        I = I->getNextNode()) {
8472     BS->doForAllOpcodes(I, [this, &Idx, BS](ScheduleData *SD) {
8473       TreeEntry *SDTE = getTreeEntry(SD->Inst);
8474       (void)SDTE;
8475       assert((isVectorLikeInstWithConstOps(SD->Inst) ||
8476               SD->isPartOfBundle() ==
8477                   (SDTE && !doesNotNeedToSchedule(SDTE->Scalars))) &&
8478              "scheduler and vectorizer bundle mismatch");
8479       SD->FirstInBundle->SchedulingPriority = Idx++;
8480 
8481       if (SD->isSchedulingEntity() && SD->isPartOfBundle())
8482         BS->calculateDependencies(SD, false, this);
8483     });
8484   }
8485   BS->initialFillReadyList(ReadyInsts);
8486 
8487   Instruction *LastScheduledInst = BS->ScheduleEnd;
8488 
8489   // Do the "real" scheduling.
8490   while (!ReadyInsts.empty()) {
8491     ScheduleData *picked = *ReadyInsts.begin();
8492     ReadyInsts.erase(ReadyInsts.begin());
8493 
8494     // Move the scheduled instruction(s) to their dedicated places, if not
8495     // there yet.
8496     for (ScheduleData *BundleMember = picked; BundleMember;
8497          BundleMember = BundleMember->NextInBundle) {
8498       Instruction *pickedInst = BundleMember->Inst;
8499       if (pickedInst->getNextNode() != LastScheduledInst)
8500         pickedInst->moveBefore(LastScheduledInst);
8501       LastScheduledInst = pickedInst;
8502     }
8503 
8504     BS->schedule(picked, ReadyInsts);
8505   }
8506 
8507   // Check that we didn't break any of our invariants.
8508 #ifdef EXPENSIVE_CHECKS
8509   BS->verify();
8510 #endif
8511 
8512 #if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS)
8513   // Check that all schedulable entities got scheduled
8514   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; I = I->getNextNode()) {
8515     BS->doForAllOpcodes(I, [&](ScheduleData *SD) {
8516       if (SD->isSchedulingEntity() && SD->hasValidDependencies()) {
8517         assert(SD->IsScheduled && "must be scheduled at this point");
8518       }
8519     });
8520   }
8521 #endif
8522 
8523   // Avoid duplicate scheduling of the block.
8524   BS->ScheduleStart = nullptr;
8525 }
8526 
8527 unsigned BoUpSLP::getVectorElementSize(Value *V) {
8528   // If V is a store, just return the width of the stored value (or value
8529   // truncated just before storing) without traversing the expression tree.
8530   // This is the common case.
8531   if (auto *Store = dyn_cast<StoreInst>(V)) {
8532     if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand()))
8533       return DL->getTypeSizeInBits(Trunc->getSrcTy());
8534     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
8535   }
8536 
8537   if (auto *IEI = dyn_cast<InsertElementInst>(V))
8538     return getVectorElementSize(IEI->getOperand(1));
8539 
8540   auto E = InstrElementSize.find(V);
8541   if (E != InstrElementSize.end())
8542     return E->second;
8543 
8544   // If V is not a store, we can traverse the expression tree to find loads
8545   // that feed it. The type of the loaded value may indicate a more suitable
8546   // width than V's type. We want to base the vector element size on the width
8547   // of memory operations where possible.
8548   SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist;
8549   SmallPtrSet<Instruction *, 16> Visited;
8550   if (auto *I = dyn_cast<Instruction>(V)) {
8551     Worklist.emplace_back(I, I->getParent());
8552     Visited.insert(I);
8553   }
8554 
8555   // Traverse the expression tree in bottom-up order looking for loads. If we
8556   // encounter an instruction we don't yet handle, we give up.
8557   auto Width = 0u;
8558   while (!Worklist.empty()) {
8559     Instruction *I;
8560     BasicBlock *Parent;
8561     std::tie(I, Parent) = Worklist.pop_back_val();
8562 
8563     // We should only be looking at scalar instructions here. If the current
8564     // instruction has a vector type, skip.
8565     auto *Ty = I->getType();
8566     if (isa<VectorType>(Ty))
8567       continue;
8568 
8569     // If the current instruction is a load, update MaxWidth to reflect the
8570     // width of the loaded value.
8571     if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) ||
8572         isa<ExtractValueInst>(I))
8573       Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty));
8574 
8575     // Otherwise, we need to visit the operands of the instruction. We only
8576     // handle the interesting cases from buildTree here. If an operand is an
8577     // instruction we haven't yet visited and from the same basic block as the
8578     // user or the use is a PHI node, we add it to the worklist.
8579     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
8580              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) ||
8581              isa<UnaryOperator>(I)) {
8582       for (Use &U : I->operands())
8583         if (auto *J = dyn_cast<Instruction>(U.get()))
8584           if (Visited.insert(J).second &&
8585               (isa<PHINode>(I) || J->getParent() == Parent))
8586             Worklist.emplace_back(J, J->getParent());
8587     } else {
8588       break;
8589     }
8590   }
8591 
8592   // If we didn't encounter a memory access in the expression tree, or if we
8593   // gave up for some reason, just return the width of V. Otherwise, return the
8594   // maximum width we found.
8595   if (!Width) {
8596     if (auto *CI = dyn_cast<CmpInst>(V))
8597       V = CI->getOperand(0);
8598     Width = DL->getTypeSizeInBits(V->getType());
8599   }
8600 
8601   for (Instruction *I : Visited)
8602     InstrElementSize[I] = Width;
8603 
8604   return Width;
8605 }
8606 
8607 // Determine if a value V in a vectorizable expression Expr can be demoted to a
8608 // smaller type with a truncation. We collect the values that will be demoted
8609 // in ToDemote and additional roots that require investigating in Roots.
8610 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
8611                                   SmallVectorImpl<Value *> &ToDemote,
8612                                   SmallVectorImpl<Value *> &Roots) {
8613   // We can always demote constants.
8614   if (isa<Constant>(V)) {
8615     ToDemote.push_back(V);
8616     return true;
8617   }
8618 
8619   // If the value is not an instruction in the expression with only one use, it
8620   // cannot be demoted.
8621   auto *I = dyn_cast<Instruction>(V);
8622   if (!I || !I->hasOneUse() || !Expr.count(I))
8623     return false;
8624 
8625   switch (I->getOpcode()) {
8626 
8627   // We can always demote truncations and extensions. Since truncations can
8628   // seed additional demotion, we save the truncated value.
8629   case Instruction::Trunc:
8630     Roots.push_back(I->getOperand(0));
8631     break;
8632   case Instruction::ZExt:
8633   case Instruction::SExt:
8634     if (isa<ExtractElementInst>(I->getOperand(0)) ||
8635         isa<InsertElementInst>(I->getOperand(0)))
8636       return false;
8637     break;
8638 
8639   // We can demote certain binary operations if we can demote both of their
8640   // operands.
8641   case Instruction::Add:
8642   case Instruction::Sub:
8643   case Instruction::Mul:
8644   case Instruction::And:
8645   case Instruction::Or:
8646   case Instruction::Xor:
8647     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
8648         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
8649       return false;
8650     break;
8651 
8652   // We can demote selects if we can demote their true and false values.
8653   case Instruction::Select: {
8654     SelectInst *SI = cast<SelectInst>(I);
8655     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
8656         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
8657       return false;
8658     break;
8659   }
8660 
8661   // We can demote phis if we can demote all their incoming operands. Note that
8662   // we don't need to worry about cycles since we ensure single use above.
8663   case Instruction::PHI: {
8664     PHINode *PN = cast<PHINode>(I);
8665     for (Value *IncValue : PN->incoming_values())
8666       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
8667         return false;
8668     break;
8669   }
8670 
8671   // Otherwise, conservatively give up.
8672   default:
8673     return false;
8674   }
8675 
8676   // Record the value that we can demote.
8677   ToDemote.push_back(V);
8678   return true;
8679 }
8680 
8681 void BoUpSLP::computeMinimumValueSizes() {
8682   // If there are no external uses, the expression tree must be rooted by a
8683   // store. We can't demote in-memory values, so there is nothing to do here.
8684   if (ExternalUses.empty())
8685     return;
8686 
8687   // We only attempt to truncate integer expressions.
8688   auto &TreeRoot = VectorizableTree[0]->Scalars;
8689   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
8690   if (!TreeRootIT)
8691     return;
8692 
8693   // If the expression is not rooted by a store, these roots should have
8694   // external uses. We will rely on InstCombine to rewrite the expression in
8695   // the narrower type. However, InstCombine only rewrites single-use values.
8696   // This means that if a tree entry other than a root is used externally, it
8697   // must have multiple uses and InstCombine will not rewrite it. The code
8698   // below ensures that only the roots are used externally.
8699   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
8700   for (auto &EU : ExternalUses)
8701     if (!Expr.erase(EU.Scalar))
8702       return;
8703   if (!Expr.empty())
8704     return;
8705 
8706   // Collect the scalar values of the vectorizable expression. We will use this
8707   // context to determine which values can be demoted. If we see a truncation,
8708   // we mark it as seeding another demotion.
8709   for (auto &EntryPtr : VectorizableTree)
8710     Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
8711 
8712   // Ensure the roots of the vectorizable tree don't form a cycle. They must
8713   // have a single external user that is not in the vectorizable tree.
8714   for (auto *Root : TreeRoot)
8715     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
8716       return;
8717 
8718   // Conservatively determine if we can actually truncate the roots of the
8719   // expression. Collect the values that can be demoted in ToDemote and
8720   // additional roots that require investigating in Roots.
8721   SmallVector<Value *, 32> ToDemote;
8722   SmallVector<Value *, 4> Roots;
8723   for (auto *Root : TreeRoot)
8724     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
8725       return;
8726 
8727   // The maximum bit width required to represent all the values that can be
8728   // demoted without loss of precision. It would be safe to truncate the roots
8729   // of the expression to this width.
8730   auto MaxBitWidth = 8u;
8731 
8732   // We first check if all the bits of the roots are demanded. If they're not,
8733   // we can truncate the roots to this narrower type.
8734   for (auto *Root : TreeRoot) {
8735     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
8736     MaxBitWidth = std::max<unsigned>(
8737         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
8738   }
8739 
8740   // True if the roots can be zero-extended back to their original type, rather
8741   // than sign-extended. We know that if the leading bits are not demanded, we
8742   // can safely zero-extend. So we initialize IsKnownPositive to True.
8743   bool IsKnownPositive = true;
8744 
8745   // If all the bits of the roots are demanded, we can try a little harder to
8746   // compute a narrower type. This can happen, for example, if the roots are
8747   // getelementptr indices. InstCombine promotes these indices to the pointer
8748   // width. Thus, all their bits are technically demanded even though the
8749   // address computation might be vectorized in a smaller type.
8750   //
8751   // We start by looking at each entry that can be demoted. We compute the
8752   // maximum bit width required to store the scalar by using ValueTracking to
8753   // compute the number of high-order bits we can truncate.
8754   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
8755       llvm::all_of(TreeRoot, [](Value *R) {
8756         assert(R->hasOneUse() && "Root should have only one use!");
8757         return isa<GetElementPtrInst>(R->user_back());
8758       })) {
8759     MaxBitWidth = 8u;
8760 
8761     // Determine if the sign bit of all the roots is known to be zero. If not,
8762     // IsKnownPositive is set to False.
8763     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
8764       KnownBits Known = computeKnownBits(R, *DL);
8765       return Known.isNonNegative();
8766     });
8767 
8768     // Determine the maximum number of bits required to store the scalar
8769     // values.
8770     for (auto *Scalar : ToDemote) {
8771       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
8772       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
8773       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
8774     }
8775 
8776     // If we can't prove that the sign bit is zero, we must add one to the
8777     // maximum bit width to account for the unknown sign bit. This preserves
8778     // the existing sign bit so we can safely sign-extend the root back to the
8779     // original type. Otherwise, if we know the sign bit is zero, we will
8780     // zero-extend the root instead.
8781     //
8782     // FIXME: This is somewhat suboptimal, as there will be cases where adding
8783     //        one to the maximum bit width will yield a larger-than-necessary
8784     //        type. In general, we need to add an extra bit only if we can't
8785     //        prove that the upper bit of the original type is equal to the
8786     //        upper bit of the proposed smaller type. If these two bits are the
8787     //        same (either zero or one) we know that sign-extending from the
8788     //        smaller type will result in the same value. Here, since we can't
8789     //        yet prove this, we are just making the proposed smaller type
8790     //        larger to ensure correctness.
8791     if (!IsKnownPositive)
8792       ++MaxBitWidth;
8793   }
8794 
8795   // Round MaxBitWidth up to the next power-of-two.
8796   if (!isPowerOf2_64(MaxBitWidth))
8797     MaxBitWidth = NextPowerOf2(MaxBitWidth);
8798 
8799   // If the maximum bit width we compute is less than the with of the roots'
8800   // type, we can proceed with the narrowing. Otherwise, do nothing.
8801   if (MaxBitWidth >= TreeRootIT->getBitWidth())
8802     return;
8803 
8804   // If we can truncate the root, we must collect additional values that might
8805   // be demoted as a result. That is, those seeded by truncations we will
8806   // modify.
8807   while (!Roots.empty())
8808     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
8809 
8810   // Finally, map the values we can demote to the maximum bit with we computed.
8811   for (auto *Scalar : ToDemote)
8812     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
8813 }
8814 
8815 namespace {
8816 
8817 /// The SLPVectorizer Pass.
8818 struct SLPVectorizer : public FunctionPass {
8819   SLPVectorizerPass Impl;
8820 
8821   /// Pass identification, replacement for typeid
8822   static char ID;
8823 
8824   explicit SLPVectorizer() : FunctionPass(ID) {
8825     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
8826   }
8827 
8828   bool doInitialization(Module &M) override { return false; }
8829 
8830   bool runOnFunction(Function &F) override {
8831     if (skipFunction(F))
8832       return false;
8833 
8834     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
8835     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
8836     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
8837     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
8838     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
8839     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
8840     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
8841     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
8842     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
8843     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
8844 
8845     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8846   }
8847 
8848   void getAnalysisUsage(AnalysisUsage &AU) const override {
8849     FunctionPass::getAnalysisUsage(AU);
8850     AU.addRequired<AssumptionCacheTracker>();
8851     AU.addRequired<ScalarEvolutionWrapperPass>();
8852     AU.addRequired<AAResultsWrapperPass>();
8853     AU.addRequired<TargetTransformInfoWrapperPass>();
8854     AU.addRequired<LoopInfoWrapperPass>();
8855     AU.addRequired<DominatorTreeWrapperPass>();
8856     AU.addRequired<DemandedBitsWrapperPass>();
8857     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
8858     AU.addRequired<InjectTLIMappingsLegacy>();
8859     AU.addPreserved<LoopInfoWrapperPass>();
8860     AU.addPreserved<DominatorTreeWrapperPass>();
8861     AU.addPreserved<AAResultsWrapperPass>();
8862     AU.addPreserved<GlobalsAAWrapperPass>();
8863     AU.setPreservesCFG();
8864   }
8865 };
8866 
8867 } // end anonymous namespace
8868 
8869 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
8870   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
8871   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
8872   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
8873   auto *AA = &AM.getResult<AAManager>(F);
8874   auto *LI = &AM.getResult<LoopAnalysis>(F);
8875   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
8876   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
8877   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
8878   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
8879 
8880   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8881   if (!Changed)
8882     return PreservedAnalyses::all();
8883 
8884   PreservedAnalyses PA;
8885   PA.preserveSet<CFGAnalyses>();
8886   return PA;
8887 }
8888 
8889 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
8890                                 TargetTransformInfo *TTI_,
8891                                 TargetLibraryInfo *TLI_, AAResults *AA_,
8892                                 LoopInfo *LI_, DominatorTree *DT_,
8893                                 AssumptionCache *AC_, DemandedBits *DB_,
8894                                 OptimizationRemarkEmitter *ORE_) {
8895   if (!RunSLPVectorization)
8896     return false;
8897   SE = SE_;
8898   TTI = TTI_;
8899   TLI = TLI_;
8900   AA = AA_;
8901   LI = LI_;
8902   DT = DT_;
8903   AC = AC_;
8904   DB = DB_;
8905   DL = &F.getParent()->getDataLayout();
8906 
8907   Stores.clear();
8908   GEPs.clear();
8909   bool Changed = false;
8910 
8911   // If the target claims to have no vector registers don't attempt
8912   // vectorization.
8913   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true))) {
8914     LLVM_DEBUG(
8915         dbgs() << "SLP: Didn't find any vector registers for target, abort.\n");
8916     return false;
8917   }
8918 
8919   // Don't vectorize when the attribute NoImplicitFloat is used.
8920   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
8921     return false;
8922 
8923   LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
8924 
8925   // Use the bottom up slp vectorizer to construct chains that start with
8926   // store instructions.
8927   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
8928 
8929   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
8930   // delete instructions.
8931 
8932   // Update DFS numbers now so that we can use them for ordering.
8933   DT->updateDFSNumbers();
8934 
8935   // Scan the blocks in the function in post order.
8936   for (auto BB : post_order(&F.getEntryBlock())) {
8937     // Start new block - clear the list of reduction roots.
8938     R.clearReductionData();
8939     collectSeedInstructions(BB);
8940 
8941     // Vectorize trees that end at stores.
8942     if (!Stores.empty()) {
8943       LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
8944                         << " underlying objects.\n");
8945       Changed |= vectorizeStoreChains(R);
8946     }
8947 
8948     // Vectorize trees that end at reductions.
8949     Changed |= vectorizeChainsInBlock(BB, R);
8950 
8951     // Vectorize the index computations of getelementptr instructions. This
8952     // is primarily intended to catch gather-like idioms ending at
8953     // non-consecutive loads.
8954     if (!GEPs.empty()) {
8955       LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
8956                         << " underlying objects.\n");
8957       Changed |= vectorizeGEPIndices(BB, R);
8958     }
8959   }
8960 
8961   if (Changed) {
8962     R.optimizeGatherSequence();
8963     LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
8964   }
8965   return Changed;
8966 }
8967 
8968 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
8969                                             unsigned Idx) {
8970   LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()
8971                     << "\n");
8972   const unsigned Sz = R.getVectorElementSize(Chain[0]);
8973   const unsigned MinVF = R.getMinVecRegSize() / Sz;
8974   unsigned VF = Chain.size();
8975 
8976   if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
8977     return false;
8978 
8979   LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx
8980                     << "\n");
8981 
8982   R.buildTree(Chain);
8983   if (R.isTreeTinyAndNotFullyVectorizable())
8984     return false;
8985   if (R.isLoadCombineCandidate())
8986     return false;
8987   R.reorderTopToBottom();
8988   R.reorderBottomToTop();
8989   R.buildExternalUses();
8990 
8991   R.computeMinimumValueSizes();
8992 
8993   InstructionCost Cost = R.getTreeCost();
8994 
8995   LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n");
8996   if (Cost < -SLPCostThreshold) {
8997     LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n");
8998 
8999     using namespace ore;
9000 
9001     R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
9002                                         cast<StoreInst>(Chain[0]))
9003                      << "Stores SLP vectorized with cost " << NV("Cost", Cost)
9004                      << " and with tree size "
9005                      << NV("TreeSize", R.getTreeSize()));
9006 
9007     R.vectorizeTree();
9008     return true;
9009   }
9010 
9011   return false;
9012 }
9013 
9014 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
9015                                         BoUpSLP &R) {
9016   // We may run into multiple chains that merge into a single chain. We mark the
9017   // stores that we vectorized so that we don't visit the same store twice.
9018   BoUpSLP::ValueSet VectorizedStores;
9019   bool Changed = false;
9020 
9021   int E = Stores.size();
9022   SmallBitVector Tails(E, false);
9023   int MaxIter = MaxStoreLookup.getValue();
9024   SmallVector<std::pair<int, int>, 16> ConsecutiveChain(
9025       E, std::make_pair(E, INT_MAX));
9026   SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false));
9027   int IterCnt;
9028   auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
9029                                   &CheckedPairs,
9030                                   &ConsecutiveChain](int K, int Idx) {
9031     if (IterCnt >= MaxIter)
9032       return true;
9033     if (CheckedPairs[Idx].test(K))
9034       return ConsecutiveChain[K].second == 1 &&
9035              ConsecutiveChain[K].first == Idx;
9036     ++IterCnt;
9037     CheckedPairs[Idx].set(K);
9038     CheckedPairs[K].set(Idx);
9039     Optional<int> Diff = getPointersDiff(
9040         Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(),
9041         Stores[Idx]->getValueOperand()->getType(),
9042         Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true);
9043     if (!Diff || *Diff == 0)
9044       return false;
9045     int Val = *Diff;
9046     if (Val < 0) {
9047       if (ConsecutiveChain[Idx].second > -Val) {
9048         Tails.set(K);
9049         ConsecutiveChain[Idx] = std::make_pair(K, -Val);
9050       }
9051       return false;
9052     }
9053     if (ConsecutiveChain[K].second <= Val)
9054       return false;
9055 
9056     Tails.set(Idx);
9057     ConsecutiveChain[K] = std::make_pair(Idx, Val);
9058     return Val == 1;
9059   };
9060   // Do a quadratic search on all of the given stores in reverse order and find
9061   // all of the pairs of stores that follow each other.
9062   for (int Idx = E - 1; Idx >= 0; --Idx) {
9063     // If a store has multiple consecutive store candidates, search according
9064     // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
9065     // This is because usually pairing with immediate succeeding or preceding
9066     // candidate create the best chance to find slp vectorization opportunity.
9067     const int MaxLookDepth = std::max(E - Idx, Idx + 1);
9068     IterCnt = 0;
9069     for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
9070       if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
9071           (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
9072         break;
9073   }
9074 
9075   // Tracks if we tried to vectorize stores starting from the given tail
9076   // already.
9077   SmallBitVector TriedTails(E, false);
9078   // For stores that start but don't end a link in the chain:
9079   for (int Cnt = E; Cnt > 0; --Cnt) {
9080     int I = Cnt - 1;
9081     if (ConsecutiveChain[I].first == E || Tails.test(I))
9082       continue;
9083     // We found a store instr that starts a chain. Now follow the chain and try
9084     // to vectorize it.
9085     BoUpSLP::ValueList Operands;
9086     // Collect the chain into a list.
9087     while (I != E && !VectorizedStores.count(Stores[I])) {
9088       Operands.push_back(Stores[I]);
9089       Tails.set(I);
9090       if (ConsecutiveChain[I].second != 1) {
9091         // Mark the new end in the chain and go back, if required. It might be
9092         // required if the original stores come in reversed order, for example.
9093         if (ConsecutiveChain[I].first != E &&
9094             Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) &&
9095             !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) {
9096           TriedTails.set(I);
9097           Tails.reset(ConsecutiveChain[I].first);
9098           if (Cnt < ConsecutiveChain[I].first + 2)
9099             Cnt = ConsecutiveChain[I].first + 2;
9100         }
9101         break;
9102       }
9103       // Move to the next value in the chain.
9104       I = ConsecutiveChain[I].first;
9105     }
9106     assert(!Operands.empty() && "Expected non-empty list of stores.");
9107 
9108     unsigned MaxVecRegSize = R.getMaxVecRegSize();
9109     unsigned EltSize = R.getVectorElementSize(Operands[0]);
9110     unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize);
9111 
9112     unsigned MinVF = R.getMinVF(EltSize);
9113     unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store),
9114                               MaxElts);
9115 
9116     // FIXME: Is division-by-2 the correct step? Should we assert that the
9117     // register size is a power-of-2?
9118     unsigned StartIdx = 0;
9119     for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) {
9120       for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
9121         ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size);
9122         if (!VectorizedStores.count(Slice.front()) &&
9123             !VectorizedStores.count(Slice.back()) &&
9124             vectorizeStoreChain(Slice, R, Cnt)) {
9125           // Mark the vectorized stores so that we don't vectorize them again.
9126           VectorizedStores.insert(Slice.begin(), Slice.end());
9127           Changed = true;
9128           // If we vectorized initial block, no need to try to vectorize it
9129           // again.
9130           if (Cnt == StartIdx)
9131             StartIdx += Size;
9132           Cnt += Size;
9133           continue;
9134         }
9135         ++Cnt;
9136       }
9137       // Check if the whole array was vectorized already - exit.
9138       if (StartIdx >= Operands.size())
9139         break;
9140     }
9141   }
9142 
9143   return Changed;
9144 }
9145 
9146 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
9147   // Initialize the collections. We will make a single pass over the block.
9148   Stores.clear();
9149   GEPs.clear();
9150 
9151   // Visit the store and getelementptr instructions in BB and organize them in
9152   // Stores and GEPs according to the underlying objects of their pointer
9153   // operands.
9154   for (Instruction &I : *BB) {
9155     // Ignore store instructions that are volatile or have a pointer operand
9156     // that doesn't point to a scalar type.
9157     if (auto *SI = dyn_cast<StoreInst>(&I)) {
9158       if (!SI->isSimple())
9159         continue;
9160       if (!isValidElementType(SI->getValueOperand()->getType()))
9161         continue;
9162       Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI);
9163     }
9164 
9165     // Ignore getelementptr instructions that have more than one index, a
9166     // constant index, or a pointer operand that doesn't point to a scalar
9167     // type.
9168     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
9169       auto Idx = GEP->idx_begin()->get();
9170       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
9171         continue;
9172       if (!isValidElementType(Idx->getType()))
9173         continue;
9174       if (GEP->getType()->isVectorTy())
9175         continue;
9176       GEPs[GEP->getPointerOperand()].push_back(GEP);
9177     }
9178   }
9179 }
9180 
9181 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
9182   if (!A || !B)
9183     return false;
9184   if (isa<InsertElementInst>(A) || isa<InsertElementInst>(B))
9185     return false;
9186   Value *VL[] = {A, B};
9187   return tryToVectorizeList(VL, R);
9188 }
9189 
9190 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
9191                                            bool LimitForRegisterSize) {
9192   if (VL.size() < 2)
9193     return false;
9194 
9195   LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
9196                     << VL.size() << ".\n");
9197 
9198   // Check that all of the parts are instructions of the same type,
9199   // we permit an alternate opcode via InstructionsState.
9200   InstructionsState S = getSameOpcode(VL);
9201   if (!S.getOpcode())
9202     return false;
9203 
9204   Instruction *I0 = cast<Instruction>(S.OpValue);
9205   // Make sure invalid types (including vector type) are rejected before
9206   // determining vectorization factor for scalar instructions.
9207   for (Value *V : VL) {
9208     Type *Ty = V->getType();
9209     if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) {
9210       // NOTE: the following will give user internal llvm type name, which may
9211       // not be useful.
9212       R.getORE()->emit([&]() {
9213         std::string type_str;
9214         llvm::raw_string_ostream rso(type_str);
9215         Ty->print(rso);
9216         return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
9217                << "Cannot SLP vectorize list: type "
9218                << rso.str() + " is unsupported by vectorizer";
9219       });
9220       return false;
9221     }
9222   }
9223 
9224   unsigned Sz = R.getVectorElementSize(I0);
9225   unsigned MinVF = R.getMinVF(Sz);
9226   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
9227   MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF);
9228   if (MaxVF < 2) {
9229     R.getORE()->emit([&]() {
9230       return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
9231              << "Cannot SLP vectorize list: vectorization factor "
9232              << "less than 2 is not supported";
9233     });
9234     return false;
9235   }
9236 
9237   bool Changed = false;
9238   bool CandidateFound = false;
9239   InstructionCost MinCost = SLPCostThreshold.getValue();
9240   Type *ScalarTy = VL[0]->getType();
9241   if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
9242     ScalarTy = IE->getOperand(1)->getType();
9243 
9244   unsigned NextInst = 0, MaxInst = VL.size();
9245   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
9246     // No actual vectorization should happen, if number of parts is the same as
9247     // provided vectorization factor (i.e. the scalar type is used for vector
9248     // code during codegen).
9249     auto *VecTy = FixedVectorType::get(ScalarTy, VF);
9250     if (TTI->getNumberOfParts(VecTy) == VF)
9251       continue;
9252     for (unsigned I = NextInst; I < MaxInst; ++I) {
9253       unsigned OpsWidth = 0;
9254 
9255       if (I + VF > MaxInst)
9256         OpsWidth = MaxInst - I;
9257       else
9258         OpsWidth = VF;
9259 
9260       if (!isPowerOf2_32(OpsWidth))
9261         continue;
9262 
9263       if ((LimitForRegisterSize && OpsWidth < MaxVF) ||
9264           (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2))
9265         break;
9266 
9267       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
9268       // Check that a previous iteration of this loop did not delete the Value.
9269       if (llvm::any_of(Ops, [&R](Value *V) {
9270             auto *I = dyn_cast<Instruction>(V);
9271             return I && R.isDeleted(I);
9272           }))
9273         continue;
9274 
9275       LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
9276                         << "\n");
9277 
9278       R.buildTree(Ops);
9279       if (R.isTreeTinyAndNotFullyVectorizable())
9280         continue;
9281       R.reorderTopToBottom();
9282       R.reorderBottomToTop(!isa<InsertElementInst>(Ops.front()));
9283       R.buildExternalUses();
9284 
9285       R.computeMinimumValueSizes();
9286       InstructionCost Cost = R.getTreeCost();
9287       CandidateFound = true;
9288       MinCost = std::min(MinCost, Cost);
9289 
9290       if (Cost < -SLPCostThreshold) {
9291         LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
9292         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
9293                                                     cast<Instruction>(Ops[0]))
9294                                  << "SLP vectorized with cost " << ore::NV("Cost", Cost)
9295                                  << " and with tree size "
9296                                  << ore::NV("TreeSize", R.getTreeSize()));
9297 
9298         R.vectorizeTree();
9299         // Move to the next bundle.
9300         I += VF - 1;
9301         NextInst = I + 1;
9302         Changed = true;
9303       }
9304     }
9305   }
9306 
9307   if (!Changed && CandidateFound) {
9308     R.getORE()->emit([&]() {
9309       return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
9310              << "List vectorization was possible but not beneficial with cost "
9311              << ore::NV("Cost", MinCost) << " >= "
9312              << ore::NV("Treshold", -SLPCostThreshold);
9313     });
9314   } else if (!Changed) {
9315     R.getORE()->emit([&]() {
9316       return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
9317              << "Cannot SLP vectorize list: vectorization was impossible"
9318              << " with available vectorization factors";
9319     });
9320   }
9321   return Changed;
9322 }
9323 
9324 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
9325   if (!I)
9326     return false;
9327 
9328   if ((!isa<BinaryOperator>(I) && !isa<CmpInst>(I)) ||
9329       isa<VectorType>(I->getType()))
9330     return false;
9331 
9332   Value *P = I->getParent();
9333 
9334   // Vectorize in current basic block only.
9335   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
9336   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
9337   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
9338     return false;
9339 
9340   // First collect all possible candidates
9341   SmallVector<std::pair<Value *, Value *>, 4> Candidates;
9342   Candidates.emplace_back(Op0, Op1);
9343 
9344   auto *A = dyn_cast<BinaryOperator>(Op0);
9345   auto *B = dyn_cast<BinaryOperator>(Op1);
9346   // Try to skip B.
9347   if (A && B && B->hasOneUse()) {
9348     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
9349     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
9350     if (B0 && B0->getParent() == P)
9351       Candidates.emplace_back(A, B0);
9352     if (B1 && B1->getParent() == P)
9353       Candidates.emplace_back(A, B1);
9354   }
9355   // Try to skip A.
9356   if (B && A && A->hasOneUse()) {
9357     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
9358     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
9359     if (A0 && A0->getParent() == P)
9360       Candidates.emplace_back(A0, B);
9361     if (A1 && A1->getParent() == P)
9362       Candidates.emplace_back(A1, B);
9363   }
9364 
9365   if (Candidates.size() == 1)
9366     return tryToVectorizePair(Op0, Op1, R);
9367 
9368   // We have multiple options. Try to pick the single best.
9369   Optional<int> BestCandidate = R.findBestRootPair(Candidates);
9370   if (!BestCandidate)
9371     return false;
9372   return tryToVectorizePair(Candidates[*BestCandidate].first,
9373                             Candidates[*BestCandidate].second, R);
9374 }
9375 
9376 namespace {
9377 
9378 /// Model horizontal reductions.
9379 ///
9380 /// A horizontal reduction is a tree of reduction instructions that has values
9381 /// that can be put into a vector as its leaves. For example:
9382 ///
9383 /// mul mul mul mul
9384 ///  \  /    \  /
9385 ///   +       +
9386 ///    \     /
9387 ///       +
9388 /// This tree has "mul" as its leaf values and "+" as its reduction
9389 /// instructions. A reduction can feed into a store or a binary operation
9390 /// feeding a phi.
9391 ///    ...
9392 ///    \  /
9393 ///     +
9394 ///     |
9395 ///  phi +=
9396 ///
9397 ///  Or:
9398 ///    ...
9399 ///    \  /
9400 ///     +
9401 ///     |
9402 ///   *p =
9403 ///
9404 class HorizontalReduction {
9405   using ReductionOpsType = SmallVector<Value *, 16>;
9406   using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
9407   ReductionOpsListType ReductionOps;
9408   /// List of possibly reduced values.
9409   SmallVector<SmallVector<Value *>> ReducedVals;
9410   /// Maps reduced value to the corresponding reduction operation.
9411   DenseMap<Value *, SmallVector<Instruction *>> ReducedValsToOps;
9412   // Use map vector to make stable output.
9413   MapVector<Instruction *, Value *> ExtraArgs;
9414   WeakTrackingVH ReductionRoot;
9415   /// The type of reduction operation.
9416   RecurKind RdxKind;
9417 
9418   static bool isCmpSelMinMax(Instruction *I) {
9419     return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) &&
9420            RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I));
9421   }
9422 
9423   // And/or are potentially poison-safe logical patterns like:
9424   // select x, y, false
9425   // select x, true, y
9426   static bool isBoolLogicOp(Instruction *I) {
9427     return match(I, m_LogicalAnd(m_Value(), m_Value())) ||
9428            match(I, m_LogicalOr(m_Value(), m_Value()));
9429   }
9430 
9431   /// Checks if instruction is associative and can be vectorized.
9432   static bool isVectorizable(RecurKind Kind, Instruction *I) {
9433     if (Kind == RecurKind::None)
9434       return false;
9435 
9436     // Integer ops that map to select instructions or intrinsics are fine.
9437     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) ||
9438         isBoolLogicOp(I))
9439       return true;
9440 
9441     if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) {
9442       // FP min/max are associative except for NaN and -0.0. We do not
9443       // have to rule out -0.0 here because the intrinsic semantics do not
9444       // specify a fixed result for it.
9445       return I->getFastMathFlags().noNaNs();
9446     }
9447 
9448     return I->isAssociative();
9449   }
9450 
9451   static Value *getRdxOperand(Instruction *I, unsigned Index) {
9452     // Poison-safe 'or' takes the form: select X, true, Y
9453     // To make that work with the normal operand processing, we skip the
9454     // true value operand.
9455     // TODO: Change the code and data structures to handle this without a hack.
9456     if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1)
9457       return I->getOperand(2);
9458     return I->getOperand(Index);
9459   }
9460 
9461   /// Creates reduction operation with the current opcode.
9462   static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS,
9463                          Value *RHS, const Twine &Name, bool UseSelect) {
9464     unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind);
9465     switch (Kind) {
9466     case RecurKind::Or:
9467       if (UseSelect &&
9468           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9469         return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name);
9470       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9471                                  Name);
9472     case RecurKind::And:
9473       if (UseSelect &&
9474           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9475         return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name);
9476       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9477                                  Name);
9478     case RecurKind::Add:
9479     case RecurKind::Mul:
9480     case RecurKind::Xor:
9481     case RecurKind::FAdd:
9482     case RecurKind::FMul:
9483       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9484                                  Name);
9485     case RecurKind::FMax:
9486       return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS);
9487     case RecurKind::FMin:
9488       return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS);
9489     case RecurKind::SMax:
9490       if (UseSelect) {
9491         Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name);
9492         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9493       }
9494       return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS);
9495     case RecurKind::SMin:
9496       if (UseSelect) {
9497         Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name);
9498         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9499       }
9500       return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS);
9501     case RecurKind::UMax:
9502       if (UseSelect) {
9503         Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name);
9504         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9505       }
9506       return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS);
9507     case RecurKind::UMin:
9508       if (UseSelect) {
9509         Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name);
9510         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9511       }
9512       return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS);
9513     default:
9514       llvm_unreachable("Unknown reduction operation.");
9515     }
9516   }
9517 
9518   /// Creates reduction operation with the current opcode with the IR flags
9519   /// from \p ReductionOps.
9520   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9521                          Value *RHS, const Twine &Name,
9522                          const ReductionOpsListType &ReductionOps) {
9523     bool UseSelect = ReductionOps.size() == 2 ||
9524                      // Logical or/and.
9525                      (ReductionOps.size() == 1 &&
9526                       isa<SelectInst>(ReductionOps.front().front()));
9527     assert((!UseSelect || ReductionOps.size() != 2 ||
9528             isa<SelectInst>(ReductionOps[1][0])) &&
9529            "Expected cmp + select pairs for reduction");
9530     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect);
9531     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9532       if (auto *Sel = dyn_cast<SelectInst>(Op)) {
9533         propagateIRFlags(Sel->getCondition(), ReductionOps[0]);
9534         propagateIRFlags(Op, ReductionOps[1]);
9535         return Op;
9536       }
9537     }
9538     propagateIRFlags(Op, ReductionOps[0]);
9539     return Op;
9540   }
9541 
9542   /// Creates reduction operation with the current opcode with the IR flags
9543   /// from \p I.
9544   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9545                          Value *RHS, const Twine &Name, Value *I) {
9546     auto *SelI = dyn_cast<SelectInst>(I);
9547     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, SelI != nullptr);
9548     if (SelI && RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9549       if (auto *Sel = dyn_cast<SelectInst>(Op))
9550         propagateIRFlags(Sel->getCondition(), SelI->getCondition());
9551     }
9552     propagateIRFlags(Op, I);
9553     return Op;
9554   }
9555 
9556   static RecurKind getRdxKind(Value *V) {
9557     auto *I = dyn_cast<Instruction>(V);
9558     if (!I)
9559       return RecurKind::None;
9560     if (match(I, m_Add(m_Value(), m_Value())))
9561       return RecurKind::Add;
9562     if (match(I, m_Mul(m_Value(), m_Value())))
9563       return RecurKind::Mul;
9564     if (match(I, m_And(m_Value(), m_Value())) ||
9565         match(I, m_LogicalAnd(m_Value(), m_Value())))
9566       return RecurKind::And;
9567     if (match(I, m_Or(m_Value(), m_Value())) ||
9568         match(I, m_LogicalOr(m_Value(), m_Value())))
9569       return RecurKind::Or;
9570     if (match(I, m_Xor(m_Value(), m_Value())))
9571       return RecurKind::Xor;
9572     if (match(I, m_FAdd(m_Value(), m_Value())))
9573       return RecurKind::FAdd;
9574     if (match(I, m_FMul(m_Value(), m_Value())))
9575       return RecurKind::FMul;
9576 
9577     if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value())))
9578       return RecurKind::FMax;
9579     if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value())))
9580       return RecurKind::FMin;
9581 
9582     // This matches either cmp+select or intrinsics. SLP is expected to handle
9583     // either form.
9584     // TODO: If we are canonicalizing to intrinsics, we can remove several
9585     //       special-case paths that deal with selects.
9586     if (match(I, m_SMax(m_Value(), m_Value())))
9587       return RecurKind::SMax;
9588     if (match(I, m_SMin(m_Value(), m_Value())))
9589       return RecurKind::SMin;
9590     if (match(I, m_UMax(m_Value(), m_Value())))
9591       return RecurKind::UMax;
9592     if (match(I, m_UMin(m_Value(), m_Value())))
9593       return RecurKind::UMin;
9594 
9595     if (auto *Select = dyn_cast<SelectInst>(I)) {
9596       // Try harder: look for min/max pattern based on instructions producing
9597       // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
9598       // During the intermediate stages of SLP, it's very common to have
9599       // pattern like this (since optimizeGatherSequence is run only once
9600       // at the end):
9601       // %1 = extractelement <2 x i32> %a, i32 0
9602       // %2 = extractelement <2 x i32> %a, i32 1
9603       // %cond = icmp sgt i32 %1, %2
9604       // %3 = extractelement <2 x i32> %a, i32 0
9605       // %4 = extractelement <2 x i32> %a, i32 1
9606       // %select = select i1 %cond, i32 %3, i32 %4
9607       CmpInst::Predicate Pred;
9608       Instruction *L1;
9609       Instruction *L2;
9610 
9611       Value *LHS = Select->getTrueValue();
9612       Value *RHS = Select->getFalseValue();
9613       Value *Cond = Select->getCondition();
9614 
9615       // TODO: Support inverse predicates.
9616       if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
9617         if (!isa<ExtractElementInst>(RHS) ||
9618             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9619           return RecurKind::None;
9620       } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
9621         if (!isa<ExtractElementInst>(LHS) ||
9622             !L1->isIdenticalTo(cast<Instruction>(LHS)))
9623           return RecurKind::None;
9624       } else {
9625         if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
9626           return RecurKind::None;
9627         if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
9628             !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
9629             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9630           return RecurKind::None;
9631       }
9632 
9633       switch (Pred) {
9634       default:
9635         return RecurKind::None;
9636       case CmpInst::ICMP_SGT:
9637       case CmpInst::ICMP_SGE:
9638         return RecurKind::SMax;
9639       case CmpInst::ICMP_SLT:
9640       case CmpInst::ICMP_SLE:
9641         return RecurKind::SMin;
9642       case CmpInst::ICMP_UGT:
9643       case CmpInst::ICMP_UGE:
9644         return RecurKind::UMax;
9645       case CmpInst::ICMP_ULT:
9646       case CmpInst::ICMP_ULE:
9647         return RecurKind::UMin;
9648       }
9649     }
9650     return RecurKind::None;
9651   }
9652 
9653   /// Get the index of the first operand.
9654   static unsigned getFirstOperandIndex(Instruction *I) {
9655     return isCmpSelMinMax(I) ? 1 : 0;
9656   }
9657 
9658   /// Total number of operands in the reduction operation.
9659   static unsigned getNumberOfOperands(Instruction *I) {
9660     return isCmpSelMinMax(I) ? 3 : 2;
9661   }
9662 
9663   /// Checks if the instruction is in basic block \p BB.
9664   /// For a cmp+sel min/max reduction check that both ops are in \p BB.
9665   static bool hasSameParent(Instruction *I, BasicBlock *BB) {
9666     if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) {
9667       auto *Sel = cast<SelectInst>(I);
9668       auto *Cmp = dyn_cast<Instruction>(Sel->getCondition());
9669       return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB;
9670     }
9671     return I->getParent() == BB;
9672   }
9673 
9674   /// Expected number of uses for reduction operations/reduced values.
9675   static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) {
9676     if (IsCmpSelMinMax) {
9677       // SelectInst must be used twice while the condition op must have single
9678       // use only.
9679       if (auto *Sel = dyn_cast<SelectInst>(I))
9680         return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse();
9681       return I->hasNUses(2);
9682     }
9683 
9684     // Arithmetic reduction operation must be used once only.
9685     return I->hasOneUse();
9686   }
9687 
9688   /// Initializes the list of reduction operations.
9689   void initReductionOps(Instruction *I) {
9690     if (isCmpSelMinMax(I))
9691       ReductionOps.assign(2, ReductionOpsType());
9692     else
9693       ReductionOps.assign(1, ReductionOpsType());
9694   }
9695 
9696   /// Add all reduction operations for the reduction instruction \p I.
9697   void addReductionOps(Instruction *I) {
9698     if (isCmpSelMinMax(I)) {
9699       ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
9700       ReductionOps[1].emplace_back(I);
9701     } else {
9702       ReductionOps[0].emplace_back(I);
9703     }
9704   }
9705 
9706   static Value *getLHS(RecurKind Kind, Instruction *I) {
9707     if (Kind == RecurKind::None)
9708       return nullptr;
9709     return I->getOperand(getFirstOperandIndex(I));
9710   }
9711   static Value *getRHS(RecurKind Kind, Instruction *I) {
9712     if (Kind == RecurKind::None)
9713       return nullptr;
9714     return I->getOperand(getFirstOperandIndex(I) + 1);
9715   }
9716 
9717 public:
9718   HorizontalReduction() = default;
9719 
9720   /// Try to find a reduction tree.
9721   bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst,
9722                                  ScalarEvolution &SE, const DataLayout &DL,
9723                                  const TargetLibraryInfo &TLI) {
9724     assert((!Phi || is_contained(Phi->operands(), Inst)) &&
9725            "Phi needs to use the binary operator");
9726     assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) ||
9727             isa<IntrinsicInst>(Inst)) &&
9728            "Expected binop, select, or intrinsic for reduction matching");
9729     RdxKind = getRdxKind(Inst);
9730 
9731     // We could have a initial reductions that is not an add.
9732     //  r *= v1 + v2 + v3 + v4
9733     // In such a case start looking for a tree rooted in the first '+'.
9734     if (Phi) {
9735       if (getLHS(RdxKind, Inst) == Phi) {
9736         Phi = nullptr;
9737         Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst));
9738         if (!Inst)
9739           return false;
9740         RdxKind = getRdxKind(Inst);
9741       } else if (getRHS(RdxKind, Inst) == Phi) {
9742         Phi = nullptr;
9743         Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst));
9744         if (!Inst)
9745           return false;
9746         RdxKind = getRdxKind(Inst);
9747       }
9748     }
9749 
9750     if (!isVectorizable(RdxKind, Inst))
9751       return false;
9752 
9753     // Analyze "regular" integer/FP types for reductions - no target-specific
9754     // types or pointers.
9755     Type *Ty = Inst->getType();
9756     if (!isValidElementType(Ty) || Ty->isPointerTy())
9757       return false;
9758 
9759     // Though the ultimate reduction may have multiple uses, its condition must
9760     // have only single use.
9761     if (auto *Sel = dyn_cast<SelectInst>(Inst))
9762       if (!Sel->getCondition()->hasOneUse())
9763         return false;
9764 
9765     ReductionRoot = Inst;
9766 
9767     // Iterate through all the operands of the possible reduction tree and
9768     // gather all the reduced values, sorting them by their value id.
9769     BasicBlock *BB = Inst->getParent();
9770     bool IsCmpSelMinMax = isCmpSelMinMax(Inst);
9771     SmallVector<Instruction *> Worklist(1, Inst);
9772     // Checks if the operands of the \p TreeN instruction are also reduction
9773     // operations or should be treated as reduced values or an extra argument,
9774     // which is not part of the reduction.
9775     auto &&CheckOperands = [this, IsCmpSelMinMax,
9776                             BB](Instruction *TreeN,
9777                                 SmallVectorImpl<Value *> &ExtraArgs,
9778                                 SmallVectorImpl<Value *> &PossibleReducedVals,
9779                                 SmallVectorImpl<Instruction *> &ReductionOps) {
9780       for (int I = getFirstOperandIndex(TreeN),
9781                End = getNumberOfOperands(TreeN);
9782            I < End; ++I) {
9783         Value *EdgeVal = getRdxOperand(TreeN, I);
9784         ReducedValsToOps[EdgeVal].push_back(TreeN);
9785         auto *EdgeInst = dyn_cast<Instruction>(EdgeVal);
9786         // Edge has wrong parent - mark as an extra argument.
9787         if (EdgeInst && !isVectorLikeInstWithConstOps(EdgeInst) &&
9788             !hasSameParent(EdgeInst, BB)) {
9789           ExtraArgs.push_back(EdgeVal);
9790           continue;
9791         }
9792         // If the edge is not an instruction, or it is different from the main
9793         // reduction opcode or has too many uses - possible reduced value.
9794         if (!EdgeInst || getRdxKind(EdgeInst) != RdxKind ||
9795             !hasRequiredNumberOfUses(IsCmpSelMinMax, EdgeInst) ||
9796             !isVectorizable(getRdxKind(EdgeInst), EdgeInst)) {
9797           PossibleReducedVals.push_back(EdgeVal);
9798           continue;
9799         }
9800         ReductionOps.push_back(EdgeInst);
9801       }
9802     };
9803     // Try to regroup reduced values so that it gets more profitable to try to
9804     // reduce them. Values are grouped by their value ids, instructions - by
9805     // instruction op id and/or alternate op id, plus do extra analysis for
9806     // loads (grouping them by the distabce between pointers) and cmp
9807     // instructions (grouping them by the predicate).
9808     MapVector<size_t, MapVector<size_t, MapVector<Value *, unsigned>>>
9809         PossibleReducedVals;
9810     initReductionOps(Inst);
9811     while (!Worklist.empty()) {
9812       Instruction *TreeN = Worklist.pop_back_val();
9813       SmallVector<Value *> Args;
9814       SmallVector<Value *> PossibleRedVals;
9815       SmallVector<Instruction *> PossibleReductionOps;
9816       CheckOperands(TreeN, Args, PossibleRedVals, PossibleReductionOps);
9817       // If too many extra args - mark the instruction itself as a reduction
9818       // value, not a reduction operation.
9819       if (Args.size() < 2) {
9820         addReductionOps(TreeN);
9821         // Add extra args.
9822         if (!Args.empty()) {
9823           assert(Args.size() == 1 && "Expected only single argument.");
9824           ExtraArgs[TreeN] = Args.front();
9825         }
9826         // Add reduction values. The values are sorted for better vectorization
9827         // results.
9828         for (Value *V : PossibleRedVals) {
9829           size_t Key, Idx;
9830           std::tie(Key, Idx) = generateKeySubkey(
9831               V, &TLI,
9832               [&PossibleReducedVals, &DL, &SE](size_t Key, LoadInst *LI) {
9833                 for (const auto &LoadData : PossibleReducedVals[Key]) {
9834                   auto *RLI = cast<LoadInst>(LoadData.second.front().first);
9835                   if (getPointersDiff(RLI->getType(), RLI->getPointerOperand(),
9836                                       LI->getType(), LI->getPointerOperand(),
9837                                       DL, SE, /*StrictCheck=*/true))
9838                     return hash_value(RLI->getPointerOperand());
9839                 }
9840                 return hash_value(LI->getPointerOperand());
9841               },
9842               /*AllowAlternate=*/false);
9843           ++PossibleReducedVals[Key][Idx]
9844                 .insert(std::make_pair(V, 0))
9845                 .first->second;
9846         }
9847         Worklist.append(PossibleReductionOps.rbegin(),
9848                         PossibleReductionOps.rend());
9849       } else {
9850         size_t Key, Idx;
9851         std::tie(Key, Idx) = generateKeySubkey(
9852             TreeN, &TLI,
9853             [&PossibleReducedVals, &DL, &SE](size_t Key, LoadInst *LI) {
9854               for (const auto &LoadData : PossibleReducedVals[Key]) {
9855                 auto *RLI = cast<LoadInst>(LoadData.second.front().first);
9856                 if (getPointersDiff(RLI->getType(), RLI->getPointerOperand(),
9857                                     LI->getType(), LI->getPointerOperand(), DL,
9858                                     SE, /*StrictCheck=*/true))
9859                   return hash_value(RLI->getPointerOperand());
9860               }
9861               return hash_value(LI->getPointerOperand());
9862             },
9863             /*AllowAlternate=*/false);
9864         ++PossibleReducedVals[Key][Idx]
9865               .insert(std::make_pair(TreeN, 0))
9866               .first->second;
9867       }
9868     }
9869     auto PossibleReducedValsVect = PossibleReducedVals.takeVector();
9870     // Sort values by the total number of values kinds to start the reduction
9871     // from the longest possible reduced values sequences.
9872     for (auto &PossibleReducedVals : PossibleReducedValsVect) {
9873       auto PossibleRedVals = PossibleReducedVals.second.takeVector();
9874       SmallVector<SmallVector<Value *>> PossibleRedValsVect;
9875       for (auto It = PossibleRedVals.begin(), E = PossibleRedVals.end();
9876            It != E; ++It) {
9877         PossibleRedValsVect.emplace_back();
9878         auto RedValsVect = It->second.takeVector();
9879         stable_sort(RedValsVect, [](const auto &P1, const auto &P2) {
9880           return P1.second < P2.second;
9881         });
9882         for (const std::pair<Value *, unsigned> &Data : RedValsVect)
9883           PossibleRedValsVect.back().append(Data.second, Data.first);
9884       }
9885       stable_sort(PossibleRedValsVect, [](const auto &P1, const auto &P2) {
9886         return P1.size() > P2.size();
9887       });
9888       ReducedVals.emplace_back();
9889       for (ArrayRef<Value *> Data : PossibleRedValsVect)
9890         ReducedVals.back().append(Data.rbegin(), Data.rend());
9891     }
9892     // Sort the reduced values by number of same/alternate opcode and/or pointer
9893     // operand.
9894     stable_sort(ReducedVals, [](ArrayRef<Value *> P1, ArrayRef<Value *> P2) {
9895       return P1.size() > P2.size();
9896     });
9897     return true;
9898   }
9899 
9900   /// Attempt to vectorize the tree found by matchAssociativeReduction.
9901   Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
9902     constexpr int ReductionLimit = 4;
9903     // If there are a sufficient number of reduction values, reduce
9904     // to a nearby power-of-2. We can safely generate oversized
9905     // vectors and rely on the backend to split them to legal sizes.
9906     unsigned NumReducedVals = std::accumulate(
9907         ReducedVals.begin(), ReducedVals.end(), 0,
9908         [](int Num, ArrayRef<Value *> Vals) { return Num + Vals.size(); });
9909     if (NumReducedVals < ReductionLimit)
9910       return nullptr;
9911 
9912     IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
9913 
9914     // Track the reduced values in case if they are replaced by extractelement
9915     // because of the vectorization.
9916     DenseMap<Value *, WeakTrackingVH> TrackedVals;
9917     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
9918     // The same extra argument may be used several times, so log each attempt
9919     // to use it.
9920     for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) {
9921       assert(Pair.first && "DebugLoc must be set.");
9922       ExternallyUsedValues[Pair.second].push_back(Pair.first);
9923       TrackedVals.try_emplace(Pair.second, Pair.second);
9924     }
9925 
9926     // The compare instruction of a min/max is the insertion point for new
9927     // instructions and may be replaced with a new compare instruction.
9928     auto &&GetCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
9929       assert(isa<SelectInst>(RdxRootInst) &&
9930              "Expected min/max reduction to have select root instruction");
9931       Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
9932       assert(isa<Instruction>(ScalarCond) &&
9933              "Expected min/max reduction to have compare condition");
9934       return cast<Instruction>(ScalarCond);
9935     };
9936 
9937     // The reduction root is used as the insertion point for new instructions,
9938     // so set it as externally used to prevent it from being deleted.
9939     ExternallyUsedValues[ReductionRoot];
9940     SmallVector<Value *> IgnoreList;
9941     for (ReductionOpsType &RdxOps : ReductionOps)
9942       for (Value *RdxOp : RdxOps) {
9943         if (!RdxOp)
9944           continue;
9945         IgnoreList.push_back(RdxOp);
9946       }
9947     bool IsCmpSelMinMax = isCmpSelMinMax(cast<Instruction>(ReductionRoot));
9948 
9949     // Need to track reduced vals, they may be changed during vectorization of
9950     // subvectors.
9951     for (ArrayRef<Value *> Candidates : ReducedVals)
9952       for (Value *V : Candidates)
9953         TrackedVals.try_emplace(V, V);
9954 
9955     DenseMap<Value *, unsigned> VectorizedVals;
9956     Value *VectorizedTree = nullptr;
9957     bool CheckForReusedReductionOps = false;
9958     // Try to vectorize elements based on their type.
9959     for (unsigned I = 0, E = ReducedVals.size(); I < E; ++I) {
9960       ArrayRef<Value *> OrigReducedVals = ReducedVals[I];
9961       InstructionsState S = getSameOpcode(OrigReducedVals);
9962       SmallVector<Value *> Candidates;
9963       DenseMap<Value *, Value *> TrackedToOrig;
9964       for (unsigned Cnt = 0, Sz = OrigReducedVals.size(); Cnt < Sz; ++Cnt) {
9965         Value *RdxVal = TrackedVals.find(OrigReducedVals[Cnt])->second;
9966         // Check if the reduction value was not overriden by the extractelement
9967         // instruction because of the vectorization and exclude it, if it is not
9968         // compatible with other values.
9969         if (auto *Inst = dyn_cast<Instruction>(RdxVal))
9970           if (isVectorLikeInstWithConstOps(Inst) &&
9971               (!S.getOpcode() || !S.isOpcodeOrAlt(Inst)))
9972             continue;
9973         Candidates.push_back(RdxVal);
9974         TrackedToOrig.try_emplace(RdxVal, OrigReducedVals[Cnt]);
9975       }
9976       bool ShuffledExtracts = false;
9977       // Try to handle shuffled extractelements.
9978       if (S.getOpcode() == Instruction::ExtractElement && !S.isAltShuffle() &&
9979           I + 1 < E) {
9980         InstructionsState NextS = getSameOpcode(ReducedVals[I + 1]);
9981         if (NextS.getOpcode() == Instruction::ExtractElement &&
9982             !NextS.isAltShuffle()) {
9983           SmallVector<Value *> CommonCandidates(Candidates);
9984           for (Value *RV : ReducedVals[I + 1]) {
9985             Value *RdxVal = TrackedVals.find(RV)->second;
9986             // Check if the reduction value was not overriden by the
9987             // extractelement instruction because of the vectorization and
9988             // exclude it, if it is not compatible with other values.
9989             if (auto *Inst = dyn_cast<Instruction>(RdxVal))
9990               if (!NextS.getOpcode() || !NextS.isOpcodeOrAlt(Inst))
9991                 continue;
9992             CommonCandidates.push_back(RdxVal);
9993             TrackedToOrig.try_emplace(RdxVal, RV);
9994           }
9995           SmallVector<int> Mask;
9996           if (isFixedVectorShuffle(CommonCandidates, Mask)) {
9997             ++I;
9998             Candidates.swap(CommonCandidates);
9999             ShuffledExtracts = true;
10000           }
10001         }
10002       }
10003       unsigned NumReducedVals = Candidates.size();
10004       if (NumReducedVals < ReductionLimit)
10005         continue;
10006 
10007       unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
10008       unsigned Start = 0;
10009       unsigned Pos = Start;
10010       // Restarts vectorization attempt with lower vector factor.
10011       unsigned PrevReduxWidth = ReduxWidth;
10012       bool CheckForReusedReductionOpsLocal = false;
10013       auto &&AdjustReducedVals = [&Pos, &Start, &ReduxWidth, NumReducedVals,
10014                                   &CheckForReusedReductionOpsLocal,
10015                                   &PrevReduxWidth, &V,
10016                                   &IgnoreList](bool IgnoreVL = false) {
10017         bool IsAnyRedOpGathered =
10018             !IgnoreVL && any_of(IgnoreList, [&V](Value *RedOp) {
10019               return V.isGathered(RedOp);
10020             });
10021         if (!CheckForReusedReductionOpsLocal && PrevReduxWidth == ReduxWidth) {
10022           // Check if any of the reduction ops are gathered. If so, worth
10023           // trying again with less number of reduction ops.
10024           CheckForReusedReductionOpsLocal |= IsAnyRedOpGathered;
10025         }
10026         ++Pos;
10027         if (Pos < NumReducedVals - ReduxWidth + 1)
10028           return IsAnyRedOpGathered;
10029         Pos = Start;
10030         ReduxWidth /= 2;
10031         return IsAnyRedOpGathered;
10032       };
10033       while (Pos < NumReducedVals - ReduxWidth + 1 &&
10034              ReduxWidth >= ReductionLimit) {
10035         // Dependency in tree of the reduction ops - drop this attempt, try
10036         // later.
10037         if (CheckForReusedReductionOpsLocal && PrevReduxWidth != ReduxWidth &&
10038             Start == 0) {
10039           CheckForReusedReductionOps = true;
10040           break;
10041         }
10042         PrevReduxWidth = ReduxWidth;
10043         ArrayRef<Value *> VL(std::next(Candidates.begin(), Pos), ReduxWidth);
10044         // Beeing analyzed already - skip.
10045         if (V.areAnalyzedReductionVals(VL)) {
10046           (void)AdjustReducedVals(/*IgnoreVL=*/true);
10047           continue;
10048         }
10049         // Early exit if any of the reduction values were deleted during
10050         // previous vectorization attempts.
10051         if (any_of(VL, [&V](Value *RedVal) {
10052               auto *RedValI = dyn_cast<Instruction>(RedVal);
10053               if (!RedValI)
10054                 return false;
10055               return V.isDeleted(RedValI);
10056             }))
10057           break;
10058         V.buildTree(VL, IgnoreList);
10059         if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true)) {
10060           if (!AdjustReducedVals())
10061             V.analyzedReductionVals(VL);
10062           continue;
10063         }
10064         if (V.isLoadCombineReductionCandidate(RdxKind)) {
10065           if (!AdjustReducedVals())
10066             V.analyzedReductionVals(VL);
10067           continue;
10068         }
10069         V.reorderTopToBottom();
10070         // No need to reorder the root node at all.
10071         V.reorderBottomToTop(/*IgnoreReorder=*/true);
10072         // Keep extracted other reduction values, if they are used in the
10073         // vectorization trees.
10074         BoUpSLP::ExtraValueToDebugLocsMap LocalExternallyUsedValues(
10075             ExternallyUsedValues);
10076         for (unsigned Cnt = 0, Sz = ReducedVals.size(); Cnt < Sz; ++Cnt) {
10077           if (Cnt == I || (ShuffledExtracts && Cnt == I - 1))
10078             continue;
10079           for_each(ReducedVals[Cnt],
10080                    [&LocalExternallyUsedValues, &TrackedVals](Value *V) {
10081                      if (isa<Instruction>(V))
10082                        LocalExternallyUsedValues[TrackedVals[V]];
10083                    });
10084         }
10085         for (unsigned Cnt = 0; Cnt < NumReducedVals; ++Cnt) {
10086           if (Cnt >= Pos && Cnt < Pos + ReduxWidth)
10087             continue;
10088           if (VectorizedVals.count(Candidates[Cnt]))
10089             continue;
10090           LocalExternallyUsedValues[Candidates[Cnt]];
10091         }
10092         V.buildExternalUses(LocalExternallyUsedValues);
10093 
10094         V.computeMinimumValueSizes();
10095 
10096         // Intersect the fast-math-flags from all reduction operations.
10097         FastMathFlags RdxFMF;
10098         RdxFMF.set();
10099         for (Value *U : IgnoreList)
10100           if (auto *FPMO = dyn_cast<FPMathOperator>(U))
10101             RdxFMF &= FPMO->getFastMathFlags();
10102         // Estimate cost.
10103         InstructionCost TreeCost = V.getTreeCost(VL);
10104         InstructionCost ReductionCost =
10105             getReductionCost(TTI, VL[0], ReduxWidth, RdxFMF);
10106         InstructionCost Cost = TreeCost + ReductionCost;
10107         if (!Cost.isValid()) {
10108           LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n");
10109           return nullptr;
10110         }
10111         if (Cost >= -SLPCostThreshold) {
10112           V.getORE()->emit([&]() {
10113             return OptimizationRemarkMissed(
10114                        SV_NAME, "HorSLPNotBeneficial",
10115                        ReducedValsToOps.find(VL[0])->second.front())
10116                    << "Vectorizing horizontal reduction is possible"
10117                    << "but not beneficial with cost " << ore::NV("Cost", Cost)
10118                    << " and threshold "
10119                    << ore::NV("Threshold", -SLPCostThreshold);
10120           });
10121           if (!AdjustReducedVals())
10122             V.analyzedReductionVals(VL);
10123           continue;
10124         }
10125 
10126         LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
10127                           << Cost << ". (HorRdx)\n");
10128         V.getORE()->emit([&]() {
10129           return OptimizationRemark(
10130                      SV_NAME, "VectorizedHorizontalReduction",
10131                      ReducedValsToOps.find(VL[0])->second.front())
10132                  << "Vectorized horizontal reduction with cost "
10133                  << ore::NV("Cost", Cost) << " and with tree size "
10134                  << ore::NV("TreeSize", V.getTreeSize());
10135         });
10136 
10137         Builder.setFastMathFlags(RdxFMF);
10138 
10139         // Vectorize a tree.
10140         Value *VectorizedRoot = V.vectorizeTree(LocalExternallyUsedValues);
10141 
10142         // Emit a reduction. If the root is a select (min/max idiom), the insert
10143         // point is the compare condition of that select.
10144         Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
10145         if (IsCmpSelMinMax)
10146           Builder.SetInsertPoint(GetCmpForMinMaxReduction(RdxRootInst));
10147         else
10148           Builder.SetInsertPoint(RdxRootInst);
10149 
10150         // To prevent poison from leaking across what used to be sequential,
10151         // safe, scalar boolean logic operations, the reduction operand must be
10152         // frozen.
10153         if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst))
10154           VectorizedRoot = Builder.CreateFreeze(VectorizedRoot);
10155 
10156         Value *ReducedSubTree =
10157             emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
10158 
10159         if (!VectorizedTree) {
10160           // Initialize the final value in the reduction.
10161           VectorizedTree = ReducedSubTree;
10162         } else {
10163           // Update the final value in the reduction.
10164           Builder.SetCurrentDebugLocation(
10165               cast<Instruction>(ReductionOps.front().front())->getDebugLoc());
10166           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
10167                                     ReducedSubTree, "op.rdx", ReductionOps);
10168         }
10169         // Count vectorized reduced values to exclude them from final reduction.
10170         for (Value *V : VL)
10171           ++VectorizedVals.try_emplace(TrackedToOrig.find(V)->second, 0)
10172                 .first->getSecond();
10173         Pos += ReduxWidth;
10174         Start = Pos;
10175         ReduxWidth = PowerOf2Floor(NumReducedVals - Pos);
10176       }
10177     }
10178     if (VectorizedTree) {
10179       // Finish the reduction.
10180       // Need to add extra arguments and not vectorized possible reduction
10181       // values.
10182       SmallPtrSet<Value *, 8> Visited;
10183       for (unsigned I = 0, E = ReducedVals.size(); I < E; ++I) {
10184         ArrayRef<Value *> Candidates = ReducedVals[I];
10185         for (Value *RdxVal : Candidates) {
10186           if (!Visited.insert(RdxVal).second)
10187             continue;
10188           Value *StableRdxVal = RdxVal;
10189           auto TVIt = TrackedVals.find(RdxVal);
10190           if (TVIt != TrackedVals.end())
10191             StableRdxVal = TVIt->second;
10192           unsigned NumOps = 0;
10193           auto It = VectorizedVals.find(RdxVal);
10194           if (It != VectorizedVals.end())
10195             NumOps = It->second;
10196           for (Instruction *RedOp :
10197                makeArrayRef(ReducedValsToOps.find(RdxVal)->second)
10198                    .drop_back(NumOps)) {
10199             Builder.SetCurrentDebugLocation(RedOp->getDebugLoc());
10200             ReductionOpsListType Ops;
10201             if (auto *Sel = dyn_cast<SelectInst>(RedOp))
10202               Ops.emplace_back().push_back(Sel->getCondition());
10203             Ops.emplace_back().push_back(RedOp);
10204             VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
10205                                       StableRdxVal, "op.rdx", Ops);
10206           }
10207         }
10208       }
10209       for (auto &Pair : ExternallyUsedValues) {
10210         // Add each externally used value to the final reduction.
10211         for (auto *I : Pair.second) {
10212           Builder.SetCurrentDebugLocation(I->getDebugLoc());
10213           ReductionOpsListType Ops;
10214           if (auto *Sel = dyn_cast<SelectInst>(I))
10215             Ops.emplace_back().push_back(Sel->getCondition());
10216           Ops.emplace_back().push_back(I);
10217           Value *StableRdxVal = Pair.first;
10218           auto TVIt = TrackedVals.find(Pair.first);
10219           if (TVIt != TrackedVals.end())
10220             StableRdxVal = TVIt->second;
10221           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
10222                                     StableRdxVal, "op.rdx", Ops);
10223         }
10224       }
10225 
10226       ReductionRoot->replaceAllUsesWith(VectorizedTree);
10227 
10228       // The original scalar reduction is expected to have no remaining
10229       // uses outside the reduction tree itself.  Assert that we got this
10230       // correct, replace internal uses with undef, and mark for eventual
10231       // deletion.
10232 #ifndef NDEBUG
10233       SmallSet<Value *, 4> IgnoreSet;
10234       for (ArrayRef<Value *> RdxOps : ReductionOps)
10235         IgnoreSet.insert(RdxOps.begin(), RdxOps.end());
10236 #endif
10237       for (ArrayRef<Value *> RdxOps : ReductionOps) {
10238         for (Value *Ignore : RdxOps) {
10239           if (!Ignore)
10240             continue;
10241 #ifndef NDEBUG
10242           for (auto *U : Ignore->users()) {
10243             assert(IgnoreSet.count(U) &&
10244                    "All users must be either in the reduction ops list.");
10245           }
10246 #endif
10247           if (!Ignore->use_empty()) {
10248             Value *Undef = UndefValue::get(Ignore->getType());
10249             Ignore->replaceAllUsesWith(Undef);
10250           }
10251           V.eraseInstruction(cast<Instruction>(Ignore));
10252         }
10253       }
10254     } else if (!CheckForReusedReductionOps) {
10255       for (ReductionOpsType &RdxOps : ReductionOps)
10256         for (Value *RdxOp : RdxOps)
10257           V.analyzedReductionRoot(cast<Instruction>(RdxOp));
10258     }
10259     return VectorizedTree;
10260   }
10261 
10262   unsigned numReductionValues() const { return ReducedVals.size(); }
10263 
10264 private:
10265   /// Calculate the cost of a reduction.
10266   InstructionCost getReductionCost(TargetTransformInfo *TTI,
10267                                    Value *FirstReducedVal, unsigned ReduxWidth,
10268                                    FastMathFlags FMF) {
10269     TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
10270     Type *ScalarTy = FirstReducedVal->getType();
10271     FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth);
10272     InstructionCost VectorCost, ScalarCost;
10273     switch (RdxKind) {
10274     case RecurKind::Add:
10275     case RecurKind::Mul:
10276     case RecurKind::Or:
10277     case RecurKind::And:
10278     case RecurKind::Xor:
10279     case RecurKind::FAdd:
10280     case RecurKind::FMul: {
10281       unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind);
10282       VectorCost =
10283           TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind);
10284       ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind);
10285       break;
10286     }
10287     case RecurKind::FMax:
10288     case RecurKind::FMin: {
10289       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
10290       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
10291       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
10292                                                /*IsUnsigned=*/false, CostKind);
10293       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
10294       ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy,
10295                                            SclCondTy, RdxPred, CostKind) +
10296                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
10297                                            SclCondTy, RdxPred, CostKind);
10298       break;
10299     }
10300     case RecurKind::SMax:
10301     case RecurKind::SMin:
10302     case RecurKind::UMax:
10303     case RecurKind::UMin: {
10304       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
10305       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
10306       bool IsUnsigned =
10307           RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin;
10308       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, IsUnsigned,
10309                                                CostKind);
10310       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
10311       ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
10312                                            SclCondTy, RdxPred, CostKind) +
10313                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
10314                                            SclCondTy, RdxPred, CostKind);
10315       break;
10316     }
10317     default:
10318       llvm_unreachable("Expected arithmetic or min/max reduction operation");
10319     }
10320 
10321     // Scalar cost is repeated for N-1 elements.
10322     ScalarCost *= (ReduxWidth - 1);
10323     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost
10324                       << " for reduction that starts with " << *FirstReducedVal
10325                       << " (It is a splitting reduction)\n");
10326     return VectorCost - ScalarCost;
10327   }
10328 
10329   /// Emit a horizontal reduction of the vectorized value.
10330   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
10331                        unsigned ReduxWidth, const TargetTransformInfo *TTI) {
10332     assert(VectorizedValue && "Need to have a vectorized tree node");
10333     assert(isPowerOf2_32(ReduxWidth) &&
10334            "We only handle power-of-two reductions for now");
10335     assert(RdxKind != RecurKind::FMulAdd &&
10336            "A call to the llvm.fmuladd intrinsic is not handled yet");
10337 
10338     ++NumVectorInstructions;
10339     return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind);
10340   }
10341 };
10342 
10343 } // end anonymous namespace
10344 
10345 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) {
10346   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
10347     return cast<FixedVectorType>(IE->getType())->getNumElements();
10348 
10349   unsigned AggregateSize = 1;
10350   auto *IV = cast<InsertValueInst>(InsertInst);
10351   Type *CurrentType = IV->getType();
10352   do {
10353     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
10354       for (auto *Elt : ST->elements())
10355         if (Elt != ST->getElementType(0)) // check homogeneity
10356           return None;
10357       AggregateSize *= ST->getNumElements();
10358       CurrentType = ST->getElementType(0);
10359     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
10360       AggregateSize *= AT->getNumElements();
10361       CurrentType = AT->getElementType();
10362     } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
10363       AggregateSize *= VT->getNumElements();
10364       return AggregateSize;
10365     } else if (CurrentType->isSingleValueType()) {
10366       return AggregateSize;
10367     } else {
10368       return None;
10369     }
10370   } while (true);
10371 }
10372 
10373 static void findBuildAggregate_rec(Instruction *LastInsertInst,
10374                                    TargetTransformInfo *TTI,
10375                                    SmallVectorImpl<Value *> &BuildVectorOpds,
10376                                    SmallVectorImpl<Value *> &InsertElts,
10377                                    unsigned OperandOffset) {
10378   do {
10379     Value *InsertedOperand = LastInsertInst->getOperand(1);
10380     Optional<unsigned> OperandIndex =
10381         getInsertIndex(LastInsertInst, OperandOffset);
10382     if (!OperandIndex)
10383       return;
10384     if (isa<InsertElementInst>(InsertedOperand) ||
10385         isa<InsertValueInst>(InsertedOperand)) {
10386       findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI,
10387                              BuildVectorOpds, InsertElts, *OperandIndex);
10388 
10389     } else {
10390       BuildVectorOpds[*OperandIndex] = InsertedOperand;
10391       InsertElts[*OperandIndex] = LastInsertInst;
10392     }
10393     LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0));
10394   } while (LastInsertInst != nullptr &&
10395            (isa<InsertValueInst>(LastInsertInst) ||
10396             isa<InsertElementInst>(LastInsertInst)) &&
10397            LastInsertInst->hasOneUse());
10398 }
10399 
10400 /// Recognize construction of vectors like
10401 ///  %ra = insertelement <4 x float> poison, float %s0, i32 0
10402 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
10403 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
10404 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
10405 ///  starting from the last insertelement or insertvalue instruction.
10406 ///
10407 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>},
10408 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
10409 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
10410 ///
10411 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
10412 ///
10413 /// \return true if it matches.
10414 static bool findBuildAggregate(Instruction *LastInsertInst,
10415                                TargetTransformInfo *TTI,
10416                                SmallVectorImpl<Value *> &BuildVectorOpds,
10417                                SmallVectorImpl<Value *> &InsertElts) {
10418 
10419   assert((isa<InsertElementInst>(LastInsertInst) ||
10420           isa<InsertValueInst>(LastInsertInst)) &&
10421          "Expected insertelement or insertvalue instruction!");
10422 
10423   assert((BuildVectorOpds.empty() && InsertElts.empty()) &&
10424          "Expected empty result vectors!");
10425 
10426   Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst);
10427   if (!AggregateSize)
10428     return false;
10429   BuildVectorOpds.resize(*AggregateSize);
10430   InsertElts.resize(*AggregateSize);
10431 
10432   findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts, 0);
10433   llvm::erase_value(BuildVectorOpds, nullptr);
10434   llvm::erase_value(InsertElts, nullptr);
10435   if (BuildVectorOpds.size() >= 2)
10436     return true;
10437 
10438   return false;
10439 }
10440 
10441 /// Try and get a reduction value from a phi node.
10442 ///
10443 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
10444 /// if they come from either \p ParentBB or a containing loop latch.
10445 ///
10446 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
10447 /// if not possible.
10448 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
10449                                 BasicBlock *ParentBB, LoopInfo *LI) {
10450   // There are situations where the reduction value is not dominated by the
10451   // reduction phi. Vectorizing such cases has been reported to cause
10452   // miscompiles. See PR25787.
10453   auto DominatedReduxValue = [&](Value *R) {
10454     return isa<Instruction>(R) &&
10455            DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
10456   };
10457 
10458   Value *Rdx = nullptr;
10459 
10460   // Return the incoming value if it comes from the same BB as the phi node.
10461   if (P->getIncomingBlock(0) == ParentBB) {
10462     Rdx = P->getIncomingValue(0);
10463   } else if (P->getIncomingBlock(1) == ParentBB) {
10464     Rdx = P->getIncomingValue(1);
10465   }
10466 
10467   if (Rdx && DominatedReduxValue(Rdx))
10468     return Rdx;
10469 
10470   // Otherwise, check whether we have a loop latch to look at.
10471   Loop *BBL = LI->getLoopFor(ParentBB);
10472   if (!BBL)
10473     return nullptr;
10474   BasicBlock *BBLatch = BBL->getLoopLatch();
10475   if (!BBLatch)
10476     return nullptr;
10477 
10478   // There is a loop latch, return the incoming value if it comes from
10479   // that. This reduction pattern occasionally turns up.
10480   if (P->getIncomingBlock(0) == BBLatch) {
10481     Rdx = P->getIncomingValue(0);
10482   } else if (P->getIncomingBlock(1) == BBLatch) {
10483     Rdx = P->getIncomingValue(1);
10484   }
10485 
10486   if (Rdx && DominatedReduxValue(Rdx))
10487     return Rdx;
10488 
10489   return nullptr;
10490 }
10491 
10492 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) {
10493   if (match(I, m_BinOp(m_Value(V0), m_Value(V1))))
10494     return true;
10495   if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1))))
10496     return true;
10497   if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1))))
10498     return true;
10499   if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1))))
10500     return true;
10501   if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1))))
10502     return true;
10503   if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1))))
10504     return true;
10505   if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1))))
10506     return true;
10507   return false;
10508 }
10509 
10510 /// Attempt to reduce a horizontal reduction.
10511 /// If it is legal to match a horizontal reduction feeding the phi node \a P
10512 /// with reduction operators \a Root (or one of its operands) in a basic block
10513 /// \a BB, then check if it can be done. If horizontal reduction is not found
10514 /// and root instruction is a binary operation, vectorization of the operands is
10515 /// attempted.
10516 /// \returns true if a horizontal reduction was matched and reduced or operands
10517 /// of one of the binary instruction were vectorized.
10518 /// \returns false if a horizontal reduction was not matched (or not possible)
10519 /// or no vectorization of any binary operation feeding \a Root instruction was
10520 /// performed.
10521 static bool tryToVectorizeHorReductionOrInstOperands(
10522     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
10523     TargetTransformInfo *TTI, ScalarEvolution &SE, const DataLayout &DL,
10524     const TargetLibraryInfo &TLI,
10525     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
10526   if (!ShouldVectorizeHor)
10527     return false;
10528 
10529   if (!Root)
10530     return false;
10531 
10532   if (Root->getParent() != BB || isa<PHINode>(Root))
10533     return false;
10534   // Start analysis starting from Root instruction. If horizontal reduction is
10535   // found, try to vectorize it. If it is not a horizontal reduction or
10536   // vectorization is not possible or not effective, and currently analyzed
10537   // instruction is a binary operation, try to vectorize the operands, using
10538   // pre-order DFS traversal order. If the operands were not vectorized, repeat
10539   // the same procedure considering each operand as a possible root of the
10540   // horizontal reduction.
10541   // Interrupt the process if the Root instruction itself was vectorized or all
10542   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
10543   // Skip the analysis of CmpInsts. Compiler implements postanalysis of the
10544   // CmpInsts so we can skip extra attempts in
10545   // tryToVectorizeHorReductionOrInstOperands and save compile time.
10546   std::queue<std::pair<Instruction *, unsigned>> Stack;
10547   Stack.emplace(Root, 0);
10548   SmallPtrSet<Value *, 8> VisitedInstrs;
10549   SmallVector<WeakTrackingVH> PostponedInsts;
10550   bool Res = false;
10551   auto &&TryToReduce = [TTI, &SE, &DL, &P, &R, &TLI](Instruction *Inst,
10552                                                      Value *&B0,
10553                                                      Value *&B1) -> Value * {
10554     if (R.isAnalizedReductionRoot(Inst))
10555       return nullptr;
10556     bool IsBinop = matchRdxBop(Inst, B0, B1);
10557     bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value()));
10558     if (IsBinop || IsSelect) {
10559       HorizontalReduction HorRdx;
10560       if (HorRdx.matchAssociativeReduction(P, Inst, SE, DL, TLI))
10561         return HorRdx.tryToReduce(R, TTI);
10562     }
10563     return nullptr;
10564   };
10565   while (!Stack.empty()) {
10566     Instruction *Inst;
10567     unsigned Level;
10568     std::tie(Inst, Level) = Stack.front();
10569     Stack.pop();
10570     // Do not try to analyze instruction that has already been vectorized.
10571     // This may happen when we vectorize instruction operands on a previous
10572     // iteration while stack was populated before that happened.
10573     if (R.isDeleted(Inst))
10574       continue;
10575     Value *B0 = nullptr, *B1 = nullptr;
10576     if (Value *V = TryToReduce(Inst, B0, B1)) {
10577       Res = true;
10578       // Set P to nullptr to avoid re-analysis of phi node in
10579       // matchAssociativeReduction function unless this is the root node.
10580       P = nullptr;
10581       if (auto *I = dyn_cast<Instruction>(V)) {
10582         // Try to find another reduction.
10583         Stack.emplace(I, Level);
10584         continue;
10585       }
10586     } else {
10587       bool IsBinop = B0 && B1;
10588       if (P && IsBinop) {
10589         Inst = dyn_cast<Instruction>(B0);
10590         if (Inst == P)
10591           Inst = dyn_cast<Instruction>(B1);
10592         if (!Inst) {
10593           // Set P to nullptr to avoid re-analysis of phi node in
10594           // matchAssociativeReduction function unless this is the root node.
10595           P = nullptr;
10596           continue;
10597         }
10598       }
10599       // Set P to nullptr to avoid re-analysis of phi node in
10600       // matchAssociativeReduction function unless this is the root node.
10601       P = nullptr;
10602       // Do not try to vectorize CmpInst operands, this is done separately.
10603       // Final attempt for binop args vectorization should happen after the loop
10604       // to try to find reductions.
10605       if (!isa<CmpInst, InsertElementInst, InsertValueInst>(Inst))
10606         PostponedInsts.push_back(Inst);
10607     }
10608 
10609     // Try to vectorize operands.
10610     // Continue analysis for the instruction from the same basic block only to
10611     // save compile time.
10612     if (++Level < RecursionMaxDepth)
10613       for (auto *Op : Inst->operand_values())
10614         if (VisitedInstrs.insert(Op).second)
10615           if (auto *I = dyn_cast<Instruction>(Op))
10616             // Do not try to vectorize CmpInst operands,  this is done
10617             // separately.
10618             if (!isa<PHINode, CmpInst, InsertElementInst, InsertValueInst>(I) &&
10619                 !R.isDeleted(I) && I->getParent() == BB)
10620               Stack.emplace(I, Level);
10621   }
10622   // Try to vectorized binops where reductions were not found.
10623   for (Value *V : PostponedInsts)
10624     if (auto *Inst = dyn_cast<Instruction>(V))
10625       if (!R.isDeleted(Inst))
10626         Res |= Vectorize(Inst, R);
10627   return Res;
10628 }
10629 
10630 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
10631                                                  BasicBlock *BB, BoUpSLP &R,
10632                                                  TargetTransformInfo *TTI) {
10633   auto *I = dyn_cast_or_null<Instruction>(V);
10634   if (!I)
10635     return false;
10636 
10637   if (!isa<BinaryOperator>(I))
10638     P = nullptr;
10639   // Try to match and vectorize a horizontal reduction.
10640   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
10641     return tryToVectorize(I, R);
10642   };
10643   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI, *SE, *DL,
10644                                                   *TLI, ExtraVectorization);
10645 }
10646 
10647 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
10648                                                  BasicBlock *BB, BoUpSLP &R) {
10649   const DataLayout &DL = BB->getModule()->getDataLayout();
10650   if (!R.canMapToVector(IVI->getType(), DL))
10651     return false;
10652 
10653   SmallVector<Value *, 16> BuildVectorOpds;
10654   SmallVector<Value *, 16> BuildVectorInsts;
10655   if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts))
10656     return false;
10657 
10658   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
10659   // Aggregate value is unlikely to be processed in vector register.
10660   return tryToVectorizeList(BuildVectorOpds, R);
10661 }
10662 
10663 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
10664                                                    BasicBlock *BB, BoUpSLP &R) {
10665   SmallVector<Value *, 16> BuildVectorInsts;
10666   SmallVector<Value *, 16> BuildVectorOpds;
10667   SmallVector<int> Mask;
10668   if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
10669       (llvm::all_of(
10670            BuildVectorOpds,
10671            [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) &&
10672        isFixedVectorShuffle(BuildVectorOpds, Mask)))
10673     return false;
10674 
10675   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n");
10676   return tryToVectorizeList(BuildVectorInsts, R);
10677 }
10678 
10679 template <typename T>
10680 static bool
10681 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming,
10682                        function_ref<unsigned(T *)> Limit,
10683                        function_ref<bool(T *, T *)> Comparator,
10684                        function_ref<bool(T *, T *)> AreCompatible,
10685                        function_ref<bool(ArrayRef<T *>, bool)> TryToVectorizeHelper,
10686                        bool LimitForRegisterSize) {
10687   bool Changed = false;
10688   // Sort by type, parent, operands.
10689   stable_sort(Incoming, Comparator);
10690 
10691   // Try to vectorize elements base on their type.
10692   SmallVector<T *> Candidates;
10693   for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) {
10694     // Look for the next elements with the same type, parent and operand
10695     // kinds.
10696     auto *SameTypeIt = IncIt;
10697     while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt))
10698       ++SameTypeIt;
10699 
10700     // Try to vectorize them.
10701     unsigned NumElts = (SameTypeIt - IncIt);
10702     LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes ("
10703                       << NumElts << ")\n");
10704     // The vectorization is a 3-state attempt:
10705     // 1. Try to vectorize instructions with the same/alternate opcodes with the
10706     // size of maximal register at first.
10707     // 2. Try to vectorize remaining instructions with the same type, if
10708     // possible. This may result in the better vectorization results rather than
10709     // if we try just to vectorize instructions with the same/alternate opcodes.
10710     // 3. Final attempt to try to vectorize all instructions with the
10711     // same/alternate ops only, this may result in some extra final
10712     // vectorization.
10713     if (NumElts > 1 &&
10714         TryToVectorizeHelper(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) {
10715       // Success start over because instructions might have been changed.
10716       Changed = true;
10717     } else if (NumElts < Limit(*IncIt) &&
10718                (Candidates.empty() ||
10719                 Candidates.front()->getType() == (*IncIt)->getType())) {
10720       Candidates.append(IncIt, std::next(IncIt, NumElts));
10721     }
10722     // Final attempt to vectorize instructions with the same types.
10723     if (Candidates.size() > 1 &&
10724         (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) {
10725       if (TryToVectorizeHelper(Candidates, /*LimitForRegisterSize=*/false)) {
10726         // Success start over because instructions might have been changed.
10727         Changed = true;
10728       } else if (LimitForRegisterSize) {
10729         // Try to vectorize using small vectors.
10730         for (auto *It = Candidates.begin(), *End = Candidates.end();
10731              It != End;) {
10732           auto *SameTypeIt = It;
10733           while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It))
10734             ++SameTypeIt;
10735           unsigned NumElts = (SameTypeIt - It);
10736           if (NumElts > 1 && TryToVectorizeHelper(makeArrayRef(It, NumElts),
10737                                             /*LimitForRegisterSize=*/false))
10738             Changed = true;
10739           It = SameTypeIt;
10740         }
10741       }
10742       Candidates.clear();
10743     }
10744 
10745     // Start over at the next instruction of a different type (or the end).
10746     IncIt = SameTypeIt;
10747   }
10748   return Changed;
10749 }
10750 
10751 /// Compare two cmp instructions. If IsCompatibility is true, function returns
10752 /// true if 2 cmps have same/swapped predicates and mos compatible corresponding
10753 /// operands. If IsCompatibility is false, function implements strict weak
10754 /// ordering relation between two cmp instructions, returning true if the first
10755 /// instruction is "less" than the second, i.e. its predicate is less than the
10756 /// predicate of the second or the operands IDs are less than the operands IDs
10757 /// of the second cmp instruction.
10758 template <bool IsCompatibility>
10759 static bool compareCmp(Value *V, Value *V2,
10760                        function_ref<bool(Instruction *)> IsDeleted) {
10761   auto *CI1 = cast<CmpInst>(V);
10762   auto *CI2 = cast<CmpInst>(V2);
10763   if (IsDeleted(CI2) || !isValidElementType(CI2->getType()))
10764     return false;
10765   if (CI1->getOperand(0)->getType()->getTypeID() <
10766       CI2->getOperand(0)->getType()->getTypeID())
10767     return !IsCompatibility;
10768   if (CI1->getOperand(0)->getType()->getTypeID() >
10769       CI2->getOperand(0)->getType()->getTypeID())
10770     return false;
10771   CmpInst::Predicate Pred1 = CI1->getPredicate();
10772   CmpInst::Predicate Pred2 = CI2->getPredicate();
10773   CmpInst::Predicate SwapPred1 = CmpInst::getSwappedPredicate(Pred1);
10774   CmpInst::Predicate SwapPred2 = CmpInst::getSwappedPredicate(Pred2);
10775   CmpInst::Predicate BasePred1 = std::min(Pred1, SwapPred1);
10776   CmpInst::Predicate BasePred2 = std::min(Pred2, SwapPred2);
10777   if (BasePred1 < BasePred2)
10778     return !IsCompatibility;
10779   if (BasePred1 > BasePred2)
10780     return false;
10781   // Compare operands.
10782   bool LEPreds = Pred1 <= Pred2;
10783   bool GEPreds = Pred1 >= Pred2;
10784   for (int I = 0, E = CI1->getNumOperands(); I < E; ++I) {
10785     auto *Op1 = CI1->getOperand(LEPreds ? I : E - I - 1);
10786     auto *Op2 = CI2->getOperand(GEPreds ? I : E - I - 1);
10787     if (Op1->getValueID() < Op2->getValueID())
10788       return !IsCompatibility;
10789     if (Op1->getValueID() > Op2->getValueID())
10790       return false;
10791     if (auto *I1 = dyn_cast<Instruction>(Op1))
10792       if (auto *I2 = dyn_cast<Instruction>(Op2)) {
10793         if (I1->getParent() != I2->getParent())
10794           return false;
10795         InstructionsState S = getSameOpcode({I1, I2});
10796         if (S.getOpcode())
10797           continue;
10798         return false;
10799       }
10800   }
10801   return IsCompatibility;
10802 }
10803 
10804 bool SLPVectorizerPass::vectorizeSimpleInstructions(
10805     SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R,
10806     bool AtTerminator) {
10807   bool OpsChanged = false;
10808   SmallVector<Instruction *, 4> PostponedCmps;
10809   for (auto *I : reverse(Instructions)) {
10810     if (R.isDeleted(I))
10811       continue;
10812     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I)) {
10813       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
10814     } else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I)) {
10815       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
10816     } else if (isa<CmpInst>(I)) {
10817       PostponedCmps.push_back(I);
10818       continue;
10819     }
10820     // Try to find reductions in buildvector sequnces.
10821     OpsChanged |= vectorizeRootInstruction(nullptr, I, BB, R, TTI);
10822   }
10823   if (AtTerminator) {
10824     // Try to find reductions first.
10825     for (Instruction *I : PostponedCmps) {
10826       if (R.isDeleted(I))
10827         continue;
10828       for (Value *Op : I->operands())
10829         OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI);
10830     }
10831     // Try to vectorize operands as vector bundles.
10832     for (Instruction *I : PostponedCmps) {
10833       if (R.isDeleted(I))
10834         continue;
10835       OpsChanged |= tryToVectorize(I, R);
10836     }
10837     // Try to vectorize list of compares.
10838     // Sort by type, compare predicate, etc.
10839     auto &&CompareSorter = [&R](Value *V, Value *V2) {
10840       return compareCmp<false>(V, V2,
10841                                [&R](Instruction *I) { return R.isDeleted(I); });
10842     };
10843 
10844     auto &&AreCompatibleCompares = [&R](Value *V1, Value *V2) {
10845       if (V1 == V2)
10846         return true;
10847       return compareCmp<true>(V1, V2,
10848                               [&R](Instruction *I) { return R.isDeleted(I); });
10849     };
10850     auto Limit = [&R](Value *V) {
10851       unsigned EltSize = R.getVectorElementSize(V);
10852       return std::max(2U, R.getMaxVecRegSize() / EltSize);
10853     };
10854 
10855     SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end());
10856     OpsChanged |= tryToVectorizeSequence<Value>(
10857         Vals, Limit, CompareSorter, AreCompatibleCompares,
10858         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10859           // Exclude possible reductions from other blocks.
10860           bool ArePossiblyReducedInOtherBlock =
10861               any_of(Candidates, [](Value *V) {
10862                 return any_of(V->users(), [V](User *U) {
10863                   return isa<SelectInst>(U) &&
10864                          cast<SelectInst>(U)->getParent() !=
10865                              cast<Instruction>(V)->getParent();
10866                 });
10867               });
10868           if (ArePossiblyReducedInOtherBlock)
10869             return false;
10870           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10871         },
10872         /*LimitForRegisterSize=*/true);
10873     Instructions.clear();
10874   } else {
10875     // Insert in reverse order since the PostponedCmps vector was filled in
10876     // reverse order.
10877     Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend());
10878   }
10879   return OpsChanged;
10880 }
10881 
10882 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
10883   bool Changed = false;
10884   SmallVector<Value *, 4> Incoming;
10885   SmallPtrSet<Value *, 16> VisitedInstrs;
10886   // Maps phi nodes to the non-phi nodes found in the use tree for each phi
10887   // node. Allows better to identify the chains that can be vectorized in the
10888   // better way.
10889   DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes;
10890   auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) {
10891     assert(isValidElementType(V1->getType()) &&
10892            isValidElementType(V2->getType()) &&
10893            "Expected vectorizable types only.");
10894     // It is fine to compare type IDs here, since we expect only vectorizable
10895     // types, like ints, floats and pointers, we don't care about other type.
10896     if (V1->getType()->getTypeID() < V2->getType()->getTypeID())
10897       return true;
10898     if (V1->getType()->getTypeID() > V2->getType()->getTypeID())
10899       return false;
10900     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10901     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10902     if (Opcodes1.size() < Opcodes2.size())
10903       return true;
10904     if (Opcodes1.size() > Opcodes2.size())
10905       return false;
10906     Optional<bool> ConstOrder;
10907     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10908       // Undefs are compatible with any other value.
10909       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) {
10910         if (!ConstOrder)
10911           ConstOrder =
10912               !isa<UndefValue>(Opcodes1[I]) && isa<UndefValue>(Opcodes2[I]);
10913         continue;
10914       }
10915       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10916         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10917           DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent());
10918           DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent());
10919           if (!NodeI1)
10920             return NodeI2 != nullptr;
10921           if (!NodeI2)
10922             return false;
10923           assert((NodeI1 == NodeI2) ==
10924                      (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10925                  "Different nodes should have different DFS numbers");
10926           if (NodeI1 != NodeI2)
10927             return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10928           InstructionsState S = getSameOpcode({I1, I2});
10929           if (S.getOpcode())
10930             continue;
10931           return I1->getOpcode() < I2->getOpcode();
10932         }
10933       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) {
10934         if (!ConstOrder)
10935           ConstOrder = Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID();
10936         continue;
10937       }
10938       if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID())
10939         return true;
10940       if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID())
10941         return false;
10942     }
10943     return ConstOrder && *ConstOrder;
10944   };
10945   auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) {
10946     if (V1 == V2)
10947       return true;
10948     if (V1->getType() != V2->getType())
10949       return false;
10950     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10951     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10952     if (Opcodes1.size() != Opcodes2.size())
10953       return false;
10954     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10955       // Undefs are compatible with any other value.
10956       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
10957         continue;
10958       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10959         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10960           if (I1->getParent() != I2->getParent())
10961             return false;
10962           InstructionsState S = getSameOpcode({I1, I2});
10963           if (S.getOpcode())
10964             continue;
10965           return false;
10966         }
10967       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
10968         continue;
10969       if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID())
10970         return false;
10971     }
10972     return true;
10973   };
10974   auto Limit = [&R](Value *V) {
10975     unsigned EltSize = R.getVectorElementSize(V);
10976     return std::max(2U, R.getMaxVecRegSize() / EltSize);
10977   };
10978 
10979   bool HaveVectorizedPhiNodes = false;
10980   do {
10981     // Collect the incoming values from the PHIs.
10982     Incoming.clear();
10983     for (Instruction &I : *BB) {
10984       PHINode *P = dyn_cast<PHINode>(&I);
10985       if (!P)
10986         break;
10987 
10988       // No need to analyze deleted, vectorized and non-vectorizable
10989       // instructions.
10990       if (!VisitedInstrs.count(P) && !R.isDeleted(P) &&
10991           isValidElementType(P->getType()))
10992         Incoming.push_back(P);
10993     }
10994 
10995     // Find the corresponding non-phi nodes for better matching when trying to
10996     // build the tree.
10997     for (Value *V : Incoming) {
10998       SmallVectorImpl<Value *> &Opcodes =
10999           PHIToOpcodes.try_emplace(V).first->getSecond();
11000       if (!Opcodes.empty())
11001         continue;
11002       SmallVector<Value *, 4> Nodes(1, V);
11003       SmallPtrSet<Value *, 4> Visited;
11004       while (!Nodes.empty()) {
11005         auto *PHI = cast<PHINode>(Nodes.pop_back_val());
11006         if (!Visited.insert(PHI).second)
11007           continue;
11008         for (Value *V : PHI->incoming_values()) {
11009           if (auto *PHI1 = dyn_cast<PHINode>((V))) {
11010             Nodes.push_back(PHI1);
11011             continue;
11012           }
11013           Opcodes.emplace_back(V);
11014         }
11015       }
11016     }
11017 
11018     HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>(
11019         Incoming, Limit, PHICompare, AreCompatiblePHIs,
11020         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
11021           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
11022         },
11023         /*LimitForRegisterSize=*/true);
11024     Changed |= HaveVectorizedPhiNodes;
11025     VisitedInstrs.insert(Incoming.begin(), Incoming.end());
11026   } while (HaveVectorizedPhiNodes);
11027 
11028   VisitedInstrs.clear();
11029 
11030   SmallVector<Instruction *, 8> PostProcessInstructions;
11031   SmallDenseSet<Instruction *, 4> KeyNodes;
11032   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
11033     // Skip instructions with scalable type. The num of elements is unknown at
11034     // compile-time for scalable type.
11035     if (isa<ScalableVectorType>(it->getType()))
11036       continue;
11037 
11038     // Skip instructions marked for the deletion.
11039     if (R.isDeleted(&*it))
11040       continue;
11041     // We may go through BB multiple times so skip the one we have checked.
11042     if (!VisitedInstrs.insert(&*it).second) {
11043       if (it->use_empty() && KeyNodes.contains(&*it) &&
11044           vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
11045                                       it->isTerminator())) {
11046         // We would like to start over since some instructions are deleted
11047         // and the iterator may become invalid value.
11048         Changed = true;
11049         it = BB->begin();
11050         e = BB->end();
11051       }
11052       continue;
11053     }
11054 
11055     if (isa<DbgInfoIntrinsic>(it))
11056       continue;
11057 
11058     // Try to vectorize reductions that use PHINodes.
11059     if (PHINode *P = dyn_cast<PHINode>(it)) {
11060       // Check that the PHI is a reduction PHI.
11061       if (P->getNumIncomingValues() == 2) {
11062         // Try to match and vectorize a horizontal reduction.
11063         if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
11064                                      TTI)) {
11065           Changed = true;
11066           it = BB->begin();
11067           e = BB->end();
11068           continue;
11069         }
11070       }
11071       // Try to vectorize the incoming values of the PHI, to catch reductions
11072       // that feed into PHIs.
11073       for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) {
11074         // Skip if the incoming block is the current BB for now. Also, bypass
11075         // unreachable IR for efficiency and to avoid crashing.
11076         // TODO: Collect the skipped incoming values and try to vectorize them
11077         // after processing BB.
11078         if (BB == P->getIncomingBlock(I) ||
11079             !DT->isReachableFromEntry(P->getIncomingBlock(I)))
11080           continue;
11081 
11082         Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I),
11083                                             P->getIncomingBlock(I), R, TTI);
11084       }
11085       continue;
11086     }
11087 
11088     // Ran into an instruction without users, like terminator, or function call
11089     // with ignored return value, store. Ignore unused instructions (basing on
11090     // instruction type, except for CallInst and InvokeInst).
11091     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
11092                             isa<InvokeInst>(it))) {
11093       KeyNodes.insert(&*it);
11094       bool OpsChanged = false;
11095       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
11096         for (auto *V : it->operand_values()) {
11097           // Try to match and vectorize a horizontal reduction.
11098           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
11099         }
11100       }
11101       // Start vectorization of post-process list of instructions from the
11102       // top-tree instructions to try to vectorize as many instructions as
11103       // possible.
11104       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
11105                                                 it->isTerminator());
11106       if (OpsChanged) {
11107         // We would like to start over since some instructions are deleted
11108         // and the iterator may become invalid value.
11109         Changed = true;
11110         it = BB->begin();
11111         e = BB->end();
11112         continue;
11113       }
11114     }
11115 
11116     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
11117         isa<InsertValueInst>(it))
11118       PostProcessInstructions.push_back(&*it);
11119   }
11120 
11121   return Changed;
11122 }
11123 
11124 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
11125   auto Changed = false;
11126   for (auto &Entry : GEPs) {
11127     // If the getelementptr list has fewer than two elements, there's nothing
11128     // to do.
11129     if (Entry.second.size() < 2)
11130       continue;
11131 
11132     LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
11133                       << Entry.second.size() << ".\n");
11134 
11135     // Process the GEP list in chunks suitable for the target's supported
11136     // vector size. If a vector register can't hold 1 element, we are done. We
11137     // are trying to vectorize the index computations, so the maximum number of
11138     // elements is based on the size of the index expression, rather than the
11139     // size of the GEP itself (the target's pointer size).
11140     unsigned MaxVecRegSize = R.getMaxVecRegSize();
11141     unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin());
11142     if (MaxVecRegSize < EltSize)
11143       continue;
11144 
11145     unsigned MaxElts = MaxVecRegSize / EltSize;
11146     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
11147       auto Len = std::min<unsigned>(BE - BI, MaxElts);
11148       ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len);
11149 
11150       // Initialize a set a candidate getelementptrs. Note that we use a
11151       // SetVector here to preserve program order. If the index computations
11152       // are vectorizable and begin with loads, we want to minimize the chance
11153       // of having to reorder them later.
11154       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
11155 
11156       // Some of the candidates may have already been vectorized after we
11157       // initially collected them. If so, they are marked as deleted, so remove
11158       // them from the set of candidates.
11159       Candidates.remove_if(
11160           [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
11161 
11162       // Remove from the set of candidates all pairs of getelementptrs with
11163       // constant differences. Such getelementptrs are likely not good
11164       // candidates for vectorization in a bottom-up phase since one can be
11165       // computed from the other. We also ensure all candidate getelementptr
11166       // indices are unique.
11167       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
11168         auto *GEPI = GEPList[I];
11169         if (!Candidates.count(GEPI))
11170           continue;
11171         auto *SCEVI = SE->getSCEV(GEPList[I]);
11172         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
11173           auto *GEPJ = GEPList[J];
11174           auto *SCEVJ = SE->getSCEV(GEPList[J]);
11175           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
11176             Candidates.remove(GEPI);
11177             Candidates.remove(GEPJ);
11178           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
11179             Candidates.remove(GEPJ);
11180           }
11181         }
11182       }
11183 
11184       // We break out of the above computation as soon as we know there are
11185       // fewer than two candidates remaining.
11186       if (Candidates.size() < 2)
11187         continue;
11188 
11189       // Add the single, non-constant index of each candidate to the bundle. We
11190       // ensured the indices met these constraints when we originally collected
11191       // the getelementptrs.
11192       SmallVector<Value *, 16> Bundle(Candidates.size());
11193       auto BundleIndex = 0u;
11194       for (auto *V : Candidates) {
11195         auto *GEP = cast<GetElementPtrInst>(V);
11196         auto *GEPIdx = GEP->idx_begin()->get();
11197         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
11198         Bundle[BundleIndex++] = GEPIdx;
11199       }
11200 
11201       // Try and vectorize the indices. We are currently only interested in
11202       // gather-like cases of the form:
11203       //
11204       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
11205       //
11206       // where the loads of "a", the loads of "b", and the subtractions can be
11207       // performed in parallel. It's likely that detecting this pattern in a
11208       // bottom-up phase will be simpler and less costly than building a
11209       // full-blown top-down phase beginning at the consecutive loads.
11210       Changed |= tryToVectorizeList(Bundle, R);
11211     }
11212   }
11213   return Changed;
11214 }
11215 
11216 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
11217   bool Changed = false;
11218   // Sort by type, base pointers and values operand. Value operands must be
11219   // compatible (have the same opcode, same parent), otherwise it is
11220   // definitely not profitable to try to vectorize them.
11221   auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) {
11222     if (V->getPointerOperandType()->getTypeID() <
11223         V2->getPointerOperandType()->getTypeID())
11224       return true;
11225     if (V->getPointerOperandType()->getTypeID() >
11226         V2->getPointerOperandType()->getTypeID())
11227       return false;
11228     // UndefValues are compatible with all other values.
11229     if (isa<UndefValue>(V->getValueOperand()) ||
11230         isa<UndefValue>(V2->getValueOperand()))
11231       return false;
11232     if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand()))
11233       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
11234         DomTreeNodeBase<llvm::BasicBlock> *NodeI1 =
11235             DT->getNode(I1->getParent());
11236         DomTreeNodeBase<llvm::BasicBlock> *NodeI2 =
11237             DT->getNode(I2->getParent());
11238         assert(NodeI1 && "Should only process reachable instructions");
11239         assert(NodeI2 && "Should only process reachable instructions");
11240         assert((NodeI1 == NodeI2) ==
11241                    (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
11242                "Different nodes should have different DFS numbers");
11243         if (NodeI1 != NodeI2)
11244           return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
11245         InstructionsState S = getSameOpcode({I1, I2});
11246         if (S.getOpcode())
11247           return false;
11248         return I1->getOpcode() < I2->getOpcode();
11249       }
11250     if (isa<Constant>(V->getValueOperand()) &&
11251         isa<Constant>(V2->getValueOperand()))
11252       return false;
11253     return V->getValueOperand()->getValueID() <
11254            V2->getValueOperand()->getValueID();
11255   };
11256 
11257   auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) {
11258     if (V1 == V2)
11259       return true;
11260     if (V1->getPointerOperandType() != V2->getPointerOperandType())
11261       return false;
11262     // Undefs are compatible with any other value.
11263     if (isa<UndefValue>(V1->getValueOperand()) ||
11264         isa<UndefValue>(V2->getValueOperand()))
11265       return true;
11266     if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand()))
11267       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
11268         if (I1->getParent() != I2->getParent())
11269           return false;
11270         InstructionsState S = getSameOpcode({I1, I2});
11271         return S.getOpcode() > 0;
11272       }
11273     if (isa<Constant>(V1->getValueOperand()) &&
11274         isa<Constant>(V2->getValueOperand()))
11275       return true;
11276     return V1->getValueOperand()->getValueID() ==
11277            V2->getValueOperand()->getValueID();
11278   };
11279   auto Limit = [&R, this](StoreInst *SI) {
11280     unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
11281     return R.getMinVF(EltSize);
11282   };
11283 
11284   // Attempt to sort and vectorize each of the store-groups.
11285   for (auto &Pair : Stores) {
11286     if (Pair.second.size() < 2)
11287       continue;
11288 
11289     LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
11290                       << Pair.second.size() << ".\n");
11291 
11292     if (!isValidElementType(Pair.second.front()->getValueOperand()->getType()))
11293       continue;
11294 
11295     Changed |= tryToVectorizeSequence<StoreInst>(
11296         Pair.second, Limit, StoreSorter, AreCompatibleStores,
11297         [this, &R](ArrayRef<StoreInst *> Candidates, bool) {
11298           return vectorizeStores(Candidates, R);
11299         },
11300         /*LimitForRegisterSize=*/false);
11301   }
11302   return Changed;
11303 }
11304 
11305 char SLPVectorizer::ID = 0;
11306 
11307 static const char lv_name[] = "SLP Vectorizer";
11308 
11309 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
11310 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
11311 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
11312 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
11313 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
11314 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
11315 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
11316 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
11317 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
11318 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
11319 
11320 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
11321